Class: WebFetch::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/web_fetch/client.rb

Overview

Client to be used in application code. Capable of spawning a server and interacting with it to gather requests and retrieve them

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, options = {}) ⇒ Client

Returns a new instance of Client.



7
8
9
10
11
# File 'lib/web_fetch/client.rb', line 7

def initialize(host, port, options = {})
  @host = host
  @port = port
  @process = options[:process]
end

Class Method Details

.create(host, port, options = {}) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/web_fetch/client.rb', line 13

def self.create(host, port, options = {})
  # Will block until process is responsive
  process = spawn(host, port, options)
  client = new(host, port, process: process)
  sleep 0.1 until client.alive?
  client
end

.spawn(host, port, options) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/web_fetch/client.rb', line 56

def spawn(host, port, options)
  process = build_process(host, port, options)
  process.cwd = File.join(File.dirname(__dir__), '..')
  process.io.inherit!
  process.start
  process
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
# File 'lib/web_fetch/client.rb', line 29

def alive?
  begin
    response = get('')
  rescue Faraday::ConnectionFailed
    return false
  end
  return false unless response.success?

  JSON.parse(response.body)['application'] == 'WebFetch'
end

#gather(requests) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/web_fetch/client.rb', line 40

def gather(requests)
  json = JSON.dump(requests: requests)
  response = post('gather', json)
  return nil unless response.success?

  JSON.parse(response.body, symbolize_names: true)[:requests]
end

#retrieve_by_uid(uid) ⇒ Object



48
49
50
51
52
53
# File 'lib/web_fetch/client.rb', line 48

def retrieve_by_uid(uid)
  response = get('retrieve', uid: uid)
  return nil unless response.success?

  JSON.parse(response.body, symbolize_names: true)
end

#stopObject



21
22
23
24
25
26
27
# File 'lib/web_fetch/client.rb', line 21

def stop
  # Will block until process dies
  return if @process.nil?

  @process.stop
  @process.wait
end