On Thu, Apr 28, 2011 at 3:58 PM, Iain Barnett <iainspeed / gmail.com> wrote:
> Hi,
>
> If I've got a simple bit of initialisation code
>
> =A0 =A0def initialize( blah )
> =A0 =A0 =A0@listener =3D Blah.new blah
> =A0 =A0end
>
> and I'd like to add a singleton method to instance (because I don't want =
to monkey patch the Blah library) where's the best place to do that? I know=
 I could do:
>
> =A0 =A0def initialize( blah )
> =A0 =A0 =A0@listener =3D Blah.new blah
> =A0 =A0 =A0def @listener.my_mental_method
> =A0 =A0 =A0 =A0self.give_it_up! "quickly"

No self needed here.

> =A0 =A0 =A0end
> =A0 =A0end
>
> but is this a good place to do it, or is there something more eloquent/pe=
rfomant? I'd like all instances, wherever they are created, to have this me=
thod, so is there a better way altogether?

First of all, I'd place the method in a module so you have less
definitions around.  Then I'd extend all instances with that module.
That also makes for easy addition of more methods.

module BlahExt
  def your_mental_method
    give_it_up! 'rather sooner than later'
  end
end

The automatic part could be handled by changing Bar's #new:

class <<Blah
  alias _new new

  def new(*a,&b)
    _new(*a,&b).extend BlahExt
  end
end

Note that this does not deal with inheritance nicely.  For that you
could do something similar with Bar's #initialize instead of #new.

If you do not need a global automatic I'd simply stick with

   def initialize( blah )
     @listener =3D Blah.new(blah).extend BlahExt
   end

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/