Class: Closure::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/closure/server.rb

Overview

The Closure Script rack server. There is Middleware available too.

Examples:

config.ru

require 'closure'
sources = Closure::Sources.new
sources.add '/myapp', '../src'
run Closure::Server.new sources

Instance Method Summary (collapse)

Constructor Details

- (Server) initialize(sources, home_page = nil)

Returns a new instance of Server

Parameters:

  • sources (Sources)

    An instance configured with your scripts.

  • home_page (home_page) (defaults to: nil)

    Optional file or closure-script to serve as root.



29
30
31
32
33
# File 'lib/closure/server.rb', line 29

def initialize(sources, home_page = nil)
  @sources = sources
  @home_page = home_page
  @working_dir = Dir.getwd
end

Instance Method Details

- (Array) call(env)

Rack interface.

Parameters:

  • env (Hash)

    Rack environment.

Returns:

  • (Array)
    status, headers, body


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
# File 'lib/closure/server.rb', line 38

def call(env)
  path_info = Rack::Utils.unescape(env['PATH_INFO'])
  return not_found if path_info.include? '..' # unsafe
  # Stand-alone projects will find this useful
  if @home_page and path_info == '/'
    Dir.chdir @working_dir
    response = FileResponse.new(env, @home_page)
    response = Script.new(env, @sources, @home_page).response unless response.found?
    if response.header["X-Cascade"] == "pass"
      if ENV["CLOSURE_SCRIPT_WELCOME"]
        welcome = File.join Closure.base_path, 'scripts', 'welcome'
        response = Script.new(env, @sources, welcome).response
      end
    end
    return response.finish
  end
  # Usurp the deps.js in detected Closure Library
  begin
    if path_info == @sources.deps_js(env)
      return @sources.deps_response(File.dirname(path_info), env).finish
    end
  rescue Sources::BaseJsNotFoundError
  end
  # Then check all the sources
  @sources.each do |dir, path|
    next unless path
    if path_info =~ %r{^#{Regexp.escape(path)}(/.*|)$}
      Dir.chdir @working_dir
      filename = File.join(dir, $1)
      response = FileResponse.new(env, filename)
      if !response.found? and File.extname(path_info) == ''
        response = FileResponse.new(env, filename + '.html')
      end
      response = Script.new(env, @sources, filename).response unless response.found?
      return response.finish
    end
  end
  not_found
end