Getting Websockets, CarrierWave, and Fog to Play Nicely Together
Getting Websockets, CarrierWave, and Fog to play nicely together
Alternate title: “Dancing with Dragons, or, how I got screwed by ActiveRecord Callbacks yet again.”
I’ve been working on the following scenario:
- 2 different people have an ember app open
- One of them adds a new record to the Rails app
- I want other-person’s ember to refresh with that new record instantaniously-ish
Fairly simple, but here’s what’s going on:
- When our photo is created, carrier wave will resize the image, upload it to S3
- We will send the JSON through Pusher to any clients subscribed to the
new_photochannel. The JSON we’re sending is the same JSON that ActiveModelSerializer will use in the API. WIN.
But then, melancholy.
The JSON that comes through has something rather odd for
large_image_url - it’s a local path to the /tmp/upload directory, which absolutely does not work. :/
Basically, when Pusher is sending PhotoSerializer.new(self).attributes, the image has not been stored up to S3. We want to do Pusher later, after fog does it’s thing.
Callbacks are run in this order:
after_create is occurring before
after_save. Let’s switch that up and our problems should be solved:
Result: Same thing. huh?
To see the order in which callbacks are run, we can do this:
That will show the name of the callbacks being called, and will look something like:
That 70220584822820 is our block callback. And it’s first. Why is it first? Can we get it to go last? Callbacks are run in a last-first order. Further, changing it to something like the following also doesn’t work.
So then what the hell works?
We need to store the image before we get the attributes. So, let’s add that
store_image! callback we saw in the list of callbacks. This will result in
store_image! being called twice, but it won’t actually store the image twice — the second call is basically a no-op.
IT WORKS. REJOICE. Then: Anger.
It reminds me of a story about a younger Rails developer warning other Rails devs about the dangers of Callbacks, and how they tend to screw you over.