Class: Hanami::Utils::Attributes
- Inherits:
-
Object
- Object
- Hanami::Utils::Attributes
- Defined in:
- lib/hanami/utils/attributes.rb
Overview
A set of attributes.
It internally stores the data as a Hash.
All the operations convert keys to strings. This strategy avoids memory attacks due to Symbol abuses when parsing untrusted input.
At the same time, this allows to get/set data with the original key or with the string representation. See the examples below.
Instance Method Summary collapse
-
#get(attribute) ⇒ Object, NilClass
(also: #[])
Get the value associated with the given attribute.
-
#initialize(hash = {}) ⇒ Hanami::Utils::Attributes
constructor
Initialize a set of attributes All the keys of the given Hash are recursively converted to strings.
-
#set(attribute, value) ⇒ NilClass
Set the given value for the given attribute.
-
#to_h ⇒ ::Hash
Returns a deep duplicated copy of the attributes as a Hash.
Constructor Details
#initialize(hash = {}) ⇒ Hanami::Utils::Attributes
Initialize a set of attributes All the keys of the given Hash are recursively converted to strings.
32 33 34 |
# File 'lib/hanami/utils/attributes.rb', line 32 def initialize(hash = {}) @attributes = Utils::Hash.new(hash, &nil).stringify! end |
Instance Method Details
#get(attribute) ⇒ Object, NilClass Also known as: []
Get the value associated with the given attribute
68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/hanami/utils/attributes.rb', line 68 def get(attribute) value = @attributes keys = attribute.to_s.split('.') keys.each do |key| break unless value value = value[key] end value.is_a?(Hash) ? self.class.new(value) : value end |
#set(attribute, value) ⇒ NilClass
Set the given value for the given attribute
109 110 111 112 |
# File 'lib/hanami/utils/attributes.rb', line 109 def set(attribute, value) @attributes[attribute.to_s] = value nil end |
#to_h ⇒ ::Hash
Returns a deep duplicated copy of the attributes as a Hash
119 120 121 122 123 124 125 |
# File 'lib/hanami/utils/attributes.rb', line 119 def to_h ::Hash[].tap do |result| @attributes.each do |k, v| result[k] = _read_value(v) end end end |