Class: HashNinja::HashAttrReader
- Inherits:
-
Object
- Object
- HashNinja::HashAttrReader
- Defined in:
- lib/hash_ninja/hash_attr_reader.rb
Overview
Provides attr_reader Hash data
Examples
member = {'name'=>'Andy', 'type' => { 'id' => 999, 'name' => 'Guest' }}.to_attr_reader
member.name # => 'Andy'
member.type.id # => 999
Instance Attribute Summary collapse
-
#hash ⇒ Object
readonly
target Hash object.
Instance Method Summary collapse
-
#initialize(hash) ⇒ HashAttrReader
constructor
The ‘hash’ should be a Hash object.
- #method_missing(name, *args, &block) ⇒ Object
-
#to_hash ⇒ Object
Returns the Hash object held internally.
Constructor Details
#initialize(hash) ⇒ HashAttrReader
The ‘hash’ should be a Hash object.
15 16 17 18 |
# File 'lib/hash_ninja/hash_attr_reader.rb', line 15 def initialize(hash) raise "hash should be a Hash object #{hash.to_s}" unless hash.is_a? Hash @hash = hash end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/hash_ninja/hash_attr_reader.rb', line 20 def method_missing(name, *args, &block) found = @hash[name] || @hash[name.to_s] if found if found.is_a? Hash found.to_attr_reader else found end end end |
Instance Attribute Details
#hash ⇒ Object (readonly)
target Hash object
12 13 14 |
# File 'lib/hash_ninja/hash_attr_reader.rb', line 12 def hash @hash end |
Instance Method Details
#to_hash ⇒ Object
Returns the Hash object held internally
32 33 34 |
# File 'lib/hash_ninja/hash_attr_reader.rb', line 32 def to_hash @hash end |