From: Devin Mullins Date: 2005-06-20T23:04:02+09:00 Subject: Re: preventing instantiation Why do you need to strictly enforce instantiation of your objects? Are you not in a position to implement dependency injection, and let the container manage instantiation? If not... R. Mark Volkmann wrote: >I'm confused. How can I create a few objects within the class and then prevent >other classes from creating additional instances? > > class Moo def initialize #initialize is an instance method that gets called right after construction #by the actual constructor, a predefined class method called 'new' puts 'created!' end end a = Moo.new created! => # def make_singleton(aClass) #use this to define class methods (like new) class << aClass def inst @inst ||= new #method calls don't need parens end #meh, i decided I want the existing 'new' method to be private private :new end end make_singleton(Moo) b = Moo.new NoMethodError: private method `new' called for Moo:Class from (irb):21 b = Moo.inst created! => # c = Moo.inst => #