Class: Nanoc3::Extra::AutoCompiler

Inherits:
Object
  • Object
show all
Defined in:
lib/nanoc3/extra/auto_compiler.rb

Overview

A web server that will automatically compile items as they are requested. It also serves static files such as stylesheets and images.

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (AutoCompiler) initialize(site_path)

Creates a new autocompiler for the given site.

Parameters:

  • site_path (String)

    The path to the site to autocompile



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/nanoc3/extra/auto_compiler.rb', line 15

def initialize(site_path)
  require 'rack'
  require 'mime/types'

  # Set site
  @site_path = site_path

  # Create mutex to prevent parallel requests
  require 'thread'
  @mutex = Mutex.new
end

Instance Attribute Details

- (Nanoc3::Site) site (readonly)

The site this autocompiler belongs to

Returns:



10
11
12
# File 'lib/nanoc3/extra/auto_compiler.rb', line 10

def site
  @site
end

Instance Method Details

- (Array) call(env)

Calls the autocompiler. The behaviour of this method is defined by the Rack specification.

body, as defined by the Rack specification

Parameters:

  • env (Hash)

    The environment, as defined by the Rack specification

Returns:

  • (Array)

    An array containing the status, the headers, and the



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/nanoc3/extra/auto_compiler.rb', line 34

def call(env)
  @mutex.synchronize do
    # Start with a new site
    build_site

    # Find rep
    path = Rack::Utils::unescape(env['PATH_INFO'])
    reps = site.items.map { |i| i.reps }.flatten
    rep = reps.find do |r|
      r.path == path ||
        r.raw_path == site.config[:output_dir] + path
    end

    # Recompile rep
    site.compiler.run(rep.item) if rep

    # Get paths by appending index filenames
    if path =~ /\/$/
      possible_paths = site.config[:index_filenames].map { |f| path + f }
    else
      possible_paths = [ path ]
    end

    # Find matching file
    modified_path = possible_paths.find { |f| File.file?(site.config[:output_dir] + f) }
    modified_path ||= path

    # Serve using Rack::File
    puts "*** serving file #{modified_path}"
    res = file_server.call(env.merge('PATH_INFO' => modified_path))
    puts "*** done serving file #{modified_path}"
    res
  end
rescue StandardError, ScriptError => e
  # Add compilation stack to env
  env['nanoc.stack'] = []
  site.compiler.stack.reverse.each do |obj|
    if obj.is_a?(Nanoc3::ItemRep) # item rep
      env['nanoc.stack'] << "[item] #{obj.item.identifier} (rep #{obj.name})"
    else # layout
      env['nanoc.stack'] << "[layout] #{obj.identifier}"
    end
  end

  # Re-raise error
  raise e
end