Append locale parameter to all paths generated by js-routes gem in rails

628 Views Asked by At

I am using js-routes gem (https://github.com/railsware/js-routes) with Rails 4.0.0.

What I want to do is include the current locale string in every route generated by js-routes in my rails app. And this locale string (e.g. "en") will be pulled from the query string for the current request. (So it can vary from one page load to the next, if the user decides to switch locales.)

In application_controller.rb I have the following to send and receive the locale. This successfully appends the locale parameter in the routes generated by Rails, but not by js-routes. (Nothing set in config/routes.rb)

application_controller.rb:

before_filter :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

def default_url_options(options={})
  { locale: I18n.locale }
end

In javascript I can call Routes.login_path() to get /login, but I want to get /login?locale=en without having to pass the locale to the login_path() method. And similarly for all my other routes.

My question is how to get js-routes to add the 'locale' parameter to all the routes it generates, e.g. /login?locale=fr, without having to pass any additional options to the Routes functions.

1

There are 1 best solutions below

0
On

If you have your locale set somewhere as a global variable, you can do the following with a current version of js-routes (assuming the use of i18next, for example)

# config/initializers/js_routes.rb

JsRoutes.setup do |config|
  config.serializer = <<~'JS'
    function(object) {
      object.locale = i18next.language
      return Routes.default_serializer(object)
    }
  JS
end

Now your locale param will be appended to all your js-routes:

Routes.some_path() //=> /path/to/page?locale=es-ES