Apr 16 2008

Non blocking merb actions

One of the most powerful features in merb is an action's ability to return a proc, thus releasing the controller block and transferring control to the application server which will be able to handle requests in a parallel manner.

Consider the following controller.

class MyController < Application
  def hello
    render "hello"
  end

  def wait_and_hello
    sleep 10
    render "hello"
  end

  def dont_wait_to_hello
    proc { sleep 10; p "hello" }
  end
end

Start merb and access http://localhost:4000/my_controller/hello after visiting http://localhost:4000/my_controller/wait_and_hello. Ten seconds will pass before /my_controller/hello is served. A request to /my_controller/hello will be served immediately regardless of whether a preceding request to /my_controller/dont_wait_to_hello has completed.