module Lazier::Hash

Extensions for `Hash` objects.

Constants

VALID_ACCESSES

The supported accesses for ensure_access

Public Instance Methods

compact(&validator) click to toggle source

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

@param validator [Proc] If present all the keys which evaluates to true will be removed. Otherwise all blank values will be removed. @return [Hash] The hash with all blank values removed.

# File lib/lazier/hash.rb, line 23
def compact(&validator)
  dup.compact!(&validator)
end
compact!(&validator) click to toggle source

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

@param validator [Proc] If present all the keys which evaluates to true will be removed. Otherwise all blank values will be removed.

# File lib/lazier/hash.rb, line 30
def compact!(&validator)
  validator ||= ->(_, v) { v.blank? }
  reject!(&validator)
end
enable_dotted_access(readonly = true) click to toggle source

Makes sure that the hash is accessible using dotted notation. This is also applied to every embedded hash.

@param readonly [Boolean] If the dotted notation is only enable for reading. `true` by default. @return [Hash] The current hash with keys enabled for dotted access.

# 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) click to toggle source

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

@param accesses [Array] The requested access for the keys. Can be `:dotted`, `:strings`, `:symbols` or `:indifferent`. If `nil` the keys are not modified. @return [Hash] The current hash with keys modified.

# 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