Rails routes with optional scope “:locale”

前端 未结 6 1203
清歌不尽
清歌不尽 2020-12-06 06:08

I\'m working on a Rails 3.1 app and I\'d like to set specific routes for the different languages the app is going to support.

/es/countries
/de/countries
…
<         


        
6条回答
  •  失恋的感觉
    2020-12-06 06:23

    I'm doing a combination of what @Arcolye and @jifenaux are doing, plus something extra to keep the code as DRY as possible. It might not be suitable for everybody, but in my case, whenever I want to support a new locale I also have to create a new .yml file in config/locales/ anyways, so this is how it works best for me.

    config/application.rb:

    locale_files = Dir["#{Rails.root}/config/locales/??.yml"]
    
    config.i18n.available_locales = locale_files.map do |d| 
      d.split('/').last.split('.').first
    end
    
    config.i18n.default_locale = :en
    

    config/routes.rb

    root_path = 'pages#welcome'
    
    scope '(:locale)', locale: /#{I18n.available_locales.join('|')}/ do
      # ...
    end
    
    root to: root_path
    get '/:locale', to: root_path
    

    app/controllers/application_controller.rb:

    private
    
    def default_url_options(options = {})
      if I18n.default_locale != I18n.locale
        {locale: I18n.locale}.merge options
      else
        {locale: nil}.merge options
      end
    end
    

提交回复
热议问题