开发者

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开发者_StackOverflow社区_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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜