views:

31

answers:

1

Hi all-

I am creating a site similar to the infamous Woot in one particular way: I would like to rotate through products at a rate of one per day. I am using RoR, and would prefer to dynamically choose a product, and not have to enter one each day. So here are the requirements:

1) Get a new product each day
2) Select dynamically from a table
3) Make sure not to select the same product twice

Thats about it. In the products table, I currently have a boolean called listed which will mark if the product has been listed. My question is, should I run some kind of database job to choose a product for that day or is there some way I can like hash the date and come up with an id that the app will display until the date changes.

Thanks for the time.

+1  A: 

Personally, I would keep it simple and go the scheduled job approach. To be more specific, I'd probably use the whenever gem to wrap a cron-job that runs once daily at midnight. You can then set up a method in your Product model to select the current 'Product of the Day'.

Something like this should work:

product.rb

class Product < ActiveRecord::Base
  # Return the current product of the day
  def self.product_of_the_day
    self.find_by_listed(true)
  end

  # Set up the product of the day
  def self.setup_product_of_the_day
    current_product = self.product_of_the_day

    product_ids = self.all(
      :select => "id",
      :conditions => ['id != ?', current_product.id]
    )

    next_product = self.find(product_ids[rand(product_ids.length)])

    current_product.update_attribute(:listed, false)
    next_product.update_attribute(:listed, true)
  end
end

schedule.rb

every 1.day do
  runner "Product.setup_product_of_the_day"
end
jerhinesmith
Hey-Thanks for the answer. Pretty much the solution I was thinking about. Here is a question though: I hope to deploy this to Heroku. How will this work using that cron job thing they have set up? Thanks.
I'm not sure how deploying to Heroku works. If you can use Capistrano, then there are tasks you can add to your deployment file to update the crontab file on deployment. If you can't use Capistrano, you might be able to at least get some ideas from the *Capistrano Integration* section on the `whenever` page.
jerhinesmith