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
Written by Matthew Rudy Jacobs
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#