Module: MetricsParser

Defined in:
lib/metrics_parser.rb

Overview

Core functions for parsing metrics from JSON web output, such as that by Coda Hale’s metrics library

Class Method Summary collapse

Class Method Details

.flatten_tree(json_tree, prefix = []) ⇒ Object

Parameters:

  • tree

    A hash tree such as that generated by JSON.parse()

  • prefix (defaults to: [])

    A list of namespace strings to prefix the generated keys by



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/metrics_parser.rb', line 7

def self.flatten_tree(json_tree, prefix=[])
  flat_tree = {}
  pairs = json_tree.each do |key, value|
    newkey = (prefix + [key]).join(".")
    flat_tree[newkey] = value
    if value.is_a?(Hash)
      flat_tree.update(MetricsParser.flatten_tree(value, prefix + [key]))
    end
  end
  flat_tree
end

.glob_key_values(json_tree, key_patterns) ⇒ Object

Parameters:

  • json_tree

    As returned by JSON,parse()

  • key_patterns

    a list of glob pattern strings for matching keys



32
33
34
35
36
37
38
39
40
# File 'lib/metrics_parser.rb', line 32

def self.glob_key_values(json_tree, key_patterns)
  matches = {}
  flat_tree = flatten_tree(json_tree)
  key_patterns.each do |key_pattern|
    matching_keys = flat_tree.keys.select { |key| File.fnmatch(key_pattern, key) }
    matches.merge!(Hash[ matching_keys.map { |key| [key, flat_tree[key]] } ])
  end
  matches
end

.list_keys_for_hash(json_tree) ⇒ Object



20
21
22
# File 'lib/metrics_parser.rb', line 20

def self.list_keys_for_hash(json_tree)
  self.flatten_tree(json_tree).keys.sort
end

.list_keys_for_hashes(json_trees) ⇒ Object



25
26
27
# File 'lib/metrics_parser.rb', line 25

def self.list_keys_for_hashes(json_trees)
  json_trees.map { |tree| self.flatten_tree(tree).keys }.flatten.uniq.sort
end