Module: PropertySets::Delegator::ClassMethods

Defined in:
lib/property_sets/delegator.rb

Instance Method Summary collapse

Instance Method Details

#delegate_to_property_set(setname, mappings) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/property_sets/delegator.rb', line 20

def delegate_to_property_set(setname, mappings)
  raise "Second argument must be a Hash" unless mappings.is_a?(Hash)

  mappings.each do |old_attr, new_attr|
    define_method(old_attr) { send(setname).send(new_attr) }
    alias_method "#{old_attr}_before_type_cast", old_attr
    define_method("#{old_attr}?") { send(setname).send("#{new_attr}?") }
    define_method("#{old_attr}=") { |value| send(setname).send("#{new_attr}=", value) }

    define_method("#{old_attr}_changed?") do
      collection_proxy = send(setname)
      return false unless collection_proxy.loaded?
      setting = collection_proxy.lookup_without_default(new_attr)

      if !setting
        false # Nothing has been set which means that the attribute hasn't changed
      elsif setting.new_record?
        collection_proxy.association_class.default(new_attr) != setting.value
      else
        setting.value_changed?
      end
    end
  end
end