ActiveRecord query caching with Sinatra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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