Module: RailVerdict::CanonicalJSON

Defined in:
lib/rail_verdict/canonical_json.rb

Class Method Summary collapse

Class Method Details

.canonicalize(value) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rail_verdict/canonical_json.rb', line 13

def canonicalize(value)
  case value
  when Hash
    value.keys.sort_by(&:to_s).to_h { |key| [key, canonicalize(value[key])] }
  when Array
    value.map { |item| canonicalize(item) }
  when String
    scrub_text(value)
  else
    value
  end
end

.generate(value) ⇒ Object



9
10
11
# File 'lib/rail_verdict/canonical_json.rb', line 9

def generate(value)
  JSON.generate(canonicalize(value))
end

.scrub_text(text) ⇒ Object



26
27
28
29
# File 'lib/rail_verdict/canonical_json.rb', line 26

def scrub_text(text)
  text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "\uFFFD")
      .gsub(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/, "?")
end