Class: Yukata::Base
- Inherits:
-
Object
- Object
- Yukata::Base
- Defined in:
- lib/yukata/base.rb
Class Method Summary collapse
-
.attribute(name, type = String, options = {}) ⇒ Object
Declares an attribute on the model.
- .attributes ⇒ Object
Instance Method Summary collapse
-
#attributes ⇒ Hash
Get the attributes on the model.
-
#attributes=(hash) ⇒ Object
Sets the attributes on the model.
-
#initialize(params = {}) ⇒ Base
constructor
A new instance of Base.
- #to_h ⇒ Object
Constructor Details
#initialize(params = {}) ⇒ Base
Returns a new instance of Base.
6 7 8 |
# File 'lib/yukata/base.rb', line 6 def initialize(params={}) self.attributes = params end |
Class Method Details
.attribute(name, type = String, options = {}) ⇒ Object
Declares an attribute on the model
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/yukata/base.rb', line 43 def self.attribute(name, type=String, ={}) attr = Attribute.new(type, ) self.attributes[name] = attr variable = "@#{name}" define_method("#{name}=") do |object| val = Yukata.coercer.coerce(object, attr.type) instance_variable_set(variable, val) end define_method(name) do val = instance_variable_get(variable) unless val val = attr.default instance_variable_set(variable, val) end val end end |
.attributes ⇒ Object
34 35 36 |
# File 'lib/yukata/base.rb', line 34 def self.attributes @attributes ||= {} end |
Instance Method Details
#attributes ⇒ Hash
Get the attributes on the model. If the attribute was not
22 23 24 25 26 27 28 |
# File 'lib/yukata/base.rb', line 22 def attributes hash = {} self.class.attributes.keys.each do |k| hash[k] = self.send(k) end hash end |
#attributes=(hash) ⇒ Object
Sets the attributes on the model
12 13 14 15 16 17 |
# File 'lib/yukata/base.rb', line 12 def attributes=(hash) hash.each do |k, v| setter = "#{k}=" self.send(setter, v) if self.respond_to?(setter) end end |
#to_h ⇒ Object
30 31 32 |
# File 'lib/yukata/base.rb', line 30 def to_h self.attributes end |