Module: SimpleEav

Defined in:
lib/version.rb,
lib/simple_eav.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"1.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/simple_eav.rb', line 69

def method_missing(method, *args, &block)
  _attributes = read_attribute(simple_eav_column.to_sym) || {}.with_indifferent_access
  if method.to_s =~ /=$/
    setter = method.to_s.gsub(/=/, '')
    _attributes[setter.to_sym] = args.shift
    return self.simple_eav_attributes = _attributes
  elsif _attributes.has_key?(method.to_sym)
   return  _attributes[method.to_sym]
  else
    super(method, *args, &block)
  end
end

Class Method Details

.included(base) ⇒ Object



11
12
13
# File 'lib/simple_eav.rb', line 11

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#assign_attributes(_attributes = {}, options = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/simple_eav.rb', line 50

def assign_attributes(_attributes={}, options={})
  #Iterate over each attribute:
  # - skip columns that are actually defined in the db
  # - remove undefined columns to prevent UnknownAttribute::Error from being thrown
  simple_eav_attrs = read_attribute(simple_eav_column.to_sym) || {}.with_indifferent_access
  _attributes.each do |column,value|
    next if reserved_attribute?(column.to_sym)
    simple_eav_attrs[column] = value
    _attributes.delete(column)
  end
  self.simple_eav_attributes = simple_eav_attrs
  super(_attributes, options)
end

#reserved_attribute?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/simple_eav.rb', line 37

def reserved_attribute?(attribute)
  reserved_attributes.include?(attribute)
end

#reserved_attributesObject



33
34
35
# File 'lib/simple_eav.rb', line 33

def reserved_attributes
  associations_of_class + actual_columns_of_table + nested_attributes
end

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
# File 'lib/simple_eav.rb', line 64

def respond_to?(method, include_private=false)
  return true if super(method, include_private)
  simple_eav_attributes.has_key?(method)
end

#simple_eav_attributesObject



41
42
43
44
# File 'lib/simple_eav.rb', line 41

def simple_eav_attributes
  _attributes = self.send(simple_eav_column.to_sym)
  (_attributes.is_a?(Hash) ? _attributes : {}).with_indifferent_access
end

#simple_eav_attributes=(attributes = {}) ⇒ Object



46
47
48
# File 'lib/simple_eav.rb', line 46

def simple_eav_attributes=(attributes={})
  self.send("#{simple_eav_column}=", attributes)
end

#simple_eav_columnObject



15
16
17
# File 'lib/simple_eav.rb', line 15

def simple_eav_column
  self.class.simple_eav_column
end