Skip to content

Instantly share code, notes, and snippets.

@mloughran
Created March 18, 2010 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloughran/336358 to your computer and use it in GitHub Desktop.
Save mloughran/336358 to your computer and use it in GitHub Desktop.
# Instances must supply a Klass.load method which is used to load the object
# in case it is not available in object space - for example from some data store.
# Also objects must provide an id method which is used as the key
#
module ObjectSpaceIdentityMap
def [](id)
obj = nil
ObjectSpace.each_object(self) do |o|
obj = o if o.id == id
end
obj = load(id) unless obj
return obj
end
end
class Foo
extend ObjectSpaceIdentityMap
attr_reader :id
def initialize(id)
@id = id
end
# This is a really trivial load - it would probably load from some datastore
def self.load(id)
new(id)
end
def to_s
"Foo object with name #{@name} and object_id #{object_id}"
end
end
puts Foo['bob']
puts Foo['charles']
puts Foo['bob'] # Should have the same object_id as first bob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment