Rails抢救NoMethodError替代方法

问题描述 投票:0回答:2

我正在创建应该在不同环境中运行的代码(每个代码都有很小的差异)。相同的类可能在一个方法中定义了一个方法,但在另一个方法中却没有。这样,我可以使用类似:

rescue NoMethodError

在方法未在一个特定类中定义但捕获异常时捕获事件不是正确的逻辑方法。

它是否存在替代方法,例如present,以了解该方法是否在特定类中定义?此类是服务,而不是ActionController

我在想类似的东西:

class User
  def name
    "my name"
  end
end

然后

User.new.has_method?(name)

或类似的东西。

ruby-on-rails exception nomethoderror
2个回答
1
投票

如此处所示:https://ruby-doc.org/core-2.7.0/Object.html#method-i-respond_to-3F它是对Object的一种方法。因此它将检查该方法的任何对象,并使用truefalse进行答复。

class User
  def name
    "my name"
  end
end

User.new.respond_to?(name)

将返回true

Rails的方法try可以尝试使用方法,但是如果该对象不存在该方法,则不会抛出错误。

@user = User.first
#=> <#User...>

@user.try(:name)
#=> "Alex"

@user.try(:nonexistant_method)
#=> nil

您可能也在寻找类似method_missing的内容,请查看有关此信息的文章:https://www.leighhalliday.com/ruby-metaprogramming-method-missing


1
投票

这可能是Given a class, see if instance has method (Ruby)的副本

从上面的链接:您可以使用此:

User.method_defined?('name')
# => true

如其他建议,您可能想看看缺少的方法:

class User
  def name
    "my name"
  end

  def method_missing(method, *args, &block)
    puts "You called method #{method} using argument #{args.join(', ')}"
    puts "--You also using block" if block_given?
  end
end

User.new.last_name('Saverin') { 'foobar' }
# => "You called last_name using argument Saverin"
# => "--You also using block"

如果您不了解Ruby元编程,可以从here开始>

© www.soinside.com 2019 - 2024. All rights reserved.