【问题标题】:Rails rescue NoMethodError alternativeRails 救援 NoMethodError 替代方案
【发布时间】:2020-03-10 01:13:42
【问题描述】:

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

rescue NoMethodError

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

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

我在想这样的事情:

class User
  def name
    "my name"
  end
end

然后

User.new.has_method?(name)

或类似的东西。

【问题讨论】:

  • 你的意思是像some_object.respond_to?(:some_method) 吗?
  • 或者对于类方法:SomeClass.respond_to?(:some_method)
  • 好吧,在 apidock.com/rails/ActionController/MimeResponds/respond_to 他们提到了它的用途,但它不仅适用于控制器吗?或者在这种情况下如何使用它?顺便说一句,我正在处理服务,而不是在 ActionController 中
  • 我不知道它是否对你有用,因为你还没有发布任何代码。请阅读问题指南并展示您的代码和用例。
  • 而respond_to? 是Ruby 中的一种方法,所以不,它不仅仅用于视图。它可以在任何地方使用。

标签: ruby-on-rails exception nomethoderror


【解决方案1】:

如图所示:https://ruby-doc.org/core-2.7.0/Object.html#method-i-respond_to-3F 是 Object 上的一个方法。因此它将检查该方法的任何对象并回复true 或false。

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

【讨论】:

    【解决方案2】:

    这可能与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开始

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多