Sha256: 5c57ec1445adfc6a2bd99681140417364a6bed9eaedf81457ce4aefa47345875

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

require 'mongrel'

module StaticMatic
  class Previewer < Mongrel::HttpHandler
    def initialize(staticmatic)
      @files       = Mongrel::DirHandler.new(staticmatic.root_dir, false)
      @guard = Mutex.new
      @staticmatic = staticmatic
    end
  
    def process(request, response)
      return if response.socket.closed?
      
      path_info   = request.params[Mongrel::Const::PATH_INFO].chomp("/")
      get_or_head = %w(GET HEAD).include? request.params[Mongrel::Const::REQUEST_METHOD]
      
      # Reload(and therefore can_render?) is not thread-safe... so lame
      @guard.synchronize {
        if @staticmatic.can_render? path_info
          file_ext  = File.extname(path_info).gsub(/^\./, '')
          file_ext  = "html" if file_ext.blank?
          file_name = CGI::unescape(path_info).gsub!(/^\//, '') || ''
          begin
            response.start(200) do |head, out|
              output = @staticmatic.render(file_name)
              head[Mongrel::Const::CONTENT_TYPE] = Mongrel::DirHandler::MIME_TYPES[".#{file_ext}"] || "application/octet-stream"
              out.write(output || "")
            end
          rescue Errno::EPIPE
            response.socket.close
          end
        elsif get_or_head and @files.can_serve(path_info)
          @files.process(request, response) # try to serve static file from site dir
        end
      }
    end
    
    class << self
      # Starts the StaticMatic preview server
      def start(staticmatic)
        staticmatic = StaticMatic::Base.new(staticmatic) if staticmatic.is_a? String
        Mongrel::Configurator.new :host => StaticMatic::Config[:host] do
          puts "Running Preview of #{staticmatic.root_dir} on port #{StaticMatic::Config[:port]}"
          listener :port => StaticMatic::Config[:port] do
            uri "/", :handler => Previewer.new(staticmatic)
            uri "/favicon", :handler => Mongrel::Error404Handler.new("")
          end
          trap("INT") { stop }
          run
        end.join
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tdreyno-staticmatic-2.9.0 lib/staticmatic/previewer.rb