Class: Tggl::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, options = {}) ⇒ Client

Returns a new instance of Client.



8
9
10
11
12
13
14
15
16
17
# File 'lib/tggl/client.rb', line 8

def initialize(api_key = nil, options = {})
  @api_key = api_key
  @url = options[:url] || 'https://api.tggl.io/flags'
  @reporter = api_key.nil? || options[:reporting] == false ? nil :  Reporting.new(
    api_key,
    app_prefix: "ruby-client:#{VERSION}/Client",
    url: options[:reporting] == true ? nil : options[:reporting]&.[](:url),
    app: options[:reporting] == true ? nil : options[:reporting]&.[](:app)
  )
end

Instance Method Details

#eval_context(context) ⇒ Object



19
20
21
22
23
24
# File 'lib/tggl/client.rb', line 19

def eval_context(context)
  response = eval_contexts([context]).first
  raise StandardError.new "Unexpected empty response from Tggl" if response.nil?

  response
end

#eval_contexts(contexts) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/tggl/client.rb', line 26

def eval_contexts(contexts)
  begin
    uri = URI(@url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(uri.path, {
      'X-Tggl-Api-Key' => @api_key,
      'Content-Type' => 'application/json'
    })
    request.body = contexts.to_json

    response = http.request(request)
    result = JSON.parse(response.body, symbolize_names: true)

    if response.code.to_i > 200
      if result.nil?
        raise StandardError.new "Invalid response from Tggl: #{response.code}"
      end
      raise StandardError.new result['error']
    end

    result.map { |flags| Response.new(flags, reporter: @reporter) }
  rescue
    contexts.map { || Response.new({}, reporter: @reporter) }
  end
end