Sha256: 60eebafb3bac2026921c3a31dd7fa1bc4ee8995780d680d26e4a01fa7172509a

Contents?: true

Size: 1.58 KB

Versions: 2

Compression:

Stored size: 1.58 KB

Contents

require 'digest/md5'
require 'faraday'
require 'multi_json'

module Metric

  # Fetch data via the metric.io API

  class Receive
    # Generate a hash of the site's secret_key and metric identifier
    #
    # @param [String] metric Metric identifier
    # @return [String]
    def self.generate_token(metric, range)
      Digest::MD5.hexdigest(Metric.configuration.secret_key + metric + range)
    end

    # Generate the url with query strings
    #
    # @param [String] metric Metric identifier
    # @param [String] range Range identifier, either total, today, week or month
    # @return [String]
    def self.compose(metric, range)
      token = generate_token(metric, range)
      parameters = {"metric" => metric, "range" => range, "token" => token}
      api_key = Metric.configuration.api_key
      url = Metric.configuration.protocol + "://" + Metric.configuration.host
      url << "/v1/sites/#{api_key}/statistics?"
      url << Metric::Util.build_query_string(parameters)
      url
    end

    # Returns and memoizes a Faraday connection
    #
    # @return [Faraday::Connection]
    def self.connection
      @connection ||= Faraday.new do |builder|
        builder.adapter :net_http
      end
    end

    # Perform the actual request and parse JSON
    #
    # @param [String] metric Metric identifier
    # @param [String] range Range identifier, either total, today, week or month
    # @return [Hash] response from the API
    def self.receive(metric, range)
      url = compose(metric, range)
      response = connection.get(url)
      MultiJson.decode(response.body)[range]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
metric-0.1.2 lib/metric/receive.rb
metric-0.1.1 lib/metric/receive.rb