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

Returns a new instance of Attributes.

Parameters:

  • params (Hash)

    the parameters you wish to initialize the model with. If the model does not have an accessor set, it will ignore the attribute passed.



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

Parameters:

  • name (String)
  • type (Class) (defaults to: String)

    a class that represents the type

  • options (Hash) (defaults to: {})

    extra options to apply to the attribute



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.

Returns:



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

Parameters:

  • attributes (Hash) (defaults to: {})


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