Created
August 5, 2011 15:49
-
-
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
This file contains 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
# 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 |
This file contains 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
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