TIL: Rails Squish
A coworker submitted a pull request with this line:
identifier = input_string.squish.split('-').last
I accepted the code as is, but right before deploy, a superior programmer asked:
“What does squish do?”
Oh wow, that programmer was right. What does squish
do? I have never
seen it before.
Honestly, because squish
is a normal word in English, I totally
glossed over it in my review.
Without any context, I had no idea what squish
does… I’m assuming
the function does the right thing since I know the programmer that
wrote the pull request and would not submit intentionally destructive
code.
But what does “squishing” a string mean?? Does any other programming language have it? How do those language handle it?
I had no idea, I had a balanced feeling of being uncomfortable and making sense.
Of course, a quick search turned up documentation on the function.
The documentation explains that squishing a string removes any extra whitespace. For example:
" This\n \n is \t\t\t an\n input string ".squish # => "This is an input string"
Nifty!
When I see this in action, of course I know what a squished string is: just remove all the extra whitespace!
This function only exists in Rails, not Ruby. The equivalent function in Ruby would be:
" This\n \n is \t\t\t an\n input string ".split.join(' ') # => "This is an input string"
So it looks like Rails just maps squish
to: split.join(' ')
, which
is kind of good and bad.
- Good: another function so I don’t have to remember how to ‘squish’.
- Bad: another function so I have to remember about ‘squish’ on pull requests.
Or maybe if I remember squish
visually:
Now I’ll definitely remember it for pull requests!