January 20, 2006

Replacing methods

Let's say we want to replace a method instead of just throwing it away. But we want the new method to be able to call the old implementation.

The standard way of doing this is by aliasing the old method and making the new one call the aliased version:


class Foo
  def method
    ...
  end

...

class Foo
  alias :method :old_method

  def method
    ...
    old_method
  end
end



This solution works perfectly for most situations, but what if we want to remove all traces of the old method?

Here's a simple trick to do exactly that:


class Foo
   old_method = instance_method(:method)

   define_method(:method) { |*args|
       # do something here ...
       old_method.bind(self).call(*args)
   }
end


It shouldn't take much to understand how it works, but let's analyze it in more detail. The first line gets a hold of the old implementation of method. instance_method returns an UnboundMethod object that wraps it.

Next, we redefine method and pass it a block with the new implementation. One thing worth mentioning is that the old_method variable inside the block is bound to the variable assigned to outside of the block. The binding is maintained even after the execution reaches the end of the class definition. As a result, the new method has a direct reference to the old one... and nobody else does.

After doing whatever it has to do, the new method calls the old one after binding the UnboundMethod to the current object (i.e., the object on which method was invoked).

If you have a keen eye, you'll notice that there's something special about self. At first glance, it looks like a standard variable that just happens to hold a reference to the current object. If that were true, it would follow that the reference to self inside the block would be bound to the self representing class Foo. That is not the case, though. The binding of self is established when the block gets called.

Labels:

8 Comments:

Blogger jChris said...

thanks for the insight... I stopped by to learn about conditional assignment, and left with unbound methods!

March 26, 2006 11:06 PM  
Blogger tim said...

How do you put old_method back as if you'd never touched it?

June 01, 2007 1:37 AM  
Blogger Daniel Cadenas said...

Tim I tried to do exactly that some months ago, check this: http://dcadenas.blogspot.com/2007/11/bit-of-metaprogramming.html

August 14, 2008 7:47 AM  
Blogger crazyloko said...

buy products wholesaleThis phenomenom is typified by China Wholesalersthe rise ofbusiness. Incredible range of products available with China Wholesale “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and China Wholesale will skyroket your profits.china wholesale productsbuy china wholesalewholesale chinawholesale productsbuy products

October 27, 2009 12:46 AM  
Blogger nike said...

Clothing has always been a thing that has been given a great importance by human beings. It displays the attitude that the people exhibit.
ed hardy clothes
ed hardy shirts
Lots of brands have been existent in the clothing industry and a famous one among them is the Ed hardy clothing brand.
ed hardy jackets
ed hardy hoodies
The brand got its name from the famous American tattoo artist Ed Hardy. He was a very famous tattoo artist and has published many books on tattooing techniques.
ed hardy boots
ed hardy polo shirts
But his tattooing turned into a brand by the efforts of a company called Christian Audiger. This company was a very famous and very powerful company in the field of clothing.
ed hardy shoes
ed hardy jeans
They felt that it would be appropriate to create a brand called Ed hardy and use Hardy's art as the main selling point for the brand. This venture had turned out to be a very successful one and Ed hardy clothing is one of the most famous brands in the clothing industry.
ed hardy outerwear
ed hardy long sleeve shirts
The brand became very famous because it was worn by many famous celebrities like Madonna, Britney spears and also Sylvester Stallone.
ed hardy bags
ed hardy uggr boots
The brand has clothes for men, women, and kids. They have also diversified their business by having a lot of accessories to support their clothing business.
ed hardy love kills slowly shirts
ed hardy love kills slowly shoes
ed hardy love kills slowly boots
for men they have a variety of products such as active wear, denim, outwear, swim trucks, sweaters, t-shirts, tops etc.
ed hardy trousers
ed hardy mens
the accessories include things such as belts, caps, scarves, shoes, socks, jeweler, sunglasses, ties and even wallets.
The art works is a unique combination of American and Japanese cultures. The unique selling proposition of the brand is the way in which the company has used the art works of Ed hardy.
ed hardy womens
ed hardy t shirts
ed hardy sunglasses

December 15, 2009 4:49 PM  
Blogger nike said...

Nice work and thanks!
Running
Adidas currently manufactures several running shoesNike shoes, including the adiStar Control 5, the adiStar Ride
Cheap nike shoes
Discount nike shoes
the Supernova Sequence and the Supernova Cushion 7, among others.
Nike shox r4
nike shox torch
nike shox shoes
Adidas also uses kangaroo leather to make their more expensive shoes.
Association football
One of the main focuses of Adidas is football kit and associated equipment.
puma cat
cheap sport shoes
Adidas also provides apparel and equipment for all teams in Major League Soccer. Adidas remain a major company in the supply of team kits for international football teams.
cheap nike shox
cheap nike max
Adidas also makes referee kits that are used in international competition and by many countries and leagues in the world. In the United States, referees wear the Adidas kits in MLS matches even though the primary referee supplier is Official Sports.
nike tn dollar
nike running shoes
The company has been an innovator in the area of footwear for the sport with notable examples including development of the Copa Mondial moulded boot on firm dry pitches for forty years.
nike air max tn
puma shoes
Adidas became renowned for advancing the "Predator" boot design.This design featured a ribbed rubber structure for the upper leather of the shoe, used to accent the movement of the ball.
discount puma shoes
puma mens shoes
The Predator also features the Craig Johnston invented "Traxion" sole. As the development and popularity of Football continued Adidas played a leading role in shaping the style of the play itself.
puma running shoes
puma shoes
FIFA, the sports governing body, commissioned specially designed footballs for use in its own World Cup tournaments to favour more attacking play.
ghd hair straighteners mk4
hair straightners
ghd iv styler hair straightener
ghd hair straightners
cheap ghd hair straighteners

December 15, 2009 4:50 PM  
Blogger ally said...

Apart from these military fashion tops and ripped and torn jeans are also hip and happening this season.2010 fashion trends for men would be dominated this season by denim. By denim we don't need to just stick to jeans but also sport denim jackets and casual pants as well. wholesale LV handbagsdiscount moncler jacketsmoncler coatsmonclermoncler vestmoncler outletmoncler t-shirtmoncler jacketsmonclernew moncler coatsmoncler vestmoncler outletmoncler polo t-shirtCoach handbags outletCheap Coach handbag 2010Discount Coach hand bagAuthentic Coach handbagNewest Coach handbags outletLouis Vuitton handbagsLV handbags 2010Discount LV handbagsCheap Louis Vuitton Outletnewest Louis Vuitton handbagscheap rain weardiscount rainweardog rain jacketscolorful rain bootsrainboots outletCheap Ture Religion Jeans outletDiesel JeansLevis JeansWholesale Ed Hardy JeansDiscount Dior Jeans outlet Jerseys and sneakers are never out of fashion. It is very urban and very hip hop.ust as leather is in trend for women it is also true for men. Leather jackets are a must in the wardrobe this season.

April 15, 2010 8:09 PM  
Blogger ally said...

It is very stylish and sleek. In the casual attire category tracksuits and tank tops rule for men. The most popular t-shirts this season would be the ones with funny sayings on them.cheap abercrombie fitch clothingdiscount abercrombie fitch T-shirtsdiscount abercrombie and fitch hoodiesabercrombie fitch outletwholesale abercrombie fitched hardy wholesale
cheap ed hardy wholesalediscount ed hardy wholesale
wholesale ed hardyed hardy outletdiscount abercrombie and fitch outletdiscount abercrombie outletdiscount abercrombie clothingdiscount abercrombie jacketdiscount abercrombie shirtdiscount abercrombie and fitch outletdiscount bercrombie and fitch clothesdiscount abercrombie and fitch hoodiediscount abercrombie and fitch shirtsdiscount abercrombie fitch jacketBesides, the urban trend, vintage clothing will also rule this season. This includes tight jeans and leather jackets and embroidered clothing.This season it seems like we are going to have a handful to choose from because the trend is a nice mix match of clothes from different seasons. So go ahead flaunt your style your own way.

April 15, 2010 8:10 PM  

Post a Comment

Links to this post:

Create a Link

<< Home