Class: TagOptions::Hash
- Inherits:
-
ActiveSupport::HashWithIndifferentAccess
- Object
- ActiveSupport::HashWithIndifferentAccess
- TagOptions::Hash
- Includes:
- ActiveSupport::Callbacks, ConvertKey
- Defined in:
- lib/tag_options/hash.rb
Instance Method Summary collapse
- #at(key, *nested_keys, as: :default) ⇒ Object
- #dig(*keys) ⇒ Object
-
#initialize(hash = {}) ⇒ Hash
constructor
A new instance of Hash.
- #populate!(*keys) ⇒ Object
- #remove_blank!(hash = self, parent_hash: nil) ⇒ Object
Methods included from ConvertKey
Constructor Details
#initialize(hash = {}) ⇒ Hash
Returns a new instance of Hash.
15 16 17 18 19 20 21 22 |
# File 'lib/tag_options/hash.rb', line 15 def initialize(hash = {}) run_callbacks :initialize do hash.each do |key, value| self[convert_key(key)] = value.is_a?(::Hash) ? self.class.new(value) : value.to_s end remove_blank! end end |
Instance Method Details
#at(key, *nested_keys, as: :default) ⇒ Object
24 25 26 |
# File 'lib/tag_options/hash.rb', line 24 def at(key, *nested_keys, as: :default) TagOptions::HashAt.new(opt_hash: self, keys: [key, *nested_keys], as: as) end |
#dig(*keys) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/tag_options/hash.rb', line 28 def dig(*keys) return self if keys.size.zero? dug_keys = [] data = self keys.each_with_index do |key, index| key = convert_key(key) return nil unless data.key?(key) data = data[key] dug_keys << key last_key = index == keys.size - 1 unless last_key || data.is_a?(self.class) raise TagOptions::Errors::NotHashError.new(dug_keys, type: data.class) end end data end |
#populate!(*keys) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/tag_options/hash.rb', line 47 def populate!(*keys) populated_keys = [] data = self keys.each do |key| key = convert_key(key) data[key] ||= self.class.new data = data[key] populated_keys << key unless data.is_a?(self.class) raise TagOptions::Errors::NotHashError.new(populated_keys, type: data.class) end end self end |
#remove_blank!(hash = self, parent_hash: nil) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/tag_options/hash.rb', line 62 def remove_blank!(hash = self, parent_hash: nil) hash.each do |key, value| if value.blank? hash.delete(key) remove_blank!(parent_hash, parent_hash: nil) if parent_hash elsif value.is_a?(Hash) remove_blank!(value, parent_hash: hash) remove_blank!(parent_hash, parent_hash: nil) if parent_hash end end hash end |