Class: Elaios::Requester

Inherits:
Object
  • Object
show all
Defined in:
lib/elaios/requester.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Requester

Returns a new instance of Requester.



4
5
6
7
8
9
10
11
12
13
# File 'lib/elaios/requester.rb', line 4

def initialize(options={})
  @name = options[:name] || 'elaios_client'
  @logger = options[:logger] || Logger.new(STDOUT).tap { |l|
    l.progname = @name
    l.level = ENV['LOG_LEVEL'] || 'info'
  }
  @blocks = {}
  @in = Simple::Queue.new
  @out = Simple::Queue.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, args = nil, &block) ⇒ Object

Call a remote JSON-RPC method. If a block is provided, then we expect a response from the server.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/elaios/requester.rb', line 30

def method_missing(name, args=nil, &block)
  id = SecureRandom.uuid
  data = {
    'jsonrpc' => '2.0',
    'method' => name,
    'params' => args
  }
  # Only set the id if the client expects a response.
  data['id'] = id if block
  payload = JSON.dump(data)
  @logger.debug(%(method_missing payload: #{payload.inspect}))
  @out << payload
  return unless block
  @logger.debug(%(registered block for id #{id}: #{block.inspect}))
  @blocks[id] = block if block
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



2
3
4
# File 'lib/elaios/requester.rb', line 2

def logger
  @logger
end

Instance Method Details

#popObject Also known as: deq, shift



22
23
24
# File 'lib/elaios/requester.rb', line 22

def pop
  @out.pop
end

#push(obj) ⇒ Object Also known as: <<, enq



15
16
17
18
# File 'lib/elaios/requester.rb', line 15

def push(obj)
  @in.push(obj)
  update
end

#updateObject

Called internally by ‘push`. Exposed for testing.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/elaios/requester.rb', line 48

def update
  results = @in.pop
  return unless results
  results.split("\n").each do |result|
    @logger.debug(%(result given: #{result}))
    payload = JSON.load(result) rescue nil
    next unless payload
    @logger.debug(%(payload parsed: #{payload.inspect}))
    block = @blocks[payload['id']]
    @logger.debug(%(block found: #{block.inspect}))
    next unless block
    self.instance_exec(payload, &block)
    @logger.debug(%(block called: #{block.inspect}))
    @blocks.delete(payload['id'])
    @logger.debug(%(block unregistered: #{block.inspect}))
  end
end