class Closure::Server

The Closure Script rack server. There is {Closure::Middleware} available too. @example config.ru

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

Public Class Methods

new(sources, home_page = nil) click to toggle source

@param (Sources) sources An instance configured with your scripts. @param (home_page) home_page Optional file or closure-script to serve as root.

# File lib/closure/server.rb, line 29
def initialize(sources, home_page = nil)
  @sources = sources
  @home_page = home_page
  @working_dir = Dir.getwd
end

Public Instance Methods

call(env) click to toggle source

Rack interface. @param (Hash) env Rack environment. @return (Array)[status, headers, body]

# 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

Private Instance Methods

not_found() click to toggle source

Status 404 with X-Cascade => pass. @return (Array)[status, headers, body]

# File lib/closure/server.rb, line 82
def not_found
  return @not_found if @not_found
  body = "404 Not Found\n"
  @not_found = [404, {'Content-Type' => 'text/plain',
         'Content-Length' => body.size.to_s,
         'X-Cascade' => 'pass'},
   [body]]
  @not_found
end