There are a lot of resources on the Internet showing how to write and run a standalone rack application or middleware, but few showing how to write one to run in other Merb applications. This is actually very easy, so I’m going to share how I did it. Hopefully to be helpful to people in such need.
The goal is to have a rack middleware in a merb application, which can be installed as gem, and then can be ued in other merb applications.
First, create the merb application:
$ merb-gen app application_name
where application_name is your proposed application name.
Second, create your code folder and ruby file. I created a “lib” folder to be the container of my middlewares.
Third, open the ruby file and write your middleware. (In this example, let’s name it samplemiddleware.rb within the “lib/test” folder)
The class could inherit Merb::Rack::Middleware if you want. Below is an example.
module Test
class SampleMiddleware < Merb::Rack::Middleware
def initialize(app)
@app = app
end
def deferred?(env)
@app.deferred?(env) if @app.respond_to?(:deferred?)
end
def call(env)
puts “do something here”
@app.call(env)
end
end
end
Fourth, write your rake file, so the rack middleware merb application can be installed as a gem.
Fifth, install the gem.
So far we finished the middleware, now we go to the other merb application which we want the middleware to run within. Assuming the merb application has a rack configuration file (rack.rb) under the “config” folder. Open this file.
We need to require our middleware, in this case:
require 'test/samplemiddleware.rb''
And then use the middleware in the same file:
use Test::SampleMiddleware
Finally remember to have a line to run the Merb::Rack application (should already have it):
run Merb::Rack::Application.new
Now when the merb application runs, the rack middleware you wrote and installed will run as well. It’s handy to use the middleware to process requests in your Merb applications before Merb handles the requests.