【问题标题】:Undefined method even after method_missing handling即使在 method_missing 处理之后也未定义的方法
【发布时间】:2013-03-24 06:16:48
【问题描述】:

我正在学习 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

【问题讨论】:

    标签: ruby method-missing


    【解决方案1】:

    您正在调用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

    【讨论】:

      【解决方案2】:

      您已将method_missing 定义为Searchable 上的 方法,但您正试图将其作为实例 方法调用。要按原样调用方法,请针对类运行它:

      Book.find_hello
      

      如果您的目的是从整个图书收藏中找到一些东西,那么这是完成的规范方式。 ActiveRecord 使用这种方法。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-17
        • 2018-08-07
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多