Sha256: 201b6462d26bd9a6a4c38d76d7781138d73759d7c5c105a3385f6b5521d2839b

Contents?: true

Size: 1.2 KB

Versions: 5

Compression:

Stored size: 1.2 KB

Contents

require "set"
require "uri"
require "net/http"
require "json/ext"

module RorVsWild
  class Client
    HTTPS = "https".freeze
    CERTIFICATE_AUTHORITIES_PATH = File.expand_path("../../../cacert.pem", __FILE__)

    attr_reader :api_url, :api_key, :threads

    def initialize(config)
      Kernel.at_exit(&method(:at_exit))
      @api_url = config[:api_url]
      @api_key = config[:api_key]
      @threads = Set.new
    end

    def post(path, data)
      uri = URI(api_url + path)
      http = Net::HTTP.new(uri.host, uri.port)

      if uri.scheme == HTTPS
        http.verify_mode = OpenSSL::SSL::VERIFY_PEER
        http.ca_file = CERTIFICATE_AUTHORITIES_PATH
        http.use_ssl = true
      end

      post = Net::HTTP::Post.new(uri.path, "X-Gem-Version".freeze => RorVsWild::VERSION)
      post.content_type = "application/json".freeze
      post.basic_auth(nil, api_key)
      post.body = data.to_json
      http.request(post)
    end

    def post_async(path, data)
      Thread.new do
        begin
          threads.add(Thread.current)
          post(path, data)
        ensure
          threads.delete(Thread.current)
        end
      end
    end

    def at_exit
      threads.each(&:join)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rorvswild-1.0.0.pre.alpha5 lib/rorvswild/client.rb
rorvswild-1.0.0.pre.alpha4 lib/rorvswild/client.rb
rorvswild-1.0.0.pre.alpha3 lib/rorvswild/client.rb
rorvswild-1.0.0.pre.alpha2 lib/rorvswild/client.rb
rorvswild-1.0.0.pre.alpha lib/rorvswild/client.rb