Wednesday 14 February 2007

ruby caching

Is so easy.

Drop the following in your environment.rb


module ActionView::Helpers::CacheHelper
  def cache(name = {}, options = nil, &block)
    @controller.cache_erb_fragment(block, name, options)
  end
end

class ActionController::Caching::Fragments::UnthreadedFileStore
  def read(name, options = nil)
    if options.is_a?(Hash) && options.has_key?(:ttl)
      ttl = options[:ttl]
    else
      ttl = 0
    end

    fn = real_file_path(name)

    # if cache expired act as if file doesn't exist
    return if ttl > 0 && File.exists?(fn) && (File.mtime(fn) < (Time.now - ttl))
    File.open(fn, 'rb') { f f.read } rescue nil
  end
end


And you can cache with ttl in views selectively:

<% cache("some_name", :ttl => x.minutes or hours or days) do -%>Heavy old content<% end %>

Of course, you can always manually expire content too:

expire_action :action => 'action_that_created_the_content'

This is not my own work. I found it and just wanted to share!

No comments: