Class: Attrocity::AttributeMethodsBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/attrocity/attributes/attribute_methods_builder.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, attributes) ⇒ AttributeMethodsBuilder

Returns a new instance of AttributeMethodsBuilder.



6
7
8
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 6

def initialize(object, attributes)
  @object, @attributes = object, attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



4
5
6
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 4

def attributes
  @attributes
end

#objectObject (readonly)

Returns the value of attribute object.



4
5
6
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 4

def object
  @object
end

Class Method Details

.for_attribute(obj, attribute) ⇒ Object



10
11
12
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 10

def self.for_attribute(obj, attribute)
  self.new(obj, Array(attribute))
end

.for_attribute_set(obj, attribute_set) ⇒ Object



14
15
16
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 14

def self.for_attribute_set(obj, attribute_set)
  self.new(obj, attribute_set.attributes)
end

Instance Method Details

#buildObject



18
19
20
21
22
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 18

def build
  attributes.each do |attr|
    define_methods(attr)
  end
end

#define_methods(attribute) ⇒ Object



24
25
26
27
28
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 24

def define_methods(attribute)
  define_reader(attribute)
  define_writer(attribute)
  define_predicate(attribute)
end

#define_predicate(attribute) ⇒ Object



40
41
42
43
44
45
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 40

def define_predicate(attribute)
  object.define_singleton_method("#{attribute.name}?") do
    # TODO: Would true & attribute.value work better here?
    !!(attribute.value)
  end
end

#define_reader(attribute) ⇒ Object



30
31
32
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 30

def define_reader(attribute)
  object.define_singleton_method(attribute.name) { attribute.value }
end

#define_writer(attribute) ⇒ Object



34
35
36
37
38
# File 'lib/attrocity/attributes/attribute_methods_builder.rb', line 34

def define_writer(attribute)
  object.define_singleton_method("#{attribute.name}=") do |value|
    attribute.value = value
  end
end