Class: RoutingFilter::Locale

Inherits:
Base
  • Object
show all
Defined in:
lib/routing_filter/locale.rb

Constant Summary collapse

@@include_default_locale =
true

Instance Attribute Summary

Attributes inherited from Base

#chain, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize, #predecessor, #run, #run_reverse, #successor

Constructor Details

This class inherits a constructor from RoutingFilter::Base

Class Method Details

.extract_locale!(path) ⇒ Object



26
27
28
29
# File 'lib/routing_filter/locale.rb', line 26

def extract_locale!(path)
  path.sub! self.locales_pattern, ''
  $1
end

.include_default_locale?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/routing_filter/locale.rb', line 10

def include_default_locale?
  @@include_default_locale
end

.localesObject



14
15
16
# File 'lib/routing_filter/locale.rb', line 14

def locales
  @@locales ||= I18n.available_locales.map(&:to_sym)
end

.locales=(locales) ⇒ Object



18
19
20
# File 'lib/routing_filter/locale.rb', line 18

def locales=(locales)
  @@locales = locales.map(&:to_sym)
end

.locales_patternObject



22
23
24
# File 'lib/routing_filter/locale.rb', line 22

def locales_pattern
  @@locales_pattern ||= %r(^/(#{self.locales.map { |l| Regexp.escape(l.to_s) }.join('|')})(?=/|$))
end

.prepend_locale!(url, locale) ⇒ Object



31
32
33
# File 'lib/routing_filter/locale.rb', line 31

def prepend_locale!(url, locale)
  url.sub!(%r(^(http.?://[^/]*)?(.*))) { "#{$1}/#{locale}#{$2}" }
end

Instance Method Details

#around_generate(*args, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/routing_filter/locale.rb', line 43

def around_generate(*args, &block)
  options = args.extract_options!

  locale = options.delete(:locale)
  unless  skip_prepend_locale? options
    locale = I18n.locale if locale.nil?            # default to I18n.locale when locale is nil (could also be false)
    locale = nil unless valid_locale?(locale)     # reset to no locale when locale is not valid
    returning yield do |result|
      if locale && prepend_locale?(locale)
        url = result.is_a?(Array) ? result.first : result
        self.class.prepend_locale!(url, locale)
      end
    end
  else
    yield
  end
end

#around_recognize(path, env, &block) ⇒ Object



36
37
38
39
40
41
# File 'lib/routing_filter/locale.rb', line 36

def around_recognize(path, env, &block)
  locale = self.class.extract_locale!(path)                 # remove the locale from the beginning of the path
  returning yield do |params|                    # invoke the given block (calls more filters and finally routing)
    params[:locale] = locale if locale           # set recognized locale to the resulting params hash
  end
end