Module: LocalizedKeys::ClassMethods

Defined in:
lib/blue_pages/localized_keys.rb

Instance Method Summary collapse

Instance Method Details

#default_language(instance = nil) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/blue_pages/localized_keys.rb', line 20

def default_language(instance = nil)
  if @default_language.respond_to?(:call)
    @default_language.call
  elsif @default_language.is_a?(Symbol)
    instance && instance.send(@default_language)
  else
    @default_language
  end
end

#default_language=(language) ⇒ Object



30
31
32
# File 'lib/blue_pages/localized_keys.rb', line 30

def default_language=(language)
  @default_language = language
end

#i18n_field(name, options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/blue_pages/localized_keys.rb', line 34

def i18n_field(name, options = {})
  localized_keys << name
  self.default_language = options.delete(:default_language) if options[:default_language]

  # Define MongoMapper key
  key_name = "#{name}_locales"
  self.field key_name, options.merge(:type => Hash, :default => {})

  # Define a getter method
  define_method(name) do |*args|
    locale = (args.empty? || args.first.nil?) ?
      self.class.default_language(self) :
      args.first
    locale_attr = read_attribute(key_name)
    locale = locale_attr.keys.first unless locale
    p locale
    locale_attr[locale || ''] if locale_attr
  end

  # Define a setter method
  define_method(:"#{name}=") do |*args|
    locale_attr = read_attribute(key_name)
    write_attribute(key_name, {}) unless locale_attr
    read_attribute(key_name)[self.class.default_language(self) || ''] = args.first
  end

  # Define a query method
  define_method(:"#{name}?") do |*args|
    self.send(name, *args).present?
  end
end

#localized_keysObject



16
17
18
# File 'lib/blue_pages/localized_keys.rb', line 16

def localized_keys
  @localized_keys ||= []
end