【问题标题】:Ruby's respond_to? method is not working - method exists but false is returnedRuby 的 response_to?方法不起作用 - 方法存在但返回 false
【发布时间】:2013-06-06 00:34:23
【问题描述】:

我正在使用 Rails 3.2、Ruby 1.9.3 和 ThinkingSphinx(最新版本)。

此代码在 Ruby 1.8.7 / Rails 2.3 上运行良好,但由于我已升级到上述代码,因此无法运行。

ads = Ad.search "ipod"

ads.respond_to?(:total_entries)

puts ads.total_entries #outputs 472

具体来说

ads.respond_to?(:total_entries)

返回 false,但是当我在 ads 对象上调用此方法时,它可以正常工作/按预期工作。

谁能看到这里发生了什么?

【问题讨论】:

  • 视情况而定。该方法是动态创建的吗? respond_to 在您第一次调用后是否有效?

标签: ruby-on-rails ruby


【解决方案1】:

这可能是动态方法或幽灵方法
如果

ads.respond_to?(:total_entries) # => false
ads.total_entries
ads.respond_to?(:total_entries) # => true

这意味着在某处(可能在method_missingtotal_entries 已被动态创建,例如:

define_method :total_entries do 
  #do some stuff here
end

如果

ads.respond_to?(:total_entries) # => false
ads.total_entries
ads.respond_to?(:total_entries) # => false

然后method_missing 只是用方法名作为参数处理它,然后做你想做的事。

【讨论】:

    【解决方案2】:

    即使ads.total_entries 有效,也不一定意味着 puts total_entries 方法存在。

    当您调用不存在的方法时,Ruby 会调用 method_missing 处理程序,该处理程序可能会处理您的调用。

    要查找确切原因,请提供Ad.search 返回的类的定义。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2021-05-17
    • 2015-01-22
    • 2011-01-13
    • 2012-02-11
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多