Module: Lazier::Hash

Extended by:
ActiveSupport::Concern
Defined in:
lib/lazier/hash.rb

Overview

Extensions for Hash objects.

Instance Method Summary collapse

Instance Method Details

#compact(&validator) ⇒ Hash

Returns a new hash, removing all keys which values are blank.

Parameters:

  • validator (Proc)

    , if present all the keys which evaluates to true will be removed. Otherwise all blank values will be removed.

Returns:

  • (Hash)

    The hash with all blank values removed.



16
17
18
19
# File 'lib/lazier/hash.rb', line 16

def compact(&validator)
  validator ||= ->(_, v) { v.blank? }
  reject(&validator)
end

#compact!(&validator) ⇒ Object

Compacts the current hash, removing all keys which values are blank.

Parameters:

  • validator (Proc)

    , if present all the keys which evaluates to true will be removed. Otherwise all blank values will be removed.



24
25
26
27
# File 'lib/lazier/hash.rb', line 24

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.

Parameters:

  • readonly (Boolean) (defaults to: true)

    If the dotted notation is only enable for reading. true by default.

Returns:

  • (Hash)

    The current hash with keys enabled for dotted access.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/lazier/hash.rb', line 42

def enable_dotted_access(readonly = true)
  extend(Hashie::Extensions::MethodReader)
  extend(Hashie::Extensions::MethodQuery)
  extend(Hashie::Extensions::MethodWriter) if !readonly

  each do |_, value|
    if value.is_a?(Hash) then
      value.enable_dotted_access(readonly)
    elsif value.respond_to?(:each) then
      value.each do |element|
        element.enable_dotted_access(readonly) if element.is_a?(Hash)
      end
    end
  end

  self
end

#ensure_access(access) ⇒ Hash

Makes sure that the keys of the hash are accessible in the desired way.

Parameters:

  • access (Symbol|NilClass)

    The requested access for the keys. Can be :strings, :symbols or :indifferent. If nil the keys are not modified.

Returns:

  • (Hash)

    The current hash with keys modified.



33
34
35
36
# File 'lib/lazier/hash.rb', line 33

def ensure_access(access)
  method = {strings: :stringify_keys, symbols: :symbolize_keys, indifferent: :with_indifferent_access, dotted: :enable_dotted_access}.fetch(access, nil)
  method ? send(method) : self
end