require 'webrick' module Nanoc class AutoCompiler ERROR_404 = < 404 File Not Found

404 File Not Found

The file you requested, <%=h path %>, was not found on this server.

END ERROR_500 = < 500 Server Error

500 Server Error

An error occurred while compiling the page you requested, <%=h path %>.

If you think this is a bug in nanoc, please do report it—thanks!

Message:

<%=h exception.message %>

Backtrace:

    <% exception.backtrace.each do |line| %>
  1. <%= line %>
  2. <% end %>
END def initialize(site) # Set site @site = site end def start(port) nanoc_require('mime/types', "'mime/types' is required to autocompile sites.") # Create server @server = WEBrick::HTTPServer.new(:Port => port || 3000) @server.mount_proc("/") { |request, response| handle_request(request, response) } # Start server trap('INT') { @server.shutdown } @server.start end def handle_request(request, response) # Reload site data @site.load_data(true) # Get page or file page = @site.pages.find { |page| page.path == request.path } file_path = @site.config[:output_dir] + request.path if page.nil? # Serve file if File.file?(file_path) serve_file(file_path, response) else serve_404(request.path, response) end else # Serve page serve_page(page, response) end end def h(s) ERB::Util.html_escape(s) end def serve_404(path, response) response.status = 404 response['Content-Type'] = 'text/html' response.body = ERB.new(ERROR_404).result(binding) end def serve_500(path, exception, response) response.status = 500 response['Content-Type'] = 'text/html' response.body = ERB.new(ERROR_500).result(binding) end def serve_file(path, response) response.status = 200 response['Content-Type'] = MIME::Types.of(path).first || 'application/octet-stream' response.body = File.read(path) end def serve_page(page, response) # Recompile page begin @site.compiler.run(page) rescue => exception serve_500(page.path, exception, response) return end # Determine most likely MIME type mime_type = MIME::Types.of(page.path).first mime_type = mime_type.nil? ? 'text/html' : mime_type.simplified response.status = 200 response['Content-Type'] = mime_type response.body = page.layouted_content end end end