Class: Constructable::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/constructable/attribute.rb

Constant Summary collapse

ATTRIBUTES =
[:group, :writable, :readable, :accessible, :required, :validate, :default, :validate_type, :converter]
REQUIREMENTS =
[
  {
    name: :validate,
    message: proc {":#{self.name} did not pass validation"},
    check: ->(hash) { self.validate.call(hash[self.name])}
  },
  {
    name: :validate_type,
    message: proc {":#{self.name} must be of type #{self.validate_type}"},
    check: ->(hash) { hash[self.name].is_a? self.validate_type }
  }
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



20
21
22
23
24
25
# File 'lib/constructable/attribute.rb', line 20

def initialize(name, options = {})
  @name = name
  ATTRIBUTES.each do |attribute|
    self.send(:"#{attribute}=", options[attribute])
  end
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



5
6
7
# File 'lib/constructable/attribute.rb', line 5

def value
  @value
end

Instance Method Details

#accessible=(boolean) ⇒ Object



27
28
29
30
31
32
# File 'lib/constructable/attribute.rb', line 27

def accessible=(boolean)
  if boolean
    self.readable = true
    self.writable = true
  end
end

#ivar_symbolObject



34
35
36
# File 'lib/constructable/attribute.rb', line 34

def ivar_symbol
  ('@' + self.name.to_s).to_sym
end

#process(constructor_hash) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/constructable/attribute.rb', line 47

def process(constructor_hash)
  unless constructor_hash[self.name].nil?
    REQUIREMENTS.each do |requirement|
      check_for_requirement(requirement, constructor_hash)
    end

    value = constructor_hash[self.name]
    self.converter ? converter.(value) : value
  else
    raise AttributeError, ":#{self.name} is a required attribute" if self.required
    self.default
  end
end