01101 November

Interesting Questions asked on Stack Overflow Part 1

Here are some questions I saw on Stack Overflow today that bears repeating.

First Question: I have a long-running task in my controller. It locks up the entire site for 5 minutes while it crunches some numbers.

This is a shockingly important question that everyone writing non-trivial applications should know: pass the task to an external process and immediately respond to the user saying “We’re processing that in the background! Feel free to continue with whatever you were doing…”

A brilliant candidate for managing background tasks is delayed_job. See the Readme and the delayed_job Railscast for more information on using delayed_job to run your long-running tasks in the background.

Second Question: I have a date_select control in my form, how do I get the date from the params hash without assigning it to an ActiveRecord model?

Step 1: replace date_select with select_date! The reason is that date_select uses an unfriendly naming convention for the year/month/day parameters, eg.

# if you do this in your view:
<%= date_select('range', 'start_date')%>

# you need to do this in your controller
@start_date = Date.civil(params[:range][:"start_date(1i)"].to_i,params[:range][:"start_date(2i)"].to_i,params[:range][:"start_date(3i)"].to_i)

# however, if you do this in your view:
<%= select_date :prefix => "range" %>

# you can do this in your controller
@start_date = Date.civil(params[:range][:year], params[:range][:month], params[:range][:day])
# Or even better, IMHO
@start_date = Date.civil *params[:range].slice(%w[year month day])

That’s how I’d do it. :)

That’s it for now! The next post is on monitoring delayed_job with bluepill.

Check out these