Skip to content

Ironworker on rails

Chiedo edited this page Jun 9, 2015 · 5 revisions

This is extremely outdated. For an up-to-date tutorial, see the following: https://devcenter.heroku.com/articles/iron_worker

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 IronWorker in 5 minutes article.

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

Confirm Ruby 1.9 or above.

IronWorker 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 IronWorker Gem

Rails 3 and Rails 4

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

gem 'iron_worker'

Rails 2

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

config.gem 'iron_worker'

Configure IronWorker Tokens

IronWorker uses OAuth2 for authentication, making use of a token and a project_ID.

Create a file at config/initializers/iron_worker.rb and put the following configuration block into it:

IronWorker.configure do |config|
  config.token = 'TOKEN'
  config.project_id = 'PROJECT_ID'
end

Configure IronWorker 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 a Rails 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 < IronWorker::Base

  attr_accessor :x

  # The run method is what IronWorker 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 IronWorker dashboard at hud.iron.io 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.