Blogdth

Jan 17

Sinatra with ActiveRecord and MySQL

I’m working on a little Sinatra project that uses ActiveRecord to access a MySQL database.  Funny thing, every fifth request or so would take a long time.  I’d just as well sit there and wait; but you wouldn’t, so I figured it out.

Son of a bitch, ActiveRecord’s connection pool.  In a Rails app, ActionPack’s request handling life cycle calls ActiveRecord::Base.clear_active_connections! to return connections to the pool. Not so in Sinatra.

Sinatra has before filters but not after filters, so it’ll have to be a Rack solution.  So simple, it isn’t even worth a gem.  I stuck this at the top of my Sinatra app:

  class Crack
    def initialize(app)
      @app = app
    end

    def call(env)
      response = @app.call(env)
      ActiveRecord::Base.clear_active_connections!
      response
    end
  end

  use Crack

Page 1 of 1