即使在method_missing处理之后,也是未定义的方法

时间:2013-03-24 06:16:48

标签: ruby method-missing

我正在研究Ruby并尝试实现method_missing,但它不起作用。例如,我想在find_之后打印方法名称,但是当我在Book实例上调用它时,ruby会引发“未定义的方法'find_hello'”。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您已在method_missing上将Searchable定义为方法,但您尝试将其作为实例方法调用。要按原样调用方法,请对类:

运行它
Book.find_hello

如果您打算从整个书籍集中找到一些东西,那么这就是它的规范方式。 ActiveRecord使用这种方法。

您可以类似地使用find_*实例方法来搜索当前的书籍实例。如果这是您的意图,请将def self.method_missing更改为def method_missing

相关问题