Sha256: 1ef17218f215810130412c0659bdb06eae4a789609de0f533a56cea0875c635d

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 KB

Contents

require 'rack'
require 'listen'

module Flutterby
  class Server
    def initialize(root, port: 4004)
      @root = root
      @port = port
    end

    def run!
      # Set up listener
      listener = Listen.to(@root.fs_path) do |modified, added, removed|
        # puts "modified absolute path: #{modified}"
        # puts "added absolute path: #{added}"
        # puts "removed absolute path: #{removed}"

        Flutterby.logger.info "Change detected, reloading everything!"
        @root.reload!
      end

      # Set up server
      server = Rack::Handler::WEBrick

      # Make sure we handle interrupts correctly
      trap('INT') do
        listener.stop
        server.shutdown
      end

      # Go!
      listener.start
      server.run self, Port: @port, Logger: Flutterby.logger
    end

    def call(env)
      req  = Rack::Request.new(env)
      res = Rack::Response.new([], 200, {})

      # Look for target node in path registry
      if node = find_node_for_path(req.path)
        # Determine MIME type
        mime_type = MIME::Types.type_for(node.ext) || "text/plain"

        # Build response
        res.headers["Content-Type"] = mime_type
        res.body = [node.render]
      else
        res.status = 404
        res.headers["Content-Type"] = "text/html"
        res.body = ["404"]
      end

      res
    end

    def find_node_for_path(path)
      @root.paths[path] ||
      @root.paths[path + ".html"] ||
      @root.paths[::File.join(path, "index.html")]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
flutterby-0.0.15 lib/flutterby/server.rb
flutterby-0.0.14 lib/flutterby/server.rb