代码之家  ›  专栏  ›  技术社区  ›  Pavel Tkackenko

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

  •  0
  • Pavel Tkackenko  · 技术社区  · 13 年前

    我正在学习Ruby并尝试实现 method_missing ,但它不起作用。例如,我想在 find_ 但当我在Book实例上调用ruby时,它会引发“未定义的方法‘find_hello’”。

    测试_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 回复  |  直到 13 年前
        1
  •  3
  •   Rahul Tapali    13 年前

    您正在上调用方法 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
  •  2
  •   Jim Stewart    13 年前

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

    Book.find_hello
    

    如果你的意图是从整本书中找到一些东西,这是典型的方法。ActiveRecord使用这种方法。

    你也可以有一个类似的 find_* 实例方法,该方法将在当前图书实例中搜索某些内容。如果这是你的意图,那就改变 def self.method_missing def method_missing .