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 |
# File 'lib/modelish/base.rb', line 14 def initialize(={}, &block) super(&block) 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.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/modelish/base.rb', line 54 def self.property(name, ={}) #Hashie::Dash.property is going to delete :required from the options hash required = [:required] super add_property_type(name, [:type]) if [:type] add_property_translation([:from], name) if [:from] if [:required] || (self.respond_to?(:required?) && required?(name)) add_validator(name) { |val| validate_required(name => val).first } end 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
90 91 92 93 94 95 96 |
# File 'lib/modelish/base.rb', line 90 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.
76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/modelish/base.rb', line 76 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 |