1

I'm trying to figure out how to do this simplest of Ruby metaprogramming things and can't get it to work. I'd like to have a module called Logger that if the class extending / including ... it can call x_mod that will then allow functionality such as the method log to be available on instances of that class. This is purely for learning and not at all meant for code in a project. This is

module Logger
  def x_mod
    def self.log
      puts "I want to log here #{inspect}"
    end
  end

  #def say_hello
  #  puts "saying hello"
  #end
end

class Jt
  #include Logger
  #include MyModule
  extend Logger
  x_mod
end

and get the following:

1.9.3-p392 :004 > require './jt'
 => false 
1.9.3-p392 :005 > j=Jt.new
 => #<Jt:0x007fecf48fafa0> 
1.9.3-p392 :006 > j.log
NoMethodError: undefined method `log' for #<Jt:0x007fecf48fafa0>
    from (irb):6
    from /Users/jt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
1.9.3-p392 :007 >

Any ideas on getting to next step? thx

4

2 回答 2

3
module Logger
  def x_mod
    define_method(:log) do
      puts "I want to log here #{inspect}"
    end
  end
end

class Jt
  extend Logger
  x_mod # comment me out to make log fail later
end

j = Jt.new
j.log
于 2013-05-11T17:41:19.877 回答
-1

哎呀,抱歉之前的回答,没有将 Logger 视为一个模块。看看这个:http ://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/你想使用包含而不是扩展。

这段代码工作得很好:

module Logger
  def x_mod
    def self.log
      puts "I want to log here #{inspect}"
    end
  end

  #def say_hello
  #  puts "saying hello"
  #end
end

class Jt
  include Logger
end

jtlog = Jt.new
Jt.log
于 2013-05-11T17:36:38.543 回答