Skip to content

Instantly share code, notes, and snippets.

@mexelout
Last active September 18, 2018 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mexelout/960025822afe45afea68f5ee56dfe3a8 to your computer and use it in GitHub Desktop.
Save mexelout/960025822afe45afea68f5ee56dfe3a8 to your computer and use it in GitHub Desktop.
ActiveSupportのtryメソッド ref: https://qiita.com/mexelout/items/567a55108155230d9337
Hoge.first.try(:name)
# => メソッドや変数の呼び出しで、objがnilでも例外を発生させずに通れる
Hoge.first.try { |hoge| { id: hoge.id, name: hoge.name } }
# => {:id => 1, :name => 'bar'}
Hoge.first.yield_self { |hoge| { id: hoge.id, name: hoge.name } }
# => { :id => 1, :name => 'bar' }
Hoge.first.then { |hoge| { id: hoge.id, name: hoge.name } }
# => { :id => 1, :name => 'bar' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment