Why isn't this simple test class's method inherited in Ruby?

Posted by Kevin Bannister on Stack Overflow See other posts from Stack Overflow or by Kevin Bannister
Published on 2010-05-29T13:31:33Z Indexed on 2010/05/29 13:42 UTC
Read the original article Hit count: 227

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about class