gpt4 book ai didi

Ruby - 实际上获取实例的所有方法

转载 作者:行者123 更新时间:2023-12-02 23:28:00 26 4
gpt4 key购买 nike

在这个问题中:

How to list all methods for an object in Ruby?

您可以调用foo.methods并获取所有方法。但这并不能获取所有方法。 Rails 中的示例,使用 ActiveStorage:

Image.first.specimens.first.methods.include?(:variant)
# => false
Image.first.specimens.first.respond_to?(:variant)
# => true
Image.first.specimens.first.variant
Traceback (most recent call last):
1: from (irb):3
ArgumentError (wrong number of arguments (given 0, expected 1))
Image.first.specimens.first.method(:variant)
# => #<Method: ActiveStorage::Attachment(id: integer, name: string, record_type: string, record_id: integer, blob_id: integer, created_at: datetime)#variant>

鉴于正在引发 ArgumentError,它respond_to?,并且我可以获取该方法,它确实具有变体方法。但它没有用 .methods 显示。我如何查看完整的方法列表?

最佳答案

也许您错过了链接帖子 How to list all methods for an object in Ruby? 已接受答案中的最后一段:

Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing and responds_to techniques to handle method calls on the fly. As a result, the methods are not listed in the methods method result.

为了更清楚地说明发生了什么,代码示例:

class Foo
def hello
puts 'Hello'
end

def method_missing(name, *args, &block)
case name
when :unknown_method
puts "handle unknown method %s" % name # name is a symbol
else
super #raises NoMethodError unless there is something else defined
end
end
end

foo = Foo.new
p foo.respond_to?(:hello) #-> true
p foo.respond_to?(:unknown_method) #-> false
foo.unknown_method #-> 'handle unknown method unknown_method'
foo.another_unknown_method #-> Exception

方法unknown_method从未定义,但有一个方法可以处理未知方法。因此,该类给人的印象是存在一个方法,但实际上并没有。

也许How can I get source code of a method dynamically and also which file is this method locate in帮助获取有关内容的信息:

Foo.instance_method(:method_missing).source_location

添加

当您定义自己的 method_missing 时,您还应该将 respond_to_missing? 的行为更改为 respond_to_missing?

  def respond_to_missing?(method, *)
return method == :unknown_method || super
#or if you have a list of methods:
#~ return %i{unknown_method}.include?(method) || super
#or with a regex for
#~ method =~ /another_(\w+)/ || super
end
end

另请参阅`respond_to?` vs. `respond_to_missing?`了解详情。

关于Ruby - 实际上获取实例的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58375403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com