Class: Servent::EventSource

Inherits:
Object
  • Object
show all
Defined in:
lib/servent/event_source.rb

Constant Summary collapse

DEFAULT_HEADERS =
{ "Accept" => "text/event-stream" }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, net_http_options: { read_timeout: 600 }) {|@proxy_config| ... } ⇒ EventSource

Returns a new instance of EventSource.

Yields:

  • (@proxy_config)


11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/servent/event_source.rb', line 11

def initialize(url, net_http_options: { read_timeout: 600 })
  @uri              = URI(url)
  @net_http_options = net_http_options
  @ready_state      = Servent::CONNECTING

  @open_blocks    = []
  @message_blocks = []
  @error_blocks   = []

  @proxy_config = ProxyConfig.new
  yield @proxy_config if block_given?
end

Instance Attribute Details

#ready_stateObject (readonly)

Returns the value of attribute ready_state.



9
10
11
# File 'lib/servent/event_source.rb', line 9

def ready_state
  @ready_state
end

#uriObject (readonly)

Returns the value of attribute uri.



9
10
11
# File 'lib/servent/event_source.rb', line 9

def uri
  @uri
end

Instance Method Details

#closeObject



43
44
45
46
# File 'lib/servent/event_source.rb', line 43

def close
  @ready_state = Servent::CLOSED
  @thread.kill unless @thread.nil?
end

#listen(http_starter = Net::HTTP) ⇒ Object



39
40
41
# File 'lib/servent/event_source.rb', line 39

def listen(http_starter = Net::HTTP)
  start(http_starter).join
end

#on_error(&error_block) ⇒ Object



56
57
58
# File 'lib/servent/event_source.rb', line 56

def on_error(&error_block)
  @error_blocks << error_block
end

#on_message(&message_block) ⇒ Object



52
53
54
# File 'lib/servent/event_source.rb', line 52

def on_message(&message_block)
  @message_blocks << message_block
end

#on_open(&open_block) ⇒ Object



48
49
50
# File 'lib/servent/event_source.rb', line 48

def on_open(&open_block)
  @open_blocks << open_block
end

#start(http_starter = Net::HTTP) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/servent/event_source.rb', line 24

def start(http_starter = Net::HTTP)
  @http_starter ||= http_starter
  params = HTTPStartParams.new(@uri, @proxy_config, @net_http_options)

  @thread = Thread.new {
    @http_starter.start(*params.parameterize) do |http|
      get = Net::HTTP::Get.new @uri
      DEFAULT_HEADERS.each { |header, value| get[header] = value }
      yield http, get if block_given?

      perform_request http, get
    end
  }
end