The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Methods That Self-Destruct

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Methods That Self-Destruct Posted: Jul 11, 2006 9:08 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Red Handed.
Original Post: Methods That Self-Destruct
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded

Advertisement

Expiring a method. And let’s keep meta out of this.

 class Trial
 def run_me
 def self.run_me; raise Exception, "NO MORE." end
 puts "Your trial period has ended." 
 end
 end
 t = Trial.new
 t.run_me
 #=> Your trial period has ended.
 t.run_me
 #=> (trial):3:in `run_me': NO MORE. (Exception)

The run_me overwrites itself. But notice it uses def self. This overwrites the method in the object, not in the class. So you can create more Trial objects which haven’t self-destructed yet.

Can also be used as a memoization technique. But, rather than caching the data, you just ensure that the code runs only once.

 class Hit
 def initialize(ip)
 @ip = ip
 end
 def country
 def self.country; @country end
 @country = `geoiplookup #{@ip}`.chomp.gsub(/^GeoIP Country Edition: /,"")
 end
 end

I should correct one thing. I’m not actually overwriting the method. Just capping it off with a new singleton method.

For more on singleton methods: an intro and some old thoughts on duck-typed singletons.

Read: Methods That Self-Destruct

Topic: A quick peek inside the Rails Scaffolding Previous Topic   Next Topic Topic: Lessons From Hpricot

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use