Class: Tuber::StatStruct

Inherits:
FasterOpenStruct
  • Object
show all
Defined in:
lib/tuber/stats/stat_struct.rb

Overview

Represents a stats hash with proper underscored keys

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Tuber::FasterOpenStruct

Class Method Details

.from_hash(hash) ⇒ Tuber::StatStruct?

Convert a stats hash into a struct.

Examples:

s = StatStruct.from_hash(:foo => "bar")
s.foo # => 'bar'

Parameters:

  • hash (Hash{String => String})

    Hash Stats hash to convert to struct

Returns:



14
15
16
17
18
# File 'lib/tuber/stats/stat_struct.rb', line 14

def self.from_hash(hash)
  return unless hash.is_a?(Hash)
  underscore_hash = hash.inject({}) { |r, (k, v)| r[k.to_s.gsub(/-/, '_')] = v; r }
  self.new(underscore_hash)
end

Instance Method Details

#[](key) ⇒ String, Integer

Access value for stat with specified key.

Keys are stored underscored (see from_hash), so hyphenated beanstalkd names like "current-jobs-ready" are underscored before lookup. This also avoids defining an invalid, hyphenated method name via method_missing.

Examples:

@stats['foo'] # => "bar"
@stats['current-jobs-ready'] # => 5

Parameters:

  • key (String)

    Key to fetch from stats.

Returns:

  • (String, Integer)

    Value for specified stat key.



32
33
34
# File 'lib/tuber/stats/stat_struct.rb', line 32

def [](key)
  self.send(key.to_s.gsub(/-/, '_'))
end

#keysArray<String>

Returns set of keys within this struct

Examples:

@stats.keys # => ['foo', 'bar', 'baz']

Returns:

  • (Array<String>)

    Value for specified stat key.



42
43
44
# File 'lib/tuber/stats/stat_struct.rb', line 42

def keys
  @hash.keys.map { |k| k.to_s }
end

#to_hObject

Returns the initialization hash



48
49
50
# File 'lib/tuber/stats/stat_struct.rb', line 48

def to_h
  @hash
end