UPDATE: DHH yanked this patch. Ah well. Open source giveth, and open source taketh away. I sure wish we could restart this discussion and get this change made, but I’ll probably pass on fighting over this one.
Here’s the (now defunct) celebratory post…
While helping a friend today with their Rails project, I found I wanted to add a simple helper method to an object. In the existing view I found something like this:
This is a code smell and I could solve it in two ways: either write a view helper or add a helper method to the
Item class. In this case, I want to ask the object a question, so this makes sense to me on the object itself.
So first we change the view:
And we implement on the model:
Ew. We’re checking a string attribute agaisnt two other strings. Let’s clean that up.
We’re basically saying “this item is for sale if the tag isn’t either ‘free’ or ‘extras’”. To shave off some cognitive load, we use Rails’
in? method and flip things around. Since we’re really talking about the tag (and not the array up front), this makes it easier to read.
That’s all fine and good, but that bang (
!) out front is still making my mind do some gymnastics. Surely, if Rails has
in? it has an opposite. But Google gave me nothing, and some other Rails friends I asked hadn’t heard of such a thing.
Turns out, Rails doesn’t have an opposite for
in?. Ruby has
include? and Rails implements
exclude?, which is nice. But Rails implements
in? without an opposite.
Putting aside the fact that I think these methods (
in?) should be added to Ruby core, I would love to see Rails go that extra step and have a
… and now it does!
As of this commit, Rails now has a
not_in? method. It works like this:
So in our previous example, we can now lead with the object in question. So this:
… turns into this:
Nice and clean! Enjoy!
Writer. Musician. Adventurer. Nerd.
Husband. Dad to three. From: all over the place.
Exvangelical, but still amazed. Enneagram 7.