Never been to DZone Snippets before?

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

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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.

   1  
   2  class MyCachedModel < ActiveRecord::Base
   3    class << self
   4      alias_method :rails_original_find_by_sql, :find_by_sql
   5      def find_by_sql(sql)
   6        cache_filename = Base64.encode64(sql)
   7        if File.exists? cache_filename
   8          Marshal.load(File.open(cache_filename))
   9        else
  10          Marshal.dump(records = rails_original_find_by_sql(sql), File.open(cache_filename, 'w'))
  11          return records
  12        end
  13      end
  14    end
  15  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS