Sha256: 8fd092f54d65015857842ea84b8cc008b6acd0b6004534845b2a5121538366af

Contents?: true

Size: 1.61 KB

Versions: 1

Compression:

Stored size: 1.61 KB

Contents

require 'hashdiff'

module Xing
  module SpecDoc
    class Document
      def initialize(path, contents)
        @path = path
        @contents = contents
      end
      attr_reader :path, :contents

      def parsed_body
        @parsed_body ||= JSON.parse(contents)
      end

      def pretty_body
        @pretty_body ||= JSON.pretty_generate(parsed_body)+"\n"
      end

      def difference_from(other)
        diff(parsed_body, other)
      end

      def diff(one, other)
        diff = HashDiff.diff(one, other)


        by_change = diff.group_by {|change| change[0]}

        adds = by_change.delete("+") || []
        subs = by_change.delete("-") || []
        mods = by_change.values.inject do |all, a_kind|
          all + a_kind
        end || []

        arr_adds, other_adds = adds.partition do |add|
          add[1] =~ /\[\d+\]$/
        end

        mods += (other_adds || [])

        arr_adds.each do |add|
          sub = subs.find{|sub| sub[1] == add[1]}
          if sub.nil?
            mods << add
          else
            subs.delete(sub)
            new_diff = diff(add[2], sub[2])
            mods += new_diff.map do |change|
              [change[0], [add[1], change[1]].join(".")] + change[2..-1]
            end
          end
        end

        mods += subs

        mods
      end

      def significant_diff_item?(change)
        return true if change[0] != "~"
        return true if change[2].class != change[3].class
        return false
      end

      def different_from?(body)
        difference_from(body).any? do |change|
          significant_diff_item?(change)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
xing-backend-specdoc-0.0.1 lib/xing/specdoc/document.rb