Sha256: 5dbe4f1addc635ad84d4875ca3be727c28cb11ecc2fe28654056f5e44cab01d7

Contents?: true

Size: 1.78 KB

Versions: 2

Compression:

Stored size: 1.78 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 ||=
          if contents.empty?
            {}
          else
            JSON.parse(contents)
          end
      end

      def pretty_body
        @pretty_body ||=
          if contents.empty?
            ""
          else
            JSON.pretty_generate(parsed_body)+"\n"
          end
      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

2 entries across 2 versions & 1 rubygems

Version Path
xing-backend-specdoc-1.0.0.pre.beta lib/xing/specdoc/document.rb
xing-backend-specdoc-0.0.2 lib/xing/specdoc/document.rb