Forum: Ruby Aliasing to an inherited method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ec9233451f7c6ba37a83388b87a1f565?d=identicon&s=25 gavin (Guest)
on 2005-12-02 00:29
(Received via mailing list)
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?
45196398e9685000d195ec626d477f0e?d=identicon&s=25 transfire (Guest)
on 2005-12-02 02:06
(Received via mailing list)
#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
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2005-12-02 07:54
(Received via mailing list)
Trans wrote:
> #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
45196398e9685000d195ec626d477f0e?d=identicon&s=25 transfire (Guest)
on 2005-12-02 14:33
(Received via mailing list)
Oops, my bad. You're right Daniel. I didn't even notice that was class
Class.
45196398e9685000d195ec626d477f0e?d=identicon&s=25 transfire (Guest)
on 2005-12-02 14:38
(Received via mailing list)
Okay, so put the class-level where it beleongs:

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

T.
This topic is locked and can not be replied to.