Ruby inherited callback runs before subclass is loaded

by john on September 22, 2009

Harrumph.

I wanted to call a class method on a subclass when the base class’s inherited callback is triggered.

But it doesn’t work, because the subclass isn’t loaded when this callback is triggered.

:-(

So the following doesn’t work (’boo’ prints instead of ‘foo’):


class Base
  def self.permalink
    'boo'
  end
  def self.inherited(c)
    puts "permalink: #{c.permalink}"
  end
end

class C < Base
  def self.permalink
    'foo'
  end
end

You may be able to get what you want by forcing the class to load with Class.new:


class Base
  def self.permalink
    'boo'
  end
  def self.inherited(c)
    puts "permalink: #{c.permalink}"
  end
end

C = Class.new(Base) do
  def self.permalink
    'foo'
  end
end

Leave a Comment

Previous post: How to embed JRuby 1.9 into a Java class

Next post: Good example of antiquity of some Core Ruby classes