Module: Hash::Cache

Defined in:
lib/hash-cache.rb

Overview

A module which adds #get and #set methods to an object, usually a Hash

To get and set values, we call the object’s indexer methods, eg.

return object[ key ]

object[ key ] = value

Any object which has [] and []= methods can have Hash::Cache included in it to get these #get and #set method implementations.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



15
16
17
18
19
# File 'lib/hash-cache.rb', line 15

def self.included base
  methods = base.respond_to?(:instance_methods) ? base.instance_methods : base.methods
  raise "Hash::Cache can only be included in objects that implement the [] method"  unless methods.include?('[]')
  raise "Hash::Cache can only be included in objects that implement the []= method" unless methods.include?('[]=')
end

.new(hash = nil) ⇒ Object

Get a new Hash object with Hash::Cache included

This allows you to easily get Hash instances with #get and #set methods without causing all instances of Hash to get these methods.

>> require 'hash-cache'
=> true

>> cache = Hash::Cache.new
=> {}

>> cache.set 'chunky', 'bacon'
=> "bacon"

>> cache.get 'chunky'
=> "bacon"

>> cache['chunky']
=> "bacon"

>> cache
=> {"chunky"=>"bacon"}

This accepts an optional Hash instance as an argument which will include Hash::Cache in just that particular instance)

>> hash = { :chunky => 'bacon' }
=> {:chunky=>"bacon"}

>> hash.get :chunky
NoMethodError: undefined method `get' for {:chunky=>"bacon"}:Hash
  from (irb):7

>> Hash::Cache.new(hash).get :chunky
=> "bacon"

>> hash.get :chunky   # the original object has the new methods too (we don't dup/clone)
=> "bacon"

>> Hash.new.get 'foo'
NoMethodError: undefined method `get' for {}:Hash
  from (irb):11


64
65
66
67
68
# File 'lib/hash-cache.rb', line 64

def self.new hash = nil
  hash = hash || Hash.new
  hash.send :extend, self
  hash
end

Instance Method Details

#get(key) ⇒ Object



70
71
72
# File 'lib/hash-cache.rb', line 70

def get key
  self[ key ]
end

#set(key, value) ⇒ Object



74
75
76
# File 'lib/hash-cache.rb', line 74

def set key, value
  self[ key ] = value
end