johnthethird
1/29/2013 - 4:16 AM

Shim for running Torquebox apps under MRI Ruby

Shim for running Torquebox apps under MRI Ruby

# Shim for running Torquebox apps under MRI Ruby
# http://www.rigelgroupllc.com/blog/2013/01/28/torquebox-shims-for-mri/
if ENV["INSIDE_TORQUEBOX"] == "true"
  Rails.logger.info "[TorqueBoxInitializer] Inside TorqueBox"
else
  Rails.logger.info "[TorqueBoxInitializer] NOT inside Torquebox, shimming TB functions..."
  module TorqueBox
    module Messaging
      class MessageProcessor
        attr_accessor :message

        def initialize
          @message = nil
        end

        def on_error(error)
          raise error
        end

        def on_message(body)
          throw "Your subclass must implement on_message(body)"
        end

        def process!(message)
          @message = message
          begin
            on_message( message.decode )
          rescue Exception => e
            on_error( e )
          end
        end
      end #MessageProcessor

      module Backgroundable
        extend ActiveSupport::Concern
        module ClassMethods
          def always_background(*methods)
          end
        end
      end #Backgroundable

    end #Messaging

    module Injectors
      # Look in the torquebox.yml file to map a queue name to a class
      def self.config
        @@config ||= YAML.load_file("#{Rails.root}/config/torquebox.yml")
      end

      class FakeQueue
        def initialize(klass)
          @klass = klass
        end
        def publish(msg)
          Rails.logger.info "[Queue] USING FAKE QUEUE #{@klass.name} -- PROCESSING EVENT DIRECTLY!"
          k = @klass.new
          k.on_message(msg)
        end
      end

      def fetch(queue_name)
        klass = Injectors.config['messaging'][queue_name].constantize
        FakeQueue.new(klass)
      end
      alias_method :inject, :fetch
      alias_method :__inject__, :fetch
    end #Injectors

  end #TorqueBox

  # Mixin to all AR models
  ActiveRecord::Base.send(:include, TorqueBox::Messaging::Backgroundable)

end