Skip to content

Instantly share code, notes, and snippets.

@guilleiguaran
Created August 5, 2011 15:49
Show Gist options
  • Save guilleiguaran/1127821 to your computer and use it in GitHub Desktop.
Save guilleiguaran/1127821 to your computer and use it in GitHub Desktop.
Hacking Object.new to ensure that only one instance of an object exists in memory
# Don't use this in a real project never!!!
class SingletonFoo < Object
def self.new(*args)
first_instance = ObjectSpace.each_object(self).first
return first_instance if first_instance
object = allocate
object.send(:initialize, *args)
object
end
end
ruby-1.9.2-p290 :057 > SingletonFoo.new
=> #<SingletonFoo:0x00000102077170>
ruby-1.9.2-p290 :058 > SingletonFoo.new
=> #<SingletonFoo:0x00000102077170>
ruby-1.9.2-p290 :059 > SingletonFoo.new
=> #<SingletonFoo:0x00000102077170>
ruby-1.9.2-p290 :060 > SingletonFoo.new
=> #<SingletonFoo:0x00000102077170>
ruby-1.9.2-p290 :061 > SingletonFoo.new
=> #<SingletonFoo:0x00000102077170>
ruby-1.9.2-p290 :062 > SingletonFoo.new == SingletonFoo.new
=> true
ruby-1.9.2-p290 :063 > SingletonFoo.new.object_id == SingletonFoo.new.object_id
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment