Class: Norman::HashProxy
- Inherits:
-
Object
- Object
- Norman::HashProxy
- Defined in:
- lib/norman/hash_proxy.rb
Overview
Wrapper around hash instances that allows values to be accessed as symbols, strings or method invocations. It behaves similary to OpenStruct, with the fundamental difference being that you instantiate one HashProxy instance and reassign its Hash during a loop in order to avoid creating garbage.
Instance Attribute Summary collapse
-
#hash ⇒ Object
readonly
Returns the value of attribute hash.
Instance Method Summary collapse
-
#[](value) ⇒ Object
Allows accessing a hash attribute as hash key, either a string or symbol.
-
#clear ⇒ Object
Remove the hash.
-
#method_missing(symbol) ⇒ Object
Allows accessing a hash attribute as a method.
-
#using(hash) ⇒ Object
Assign the value to hash and return self.
-
#with(hash, &block) ⇒ Object
Set the hash to use while calling the block.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(symbol) ⇒ Object
Allows accessing a hash attribute as a method.
10 11 12 |
# File 'lib/norman/hash_proxy.rb', line 10 def method_missing(symbol) hash[symbol] or raise NoMethodError end |
Instance Attribute Details
#hash ⇒ Object (readonly)
Returns the value of attribute hash.
7 8 9 |
# File 'lib/norman/hash_proxy.rb', line 7 def hash @hash end |
Instance Method Details
#[](value) ⇒ Object
Allows accessing a hash attribute as hash key, either a string or symbol.
15 16 17 |
# File 'lib/norman/hash_proxy.rb', line 15 def [](value) hash[value || value.to_sym || value.to_s] end |
#clear ⇒ Object
Remove the hash.
20 21 22 |
# File 'lib/norman/hash_proxy.rb', line 20 def clear @hash = nil end |
#using(hash) ⇒ Object
Assign the value to hash and return self.
25 26 27 |
# File 'lib/norman/hash_proxy.rb', line 25 def using(hash) @hash = hash ; self end |
#with(hash, &block) ⇒ Object
Set the hash to use while calling the block. When the block ends, the hash is unset.
31 32 33 |
# File 'lib/norman/hash_proxy.rb', line 31 def with(hash, &block) yield using hash ensure clear end |