Aliasing to an inherited method

P

Phrogz

I tried to modify Daniel Schierbeck's code (in response to the recent
"abstract class" thread) to not have an additional method dispatch.
This line here:

def self.new(*args, &block)
__new__(*args, &block)
end

cries out for a direct alias, to me. Unfortunately, what I hoped would
work didn't. It looks like #alias_method only looks for methods on the
current class; it's not able to alias to a method from an ancestor
class.

class Class
alias_method :__new__, :new
end

module NonInstantiable
def self.included(klass)
super
klass.module_eval {
def self.inherited( subklass )
subklass.module_eval {
puts "Is __new__ available? #{method( :__new__ )}"
alias_method :new, :__new__
}
end
}
end
end

class BaseKlass
include NonInstantiable
end

class SubKlass < BaseKlass; end

p SubKlass.new
p BaseKlass.new

#=> Is __new__ available? #<Method: Class#__new__>
#=> tmp.rb:12:in `alias_method': undefined method `__new__' for class
`SubKlass' (NameError)


Is this behavior desirable, a necessary evil, or an oversight?
 
T

Trans

#new is a class method so you got to get up in that class level.

class Class
class << self
alias_method :__new__, :new
end
end
 
D

Daniel Schierbeck

Trans said:
#new is a class method so you got to get up in that class level.

class Class
class << self
alias_method :__new__, :new
end
end

Actually, the instance methods defined in Class become class methods in
every instance of it (classes)

class Class
def foo; "bar; end
end

Integer.foo => "bar"

It's a bit confusing, but just think of every class in Ruby as an
instance of Class.


Cheers,
Daniel
 
T

Trans

Okay, so put the class-level where it beleongs:

puts "Is __new__ available? #{method( :__new__ )}"
class << self
alias_method :new, :__new__
end

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top