Skip to content

Instantly share code, notes, and snippets.

@robhurring
Created November 23, 2010 17:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robhurring/712114 to your computer and use it in GitHub Desktop.
Save robhurring/712114 to your computer and use it in GitHub Desktop.
ActiveRecord query caching with 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment