Module: TranslatableAttributes::ClassMethods

Defined in:
lib/translatable_attributes.rb

Instance Method Summary collapse

Instance Method Details

#translatable_attribute_accessor(*attributes) ⇒ Object

Adds a reader and writer for each available locale for each of the given attributes. For example (and assuming that the available locales are :en and :de):

I18n.available_locales                            # => [:en, :de]

class Post < ActiveModel::Base
  translatable_attribute_accessor :title, :body
end

This creates the methods ‘title_en`, `title_en=`, `title_de`, `title_de=`, `body_en`, `body_en=`, `body_de` and `body_de=`



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/translatable_attributes.rb', line 42

def translatable_attribute_accessor(*attributes)
  attributes.each do |attr|
    I18n::Backend::ActiveRecord::Translation.available_locales.map(&:to_s).each do |locale|
      class_eval do
        name = "#{attr.to_s}_#{locale.gsub('-', '_').downcase}"

        define_method name do
          translatable_attribute_record(attr, locale).value
        end

        define_method "#{name}=" do |value|
          translatable_attribute_record(attr, locale).value = value
        end

      end
    end
  end
end