Created
January 31, 2009 22:25
-
-
Save softprops/55680 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
# rb singletons | |
# idea from http://ozmm.org/posts/singin_singletons.html | |
# using the 'extend self' technique to treat a | |
# module like a singleton class. note: | |
# module now behaves like a class but | |
# since it is not a class you cannot create a new | |
# instance | |
module SelfTest | |
extend self | |
def test | |
puts "#{self.ancestors.first} test called" | |
end | |
end | |
# using standard self.method_name | |
# works like extend self example except you | |
# have to specify self when defining method but | |
# you can still create instances with new | |
class ClassMethodTest | |
def self.test | |
puts "#{self.ancestors.first} test called" | |
end | |
end | |
require 'singleton' # need to require this | |
# including Singleton undefines new | |
# to deter the creation of instances | |
class SingletonTest | |
include Singleton | |
def test | |
puts "#{self.class} test called" | |
end | |
end | |
if __FILE__ == $0 | |
SelfTest.test | |
ClassMethodTest.test | |
SingletonTest.instance.test | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment