Class: Choice::LazyHash
Overview
This class lets us get away with really bad, horrible, lazy hash accessing. Like so:
hash = LazyHash.new
hash[:someplace] = "somewhere"
puts hash[:someplace]
puts hash['someplace']
puts hash.someplace
If you’d like, you can pass in a current hash when initializing to convert it into a lazyhash. Or you can use the .to_lazyhash method attached to the Hash object (evil!).
Instance Method Summary collapse
-
#[](key) ⇒ Object
Every key is stored as a string.
-
#[]=(key, value) ⇒ Object
Store every key as a string.
-
#fetch(key) ⇒ Object
Wrapper for []=.
-
#initialize(hash = nil) ⇒ LazyHash
constructor
You can pass in a normal hash to convert it to a LazyHash.
-
#method_missing(meth, *args) ⇒ Object
You can use hash.something or hash.something = ‘thing’ since this is truly a lazy hash.
- #old_fetch ⇒ Object
-
#old_store ⇒ Object
Keep the old methods around.
-
#store(key, value) ⇒ Object
Wrapper for [].
Methods inherited from Hash
Constructor Details
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args) ⇒ Object
You can use hash.something or hash.something = ‘thing’ since this is truly a lazy hash.
50 51 52 53 54 55 56 57 |
# File 'lib/choice/lazyhash.rb', line 50 def method_missing(meth, *args) meth = meth.to_s if meth =~ /=/ self[meth.sub('=','')] = args.first else self[meth] end end |
Instance Method Details
#[](key) ⇒ Object
Every key is stored as a string. Like a normal hash, nil is returned if the key does not exist.
43 44 45 46 |
# File 'lib/choice/lazyhash.rb', line 43 def [](key) key = key.to_s if key.is_a? Symbol self.old_fetch(key) rescue return nil end |
#[]=(key, value) ⇒ Object
Store every key as a string.
36 37 38 39 |
# File 'lib/choice/lazyhash.rb', line 36 def []=(key, value) key = key.to_s if key.is_a? Symbol self.old_store(key, value) end |
#fetch(key) ⇒ Object
Wrapper for []=
31 32 33 |
# File 'lib/choice/lazyhash.rb', line 31 def fetch(key) self[key] end |
#old_fetch ⇒ Object
18 |
# File 'lib/choice/lazyhash.rb', line 18 alias_method :old_fetch, :fetch |
#old_store ⇒ Object
Keep the old methods around.
17 |
# File 'lib/choice/lazyhash.rb', line 17 alias_method :old_store, :store |
#store(key, value) ⇒ Object
Wrapper for []
26 27 28 |
# File 'lib/choice/lazyhash.rb', line 26 def store(key, value) self[key] = value end |