From: Kevin Olbrich Date: 2006-04-20T06:02:04+09:00 Subject: Re: overriding a class method Thanks! I am slowly but surely getting the hang of this metaprogramming thing. On Thursday, April 20, 2006, at 4:49 AM, Brian Mitchell wrote: >On 4/19/06, Kevin Olbrich wrote: >> Yeah, not looking to subclass. > >class A > def self.meth_a > puts "one" > end >end > >class A > class << self; alias meth_a_old meth_a end > def self.meth_a > meth_a_old > puts "two" > end >end > >Though I personally think use of alias for this sort of thing as a >"hack" (just my opinion of course). Another technique is to use a >lexical closure: > >class A > def self.meth_a > puts "one" > end >end > >class A > old_a = method(:meth_a) > # The ugly part. This usually is nicer for instance methods. > # You could write this a few different ways but they are all > # ugly. Possibly something to factor out as a method. > sclass = class << self; self end > sclass.send :define_method, :meth_a do > old_a.call > puts "two" > end >end > >Both are messy but one is less likely to collide or cause problems >with other code (not to mention littering the class with aliases). > >Brian. > _Kevin -- Posted with http://DevLists.com. Sign up and save your mailbox.