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?
+1
A:
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
John Topley
2010-02-24 14:47:08
tried that, same issue :-(2) Error:test_something(WithDescendantsTest):NoMethodError: undefined method `direct_descendants' for #<AdvertisementVersion:0x105cceb78>lib/with_descendants.rb:40:in `try'
Teflon Ted
2010-02-24 17:04:27