简体   繁体   中英

How do I get .try() working in a Rails module?

With Rails 2.3.5 I've written a module in RAILS_ROOT/lib/foo.rb which I'm including in some models via "include Foo" and all is well except where I try to use some_object.try(:some_method) in the module code - it throws a NoMethodError rather than returning nil like it would from a Rails model/controller/etc. Do I need to require a Rails file from my module?

The try method is added by Rails' ActiveSupport module, so you need to require active_support within your module.

Edit: Alternatively, it's trivial to add it to Object yourself if you don't want to bring in the whole of ActiveSupport:

From active_support/lib/active_support/core_ext/object/try.rb :

class Object
  def try(method, *args, &block)
    send(method, *args, &block)
  end
  remove_method :try
  alias_method :try, :__send__
end

class NilClass #:nodoc:
  def try(*args)
    nil
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM