Class: Croesus::Attributes
Class Method Summary collapse
- .attr_accessor(*args) ⇒ Object
-
.attribute(name, type = String, options = {}) ⇒ Object
Declares an attribute on the model.
- .attributes ⇒ Object
Instance Method Summary collapse
-
#attributes ⇒ Hash
Get and ser the attributes on the model.
-
#attributes=(attributes = {}) ⇒ Object
Sets the attributes on the model.
-
#initialize(attributes = {}) ⇒ Attributes
constructor
A new instance of Attributes.
- #to_h ⇒ Object
Constructor Details
#initialize(attributes = {}) ⇒ Attributes
Returns a new instance of 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, ={}) config = { writer: true, reader: true }.merge() attr = Attribute.new(type, ) 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 |
.attributes ⇒ Object
52 53 54 |
# File 'lib/croesus/attributes.rb', line 52 def self.attributes @attributes ||= {} end |
Instance Method Details
#attributes ⇒ Hash
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_h ⇒ Object
48 49 50 |
# File 'lib/croesus/attributes.rb', line 48 def to_h self.attributes end |