Class: Modelish::Base
- Inherits:
-
Hashie::Dash
- Object
- Hashie::Dash
- Modelish::Base
- Extended by:
- Configuration
- Includes:
- PropertyTranslations, PropertyTypes, Validations
- Defined in:
- lib/modelish/base.rb
Instance Attribute Summary
Attributes included from Configuration
Class Method Summary collapse
-
.property(name, options = {}) ⇒ Object
Creates a new attribute.
Instance Method Summary collapse
- #[]=(property, value) ⇒ Object
-
#initialize(options = {}, &block) ⇒ Base
constructor
A new instance of Base.
-
#to_hash ⇒ Hash
Convert this Modelish object into a vanilla Hash with stringified keys.
Methods included from Configuration
configure, extended, ignore_unknown_properties!, raise_errors_on_unknown_properties!, reset
Methods included from Validations
#valid?, #validate, #validate!
Constructor Details
#initialize(options = {}, &block) ⇒ Base
Returns a new instance of Base.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/modelish/base.rb', line 14 def initialize(={}, &block) super(&block) self.class.defaults.each_pair do |prop, value| self[prop] = value end attributes = ? .dup : {} attributes.delete_if do |k,v| if self.class.translations.keys.include?(k.to_sym) self[k]=v true end end attributes.each_pair do |att, value| self[att] = value end end |
Class Method Details
.property(name, options = {}) ⇒ Object
Creates a new attribute.
59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/modelish/base.rb', line 59 def self.property(name, ={}) super add_property_type(name, [:type]) if [:type] add_property_translation([:from], name) if [:from] add_validator(name) { |val| validate_required(name => val).first } if [:required] add_validator(name) { |val| validate_length(name, val, [:max_length]) } if [:max_length] add_validator(name, &[:validator]) if [:validator] add_validator(name) { |val| validate_type(name, val, [:type]) } if [:validate_type] end |
Instance Method Details
#[]=(property, value) ⇒ Object
88 89 90 91 92 93 94 |
# File 'lib/modelish/base.rb', line 88 def []=(property, value) if self.class.translations.keys.include?(property.to_sym) send("#{property}=", value) elsif property_exists?(property) super end end |
#to_hash ⇒ Hash
Convert this Modelish object into a vanilla Hash with stringified keys.
74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/modelish/base.rb', line 74 def to_hash out = {} self.class.properties.each do |p| val = self.send(p) if val.is_a?(Array) out[p.to_s]||=[] out[p.to_s].concat(val.collect{|x|x.respond_to?(:to_hash) ? x.to_hash : x}) else out[p.to_s] = val.respond_to?(:to_hash) ? val.to_hash : val end end out end |