File: serializer.rb

package info (click to toggle)
ruby-benchmark-memory 0.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: ruby: 1,121; makefile: 7; sh: 4
file content (66 lines) | stat: -rw-r--r-- 1,780 bytes parent folder | download
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# frozen_string_literal: true

require 'json'

module Benchmark
  module Memory
    class HeldResults
      # Serialize objects for holding between runs.
      class Serializer
        # Load an object from a JSON document.
        #
        # @param json [String] A JSON document as a string.
        #
        # @return [Object] The object converted from the JSON document.
        def self.load(json)
          json = JSON.parse(json) if json.is_a?(String)
          new.load(json).object
        end

        # Instantiate a new serializer.
        #
        # @param object [Object] The object to serialize.
        def initialize(object = nil)
          @object = object
        end

        # @return [Object] The object to serialize.
        attr_reader :object

        # Convert a JSON document into an object.
        #
        # @param _hash [Hash] A JSON document hash.
        #
        # @return [Object]
        # @raise [NotImplementedError]
        #   If the inheriting subclass didn't implement.
        def load(_hash)
          raise(
            NotImplementedError,
            'You must implement a concrete version in a subclass'
          )
        end

        # Convert the object to a Hash.
        #
        # @return [Hash] The object as a Hash.
        # @raise [NotImplementedError]
        #   If the inheriting subclass didn't implement.
        def to_h
          raise(
            NotImplementedError,
            'You must implement a concrete version in a subclass'
          )
        end

        # Convert the object to a JSON document.
        #
        # @return [String] The object as a JSON document.
        def to_json(*args)
          JSON.generate(to_h, *args)
        end
        alias to_s to_json
      end
    end
  end
end