The Siphoning Splat #
I’m serious about this. The splat is such a wildly devious little asterisk.
>> instruments = {'trombones' => 1, 'clarinets' => 2} >> p instruments.to_a [["trombones", 1], ["clarinets", 2]] >> p *instruments ["trombones", 1] ["clarinets", 2]
A 2-in-1 combo move! Look at that splat. It’s not just to_a
. It called to_a
and it siphoned the arguments.
So, Camping has an r
method which is for making HTTP responses from scratch. The signature of this method is: r(status, body, headers = {})
.
r(404, 'Not Found', 'X-Powered-By' => 'Camping')
And it has controller objects (descended from Camping::Base
) which you run into sometimes. These objects have @status
, @headers
and @body
ivars inside them.
class Camping::Base def to_a [@status, @body, @headers] end end
With the above to_a
method, I can now do:
r(*controller)
Which can be used as a syntax for forwarding HTTP requests.
See, Camping has a technique for making requests inside itself. For example, let’s say we’ve got a Search
controller that takes a q
variable with search terms in it. And, let’s say we want the front page (the Index
controller) to show the results page for a search containing the word “clarinet.”
class Index < R '/' def get r *AppName.post(:Search, :env => @env, :input => {:q => "clarinet"}) end end
The splat is Ruby’s pipe for arrays. Put that in your pipe and splat it!
Ryan Mulligan
well, interesting. I have always been disconcerted about the splat. It doesn’t seem very intuitive.
why
This could be used to forward stuff to the 404 handler in Camping, which is a common question.
Evan Farrar
why
Nooo!! The words chunky and bacon should NEVER be split!!
Jon Leighton
If
r
takesr(status, body, headers = {})
andCamping::Base#to_a
returns[@status, @headers, @body]
, then surelyr(*controller)
will end up passing headers to the body param and the body to the headers param?Danno
I have greatly missed entries like this, _why
I guess you’ve been busy with Monkey Starfishies and such?
why
John: Surely. Thanks!
Danno: Actually, been off harvesting a cheetah-based apple solution. And such.
Adam
Adam
Gny
Well but for readability that is da Horror. You are making me a bit freid now.
But it’s Ooooo so cool :D.