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
# File 'lib/metric/receive.rb', line 23

def self.compose(metric, range)
  key = "?api_key=" + Metric.configuration.api_key
  url = Metric.configuration.protocol + "://" + Metric.configuration.host + '/receive'
  url << key
  url << "&token=" + generate_token(metric)
  url << parse_metric(metric)
  url << "&range=" + range
end

.connectionFaraday::Connection

Returns and memoizes a Faraday connection

Returns:

  • (Faraday::Connection)


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

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

.generate_token(metric) ⇒ 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)
  Digest::MD5.hexdigest(Metric.configuration.secret_key + metric)
end

.parse_metric(metric) ⇒ String

CGI escape the metric name so spaces and characters are allowed

Parameters:

  • metric (String)

    Metric identifier

Returns:

  • (String)


56
57
58
# File 'lib/metric/receive.rb', line 56

def self.parse_metric(metric)
  "&metric=#{CGI.escape(metric)}"
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



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

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