Module: Perfectline::T9n::TranslatableAttribute::InstanceMethods

Defined in:
lib/t9n/active_record/translatable_attribute.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
# File 'lib/t9n/active_record/translatable_attribute.rb', line 99

def method_missing(method, *args, &block)
  if method.to_s.match(/^(#{self.class.translated_attributes.keys.map(&:to_s).join("|")})_([a-z]{2})(=)?$/)
    if $3 == "="
      write_translatable_attribute($1, args.first, $2)
    else
      read_translatable_attribute($1, $2)
    end
  else
    super
  end
end

Instance Method Details

#read_translatable_attribute(attribute, locale) ⇒ Object



88
89
90
91
92
93
94
95
96
97
# File 'lib/t9n/active_record/translatable_attribute.rb', line 88

def read_translatable_attribute(attribute, locale)
  options = self.class.translated_attributes.fetch(attribute.to_sym)

  if options.fetch(:real_attribute) && I18n.default_locale.to_s == locale
    __send__(options.fetch(:default))
  else
    translation = translations.detect{ |t| t.key == options.fetch(:key) && t.locale == locale}
    translation.nil? ? nil : translation.value
  end
end

#respond_to?(method, *args, &block) ⇒ Boolean

Returns:

  • (Boolean)


111
112
113
# File 'lib/t9n/active_record/translatable_attribute.rb', line 111

def respond_to?(method, *args, &block)
  !method.to_s.match(/^(#{self.class.translated_attributes.keys.map(&:to_s).join("|")})_([a-z]{2})(=)?$/).nil? || super
end

#write_translatable_attribute(attribute, value, locale) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/t9n/active_record/translatable_attribute.rb', line 76

def write_translatable_attribute(attribute, value, locale)
  options = self.class.translated_attributes.fetch(attribute.to_sym)

  if options.fetch(:real_attribute) && I18n.default_locale.to_s == locale
    __send__("#{options.fetch(:default)}=", value)
  else
    translation = translations.detect{ |t| t.key == options.fetch(:key) && t.locale == locale }
    translation = translations.build(:key => options.fetch(:key), :locale => locale) if translation.nil?
    translation.value = value
  end
end