Class: RoutingFilter::Locale

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

Constant Summary collapse

@@include_default_locale =
true

Instance Attribute Summary collapse

Attributes inherited from Filter

#next, #options, #previous

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Filter

#run, #run_reverse

Constructor Details

#initialize(*args) ⇒ Locale

Returns a new instance of Locale.



48
49
50
51
# File 'lib/routing_filter/filters/locale.rb', line 48

def initialize(*args)
  super
  @exclude = options[:exclude]
end

Instance Attribute Details

#excludeObject (readonly)

Returns the value of attribute exclude.



47
48
49
# File 'lib/routing_filter/filters/locale.rb', line 47

def exclude
  @exclude
end

Class Method Details

.include_default_locale?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/routing_filter/filters/locale.rb', line 29

def include_default_locale?
  @@include_default_locale
end

.localesObject



33
34
35
# File 'lib/routing_filter/filters/locale.rb', line 33

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

.locales=(locales) ⇒ Object



37
38
39
# File 'lib/routing_filter/filters/locale.rb', line 37

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

.locales_patternObject



41
42
43
# File 'lib/routing_filter/filters/locale.rb', line 41

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

Instance Method Details

#around_generate(*args, &block) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/routing_filter/filters/locale.rb', line 61

def around_generate(*args, &block)
  params = args.extract_options!                              # this is because we might get a call like forum_topics_path(forum, topic, :locale => :en)

  locale = params.delete(:locale)                             # extract the passed :locale option
  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

  args << params

  yield.tap do |result|
    result.update prepend_segment(result.url, locale) if prepend_locale?(locale) && !excluded?(result.url)
  end
end

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



54
55
56
57
58
59
# File 'lib/routing_filter/filters/locale.rb', line 54

def around_recognize(path, env, &block)
  locale = extract_segment!(self.class.locales_pattern, path) # remove the locale from the beginning of the path
  yield.tap 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