Module: Monglobal::ClassMethods

Defined in:
lib/monglobal.rb

Instance Method Summary collapse

Instance Method Details

#translates(*args) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/monglobal.rb', line 47

def translates(*args)
  klass_name = "#{name.camelcase}Translation"
  
  # Create the translation model
  translation_model = Class.new do
    include MongoMapper::EmbeddedDocument
    key :locale, String
    args.each do |attr|
      key attr.to_sym, String
    end
  end
  Object.const_set klass_name, translation_model
  
  instance_eval do
    has_many klass_name.underscore.pluralize.to_sym
  end
  
  # Add attributes readers
  class_eval do
    args.each do |attr|
      define_method(attr) do | *params |
        requested_locale = params.first
        requested_locale = I18n.locale if requested_locale.nil?
        if requested_locale == I18n.default_locale
          instance_variable_get("@#{attr}")
        else
          translations = send(klass_name.underscore.pluralize.to_sym)
          translated_attr = nil
          translations.each do |translation|
            translated_attr = translation.send(attr.to_sym) if translation.locale.to_sym == requested_locale
          end
          translated_attr = instance_variable_get("@#{attr}") if translated_attr.nil?
          translated_attr
        end
      end
    end
  end
end