[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Preferred monkeypatching technique
From:       "Sean O'Halpin" <sean.ohalpin () gmail ! com>
Date:       2006-07-14 22:15:21
Message-ID: 3736dd30607141515g75e1904au31be119019830522 () mail ! gmail ! com
[Download RAW message or body]

On 7/14/06, Tom Werner <tom@helmetstohardhats.org> wrote:
> Daniel Schierbeck wrote:
> >
> > Not a solution, but:
> >
> >   <http://rcrchive.net/rcr/show/321>
> >
> >   cut MyCut < Firetruck
> >     def put_out_fire(options = {})
> >       super(options.merge(:nozzle => :big))
> >     end
> >   end
> >
> > (Trans, can I omit the `MyCut <' part?)
> >
> >
> > Cheers,
> > Daniel
> >
> >
>
> I looked at that RCR a while back, but only glanced over it as it was
> not applicable to my situation at the time. Looking at it again, I see
> the beauty and power in it. I would love to see that end up in 2.0!
>
> Tom
>
> --

I can't remember if I've posted this before, but here is my "poor
man's cut" which might be handy in the meantime:

def cut(klass, &block)
  klass = Object.send(:remove_const, klass.to_s)
  Object.const_set(klass.to_s, Class.new(klass, &block))
end

class A
  def hello
    "hello"
  end
end

a = A.new
puts a.hello

cut A do
  def hello
    "{" + super + "}"
  end
end

b = A.new
puts b.hello

# but beware - it only works on instances created ~after~ the cut
puts a.hello

__END__
hello
{hello}
hello

Regards,
Sean

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic