Module: Lazier::Hash
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/lazier/hash.rb
Overview
Extensions for Hash
objects.
Constant Summary collapse
- VALID_ACCESSES =
The supported accesses for #ensure_access
{ strings: :stringify_keys, symbols: :symbolize_keys, indifferent: :with_indifferent_access, dotted: :enable_dotted_access }.freeze
Instance Method Summary collapse
-
#compact(&validator) ⇒ Hash
Returns a new hash, removing all keys which values are blank.
-
#compact!(&validator) ⇒ Object
Compacts the current hash, removing all keys which values are blank.
-
#enable_dotted_access(readonly = true) ⇒ Hash
Makes sure that the hash is accessible using dotted notation.
-
#ensure_access(*accesses) ⇒ Hash
Makes sure that the keys of the hash are accessible in the desired way.
Instance Method Details
#compact(&validator) ⇒ Hash
Returns a new hash, removing all keys which values are blank.
23 24 25 |
# File 'lib/lazier/hash.rb', line 23 def compact(&validator) dup.compact!(&validator) end |
#compact!(&validator) ⇒ Object
Compacts the current hash, removing all keys which values are blank.
30 31 32 33 |
# File 'lib/lazier/hash.rb', line 30 def compact!(&validator) validator ||= ->(_, v) { v.blank? } reject!(&validator) end |
#enable_dotted_access(readonly = true) ⇒ Hash
Makes sure that the hash is accessible using dotted notation. This is also applied to every embedded hash.
48 49 50 51 52 53 54 55 56 |
# File 'lib/lazier/hash.rb', line 48 def enable_dotted_access(readonly = true) extend(Hashie::Extensions::MethodReader) extend(Hashie::Extensions::MethodQuery) extend(Hashie::Extensions::MethodWriter) unless readonly each { |_, value| enable_dotted_access_for_value(value, readonly) } self end |
#ensure_access(*accesses) ⇒ Hash
Makes sure that the keys of the hash are accessible in the desired way.
39 40 41 42 |
# File 'lib/lazier/hash.rb', line 39 def ensure_access(*accesses) methods = accesses.ensure_array(compact: true, no_duplicates: true, flatten: true) { |m| VALID_ACCESSES[m.ensure_string.to_sym] }.compact methods.reduce(self) { |a, e| a.send(e) } end |