“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

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
user.try(:id)
def try(*a, &b)
  if a.empty? && block_given?
    yield self
  else
    __send__(*a, &b)
  end
end

Rails 4

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

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

source.try(&:id)

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