Class: Linner::Reactor

Inherits:
Reel::Server::HTTP
  • Object
show all
Includes:
Celluloid
Defined in:
lib/linner/reactor.rb

Defined Under Namespace

Classes: Client

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host = "127.0.0.1", port = 35729) ⇒ Reactor

Returns a new instance of Reactor.



12
13
14
15
# File 'lib/linner/reactor.rb', line 12

def initialize(host = "127.0.0.1", port = 35729)
  @clients = []
  super(host, port, &method(:on_connection))
end

Instance Attribute Details

#clientsObject

Returns the value of attribute clients.



10
11
12
# File 'lib/linner/reactor.rb', line 10

def clients
  @clients
end

Instance Method Details

#on_connection(connection) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/linner/reactor.rb', line 17

def on_connection(connection)
  while request = connection.request
    if request.websocket?
      connection.detach
      route_websocket request.websocket
      return
    else
      route_request connection, request
    end
  end
end

#reload_browser(paths = []) ⇒ Object



63
64
65
66
67
# File 'lib/linner/reactor.rb', line 63

def reload_browser(paths = [])
  paths.each do |path|
    @clients.each {|c| c.notify_asset_change path }
  end
end

#route_request(connection, request) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/linner/reactor.rb', line 29

def route_request(connection, request)
  if request.url.start_with? "/livereload.js"
    return connection.respond :ok, {"Content_Type" => 'application/ecmascript'}, File.read(File.join(File.dirname(__FILE__), "../../vendor", "livereload.js"))
  end

  path = File.join(Linner.environment.public_folder, request.url[1..-1])
  if File.exist?(path)
    content_type = case File.extname(path)
    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
    return connection.respond :ok, {"Content_Type" => content_type, "Content_Length" => File.size(path)}, File.read(path)
  end

  connection.respond :not_found, "Not found"
end

#route_websocket(socket) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/linner/reactor.rb', line 50

def route_websocket(socket)
  socket << JSON.generate({
    :command    => 'hello',
    :protocols  => ['http://livereload.com/protocols/official-7'],
    :serverName => 'reel-livereload'
  })
  if socket.url == "/livereload"
    @clients << Client.new(socket)
  else
    socket.close
  end
end