Module: Puret::ActiveRecordExtensions::ClassMethods

Defined in:
lib/puret/active_record_extensions.rb

Instance Method Summary collapse

Instance Method Details

#puret(*attributes) ⇒ Object

Configure translated attributes. Eg:

class Post < ActiveRecord::Base
  puret :title, :description
end

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
49
50
# File 'lib/puret/active_record_extensions.rb', line 20

def puret(*attributes)
  make_it_puret! unless included_modules.include?(InstanceMethods)

  attributes.each do |attribute|
    # attribute setter
    define_method "#{attribute}=" do |value|
      puret_attributes[I18n.locale][attribute] = value
    end

    # attribute getter
    define_method attribute do
      # return previously setted attributes if present
      return puret_attributes[I18n.locale][attribute] if puret_attributes[I18n.locale][attribute]
      return if new_record?

      # Lookup chain:
      # if translation not present in current locale,
      # use default locale, if present.
      # Otherwise use first translation
      translation = translations.detect { |t| t.locale.to_sym == I18n.locale && t[attribute] } ||
        translations.detect { |t| t.locale.to_sym == puret_default_locale && t[attribute] } ||
        translations.first

      translation ? translation[attribute] : nil
    end

    define_method "#{attribute}_before_type_cast" do
      self.send(attribute)
    end
  end
end

#puret_for(model) ⇒ Object

Configure translation model dependency. Eg:

class PostTranslation < ActiveRecord::Base
  puret_for :post
end

9
10
11
12
13
# File 'lib/puret/active_record_extensions.rb', line 9

def puret_for(model)
  belongs_to model
  validates_presence_of :locale
  validates_uniqueness_of :locale, :scope => "#{model}_id"
end