Module: DataMapper::Is::Localizable

Defined in:
lib/dm-is-localizable/is/localizable.rb,
lib/dm-is-localizable/storage/translation.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods, Translation

Instance Method Summary collapse

Instance Method Details

#is_localizable(options = {}, &block) ⇒ Object



12
13
14
15
16
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
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
# File 'lib/dm-is-localizable/is/localizable.rb', line 12

def is_localizable(options = {}, &block)

  extend  ClassMethods
  include InstanceMethods

  options = {
    :as                       => nil,
    :model                    => "#{self}Translation",
    :accept_nested_attributes => true
  }.merge(options)

  remixer_fk = ActiveSupport::Inflector.foreign_key(self.name).to_sym
  remixer    = remixer_fk.to_s.gsub('_id', '').to_sym
  remixee    = ActiveSupport::Inflector.tableize(options[:model]).to_sym

  remix n, Translation, :as => options[:as], :model => options[:model]

  @translation_model = ActiveSupport::Inflector.constantize(options[:model])

  enhance :translation, @translation_model do

    property remixer_fk,   Integer, :min => 1, :required => true, :unique_index => :unique_languages
    property :language_id, Integer, :min => 1, :required => true, :unique_index => :unique_languages

    belongs_to remixer
    belongs_to :language

    class_eval &block

    validates_uniqueness_of :language_id, :scope => remixer_fk

  end

  has n, :languages, :through => remixee, :constraint => :destroy

  self.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)

    alias :translations :#{remixee}

    if options[:accept_nested_attributes]

      # cannot accept_nested_attributes_for :translations
      # since this is no valid relationship name, only an alias

      accepts_nested_attributes_for :#{remixee}
      alias :translations_attributes :#{remixee}_attributes

    end

  RUBY

  localizable_properties.each do |property_name|
    self.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)

      def #{property_name}(language_code)
        translate(:#{property_name.to_sym}, language_code)
      end

    RUBY
  end

end