Skip to content

Instantly share code, notes, and snippets.

@softprops
Created January 31, 2009 22:25
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 softprops/55680 to your computer and use it in GitHub Desktop.
Save softprops/55680 to your computer and use it in GitHub Desktop.
# 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