class Guard::LiveReload::WebSocket

Constants

HTTP_DATA_FORBIDDEN
HTTP_DATA_NOT_FOUND

Public Class Methods

new(options) click to toggle source
Calls superclass method
# File lib/guard/livereload/websocket.rb, line 12
def initialize(options)
  @livereload_js_path = options[:livereload_js_path]
  super
end

Public Instance Methods

dispatch(data) click to toggle source
Calls superclass method
# File lib/guard/livereload/websocket.rb, line 17
def dispatch(data)
  parser = Http::Parser.new
  parser << data
  # prepend with '.' to make request url usable as a file path
  request_path = '.' + URI.parse(parser.request_url).path
  request_path += '/index.html' if File.directory? request_path
  if parser.http_method != 'GET' || parser.upgrade?
    super # pass the request to websocket
  else
    _serve(request_path)
  end
end

Private Instance Methods

_content_type(path) click to toggle source
# File lib/guard/livereload/websocket.rb, line 46
def _content_type(path)
  case File.extname(path).downcase
  when '.html', '.htm' then 'text/html'
  when '.css' then 'text/css'
  when '.js' then 'application/ecmascript'
  when '.gif' then 'image/gif'
  when '.jpeg', '.jpg' then 'image/jpeg'
  when '.png' then 'image/png'
  else; 'text/plain'
  end
end
_livereload_js_path() click to toggle source
# File lib/guard/livereload/websocket.rb, line 58
def _livereload_js_path
  @livereload_js_path
end
_readable_file(path) click to toggle source
# File lib/guard/livereload/websocket.rb, line 69
def _readable_file(path)
  File.readable?(path) && !File.directory?(path)
end
_serve(path) click to toggle source
# File lib/guard/livereload/websocket.rb, line 62
def _serve(path)
  return _serve_file(_livereload_js_path) if path == './livereload.js'
  data = _readable_file(path) ? HTTP_DATA_FORBIDDEN : HTTP_DATA_NOT_FOUND
  send_data(data)
  close_connection_after_writing
end
_serve_file(path) click to toggle source
# File lib/guard/livereload/websocket.rb, line 32
def _serve_file(path)
  UI.debug "Serving file #{path}"

  data = [
    'HTTP/1.1 200 OK',
    'Content-Type: %s',
    'Content-Length: %s',
    '',
    '']
  data = format(data * "\r\n", _content_type(path), File.size(path))
  send_data(data)
  stream_file_data(path).callback { close_connection_after_writing }
end