Skip to content

Instantly share code, notes, and snippets.

@theterminalguy
Last active September 8, 2017 21:19
Show Gist options
  • Save theterminalguy/a392eab5b7075410624f27a3da8812fb to your computer and use it in GitHub Desktop.
Save theterminalguy/a392eab5b7075410624f27a3da8812fb to your computer and use it in GitHub Desktop.
Avoid several `.try` in your rails code
# https://www.mobomo.com/2010/11/calling-methods-on-potential-nil-objects-in-rails/
# http://tony.pitluga.com/2011/08/08/destructuring-with-ruby.html
module ActiveSupport
refine Object do
def try_chain(*args)
args.size > 1 ? eval("self.try(args[0]).try_chain(#{args[1..-1].inspect[1..-2]})") : self.try(args[0])
end
end
end
# sample usage
class FoosControlloer < ApplicationsController
using ActiveSupport
def baz
"Don'tRepeatYourselfs ".try_chain(:underscore, :capitalize, :chop!, :chop!)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment