Class: Perfectline::LocaleRouting::Locale
- Inherits:
-
Object
- Object
- Perfectline::LocaleRouting::Locale
- Defined in:
- lib/locale_routing/locale.rb
Overview
class containing Locale handling methods
Class Method Summary collapse
-
.extract(path, env) ⇒ Object
extract and set locale.
- .extract_from_host(env) ⇒ Object
- .extract_from_params(path) ⇒ Object
-
.match_params_locale ⇒ Object
locale matching pattern.
- .match_url ⇒ Object
-
.prepend(result, locale) ⇒ Object
prepend locale to generated url.
Class Method Details
.extract(path, env) ⇒ Object
extract and set locale
34 35 36 37 38 39 40 41 |
# File 'lib/locale_routing/locale.rb', line 34 def extract(path, env) case Perfectline::LocaleRouting::Config.match_from when :params then path = extract_from_params(path) when :host then extract_from_host(env) end return path end |
.extract_from_host(env) ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/locale_routing/locale.rb', line 60 def extract_from_host(env) if env[:host].nil? raise "Valid host not found (Perfectline::LocaleRouting.match_from = :host)." end host = env[:host].to_s locale = I18n.default_locale mappings = Perfectline::LocaleRouting::Config.host_mapping if mappings.nil? || mappings.empty? RAILS_DEFAULT_LOGGER.warn "Perfectline::LocaleRouting.host_mapping is nil or empty." end puts mappings.inspect mappings.each do |element| unless host.match(%r(^#{element[:host]}$)).nil? locale = element[:locale] and break end end I18n.locale = locale end |
.extract_from_params(path) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/locale_routing/locale.rb', line 43 def extract_from_params(path) # match for configured locales and remove them replacement = path.sub!(self.match_params_locale, '') locale = I18n.default_locale # if matches were found, set the locale and new path if (not replacement.nil?) path = replacement locale = $1.to_sym else RAILS_DEFAULT_LOGGER.info "No valid locale string found in the URL, falling back to #{locale}" end # set the locale and return the 'cleaned' path string I18n.locale = locale and return path end |
.match_params_locale ⇒ Object
locale matching pattern
8 9 10 |
# File 'lib/locale_routing/locale.rb', line 8 def match_params_locale @@match_params_locale ||= %r(^/((#{I18n.available_locales.map{|o| Regexp.escape(o.to_s)}.join('|')})(?=/|$))) end |
.match_url ⇒ Object
12 13 14 |
# File 'lib/locale_routing/locale.rb', line 12 def match_url @@match_url ||= %r(^(http.?://[^/]*)?(.*)) end |
.prepend(result, locale) ⇒ Object
prepend locale to generated url
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/locale_routing/locale.rb', line 18 def prepend(result, locale) # check the results url = result.is_a?(Array) ? result.first : result locale = I18n.locale if locale.nil? # substitute the locale url.sub!(self.match_url) do hostname = $1 path = $2 == '/' ? '' : $2 "#{hostname}/#{locale}#{path}" end end |