bastos (owner)

Revisions

gist: 45273 Download_button fork
public
Description:
Render for Sinatra using markaby and with cache.
Public Clone URL: git://gist.github.com/45273.git
Embed All Files: show embed
example.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
render.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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