BackgrounDRb a ruby library along with rails

25 Apr 2008

Since Rails is single threaded and can't handle multiple requests at a time , when I need such functionality I was helpless.Then I came to know about BackgrounDRb a ruby library which will help us to make "RAILS" handle multiple requests at the same time.To make use of this library is pretty simple. Following steps will help you to do so.BackgrounDRb depends on chronic and packet gems. Thus lets get started by installing these two gems first

sudo gem install chronic packet

Now we are ready to install backgroundrb , for this we need to do

script/plugin install svn://rubyforge.org//var/svn/backgroundrb

Now backgroundrb plugin is installed on our application, now set it up using the command

rake backgroundrb:setup :this will create three files on our application

creates a config file backgroundrb.yml in config directory of your rails application. Creates RAILSROOT/lib/workers directory for keeping BackgrounDRb workers in one place. Creates RAILSROOT/test/bdrbtesthelper.rb as a test helper for your workers

How this helps to balance the load is very interesting. Here we have one class called "worker". Using this worker class we can make our time-consuming tasks run in the background of application, instead of running in controller.Now we can create our worker using the command

./script/generate worker <classname> which will generate your worker class and there you can write your time taking process.

Now we can invoke the worker on request using

MiddleMan.newworker :class => :nameofyourworker, :args => {arguments to pass}

Before you start your web server do start backgroundrb, you can start and stop this by

./script/backgroundrb/start ./script/backgroundrb/stop

Now our app will act as multi threaded. Try an example given below

Let me first thank my colleague Mr.Unni for his code on "downloading the song from YouTube using a ruby script", I am borrowing few parts of it. So in the sample app you can download a song from YouTube using the URL of that particular song. Here Backgroundrb plays well to download multiple songs at same time by running it on background. Run this app on clicking the link below: Download and run me