Skip to content

Instantly share code, notes, and snippets.

@chinshr
Last active December 16, 2015 04:09
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 chinshr/5374955 to your computer and use it in GitHub Desktop.
Save chinshr/5374955 to your computer and use it in GitHub Desktop.
Adding with() blocks so we avoid the ugliness of assigning values in the if comparisons in Ruby.
# ==with
#
# We have been struggling with the absence of @with@ blocks
# in Ruby for a long time. We had something similar in
# Object Pascal.
#
# Let me explain what it does:
#
# with Invoice.find_by_id(params[:id]) do |invoice|
# puts invoice.total
# end
#
# and essentially this resolved to how we used to
# to things in Ruby:
#
# if invoice = Invoice.find_by_id(params[:id])
# invoice.total
# end
#
# See: http://bit.ly/14iimBe, page 93
#
def with(evaluated_object, &block)
yield(evaluated_object) if evaluated_object
end
@jpemberthy
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment