Sha256: 276da3b0d54fd17acb29331ec019d89338f2483a102d68353da4daab6644012d

Contents?: true

Size: 1.99 KB

Versions: 1

Compression:

Stored size: 1.99 KB

Contents

require 'multi_json'

module Guard
  class LiveReload
    class Reactor
      attr_reader :web_sockets, :thread, :options

      def initialize(options)
        @web_sockets = []
        @options     = options
        @thread      = start_threaded_reactor(options)
      end

      def stop
        thread.kill
      end

      def reload_browser(paths = [])
        UI.info "Reloading browser: #{paths.join(' ')}"
        paths.each do |path|
          data = {
            :command  => 'reload',
            :path     => "#{Dir.pwd}/#{path}",
            :liveCSS  => @options[:apply_css_live]
          }
          if options[:override_url] && File.exist?(path)
            data[:overrideURL] = '/' + path
          end
          UI.debug data
          web_sockets.each { |ws| ws.send(MultiJson.encode(data)) }
        end
      end

    private

      def start_threaded_reactor(options)
        Thread.new do
          EventMachine.run do
            UI.info "LiveReload is waiting for a browser to connect."
            EventMachine.start_server(options[:host], 35729, WebSocket, {}) do |ws|
              ws.onopen do
                begin
                  UI.info "Browser connected."
                  ws.send MultiJson.encode({
                    :command    => 'hello',
                    :protocols  => ['http://livereload.com/protocols/official-7'],
                    :serverName => 'guard-livereload'
                  })
                  @web_sockets << ws
                rescue
                  UI.errror $!
                  UI.errror $!.backtrace
                end
              end

              ws.onmessage do |msg|
                msg = MultiJson.decode(msg)
                if msg['command'] == 'url'
                  UI.info "Browser URL: #{msg['url']}"
                end
              end

              ws.onclose do
                @web_sockets.delete(ws)
                UI.info "Browser disconnected."
              end
            end
          end
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
guard-livereload-1.2.0 lib/guard/livereload/reactor.rb