为Ruby模块中的每个方法调用执行代码

我正在Ruby 1.9.2中编写一个定义几种方法的模块。当调用这些方法中的任何一个时,我希望它们中的每一个都首先执行特定的语句。


module MyModule

  def go_forth

    a re-used statement

    # code particular to this method follows ...

  end


  def and_multiply

    a re-used statement

    # then something completely different ...

  end

end

但是我想避免将a re-used statement代码明确地放在每个方法中。有办法吗?


(如果有关系,a re-used statement将在调用每个方法时打印其自己的名称。它将通过的某些变体来实现puts __method__。)


叮当猫咪
浏览 672回答 3
3回答

ibeautiful

您可以method_missing通过代理模块实现它,如下所示:module MyModule  module MyRealModule    def self.go_forth      puts "it works!"      # code particular to this method follows ...    end    def self.and_multiply      puts "it works!"      # then something completely different ...    end  end  def self.method_missing(m, *args, &block)    reused_statement    if MyModule::MyRealModule.methods.include?( m.to_s )      MyModule::MyRealModule.send(m)    else      super    end  end  def self.reused_statement    puts "reused statement"  endendMyModule.go_forth#=> it works!MyModule.stop_forth#=> NoMethodError...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby