Ruby has a quasi-convention of taking a method, slightly modifying its behavior, and denoting it with a trailing exclaimation mark, e.g.
#select!. Sometimes these methods raise an error, modify the receiver in place, or return
nil on no-op, or do some combination of these, or something else entirely. Such methods are collectively referred to as “bang” methods, and there’s no hard-and-fast rule for what makes them special—just that they are “more dangerous” than their non-bang counterparts.
Today I’d like to write about bang methods that modify their receivers in place and return
nil on no-op, and how you can improve performance in Ruby applications by (ab)using them to reduce object churn in hot paths.
I was working with the official Ruby gem for the Zendesk API. It’s a quirky little thing but on the whole quite nice to work with. I did run into one little gotcha: in order to retrieve all the items in a paginated collection, you have to use the
#all methods (the bang version raises an error), and you must pass it a block.
I’m fiddling with a bit of Ruby code for my silly Ioughta gem. In this module, the
each_resolved_pair method takes a structure of “pairs” (of symbols and lambdas) and mutates them (by calling the lambda with an incrementing value), returning the resolved pairs.
If your Rack application (and probably other types of applications) lives behind a reverse proxy, always set an X-Forwarded-Proto request header. I recently ran into an issue where Rack::Session (which I’m using for an OAuth1.0a server-side login flow) wouldn’t let me set a secure cookie because it didn’t think I was serving a secure web site.
I have forwardfor disabled in my HAproxy config because I’m using PROXY protocol to talk to Varnish. Manually adding the X-Forwarded-Proto header to the request fixed the issue, and now I want those three hours of my life back! Hopefully this comes up in someone else’s frantic googling at some point in the future and saves them a similar headache.