Last Updated: February 25, 2016
·
419
· matthewrudy

Singleton Objects in Ruby

I'm bored of reinventing singleton objects all the time in Ruby;

module MyObject
  def self.call
    puts "I am a singleton object
  end
end

That's fine, but I don't want to have to call self all the time,
and I want to be able to add private methods.

With a little bit of magic;

def singleton(&block)
  mod = Module.new
  mod.singleton_class.module_eval(&block)
  mod
end

I can now define a singleton object with a clear intent

MyObject = singleton do
  def call
    puts "I am a singleton object"
  end
end

Then just call it when I need it!

MyObject.()
# I am a singleton object