Created
March 18, 2010 13:41
-
-
Save mloughran/336358 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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