Sha256: 5e7d00e2e0d08acc9212e501734dfd18ed0b8c722c93c600c9b3290fb72dbce5

Contents?: true

Size: 1.45 KB

Versions: 7

Compression:

Stored size: 1.45 KB

Contents

module GoogleDistanceMatrix
  class UrlBuilder
    BASE_URL = "maps.googleapis.com/maps/api/distancematrix/json"
    DELIMITER = CGI.escape("|")
    MAX_URL_SIZE = 2048

    attr_reader :matrix
    delegate :configuration, to: :matrix

    def initialize(matrix)
      @matrix = matrix

      fail InvalidMatrix.new matrix if matrix.invalid?
    end

    def url
      @url ||= build_url
    end


    private

    def build_url
      url = [protocol, BASE_URL, "?", get_params_string].join

      if sign_url?
        url = GoogleBusinessApiUrlSigner.add_signature(url, configuration.google_business_api_private_key)
      end

      if url.length > MAX_URL_SIZE
        fail MatrixUrlTooLong.new url, MAX_URL_SIZE
      end

      url
    end

    def sign_url?
      configuration.google_business_api_client_id.present? and
      configuration.google_business_api_private_key.present?
    end

    def get_params_string
      params.to_a.map { |key_value| key_value.join("=") }.join("&")
    end

    def params
      places_to_param_config = {lat_lng_scale: configuration.lat_lng_scale}

      configuration.to_param.merge(
        origins: matrix.origins.map { |o| escape o.to_param(places_to_param_config) }.join(DELIMITER),
        destinations: matrix.destinations.map { |d| escape d.to_param(places_to_param_config) }.join(DELIMITER),
      )
    end

    def protocol
      configuration.protocol + "://"
    end

    def escape(string)
      CGI.escape string
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
google_distance_matrix-0.1.3 lib/google_distance_matrix/url_builder.rb
google_distance_matrix-0.1.2 lib/google_distance_matrix/url_builder.rb
google_distance_matrix-0.1.1 lib/google_distance_matrix/url_builder.rb
google_distance_matrix-0.1.0 lib/google_distance_matrix/url_builder.rb
google_distance_matrix-0.0.3 lib/google_distance_matrix/url_builder.rb
google_distance_matrix-0.0.2 lib/google_distance_matrix/url_builder.rb
google_distance_matrix-0.0.1 lib/google_distance_matrix/url_builder.rb