Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform some task after render in Rails 3.1

I'm using Impressionist to record page impressions. The database write only takes about 50ms, but I'd really prefer to do it after the page has rendered and been sent to the client.

I've looked into forking via Spawn, but it establishes a new database connection, which seems to be overkill for such a small job. Delayed Job and other background processing libraries seem like major overkill. Writing to the database just to defer writing to the database...not a win.

I wish I could just:

def show
  render
  impressionist(@article)
end

...and have impressionist do its thing with the same database connection and all the same request data as the action, just after the action has already returned to the client. But of course that's not how the render method works.

Any solutions? Running Rails 3.1 and Ruby 1.9.2 on Heroku Cedar.

like image 908
jasongarber Avatar asked Nov 17 '11 12:11

jasongarber


3 Answers

Spawn a new thread. Heroku will allow you up to 15 threads per dyno.

def show
  render
  Thread.new do
    impressionist(@article)
  end
end
like image 69
dmzza Avatar answered Nov 16 '22 13:11

dmzza


There is a pretty cool railscast on using Resque for exactly this, but I am pretty sure it also involves forking, as do all other methods I have seen.

like image 1
fdot Avatar answered Nov 16 '22 15:11

fdot


This came along and looks promising: https://github.com/brandonhilkert/sucker_punch

Brandon's a solid dude. Can't wait to try Sucker Punch out!

like image 1
jasongarber Avatar answered Nov 16 '22 15:11

jasongarber