Class: Croesus::Attributes

Inherits:
Object show all
Defined in:
lib/croesus/attributes.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Attributes



25
26
27
# File 'lib/croesus/attributes.rb', line 25

def initialize(attributes = {})
  self.attributes = attributes
end

Class Method Details

.attr_accessor(*args) ⇒ Object



57
58
59
60
# File 'lib/croesus/attributes.rb', line 57

def self.attr_accessor(*args)
  args.each { |name| self.attributes[name] = Attribute.new(Object) }
  super
end

.attribute(name, type = String, options = {}) ⇒ Object

Declares an attribute on the model



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/croesus/attributes.rb', line 67

def self.attribute(name, type=String, options={})
  config = { writer: true, reader: true }.merge(options)

  attr = Attribute.new(type, options)
  self.attributes[name] = attr
  variable = "@#{name}"

  if config[:writer]
    define_method("#{name}=") do |object|
      val = Croesus.coercer.coerce(object, attr.type)
      instance_variable_set(variable, val)
    end
  end

  if config[:reader]
    define_method(name) do
      val = instance_variable_get(variable)
      unless val
        val = attr.default
        instance_variable_set(variable, val)
      end
      val
    end
  end
end

.attributesObject



52
53
54
# File 'lib/croesus/attributes.rb', line 52

def self.attributes
  @attributes ||= {}
end

Instance Method Details

#attributesHash

Get and ser the attributes on the model.



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

def attributes
  hash = {}
  self.class.attributes.keys.each do |k|
    hash[k] = send(k) if respond_to?(k)
  end
  hash
end

#attributes=(attributes = {}) ⇒ Object

Sets the attributes on the model



31
32
33
34
35
# File 'lib/croesus/attributes.rb', line 31

def attributes=(attributes = {})
  attributes.each do |attr, value|
    self.send("#{attr}=", value) if self.respond_to?("#{attr}=")
  end
end

#to_hObject



48
49
50
# File 'lib/croesus/attributes.rb', line 48

def to_h
  self.attributes
end