Thursday, July 10, 2008

A link back to referring page in Rails

So here's the quick problem. You have a long list of records in your rails application, such as posts. You end up using the standard pagination offered in rails, which we all know is slow. Regardless, it's pretty annoying to go down into an individual post, edit it in-place, and then hit the back button, since there's no link back to the previous page.

Well, since it's a pagination, there's not a static page to link a "back to list" link. You could pass in the page, but that's a pain in the butt. It's much easier to do:

<%= link_to "Back up to list", request.env["HTTP_REFERER"] %>

This'll put a link back to the same page in the pagination list that you came from. Saves pains. Ends up reading the HTTP spec on headers is a helpful, in addition to some Rails source.

Ends up that "redirect_to :back" also uses the same trick. You can use that in your controller to just redirect back to whatever method called it.

Tuesday, July 8, 2008

rake, cron, ruby, and scheduling tasks

This post is how to setup a cron job, on *nix server using rake. Why use rake ? well rake allows you access to all your models within your application. So writing a task is like writing any other function, and all that DRY goodness without having to rewrite a thing. A very good write up on Rake here : Rake Tutorial.
Setting up a cron job is simple, here is a write up in the Ubuntu documentation - Cron How To.

So just create a directory in your home, or anywhere , to where you will be placing your shell scripts, and/or logs. You could call rake directly in the crontab, but I prefer to keep it in a script, the more complex it gets later, will be easier to change.

its simple after that
cd / && /usr/bin/rake RAILS_ENV=production raketask1 raketask2

and yes you can chain rake tasks and they will run in that order. Very cool stuff. Another good write up where I found out about chaining - Rake Around the Rosie