Did you know they changed #try ?

Did you know #try has been changed since Rails 4? I didn’t.

Look at the implementation for Rails 4 and Rails 3. Rails 4 implementation uses respond_to? to check the method presence before calling it via send. It’s a subtle change, but it’s enough to become a problem: In Rails 3 you could use try even when you are dealing with method_missing. Now you have to override the respond_to? to make it work. E.g.:

class A
  def method_missing name, *args, &block
    if name.to_s == 'foo'
      'bar'
    else
      super
    end
  end

  def respond_to? name
    name.to_s == 'foo' || super
  end
end

A.new.try :foo # this returns nil if we don't override #respond_to?

Leave a Reply

wpDiscuz