Module: Trax::Model::MTI::Abstract::ClassMethods

Defined in:
lib/trax/model/mti/abstract.rb

Instance Method Summary collapse

Instance Method Details

#entity_model(options) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/trax/model/mti/abstract.rb', line 53

def entity_model(options)
  valid_options = options.assert_valid_keys(:class_name, :foreign_key)

  mti_config.merge!(valid_options)

  self.has_one(:entity, mti_config.symbolize_keys)
  self.accepts_nested_attributes_for(:entity)
end

#inherited(subklass) ⇒ Object



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
# File 'lib/trax/model/mti/abstract.rb', line 21

def inherited(subklass)
  super(subklass)

  subklass.after_create do |record|
    entity_model = mti_config[:class_name].constantize.new

    record.attributes.each_pair do |k,v|
      entity_model.__send__("#{k}=", v) if entity_model.respond_to?(k)
    end

    entity_model.save
  end

  subklass.after_update do |record|
    entity_model = record.entity

    if record.changed.any?
      record.changes.each_pair do |k,v|
        entity_model.__send__("#{k}=", v[1]) if entity.respond_to?(:"#{k}")
      end
    end

    entity_model.save if entity_model.changed.any?
  end

  subklass.after_destroy do |record|
    entity_model = record.entity

    entity_model.destroy
  end
end