Ruby‎ > ‎Getting Started‎ > ‎

SimpleWorker on Rails

Here's a simple example of how to create and run workers in Ruby on Rails.

If you haven't already, please start with our SimpleWorker in 5 minutes article, which uses just the Ruby language. 

This example takes it the next step to use it within a Rails environment.

Confirm Ruby 1.9 or above.

SimpleWorker uses Ruby 1.9 or above and so if you're still on Ruby 1.8.7, you'll need to upgrade your Ruby version.

Configure SimpleWorker Gem

Rails 3

For Rails 3.X, add the following to your Gemfile:

gem 'simple_worker'

Rails 2

For Rails 2.X, add the following to your environment.rb file:

config.gem 'simple_worker'

Configure SimpleWorker Access Keys

Then create a file at config/initializers/simple_worker.rb and put the following configuration block into it:

Use this config block for >v2.x of the simple_worker gem

# Use this for simple_worker gem v2.X
SimpleWorker.configure do |config|
  config.token = "TOKEN"
  config.project_id = "PROJECT_ID"
end
If you're using v1.x of the simple_worker gem then use the following config block:
# Use this for simple_worker gem v1.X
SimpleWorker.configure do |config|
  config.access_key = "ACCESS_KEY"
  config.secret_key = "SECRET_KEY"
end

Configure SimpleWorker Worker Path

NOTE: This is only required in Rails < 3. 

And finally, add the workers directory to your load paths. In environment. rb:
config.load_paths += %W( #{RAILS_ROOT}/app/workers )

Create a Worker

Now that things are configured, let's queue up a worker from an action.

First, create a workers directory at: 

#{Rails.root}/app/workers

Now create a file called my_worker.rb in that directory (/app/workers/my_worker.rb) and put the following code in it:

class MyWorker < SimpleWorker::Base

  attr_accessor :x

  # The run method is what SimpleWorker calls to run your worker
  def run
    x.times do |n|
      log "Hello, I've done something #{n.to_s} times!"
      sleep 2
    end
  end

end

Queue up the Worker in the Cloud

Let's say we have a controller called WelcomeController, now let's just add the following to the index action to keep it simple.

def index
  worker = MyWorker.new
  worker.x = 5
  worker.queue
end

Now just visit your welcome controller, eg: http://localhost:3000/welcome and this job will be queued up!

You can visit your SimpleWorker dashboard at www.simpleworker.com to get the status of the job or make use of the status method to check in on it via your code.

To run jobs with a higher priority, just pass in a priority when you queue them.

worker.queue(:priority=>1)
worker.queue(:priority=>2)

Check out this github repository for a full Rails example.

Comments