Marshalize (Cache) ActiveRecord Query Results
Join the DZone community and get the full member experience.Join For Free
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