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

Snippets has posted 5883 posts at DZone. View Full User Profile

Marshalize (Cache) ActiveRecord Query Results

01.30.2008
| 6254 views |
  • submit to reddit
        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