Module: RailsLocaleDetection::DetectionMethods

Included in:
LocaleDetector
Defined in:
lib/rails_locale_detection/detection_methods.rb

Instance Method Summary collapse

Instance Method Details

#detect_localeObject



30
31
32
# File 'lib/rails_locale_detection/detection_methods.rb', line 30

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

#locale_from(key) ⇒ Object



26
27
28
# File 'lib/rails_locale_detection/detection_methods.rb', line 26

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


14
15
16
# File 'lib/rails_locale_detection/detection_methods.rb', line 14

def locale_from_cookie
  validate_locale(cookies[locale_key])
end

#locale_from_paramObject



10
11
12
# File 'lib/rails_locale_detection/detection_methods.rb', line 10

def locale_from_param
  validate_locale(params[locale_key])
end

#locale_from_requestObject



18
19
20
# File 'lib/rails_locale_detection/detection_methods.rb', line 18

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

#locale_from_userObject



22
23
24
# File 'lib/rails_locale_detection/detection_methods.rb', line 22

def locale_from_user
  validate_locale(user_locale)
end

#set_default_url_option_for_request?Boolean

Returns:

  • (Boolean)


51
52
53
54
55
56
57
58
59
60
# File 'lib/rails_locale_detection/detection_methods.rb', line 51

def set_default_url_option_for_request?
  case RailsLocaleDetection.set_default_url_option
  when true, :always
    true
  when :explicitly
    params[locale_key].present?
  else
    false
  end
end

#set_localeObject

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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rails_locale_detection/detection_methods.rb', line 36

def set_locale
  self.current_locale = detect_locale

  if set_default_url_option_for_request?
    default_url_options[locale_key] = current_locale
  end

  if locale_from_cookie != current_locale
    cookies[locale_key] = {
      value: current_locale,
      expires: RailsLocaleDetection.locale_expiry.from_now
    }
  end
end

#validate_locale(locale) ⇒ Object

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



6
7
8
# File 'lib/rails_locale_detection/detection_methods.rb', line 6

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