Why isn't this simple test class's method inherited in Ruby?
- by Kevin Bannister
Consider this very simple logging class:
class MockLog
  def self.log_stub_method(*args)
    args.each do |a|
      define_method "#{a}" do |msg|
        t = Time.now.strftime("%Y-%m-%d %H:%M:%S")
        $stderr.puts "[#{a.upcase}] \u00bb [#{t}] #{msg}"
      end
    end
  end
  log_stub_method :fatal, :error, :warn, :info, :debug
end
Let's add logging to all our classes:
class Module
  def has_logging()
    class_eval {
      @log = MockLog.new
      def log
        self.class.instance_variable_get :@log
      end
    }
  end
end
Now, why doesn't this work?
class Foo
  has_logging
end
Foo.new.log.nil?   # => false, as expected
class Bar < Foo
end
Bar.new.log.nil?   # => true?! Why wasn't the `log` method inherited?