Active Record Query Caching with Sinatra

Sinatra is awesome, but Rails has a lot of useful features. One of those is Active Record’s Query Caching. I never realized how useful this is until I started to optimize Sinatra apps and felt its absence. Here is a simple way to enable active record query caching in Sinatra.

# ActiveRecord refuses to enable query caching _unless_ you have the following setup
#   1) you _must_ use ActiveRecord::Base.configurations to store your auth details
#   2) you _must_ include the ActiveRecord::QueryCache middleware
#   3) you _must_ inherit from the _Base_ connection -- abstract models don't 
#       cache without a bit of hacking, it only query caches anything from AR::Base

require 'sinatra'
require 'active_record'

# query caching requires that you use AR::Base.configurations to store your
# auth info, otherwise it won't work.
ActiveRecord::Base.configurations = {
  'development' => {
    :adapter => 'mysql',
    :username => 'root',
    :password => '',
    :database => 'mysql'
  },
  'production' => {
    :adapter => 'mysql',
    :username => 'produser',
    :password => 'prodpasswd',
    :database => 'mysql'
  }
}

# establish connection to the db in your environment file
ActiveRecord::Base.establish_connection('development')

# we also need a logger to work properly
ActiveRecord::Base.logger = Logger.new(STDOUT)

# make sure we're using the QueryCache middleware
use ActiveRecord::QueryCache

# make sure our model is inheriting from AR::Base
class User < ActiveRecord::Base
  set_table_name 'user'
end

# run a test to make sure we are actually caching
# You should see:
#   User Load (0.2ms)   SELECT * FROM `user` LIMIT 1
#   CACHE (0.0ms)   SELECT * FROM `user` LIMIT 1
#   ...
get '/' do
  10.times{ User.first }
end

View Gist