Gregory Brown
7/30/2008 2:34:00 PM
On Wed, Jul 30, 2008 at 10:10 AM, Phlip <phlip2005@gmail.com> wrote:
>> Given that Ruby is typeless, I'm not sure how it would be otherwise.
>
> Ruby is strongly typed, dynamic, and extensible, permitting Monkey Patching.
>
> For example, just yesterday we needed the Rails number_to_currency method to
> implement its :negative_parens option. That's not published yet, so we
> looked up its patch and pasted it into our code directly. Problem solved -
> and note this is a kind of polymorph. You can't have the old method back,
> though!
Granted you can't literally get the method back but if you use *args
and alias_method effectively, you can avoid changing the signature of
the original method and revert back to it for the things your patch
doesn't cover. Of course, in the case you mentioned, if the support
for that option was midstream in the method, you might be out of luck.
>> class Foo
>> def foo(a,b)
>> a + b
>> end
>> alias_method :original_foo, :foo
>> def foo(*args)
>> if Hash === args[0]
>> original_foo(args[0][:a], args[0][:b])
>> else
?> original_foo(*args)
>> end
>> end
>> end
=> nil
>> a = Foo.new
=> #<Foo:0x5651a8>
>> a.foo(3,2)
=> 5
>> a.foo(:a => 3, :b => 2)
=> 5
-greg