module Served::Resource::Attributable
Public Class Methods
new(hash = {})
click to toggle source
# File lib/served/resource/attributable.rb, line 50 def initialize(hash = {}) reload_with_attributes(normalize_keys(hash)) end
Public Instance Methods
attributes()
click to toggle source
@return [Array] the keys for all the defined attributes
# File lib/served/resource/attributable.rb, line 55 def attributes Hash[self.class.attributes.keys.collect { |name| [name, send(name)] }] end
Private Instance Methods
normalize_keys(params)
click to toggle source
# File lib/served/resource/attributable.rb, line 90 def normalize_keys(params) case params when Hash Hash[params.map { |k, v| [k.to_s.tr('-', '_'), normalize_keys(v)] }] when Array params.map { |v| normalize_keys(v) } else params end end
reload_with_attributes(result)
click to toggle source
Reloads the instance with the new attributes If result is an Errors object it will create validation errors on the instance @return [Boolean]
# File lib/served/resource/attributable.rb, line 64 def reload_with_attributes(result) if result.is_a?(Served::Error) serializer.parse_errors(result, self) set_attribute_defaults false else attributes = self.class.from_hash(result) attributes.each do |name, value| set_attribute(name.to_sym, value) end set_attribute_defaults true end end
set_attribute(name, value)
click to toggle source
# File lib/served/resource/attributable.rb, line 86 def set_attribute(name, value) instance_variable_set("@#{name}", value) end
set_attribute_defaults()
click to toggle source
# File lib/served/resource/attributable.rb, line 79 def set_attribute_defaults self.class.attributes.each do |attr, options| next if options[:default].nil? || send(attr) set_attribute(attr, options[:default]) end end