Class: Resto::Attributes
- Inherits:
-
Object
- Object
- Resto::Attributes
- Defined in:
- lib/resto/attributes.rb
Instance Method Summary collapse
- #add_error(key, value) ⇒ Object
- #errors ⇒ Object
- #get(key) ⇒ Object
- #get_without_cast(key) ⇒ Object
-
#initialize(attributes, resource, property_handler = nil) ⇒ Attributes
constructor
A new instance of Attributes.
- #present?(key) ⇒ Boolean
- #set(key, value) ⇒ Object
- #to_hash ⇒ Object
- #update_attributes(attributes) ⇒ Object
- #valid? ⇒ Boolean
Constructor Details
#initialize(attributes, resource, property_handler = nil) ⇒ Attributes
Returns a new instance of Attributes.
5 6 7 8 9 10 11 12 13 |
# File 'lib/resto/attributes.rb', line 5 def initialize(attributes, resource, property_handler = nil) @resource = resource @property_handler = property_handler || resource.class.property_handler @attributes = {} # TODO must handle indifferent access :name and 'name' @attributes_before_cast = {} @errors = {} update_attributes(attributes) end |
Instance Method Details
#add_error(key, value) ⇒ Object
44 45 46 |
# File 'lib/resto/attributes.rb', line 44 def add_error(key, value) @errors.store(key, value) end |
#errors ⇒ Object
48 49 50 |
# File 'lib/resto/attributes.rb', line 48 def errors @errors.map {|key, value| value }.compact end |
#get(key) ⇒ Object
27 28 29 |
# File 'lib/resto/attributes.rb', line 27 def get(key) @attributes.fetch(key, nil) end |
#get_without_cast(key) ⇒ Object
31 32 33 |
# File 'lib/resto/attributes.rb', line 31 def get_without_cast(key) @attributes_before_cast.fetch(key, nil) end |
#present?(key) ⇒ Boolean
35 36 37 |
# File 'lib/resto/attributes.rb', line 35 def present?(key) @attributes.fetch(key, false) ? true : false end |
#set(key, value) ⇒ Object
22 23 24 25 |
# File 'lib/resto/attributes.rb', line 22 def set(key, value) @attributes_before_cast.store(key, value) @attributes.store(key, @property_handler.cast(key, value, @errors)) end |
#to_hash ⇒ Object
52 53 54 |
# File 'lib/resto/attributes.rb', line 52 def to_hash @attributes.merge({}) end |
#update_attributes(attributes) ⇒ Object
15 16 17 18 19 20 |
# File 'lib/resto/attributes.rb', line 15 def update_attributes(attributes) attributes.each do |key, value| key = @property_handler.attribute_key(key) set(key, value) if key end end |
#valid? ⇒ Boolean
39 40 41 42 |
# File 'lib/resto/attributes.rb', line 39 def valid? @property_handler.validate(@resource) errors.empty? end |