Class: Choice::LazyHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/choice/lazyhash.rb

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

Methods inherited from Hash

#to_lazyhash

Constructor Details

#initialize(hash = nil) ⇒ LazyHash

You can pass in a normal hash to convert it to a LazyHash.



21
22
23
# 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

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_fetchObject



18
# File 'lib/choice/lazyhash.rb', line 18

alias_method :old_fetch, :fetch

#old_storeObject

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