File: livereload.rb

package info (click to toggle)
ruby-rack-livereload 0.3.17%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 216 kB
  • sloc: javascript: 973; ruby: 470; makefile: 4
file content (53 lines) | stat: -rw-r--r-- 1,315 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
require 'erb'
require 'rack/livereload/processing_skip_analyzer'
require 'rack/livereload/body_processor'

module Rack
  class LiveReload
    attr_reader :app

    def initialize(app, options = {})
      @app, @options = app, options
    end

    def call(env)
      dup._call(env)
    end

    def _call(env)
      _, path, file = (env['PATH_INFO'] || '').split('/')

      if path == '__rack' && ::File.file?(target = ::File.expand_path("../../../js/#{file}", __FILE__))
        deliver_file(target)
      else
        status, headers, body = result = @app.call(env)

        return result if ProcessingSkipAnalyzer.skip_processing?(result, env, @options)

        processor = BodyProcessor.new(body, @options)
        processor.process!(env)

        headers['Content-Length'] = processor.content_length.to_s

        if processor.livereload_added
          headers['X-Rack-LiveReload'] = '1'
        end

        [ status, headers, processor.new_body ]
      end
    end

    private
    def deliver_file(file)
      type = case ::File.extname(file)
             when '.js'
               'text/javascript'
             when '.swf'
               'application/swf'
             end

      [ 200, { 'Content-Type' => type, 'Content-Length' => ::File.size(file).to_s }, [ ::File.read(file) ] ]
    end
  end
end