Module: EavPresenter::ClassMethods

Defined in:
lib/eav_presenter.rb

Instance Method Summary collapse

Instance Method Details

#eav(opts) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/eav_presenter.rb', line 56

def eav(opts)
  @eav_attr_class = opts[:eav_attr_class]
  @eav_value_class = opts[:eav_value_class]
  @eav_entity_foreign_key = opts[:eav_entity_foreign_key]
  @eav_attr_foreign_key = opts[:eav_attr_foreign_key]
  @eav_attrs = @eav_attr_class.all
  
  define_method(:attributes) {
   super.merge(Hash[self.class.instance_variable_get("@eav_attrs").map(&:eav_attr_name).map { |name| [name, send(name)] }])
  }
  # define_attribute_methods(@eav_attrs.collect(&:eav_attr_name))
  
  @eav_attrs.each { |at|
    define_method(at.eav_attr_name) { |*args|
      eavs = load_eav_attr_values_if_not_loaded
      if instance_variables.collect(&:to_s).include?("@#{at.eav_attr_name}")
        instance_variable_get("@#{at.eav_attr_name}")
      else
        eavs.find { |i| i.send(self.class.instance_variable_get("@eav_attr_foreign_key")) == at.id }.try(:value)
      end
    }

    define_method("#{at.eav_attr_name}=") { |value|
      # raise "EAV value for #{at.eav_attr_name} must be a string or nil" unless value.nil? || value.is_a?(String)
      eavs = load_eav_attr_values_if_not_loaded
      instance_variable_set("@#{at.eav_attr_name}",value)
      old = eavs.find { |i| i.send(self.class.instance_variable_get("@eav_attr_foreign_key")) == at.id }.try(:value)
      if value.to_s == old.to_s # to consider nil and blank as same
        changed_attributes.delete(at.eav_attr_name)
      else
        changed_attributes[at.eav_attr_name] = old
      end
    }
  }
  after_save :save_eav_attr_values # Register a callback which makes sure that any changes made are sync'ed to the AttrValues table
  after_find :load_eav_attr_values_if_not_loaded
end