Class: Compony::MethodAccessibleHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/compony/method_accessible_hash.rb

Overview

This class is intended for configs with predefined interfaces and should be used with instances of Hash:
Example:

instance_of_a_hash = Compony::MethodAccessibleHash.new
instance_of_a_hash.merge!({ foo: :bar })
instance_of_a_hash.foo --> :bar
instance_of_a_hash.roo --> nil

See: https://gist.github.com/kalsan/87826048ea0ade92ab1be93c0919b405

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ MethodAccessibleHash

Takes an optional hash as argument and constructs a new MethodAccessibleHash.



15
16
17
18
19
20
21
# File 'lib/compony/method_accessible_hash.rb', line 15

def initialize(hash = {})
  super()

  hash.each do |key, value|
    self[key.to_sym] = value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/compony/method_accessible_hash.rb', line 29

def method_missing(method, *args, &)
  if method.end_with?('=')
    name = method.to_s.gsub(/=$/, '')
    self[name.to_sym] = args.first
  else
    self[method.to_sym]
  end
end

Instance Method Details

#merge(hash) ⇒ Object



24
25
26
# File 'lib/compony/method_accessible_hash.rb', line 24

def merge(hash)
  super(hash.symbolize_keys)
end

#respond_to_missing?(_method, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/compony/method_accessible_hash.rb', line 39

def respond_to_missing?(_method, _include_private = false)
  true
end