Class: Rack::I18nLocaleSwitcher

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/i18n_locale_switcher.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :param  => 'locale',
  :source => [ :param, :path, :host, :header ]
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ I18nLocaleSwitcher

Returns a new instance of I18nLocaleSwitcher.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rack/i18n_locale_switcher.rb', line 12

def initialize(app, options = {})
  @app = app
  
  invalid_options = (options.keys - DEFAULT_OPTIONS.keys)
  
  if invalid_options.any?
    raise ArgumentError, "Invalid option(s) #{ invalid_options.map(&:inspect).join(', ') }" 
  end
  
  @options = DEFAULT_OPTIONS.merge(options)
  @options[:source] = Array(@options[:source]) unless @options[:source].is_a?(Array)
end

Instance Method Details

#call(env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rack/i18n_locale_switcher.rb', line 25

def call(env)
  I18n.locale = I18n.default_locale
  
  @options[:source].each do |source|
    if locale = send(:"get_locale_from_#{source}", env)
      I18n.locale = locale
      break
    end
  end
        
  @app.call(env)
end