Skip to content

Instantly share code, notes, and snippets.

@robhurring

robhurring/app.rb

Created Nov 23, 2010
Embed
What would you like to do?
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
You can’t perform that action at this time.