Class: Meander::Plain
- Inherits:
-
Thor::CoreExt::HashWithIndifferentAccess
- Object
- Thor::CoreExt::HashWithIndifferentAccess
- Meander::Plain
- Includes:
- CommonMethods
- Defined in:
- lib/meander/plain.rb
Overview
Brief
This class is a sugar filled version of HashWithIndifferentAccess
It supports key-based method 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 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
- #[]=(key, value) ⇒ Object
-
#initialize(val = {}) ⇒ Plain
constructor
A new instance of Plain.
- #method_missing(method, *args, &block) ⇒ Object
- #respond_to_missing?(method, include_private = false) ⇒ Boolean
Methods included from CommonMethods
Constructor Details
#initialize(val = {}) ⇒ Plain
Returns a new instance of Plain.
36 37 38 39 |
# File 'lib/meander/plain.rb', line 36 def initialize(val = {}) val ||= {} super(val) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/meander/plain.rb', line 49 def method_missing(method, *args, &block) method = method.to_s if new_key_method? method key_name = method.gsub(/\=$/, '') send :[]=, key_name, *args, &block elsif block_given? val = self[method] val = {} unless self.class.hash_or_cover_class?(val) send :[]=, method, val yield(self[method]) elsif key?(method) define_getter(method) send method, &block else super end end |
Instance Method Details
#[]=(key, value) ⇒ Object
41 42 43 44 45 46 47 |
# File 'lib/meander/plain.rb', line 41 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, include_private = false) ⇒ Boolean
67 68 69 |
# File 'lib/meander/plain.rb', line 67 def respond_to_missing?(method, include_private = false) new_key_method?(method) || key?(method) || super end |