Module: I18nColumn::Base::ClassMethods

Defined in:
lib/i18n_column/base.rb

Instance Method Summary collapse

Instance Method Details

#i18n_column(*col_names) ⇒ Object

Creates i18n getter and setter methods for the given column names.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/i18n_column/base.rb', line 17

def i18n_column(*col_names)
  for col_name in col_names
    class_eval <<-EOV
      def #{col_name}
        json = decode_#{col_name}
        json.nil? ? nil : json[::I18n.locale.to_s]
      end
      
      def #{col_name}=(value)
        json = decode_#{col_name} || {}
        json[::I18n.locale.to_s] = value
        self[:#{col_name}] = json.to_json
        value
      end
      
      def f#{col_name}
        self.#{col_name}
      end
      
      def f#{col_name}=(value)
        self.#{col_name} = value
      end
      
      private
      
      def decode_#{col_name}
        val = self[:#{col_name}]
        (val.inspect == "nil" || val.to_s.blank?) ? nil : ::ActiveSupport::JSON::decode(val.to_s)
      end
    EOV
  end
end