Rigel Group

They shoot Yaks, don't they?

Torquebox Really Does Go to 11!

After working with Torquebox for the last year, I couldn’t imagine writing a Rails app without it. I came for the deployment story, but I stayed because of all the fantastic tools you get for free. From diagnostic tools on the JVM, to message queueing, background tasks, the awesome Infinispan cache, etc. Do yourself a favor and check it out.

But, when doing development, I like to make sure the app will run outside of Torquebox as well, with a simple ‘rails s’, so here are a few tricks to make that happen.

When setting Torquebox-specific features, like for example setting the Rails cache store to Infinispan, do this:

1
 config.cache_store = :torque_box_store if defined?(TorqueBox)

That way, when you run outside of Torquebox, Rails will use the default file cache and all will be well.

Another great Torquebox feature is the ability to mark any method as backgroundable, and the JVM will transparently spin off that method in a new thread. You accomplish that with this code:

1
2
3
4
5
6
7
8
class Battlestar
  include Backgroundable
  always_background :fire

  def fire
    # fire something
  end
end

This of course will cause problems when running without Torquebox, so if you add this shim into your initializers, the method will just run in the foreground like normal.

1
2
3
4
5
6
7
8
9
unless defined?(Torquebox)
  module Backgroundable
    extend ActiveSupport::Concern
    module ClassMethods
      def always_background(method)
      end
    end
  end
end

Another technique I use, especially for accessing the Torquebox message queues, is make sure you use your own class as a central point of control, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
class QueueManager
  include TorqueBox::Injectors if defined?(TorqueBox)

  def publish_weapon_event(event)
    @weapon_queue ||= inject("/queues/myapp/weapon_events") if defined?(TorqueBox)

    if @weapon_queue
      @weapon_queue.publish(event)
    else
      processor = WeaponEventProcessor.new
      processor.on_message(event)
    end
  end

So, when running inside Torquebox, the message gets sent to the queue, which would then at some point in the future execute the event processor, but when running under Webrick, it calls the event processor directly.