File: stat_struct.rb

package info (click to toggle)
ruby-beaneater 1.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 296 kB
  • sloc: ruby: 1,628; sh: 4; makefile: 2
file content (45 lines) | stat: -rw-r--r-- 1,213 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Beaneater
  # Represents a stats hash with proper underscored keys
  class StatStruct < FasterOpenStruct
    # Convert a stats hash into a struct.
    #
    # @param [Hash{String => String}] hash Hash Stats hash to convert to struct
    # @return [Beaneater::StatStruct, nil] Stats struct from hash
    # @example
    #   s = StatStruct.from_hash(:foo => "bar")
    #   s.foo # => 'bar'
    #
    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

    # Access value for stat with specified key.
    #
    # @param [String] key Key to fetch from stats.
    # @return [String, Integer] Value for specified stat key.
    # @example
    #  @stats['foo'] # => "bar"
    #
    def [](key)
      self.send(key.to_s)
    end

    # Returns set of keys within this struct
    #
    # @return [Array<String>] Value for specified stat key.
    # @example
    #  @stats.keys # => ['foo', 'bar', 'baz']
    #
    def keys
      @hash.keys.map { |k| k.to_s }
    end

    # Returns the initialization hash
    #
    def to_h
      @hash
    end
  end # StatStruct
end # Beaneater