Sha256: 0c802b203077c15bf3e43c4cffba35bd1d3e46144b62da99bc26ca439da5b01e

Contents?: true

Size: 1.04 KB

Versions: 25

Compression:

Stored size: 1.04 KB

Contents

# frozen_string_literal: true

require "digest"

module Decidim
  # This class will generate a unique fingerprint given an arbitrarily deep hash,
  # ensuring that the same fingerprint will be generated regardless of ordering and
  # whether keys are symbols or strings.
  #
  class FingerprintCalculator
    # Public: Initializes the class with a source data to be fingerprinted.
    def initialize(data)
      @data = data
    end

    # Public: Generates a fingerprint hash.
    #
    # Returns a String with the fingerprint.
    def value
      @value ||= Digest::SHA256.hexdigest(source)
    end

    # Public: Returns the fingerprint source *before* hashing, so that it can be
    # inspected by the user.
    #
    # Returns a String with the JSON representation of the normalized data.
    def source
      @source ||= JSON.generate(sort_hash(@data))
    end

    private

    def sort_hash(hash)
      return hash unless hash.is_a?(Hash)

      hash.map { |key, value| [key, sort_hash(value)] }
          .sort_by { |key, _value| key }.to_h
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
decidim-core-0.29.1 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.4 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.9 lib/decidim/fingerprint_calculator.rb
decidim-core-0.29.0 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.3 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.8 lib/decidim/fingerprint_calculator.rb
decidim-core-0.29.0.rc4 lib/decidim/fingerprint_calculator.rb
decidim-core-0.29.0.rc3 lib/decidim/fingerprint_calculator.rb
decidim-core-0.29.0.rc2 lib/decidim/fingerprint_calculator.rb
decidim-core-0.29.0.rc1 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.2 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.7 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.1 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.6 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.0 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.5 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.0.rc5 lib/decidim/fingerprint_calculator.rb
decidim-core-0.28.0.rc4 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.4 lib/decidim/fingerprint_calculator.rb
decidim-core-0.27.3 lib/decidim/fingerprint_calculator.rb