Module: Ibex::TableArtifact::Serializer

Defined in:
lib/ibex/table_artifact/serializer.rb,
sig/ibex/table_artifact/serializer.rbs

Overview

Canonical JSON ordering and digest primitives shared by writer and loader.

Class Method Summary collapse

Class Method Details

.canonical(value) ⇒ json_value

RBS:

  • (json_value value) -> json_value

Parameters:

  • value (json_value)

Returns:

  • (json_value)


12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ibex/table_artifact/serializer.rb', line 12

def canonical(value)
  case value
  when Hash
    value.keys.sort.to_h { |key| [key, canonical(value.fetch(key))] }
  when Array
    value.map { |item| canonical(item) }
  when String
    normalized = value.dup.force_encoding(Encoding::UTF_8)
    normalized.valid_encoding? ? normalized : normalized.scrub
  else
    value
  end
end

.compact(value) ⇒ String

RBS:

  • (json_value value) -> String

Parameters:

  • value (json_value)

Returns:

  • (String)


27
28
29
# File 'lib/ibex/table_artifact/serializer.rb', line 27

def compact(value)
  JSON.generate(canonical(value))
end

.deep_freeze(value) ⇒ json_value

RBS:

  • (json_value value) -> json_value

Parameters:

  • value (json_value)

Returns:

  • (json_value)


42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ibex/table_artifact/serializer.rb', line 42

def deep_freeze(value)
  case value
  when Hash
    value.each do |key, item|
      deep_freeze(key)
      deep_freeze(item)
    end
  when Array
    value.each { |item| deep_freeze(item) }
  end
  value.freeze
end

.digest(value) ⇒ String

RBS:

  • (json_value value) -> String

Parameters:

  • value (json_value)

Returns:

  • (String)


37
38
39
# File 'lib/ibex/table_artifact/serializer.rb', line 37

def digest(value)
  "sha256:#{Digest::SHA256.hexdigest(compact(value))}"
end

.dump(value) ⇒ String

RBS:

  • (json_value value) -> String

Parameters:

  • value (json_value)

Returns:

  • (String)


32
33
34
# File 'lib/ibex/table_artifact/serializer.rb', line 32

def dump(value)
  "#{JSON.pretty_generate(canonical(value))}\n"
end