ruby self.inherited alias_method

376 Views Asked by At
class Base
  def sam
    "I m the base"
  end

  def self.inherited(base)
    alias_method :old_sam, :sam
    base.class_eval do
      def sam
        old_sam 
        p "Inside inherited"
      end
    end
    super
  end
end

class Derived < Base
  def sam
   p "Inside Derived"
  end
end

when Derived.new.sam => "Inside Derived"

But I expect

"Inside Derived"

"Inside inherited"

New to ruby. Any help will be greatly appreciated.

1

There are 1 best solutions below

2
On

You have simply overriden the defined by base.class_eval method sam in Derived.

If you remove the method sam from Derived:

class Derived < Base
end

You will get:

#=> "Inside inherited"
#=> ArgumentError: wrong number of arguments (given 1, expected 0)

The latter is because you are passing an argument to old_sam method, which does not take it:

old_sam p "Inside inherited"

But I expect

"Inside Derived"

"Inside inherited"

This is not possible with your set up, because what you do is first defining an instance method sam in class_eval block for all descending classes, but later just overriding in.