Class: Meander::Plain

Inherits:
Thor::CoreExt::HashWithIndifferentAccess
  • Object
show all
Includes:
CommonMethods
Defined in:
lib/meander/plain.rb

Overview

Brief

This class is a sugar filled version of HashWithIndifferentAccess

It supports key-based method_name calling and value block evaluation

Configuration

You can set class that will be applied to newly assigned values

require 'active_support/core_ext/hash'
class MyClass < Meander::Plain
  cover_class = HashWithIndifferentAccess
end

m = MyClass.new
m[:a] = {}
m[:a].class # => ActiveSupport::HashWithIndifferentAccess

Usage

Key based method_name evaluation

m = Meander::Plain.new({:a => 1})
m.a # => 1

New value assignment

n = Meander::Plain.new
n.a = 1
n.a # => 1

Block values evaluation

k = Meander::Plain.new({config: nil})
k.config do |k|
  k.path = "some_config_path.yml"
end
k.config.path # => "some_config_path.yml"

Instance Method Summary collapse

Methods included from CommonMethods

included

Constructor Details

#initialize(val = {}) ⇒ Plain

Returns a new instance of Plain.



38
39
40
41
# File 'lib/meander/plain.rb', line 38

def initialize(val = {})
  val ||= {}
  super(val)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/meander/plain.rb', line 51

def method_missing(method_name, *args, &block)
  method_name = method_name.to_s
  if new_key_method? method_name
    key_name = method_name.gsub(/=$/, '')
    send :[]=, key_name, *args, &block
  elsif block_given?
    val = self[method_name]
    val = {} unless self.class.hash_or_cover_class?(val)
    send :[]=, method_name, val
    yield(self[method_name])
  elsif key?(method_name)
    self[method_name]
  else
    super
  end
end

Instance Method Details

#[]=(key, value) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/meander/plain.rb', line 43

def []=(key, value)
  if value.is_a?(Hash) && !value.is_a?(self.class.cover_class)
    super(key, self.class.cover_class.new(value))
  else
    super
  end
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/meander/plain.rb', line 68

def respond_to_missing?(method_name, include_private = false)
  new_key_method?(method_name) || key?(method_name) || super
end