【问题标题】:rails < 4.0 "try" method throwing NoMethodError?rails < 4.0“尝试”方法抛出 NoMethodError?
【发布时间】:2011-09-15 06:38:51
【问题描述】:

为什么尝试抛出错误?这不是破坏了整个目的吗?也许它只是在控制台中?

ruby-1.9.2-p180 :101 > User.first.try(:something)
NoMethodError: undefined method `something' for #<User:0x000001046ad128>
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activemodel-3.0.10/lib/active_model/attribute_methods.rb:392:in `method_missing'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.10/lib/active_record/attribute_methods.rb:46:in `method_missing'
    from (irb):101
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

编辑:

谢谢大家,我明白了。

有没有办法在不使用respond_to? 的情况下做我想做的事情,这样User.try(:something) 返回nil 而不是抛出错误?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord nomethoderror


    【解决方案1】:

    导轨 3

    您误解了try 的工作原理,来自fine manual

    试试(*a, &b)
    调用由符号方法标识的方法,将任何参数和/或指定的块传递给它,就像常规的 Ruby Object#send 所做的那样。

    然而,与该方法不同的是,如果接收对象是nil 对象或NilClass,则不会引发NoMethodError 异常,而是返回nil

    还有try that is patched into NilClass的版本:

    尝试(*args)
    nil 上调用try 总是返回nil

    所以try 不会忽略您尝试调用对象上不存在的方法的尝试,它会忽略您尝试调用nil 上的方法并返回nil 而不是引发异常。 try 方法只是一种避免在方法调用链中的每一步都检查nil 的简单方法。


    导轨 4

    try 的行为在 Rails 4 中发生了变化,所以现在:

    调用名称作为第一个参数的公共方法,就像public_send 所做的那样,除了如果接收者没有响应它,调用将返回nil 而不是引发异常。

    所以现在try 会同时处理这两项检查。如果你想要 Rails 3 的行为,有try!:

    try 相同,但如果接收 [sic] 不是 nil 并且未实现 [sic] 尝试的方法,则会引发 NoMethodError 异常。

    【讨论】:

    • 这种行为在 Rails 4.0 中改变了,try 现在不会在缺少该方法时引发,但是,try! 会在缺少该方法时引发。见github.com/rails/rails/commit/…
    • @TimonVonk:感谢您的提醒,我已经更新了区分 Rails3 和 Rails4 的答案。
    【解决方案2】:

    这就是尝试的作用

    调用由符号方法标识的方法,传递给它任何 参数和/或指定的块,就像常规的 Ruby Object#send 确实如此。然而,与该方法不同的是,NoMethodError 不会引发异常,而是返回 nil,如果 接收对象是一个 nil 对象或 NilClass。

    所以,假设您在控制器中设置了@user,但您没有实例化它然后@user.try(:foo) => nil 而不是

    @user.foo
    NoMethodError: undefined method `foo' for nil:NilClass
    

    这里的重点是 try 是一个实例方法。还有doesn't return nil if the object you try on isn't nil

    【讨论】:

    • 哦,有道理。有什么功能可以做我想做的事吗?
    • User.column_names.include?("name")@u.attributes.has_key?("name")
    • 所以我必须先检查一下,有没有办法做到这一点是一条线?这将是一个不错的功能;)
    【解决方案3】:

    我知道这是旧的,但它可能对其他人有所帮助,因为这是我在谷歌上搜索此问题时弹出的第一件事。我“借用”了 try 的代码并实现了我自己的 try_method 方法,它的作用类似于 try,只是它首先检查是否方法在调用 send 之前存在。我在 Object 中实现了它并将其放入初始化程序中,现在我可以在任何对象上调用它。

    class Object
      # Invokes the method identified by _method_, passing it any
      # arguments specified, just like the regular Ruby <tt>Object#send</tt> does.
      #
      # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
      # if the method does not exist.
      #
      # This differs from the regular Ruby <tt>Object#try</tt> method which only
      # suppresses the +NoMethodError+ exception if the object is Nil
      #
      # If try_method is called without a method to call, it will yield any given block with the object.
      #
      # Please also note that +try_method+ is defined on +Object+, therefore it won't work with
      # subclasses of +BasicObject+. For example, using try_method with +SimpleDelegator+ will
      # delegate +try_method+ to target instead of calling it on delegator itself.
      #
      # ==== Examples
      #
      # Without +try_method+
      #   @person && @person.respond_to?(:name) && @person.name
      # or
      #   (@person && @person.respond_to?(:name)) ? @person.name : nil
      #
      # With +try_method+
      #   @person.try_method(:name)
      #
      # +try_method+ also accepts arguments and/or a block, for the method it is trying
      #   Person.try_method(:find, 1)
      #   @people.try_method(:collect) {|p| p.name}
      #
      # Without a method argument try_method will yield to the block unless the receiver is nil.
      #   @person.try_method { |p| "#{p.first_name} #{p.last_name}" }
      #--
      # +try_method+ behaves like +Object#send+, unless called on +NilClass+ or a class that does not implement _method_.
      def try_method(method=nil, *args, &block)
        if method == nil && block_given?
          yield self
        elsif respond_to?(method)
          __send__(method, *args, &block)
        else
          nil
        end
      end
    end
    
    class NilClass
      # Calling +try_method+ on +nil+ always returns +nil+.
      # It becomes specially helpful when navigating through associations that may return +nil+.
      #
      # === Examples
      #
      #   nil.try_method(:name) # => nil
      #
      # Without +try_method+
      #   @person && @person.respond_to(:children) && !@person.children.blank? && @person.children.respond_to(:first) && @person.children.first.respond_to(:name) && @person.children.first.name
      #
      # With +try_method+
      #   @person.try_method(:children).try_method(:first).try_method(:name)
      def try_method(*args)
        nil
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多