DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Marshalize (Cache) ActiveRecord Query Results
A quick way to cache results in a file and read from the file on subsequent requests instead of the database. Makes the initial query a bit slower, but later queries *much* faster.
class MyCachedModel < ActiveRecord::Base class << self alias_method :rails_original_find_by_sql, :find_by_sql def find_by_sql(sql) cache_filename = Base64.encode64(sql) if File.exists? cache_filename Marshal.load(File.open(cache_filename)) else Marshal.dump(records = rails_original_find_by_sql(sql), File.open(cache_filename, 'w')) return records end end end end