Last active
September 8, 2017 21:19
-
-
Save theterminalguy/a392eab5b7075410624f27a3da8812fb to your computer and use it in GitHub Desktop.
Avoid several `.try` in your rails code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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