Skip to content

Instantly share code, notes, and snippets.

@carlosipe
Forked from alfanick/cache.rb
Last active August 29, 2015 14:08
Show Gist options
  • Save carlosipe/ecd3b050a36b85e11e33 to your computer and use it in GitHub Desktop.
Save carlosipe/ecd3b050a36b85e11e33 to your computer and use it in GitHub Desktop.
# Amadeusz Juskowiak <[email protected]> 2012 - MIT License
# 1. Put inside helpers do .. end
# 2. Set CACHE_DIR to somewhere writable and private (like CACHE_DIR=File.dirname(__FILE__) + '/tmp'
# 3. Use it! You can use fragment_expire to remove cache with given name.
#
# Example:
# %h1 foo
# = cache_fragment(:report, 300) do
# - data = get_data_slowly
# %h2 my super extensive table generation
#
# In example above, block will be cached for 300 seconds.
#
# Remember:
# Cache entries are identified only by their name - so no matter where you access your
# :report it will be the same report! This means you have to be careful with sensible data.
# If you want cache different data in same view use something like
# "#{@user._id}/#{@basket._id}" as a key.
#
# Have fun!
def cache_fragment(name, expires, &haml)
filename = CACHE_DIR + '/' + name.to_s + '.cache'
now = Time.now
result = 'Cache Error!'
needs_caching = true
if File.file? filename
if (((now - File.mtime(filename)).to_i) >= expires)
needs_caching = true
else
needs_caching = false
result = File.read(filename)
end
end
if needs_caching
f = File.new(filename, 'w')
f.write(result = capture_haml(&haml))
f.close
end
result
end
def fragment_expire(name)
filename = CACHE_DIR + '/' + name.to_s + '.cache'
if File.file? filename
File.unlink filename rescue (return false)
return true
end
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment