class Choice::LazyHash
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!).
Public Class Methods
new(hash = nil)
click to toggle source
You can pass in a normal hash to convert it to a LazyHash
.
# File lib/choice/lazyhash.rb, line 21 def initialize(hash = nil) hash.each { |key, value| self[key] = value } if !hash.nil? && hash.is_a?(Hash) end
Public Instance Methods
[](key)
click to toggle source
Every key is stored as a string. Like a normal hash, nil is returned if the key does not exist.
# 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)
click to toggle source
Store every key as a string.
# 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)
click to toggle source
Wrapper for []=
# File lib/choice/lazyhash.rb, line 31 def fetch(key) self[key] end
Also aliased as: old_fetch
method_missing(meth, *args)
click to toggle source
You can use hash.something or hash.something = 'thing' since this is truly a lazy hash.
# 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
store(key, value)
click to toggle source
Wrapper for []
# File lib/choice/lazyhash.rb, line 26 def store(key, value) self[key] = value end
Also aliased as: old_store