Module: ShallowAttributes::InstanceMethods Abstract
- Included in:
- ShallowAttributes
- Defined in:
- lib/shallow_attributes/instance_methods.rb
Overview
This module is abstract.
Abstract class for value classes. Provides some helper methods for working with attributes.
Constant Summary collapse
- TO_H_PROC =
Lambda object for gettring attributes hash for specific value object.
-> (value) { value.respond_to?(:to_hash) ? value.to_hash : value }
Instance Method Summary collapse
-
#==(object) ⇒ boolean
Equalate two value objects.
-
#attributes ⇒ Hash
(also: #to_h, #to_hash)
Returns hash of object attributes.
-
#attributes=(attributes) ⇒ Hash
Mass-assignment attribut values.
-
#coerce(value, options = {}) ⇒ Object
Sets new values and returns self.
-
#initialize(attrs = {}) ⇒ Object
Initialize instance object with specific attributes.
-
#inspect ⇒ String
Inspect instance object.
-
#reset_attribute(attribute) ⇒ Object
Reser specific attribute to defaul value.
Instance Method Details
#==(object) ⇒ boolean
Equalate two value objects
156 157 158 |
# File 'lib/shallow_attributes/instance_methods.rb', line 156 def ==(object) self.to_h == object.to_h end |
#attributes ⇒ Hash Also known as: to_h, to_hash
Returns hash of object attributes
52 53 54 55 56 57 58 59 |
# File 'lib/shallow_attributes/instance_methods.rb', line 52 def attributes hash = {} @attributes.map do |key, value| hash[key] = value.is_a?(Array) ? value.map!(&TO_H_PROC) : TO_H_PROC.call(value) end hash end |
#attributes=(attributes) ⇒ Hash
Mass-assignment attribut values
84 85 86 87 |
# File 'lib/shallow_attributes/instance_methods.rb', line 84 def attributes=(attributes) @attributes.merge!(attributes) define_attributes end |
#coerce(value, options = {}) ⇒ Object
Sets new values and returns self. Needs for embedded value.
134 135 136 137 |
# File 'lib/shallow_attributes/instance_methods.rb', line 134 def coerce(value, = {}) self.attributes = value self end |
#initialize(attrs = {}) ⇒ Object
Initialize instance object with specific attributes
32 33 34 35 36 |
# File 'lib/shallow_attributes/instance_methods.rb', line 32 def initialize(attrs = {}) @attributes = attrs.delete_if { |key, _| !default_values.key?(key) } define_attributes define_default_attributes end |
#inspect ⇒ String
Inspect instance object
174 175 176 |
# File 'lib/shallow_attributes/instance_methods.rb', line 174 def inspect "#<#{self.class}#{attributes.map{ |k, v| " #{k}=#{v.inspect}" }.join}>" end |
#reset_attribute(attribute) ⇒ Object
Reser specific attribute to defaul value.
106 107 108 |
# File 'lib/shallow_attributes/instance_methods.rb', line 106 def reset_attribute(attribute) instance_variable_set("@#{attribute}", default_value_for(attribute)) end |