Class: ActiveAccess::Utility::HashMapper

Inherits:
Hash
  • Object
show all
Defined in:
lib/active-access/utility/hash_mapper.rb

Direct Known Subclasses

Config

Constant Summary collapse

ALLOWED_SUFFIXES =
%w[? =].freeze

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ HashMapper

Returns a new instance of HashMapper.



58
59
60
61
# File 'lib/active-access/utility/hash_mapper.rb', line 58

def initialize(hash = nil)
  update!(hash) if hash
  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &blk) ⇒ Object

Will try to resolve the called method to a stored hash KV pair

Example config = ActiveAccess::Utility::HashMapper.new config.day? #=> false config.day = “Monday” #=> => “Monday” config.day? #=> true config.day #=> “Monday”



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/active-access/utility/hash_mapper.rb', line 30

def method_missing(method_name, *args, &blk)
  return self.[](method_name.to_s, &blk) if key?(method_name)
  name, suffix = method_name_and_suffix(method_name)
  case suffix
  when "="
    self[name.to_s] = args.first
  when "?"
    !!self[name.to_s] # rubocop:disable Style/DoubleNegation
  when nil
    self[method_name.to_s]
  else
    super
  end
end

Instance Method Details

#key?(key) ⇒ Boolean

Ensure all key checks are in string format

Returns:

  • (Boolean)


10
11
12
# File 'lib/active-access/utility/hash_mapper.rb', line 10

def key?(key)
  super(key.to_s)
end

#respond_to_missing?(method_name, *args) ⇒ Boolean

Check to see if missing method should call the ‘method_missing/3` method

Returns:

  • (Boolean)


16
17
18
19
# File 'lib/active-access/utility/hash_mapper.rb', line 16

def respond_to_missing?(method_name, *args)
  return true if key?(method_name)
  super
end

#update!(**hash) ⇒ Object Also known as: merge!, merge

Convert all keys to proper form. This will not work with deep merging!

Example: config = ActiveAccess::Utility::HashMapper.new #=> { “enabled” => true, … } config.merge(tip: 2.00, flip: 1) #=> { “enabled” => true, “tip” => 2.00, “flip” => 1, … }



50
51
52
53
# File 'lib/active-access/utility/hash_mapper.rb', line 50

def update!(**hash)
  hash.each_pair { |key, value| self[key.to_s] = value } unless hash.empty?
  self
end