rack-livereload/lib/rack/livereload.rb

84 lines
2.2 KiB
Ruby
Raw Normal View History

2011-11-04 15:51:22 +00:00
module Rack
class LiveReload
LIVERELOAD_JS_PATH = '/__rack/livereload.js'
LIVERELOAD_LOCAL_URI = 'http://localhost:35729/livereload.js'
2011-11-04 15:51:22 +00:00
attr_reader :app
def initialize(app, options = {})
2011-11-04 15:51:22 +00:00
@app = app
@options = options
2011-11-04 15:51:22 +00:00
end
def use_vendored?
return @use_vendored if @use_vendored
if @options[:source]
@use_vendored = (@options[:source] == :vendored)
else
require 'net/http'
require 'uri'
uri = URI.parse(LIVERELOAD_LOCAL_URI)
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = 1
begin
http.send_request('GET', uri.path)
@use_vendored = false
rescue Timeout::Error, Errno::ECONNREFUSED
@use_vendored = true
end
end
@use_vendored
end
2011-11-04 15:51:22 +00:00
def call(env)
if env['PATH_INFO'] == LIVERELOAD_JS_PATH
deliver_file(::File.expand_path('../../../js/livereload.js', __FILE__))
else
status, headers, body = @app.call(env)
case headers['Content-Type']
when %r{text/html}
2011-11-07 13:49:42 +00:00
content_length = 0
2011-11-04 15:51:22 +00:00
body.each do |line|
2011-11-07 13:49:42 +00:00
if !headers['X-Rack-LiveReload'] && line['</head>']
host_to_use = @options[:host] || env['HTTP_HOST'].gsub(%r{:.*}, '')
if use_vendored?
src = LIVERELOAD_JS_PATH.dup + "?host=#{host_to_use}"
else
src = LIVERELOAD_LOCAL_URI.dup.gsub('localhost', host_to_use) + '?'
end
src << "&mindelay=#{@options[:min_delay]}" if @options[:min_delay]
src << "&maxdelay=#{@options[:max_delay]}" if @options[:max_delay]
src << "&port=#{@options[:port]}" if @options[:port]
2011-11-04 15:51:22 +00:00
line.gsub!('</head>', %{<script type="text/javascript" src="#{src}"></script></head>})
2011-11-07 13:41:51 +00:00
2011-11-07 13:49:42 +00:00
headers["X-Rack-LiveReload"] = '1'
2011-11-04 15:51:22 +00:00
end
2011-11-07 13:49:42 +00:00
content_length += line.length
2011-11-04 15:51:22 +00:00
end
2011-11-07 13:49:42 +00:00
headers['Content-Length'] = content_length.to_s
2011-11-04 15:51:22 +00:00
end
[ status, headers, body ]
end
end
private
def deliver_file(file)
[ 200, { 'Content-Type' => 'text/javascript', 'Content-Length' => ::File.size(file).to_s }, [ ::File.read(file) ] ]
end
end
end