Module: Rails::LocaleDetection

Defined in:
lib/rails/locale_detection.rb

Constant Summary collapse

@@locale_expiry =
3.months
@@set_default_url_option =
:always
@@detection_order =
[:user, :param, :cookie, :request]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.config {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



12
13
14
# File 'lib/rails/locale_detection.rb', line 12

def self.config
  yield self
end

Instance Method Details

#available_localesObject



16
17
18
# File 'lib/rails/locale_detection.rb', line 16

def available_locales
  I18n.available_locales
end

#default_localeObject



20
21
22
# File 'lib/rails/locale_detection.rb', line 20

def default_locale
  I18n.default_locale
end

#get_localeObject



53
54
55
# File 'lib/rails/locale_detection.rb', line 53

def get_locale
  detection_order.inject(nil) { |result, source| result || locale_from(source) } || default_locale
end

#locale_from(key) ⇒ Object



49
50
51
# File 'lib/rails/locale_detection.rb', line 49

def locale_from(key)
  send("locale_from_#{key}")
end


37
38
39
# File 'lib/rails/locale_detection.rb', line 37

def locale_from_cookie
  validate_locale(cookies[:locale])
end

#locale_from_paramObject



33
34
35
# File 'lib/rails/locale_detection.rb', line 33

def locale_from_param
  validate_locale(params[:locale])
end

#locale_from_requestObject



41
42
43
# File 'lib/rails/locale_detection.rb', line 41

def locale_from_request
  validate_locale(request.preferred_language_from(available_locales))
end

#locale_from_userObject



45
46
47
# File 'lib/rails/locale_detection.rb', line 45

def locale_from_user
  validate_locale(user_locale)
end

#set_default_url_option_for_request?Boolean

returns true if the default url option should be set for this request

Returns:

  • (Boolean)


58
59
60
# File 'lib/rails/locale_detection.rb', line 58

def set_default_url_option_for_request?
  set_default_url_option === true || set_default_url_option == :always || set_default_url_option == :explicitly && params[:locale].present?
end

#set_localeObject

set I18n.locale, default_url_options and cookies to the value returned by get_locale



64
65
66
67
68
69
70
71
72
# File 'lib/rails/locale_detection.rb', line 64

def set_locale
  I18n.locale = get_locale
  
  default_url_options[:locale] = I18n.locale if set_default_url_option_for_request?
  
  cookies[:locale] = { :value => I18n.locale, :expires => locale_expiry.from_now }
  
  I18n.locale
end

#user_localeObject



24
25
26
# File 'lib/rails/locale_detection.rb', line 24

def user_locale
  nil
end

#validate_locale(locale) ⇒ Object

returns the (symbolized) value passed if it’s in the available_locales



29
30
31
# File 'lib/rails/locale_detection.rb', line 29

def validate_locale(locale)
  locale.to_sym if locale && available_locales.include?(locale.to_sym)
end