2013-03-24 27 views
0

我正在學習Ruby並嘗試實施method_missing,但它不起作用。例如,我想在find_之後打印方法名稱,但是當我在Book實例上調用它時,ruby引發了「未定義的方法'find_hello'」。即使在method_missing處理後未定義的方法

TEST_05.RB

module Searchable 
    def self.method_missing(m, *args) 
     method = m.to_s 
     if method.start_with?("find_") 
      attr = method[5..-1] 
      puts attr 
     else 
      super 
     end 
    end 
end 

class Book 

    include Searchable 

    BOOKS = [] 
    attr_accessor :author, :title, :year 

    def initialize(name = "Undefined", author = "Undefined", year = 1970) 
     @name = name 
     @author = author 
     @year = year 
    end 
end 


book = Book.new 
book.find_hello 

回答

3

您正在呼籲object方法,尋找instance_level方法。所以,你需要定義instance_level method_missing方法:

module Searchable 
    def method_missing(m, *args) 
     method = m.to_s 
     if method.start_with?("find_") 
      attr = method[5..-1] 
      puts attr 
     else 
      super 
     end 
    end 
end 

class Book 

    include Searchable 

    BOOKS = [] 
    attr_accessor :author, :title, :year 

    def initialize(name = "Undefined", author = "Undefined", year = 1970) 
     @name = name 
     @author = author 
     @year = year 
    end 
end 


book = Book.new 
book.find_hello #=> hello 

當您使用self與方法的定義。它被定義爲class level方法。在你的情況下,Book.find_hello將輸出hello

+0

非常感謝!現在它工作正常。 – 2013-03-24 06:35:11

2

您已經定義method_missing作爲Searchable一個方法,但是你要調用它作爲實例方法。要調用該方法,因爲它是,它運行對類:

Book.find_hello 

如果你的目的是要找到書的整個集合的東西,這是規範的方法,它的完成。 ActiveRecord使用這種方法。

您可能同樣有一個find_*實例方法,它將搜索當前書籍實例。如果這是您的意圖,請將def self.method_missing更改爲def method_missing

相關問題