Skip to content

Instantly share code, notes, and snippets.

@bastos
Created January 9, 2009 20:37
Show Gist options
  • Save bastos/45273 to your computer and use it in GitHub Desktop.
Save bastos/45273 to your computer and use it in GitHub Desktop.
Render for Sinatra using markaby and with cache.
require "rubygems"
require "sinatra"
require "render"
Sinatra::EventContext.send :include, Render
SVN_REPO_PATH = "/home/tiago/projects/repo/trunk"
get "/" do
render :cache => true, :expire => 60 do
head {
title "SVN WATCH"
style "body {
background-color:#f7fcff;
font-family:arial;
padding:30px;
}
pre {
background-color:#fff;
padding:10px;
border-top:1px solid #333;
border-bottom:1px solid #333;
}
", :type => "text/css"
}
body do
h1 "Watch #{SVN_REPO_PATH} - Last update #{Time.now}"
h2 "HEAD LOG"
pre `svn log --revision HEAD #{SVN_REPO_PATH}`
h2 "DIFF PREV:HEAD"
pre `svn diff --revision HEAD #{SVN_REPO_PATH}`
end
end
end
get "/test" do
render :cache => true, :expire => 10 do
h1 "Last update at: #{Time.now}"
end
end
require "markaby"
require "fileutils"
# Render/Cache system for Sinatra with Markaby.
module Render
# Will receive a block and render with Markaby.
# Cache options:
# * cache - Boolean.
# * Expire - Number (seconds).
# Example:
# require "rubygems"
# require "sinatra"
# require "markaby"
# require "fileutils"
# require "markaby"
# Sinatra::EventContext.send :include, Render
# get "/"
# render :cache => true, :expire => 10 do
# h1 "Last update at: #{Time.now}"
# end
# end
def render(options={:cache => false, :expire => 60 }, &block)
mab = Markaby::Builder.new
uri = request.env["REQUEST_URI"] == "/" ? 'index' : request.env["REQUEST_URI"]
uri << '.html'
path = File.join(File.dirname(__FILE__), 'cache', uri)
if File.exists?(path) and options[:cache]
File.unlink(path) if Time.now > (File.ctime(path) + options[:expire])
end
if File.exists?(path) and options[:cache]
File.open(path, 'r').readlines
else
content = mab.html(&block)
if options[:cache]
FileUtils.mkdir_p(File.dirname(path)) unless File.exists?(File.dirname(path))
File.open(path, 'w') { |f| f.write( content ) }
end
content
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment