upgrading Rails 3 to Rails 4 and try

In a Rails project I am using the ZendeskAPI gem to integrate with Zendesk. It’s a simple integration with Hash-like objects representing the remote data.

e.g. ZendeskAPI::User #- is a kind of Hash with magic methods

Subtle differences between Rails 3 and 4 make Jack a dull boy.

Rails 3

# just calls send on source if it is not nil
def try(*a, &b)
  if a.empty? && block_given?
    yield self
    __send__(*a, &b)

Rails 4

# just calls send on source if it isn’t nil and responds to ‘id'
def try(*a, &b)
  try!(*a, &b) if a.empty? || respond_to?(a.first)

user can potentially be nil at any point we when we call try on it, it will always return nil because the ZendeskAPI::User does not respond to the those methods. So in cases where you might be overriding method_missing try most certainly won’t work.

However, ‘try’ takes a block…so I discovered quite by accident that I can do this instead


This works because if the first argument is empty it simply instance_evals the block I gave it, which calls ‘id’. And relax.