Module: ActAsAttributes::ClassMethods

Defined in:
lib/act_as_attribute.rb

Instance Method Summary collapse

Instance Method Details

#act_as_attribute(model_name, model_attr_as_key = "name", model_attr_as_value = "value") ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
# File 'lib/act_as_attribute.rb', line 27

def act_as_attribute(model_name, model_attr_as_key= "name", model_attr_as_value="value")

  get_constants

  self::AVAILABLE_ATTRIBUTES.each do |attr|
    if method_available_as_attribute?(attr)
      deal_with_duplicate_method(attr)
    end

    define_method(attr.underscore) do
      available_objects = self.send(model_name)
      if available_objects.map(&model_attr_as_key.to_sym).include? attr
        available_objects.send("find_by_#{model_attr_as_key}", attr).send(model_attr_as_value)
      else
        new_object = model_name.to_s.classify.constantize.create(model_attr_as_key.to_sym => attr)
        available_objects << new_object
        new_object.send(model_attr_as_value)
      end
    end

    define_method("#{attr.underscore}=") do |value|
      available_objects = self.send(model_name)
      if available_objects.map(&model_attr_as_key.to_sym).include? attr
        new_association= available_objects.send("find_by_#{model_attr_as_key}", attr)
        new_association.send("#{model_attr_as_value.to_s}=", value)
        new_association.save
      else
        new_object = model_name.to_s.classify.constantize.create(model_attr_as_key.to_sym => attr)
        new_object.send("#{model_attr_as_value}=", value)
        new_object.save
        available_objects << new_object
      end
    end
  end
end

#deal_with_duplicate_method(arg) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/act_as_attribute.rb', line 19

def deal_with_duplicate_method(arg)
  if self::ACCEPTANCE_LEVEL == "error"
    raise Exceptions::AlreadyPresentAsAttribute
  else
    warn "Warning: Method '#{arg}' already available as attribute"
  end
end

#get_constantsObject



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

def get_constants
  self::AVAILABLE_ATTRIBUTES ||= []
  self::ACCEPTANCE_LEVEL ||= "error"
end

#method_available_as_attribute?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


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

def method_available_as_attribute?(attribute)
  self.attribute_method?(attribute) ? true : false
end