Class: Middleman::LiveReload::Reactor

Inherits:
Object
  • Object
show all
Defined in:
lib/middleman-livereload/reactor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, app) ⇒ Reactor

Returns a new instance of Reactor.



9
10
11
12
13
14
15
# File 'lib/middleman-livereload/reactor.rb', line 9

def initialize(options, app)
  @app = app
  @web_sockets = []
  @options     = options
  @thread      = start_threaded_reactor(options)
  @mutex       = Thread::Mutex.new
end

Instance Attribute Details

#appObject

Returns the value of attribute app.



7
8
9
# File 'lib/middleman-livereload/reactor.rb', line 7

def app
  @app
end

#threadObject (readonly)

Returns the value of attribute thread.



7
8
9
# File 'lib/middleman-livereload/reactor.rb', line 7

def thread
  @thread
end

#web_socketsObject (readonly)

Returns the value of attribute web_sockets.



7
8
9
# File 'lib/middleman-livereload/reactor.rb', line 7

def web_sockets
  @web_sockets
end

Instance Method Details

#loggerObject



21
22
23
# File 'lib/middleman-livereload/reactor.rb', line 21

def logger
  @mutex.synchronize { @app.logger }
end

#reload_browser(paths = []) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/middleman-livereload/reactor.rb', line 29

def reload_browser(paths = [])
  paths = Array(paths)
  logger.info "== LiveReloading path: #{paths.join(' ')}"
  paths.each do |path|
    data = JSON.dump(['refresh', {
      :path           => path,
      :apply_js_live  => @options[:apply_js_live],
      :apply_css_live => @options[:apply_css_live]
    }])

    @web_sockets.each { |ws| ws.send(data) }
  end
end

#start_threaded_reactor(options) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/middleman-livereload/reactor.rb', line 43

def start_threaded_reactor(options)
  Thread.new do
    EventMachine.run do
      logger.info "== LiveReload accepting connections from ws://#{options[:host]}:#{options[:port]}"
      EventMachine.start_server(options[:host], options[:port], EventMachine::WebSocket::Connection, {}) do |ws|
        ws.onopen do
          begin
            ws.send "!!ver:1.6"
            @web_sockets << ws
            logger.debug "== LiveReload browser connected"
          rescue
            logger.error $!
            logger.error $!.backtrace
          end
        end

        ws.onmessage do |msg|
          logger.debug "LiveReload Browser URL: #{msg}"
        end

        ws.onclose do
          @web_sockets.delete ws
          logger.debug "== LiveReload browser disconnected"
        end
      end
    end
  end
end

#stopObject



25
26
27
# File 'lib/middleman-livereload/reactor.rb', line 25

def stop
  thread.kill
end