module Mongoid::Globalize

Helper class for storing values per locale. Used by Mongoid::Globalize::Adapter to stash and cache attribute values.

Public Class Methods

fallbacks(locale = self.locale) click to toggle source

Returns fallback locales for given locale if any. Returns Array of Symbols

# File lib/mongoid_globalize.rb, line 90
def fallbacks(locale = self.locale)
  fallbacks? ? I18n.fallbacks[locale] : [locale.to_sym]
end
fallbacks?() click to toggle source

Checks whether I18n respond to fallbacks method. Returns true or false

# File lib/mongoid_globalize.rb, line 84
def fallbacks?
  I18n.respond_to?(:fallbacks)
end
locale() click to toggle source

Get current locale. If curent locale doesn’t set obviously for Mongoid::Globalize, returns I18n locale

Mongoid::Globalize.locale   #=> :en

Returns Symbol

# File lib/mongoid_globalize.rb, line 45
def locale
  read_locale || I18n.locale
end
locale=(locale) click to toggle source

Set current locale by saving it in current thread.

Mongoid::Globalize.locale = 'ru'    #=> :ru

Param String or Symbol Returns Symbol or nil

# File lib/mongoid_globalize.rb, line 53
def locale=(locale)
  set_locale(locale)
end
with_locale(locale) { |locale| ... } click to toggle source

Runs block as if given locale is setted. Don’t touch current locale. Yelds locale into block.

Mongoid::Globalize.with_locale(:de) { post.title = 'Titel' }

Param String or Symbol Param Proc Returns result from block

# File lib/mongoid_globalize.rb, line 63
def with_locale(locale, &block)
  previous_locale = read_locale
  set_locale(locale)
  result = yield(locale)
  set_locale(previous_locale)
  result
end
with_locales(*locales, &block) click to toggle source

Runs block for each given locale.

Mongoid::Globalize.with_locale(:ru, [:de, :fr]) { post.title = 'Title' }

Params String or Symbol or Array of Strings or Symbols Param Proc Returns Array with results from block for each locale

# File lib/mongoid_globalize.rb, line 76
def with_locales(*locales, &block)
  locales.flatten.map do |locale|
    with_locale(locale, &block)
  end
end

Protected Class Methods

read_locale() click to toggle source

Reads locale from current thread

# File lib/mongoid_globalize.rb, line 96
def read_locale
  Thread.current[:globalize_locale]
end
set_locale(locale) click to toggle source

Writes locale to current thread

# File lib/mongoid_globalize.rb, line 101
def set_locale(locale)
  Thread.current[:globalize_locale] = locale.to_sym rescue nil
end