Module: ActiveRecord::ActsAs::HasEav::ClassMethods

Defined in:
lib/has_eav.rb

Instance Method Summary collapse

Instance Method Details

#class_eav_attributesObject

class accessor - when the superclass != AR::Base asume we are in STI mode



80
81
82
83
84
# File 'lib/has_eav.rb', line 80

def class_eav_attributes # :nodoc:
  superclass != ActiveRecord::Base ?
    superclass.class_eav_attributes.merge(@eav_attributes || {}) :
    @eav_attributes
end

#eav_attribute(name, type = String) ⇒ Object

Add an other attribute to the class list



72
73
74
75
76
# File 'lib/has_eav.rb', line 72

def eav_attribute name, type = String
  name = name.to_s if !name.is_a? String

  @eav_attributes[name] = type
end

#eav_classObject

class accessor - when the superclass != AR::Base asume we are in STI mode



88
89
90
# File 'lib/has_eav.rb', line 88

def eav_class # :nodoc:
  superclass != ActiveRecord::Base ? superclass.eav_class : @eav_class
end

#has_eav(opts = {}, &block) ⇒ Object

Specify that the ActiveModel is an EAV model

Usage

# specifiy eav_attributes at instance level
has_eav :through => :some_class_with_name_and_value_attributes
def available_eav_attributes
  case self.origin
  when "remote"
    %(remote_ip user_agent)
  when "local"
    %(user)
  end + [ :uniq_id ]
end

# specify some eav_attributes at class level
has_eav :through => "BoundAttribute" do
  eav_attribute :remote_ip
  eav_attribute :uniq_id
end

# specify more attributes in an STI class
class ItalianJob < Job
  has_eav do
    eav_attribute :mini_driver
  end
end

Mixing class and instance defined EAV attributes

You can define EAV attributes both in class and instance context and they will be both adhered



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
# File 'lib/has_eav.rb', line 40

def has_eav opts={}, &block
  if self.superclass != ActiveRecord::Base && (opts.nil? || opts.empty?)
    @eav_attributes = {}
    yield
    return
  end

  klass = opts.delete :through
  klass = klass.to_s if klass.is_a? Symbol
  klass = klass.camelize

  raise(
    "Eav Class cannot be nil. Specify a class using " +
    "has_eav :through => :class"
  ) if klass.blank?

  opts[:class_name] = klass

  class_eval do
    has_many   :eav_attributes, opts
    after_save :save_eav_attributes
  end

  @eav_class      = klass.constantize
  @eav_attributes = {}

  yield if block_given?

  send :include, ActiveRecord::ActsAs::HasEav::InstanceMethods
end