Class: Yukata::Base
- Inherits:
-
Object
- Object
- Yukata::Base
- Defined in:
- lib/yukata/base.rb
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 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
.attr_accessor(*args) ⇒ Object
39 40 41 42 |
# File 'lib/yukata/base.rb', line 39 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
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/yukata/base.rb', line 49 def self.attribute(name, type=String, ={}) config = { writer: true, reader: true, coerce: true }.merge() attr = Attribute.new(type, ) self.attributes[name] = attr variable = "@#{name}" # ------------- # Define Writer # ------------- if config[:writer] define_method("#{name}=") do |object| if config[:coerce] val = Yukata.coercer.coerce(object, attr.type) instance_variable_set(variable, val) else instance_variable_set(variable, object) end end end # ------------- # Define reader # ------------- 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
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] = send(k) if respond_to?(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 |