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
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.