Sha256: f1a3e83816ef2d511afbf1542c92af5dbc4ab7227ada4c8db5b49288925c8b32

Contents?: true

Size: 1.95 KB

Versions: 8

Compression:

Stored size: 1.95 KB

Contents

require 'rack/request'
require 'rack/response'
require 'rack/file'

module HtmlMockup
  module Rack
    class HtmlMockup
      def initialize(root,partial_path)
        @docroot = root
        @partial_path = partial_path
        @file_server = ::Rack::File.new(@docroot)
      end

      def call(env)
        path = env["PATH_INFO"]
        
        # Append index.html/index.htm/index.rhtml if it's a diretory
        if File.directory?(File.join(@docroot,path))
          search_files = %w{.html .htm .rhtml}.map!{|p| File.join(@docroot,path,"index#{p}")}
        # If it's already a .html/.htm/.rhtml file, render that file
        elsif (path =~ /\.r?html?$/)
          search_files = [File.join(@docroot,path)]
        # If it ends with a slash or does not contain a . and it's not a directory
        # try to add .html/.htm/.rhtml to see if that exists.
        elsif (path =~ /\/$/) || (path =~ /^[^.]+$/)
          search_files = [path + ".html", path + ".htm", path + ".rhtml"].map!{|p| File.join(@docroot,p) }
        # Otherwise don't render anything at all.
        else
          search_files = []
        end

        if template_path = search_files.find{|p| File.exist?(p)}
          env["rack.errors"].puts "Rendering template #{template_path.inspect} (#{path.inspect})"
          begin
            templ = ::HtmlMockup::Template.open(template_path, :partial_path => @partial_path)
            resp = ::Rack::Response.new do |res|
              res.status = 200
              res.write templ.render
            end
            resp.finish
          rescue StandardError => e
            env["rack.errors"].puts "  #{e.message}"
            resp = ::Rack::Response.new do |res|
              res.status = 500
              res.write "An error occurred"
            end
            resp.finish
          end
        else
          env["rack.errors"].puts "Invoking file handler for #{path.inspect}"
          @file_server.call(env)
        end
      end    
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
flurin-html_mockup-0.1.2 lib/html_mockup/rack/html_mockup.rb
flurin-html_mockup-0.2.0 lib/html_mockup/rack/html_mockup.rb
flurin-html_mockup-0.3.0 lib/html_mockup/rack/html_mockup.rb
flurin-html_mockup-0.3.1 lib/html_mockup/rack/html_mockup.rb
html_mockup-0.4.0 lib/html_mockup/rack/html_mockup.rb
html_mockup-0.3.5 lib/html_mockup/rack/html_mockup.rb
html_mockup-0.3.4 lib/html_mockup/rack/html_mockup.rb
html_mockup-0.3.2 lib/html_mockup/rack/html_mockup.rb