Class: Metric::Receive

Inherits:
Object
  • Object
show all
Defined in:
lib/metric/receive.rb

Overview

Fetch data via the metric.io API

Class Method Summary collapse

Class Method Details

.compose(metric, range) ⇒ String

Generate the url with query strings

Parameters:

  • metric (String)

    Metric identifier

  • range (String)

    Range identifier, either total, today, week or month

Returns:

  • (String)


23
24
25
26
27
28
29
30
31
# File 'lib/metric/receive.rb', line 23

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

.connectionFaraday::Connection

Returns and memoizes a Faraday connection

Returns:

  • (Faraday::Connection)


36
37
38
39
40
# File 'lib/metric/receive.rb', line 36

def self.connection
  @connection ||= Faraday.new do |builder|
    builder.adapter :net_http
  end
end

.generate_token(metric, range) ⇒ String

Generate a hash of the site’s secret_key and metric identifier

Parameters:

  • metric (String)

    Metric identifier

Returns:

  • (String)


14
15
16
# File 'lib/metric/receive.rb', line 14

def self.generate_token(metric, range)
  Digest::MD5.hexdigest(Metric.configuration.secret_key + metric + range)
end

.receive(metric, range) ⇒ Hash

Perform the actual request and parse JSON

Parameters:

  • metric (String)

    Metric identifier

  • range (String)

    Range identifier, either total, today, week or month

Returns:

  • (Hash)

    response from the API



47
48
49
50
51
# File 'lib/metric/receive.rb', line 47

def self.receive(metric, range)
  url = compose(metric, range)
  response = connection.get(url)
  MultiJson.decode(response.body)[range]
end