Sha256: 3fd5585c509c6699560b64f806aa080d4f4a6a2941a9010fc263e1e55a48e4aa

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

require 'cgi'

module Userstack
  # A class which builds URI of Userstack api
  class UriBuilder
    USERSTACK_API_DOMAIN = 'api.userstack.com'
    private_constant :USERSTACK_API_DOMAIN

    private_class_method :new

    # @param access_key [String] Userstack Access key
    # @param useragent [String] useragent
    # @param use_ssl [Boolean] Use ssl or not
    # @param legacy [Boolean] Legacy response
    # @return [URI::HTTP, URI::HTTPS]
    def self.execute(access_key, useragent, use_ssl, legacy)
      new(access_key, useragent, use_ssl, legacy).send(:execute)
    end

    private

    attr_reader :access_key, :useragent, :use_ssl, :legacy

    def initialize(access_key, useragent, use_ssl, legacy)
      @access_key = access_key.freeze
      @useragent = useragent.freeze
      @use_ssl = use_ssl
      @legacy = legacy
      freeze
    end

    def execute
      fqdn = URI("#{scheme}://#{USERSTACK_API_DOMAIN}/")
      fqdn.tap do |uri|
        uri.path = '/detect'
        uri.query = query
      end
    end

    def query
      q = {
        access_key: access_key,
        ua: CGI.escape(useragent)
      }
      q[:legacy] = 1 if legacy
      q.map { |k, v| "#{k}=#{v}" }.join('&')
    end

    def scheme
      use_ssl ? 'https' : 'http'
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
userstack-0.1.0 lib/userstack/uri_builder.rb