diff --git a/README.rdoc b/README.rdoc index 02ba355..65c3e48 100644 --- a/README.rdoc +++ b/README.rdoc @@ -72,6 +72,7 @@ Need a different output format? We've got a few of those too. Differ.format = :ascii # <- Default Differ.format = :color Differ.format = :html + Differ.format = :patch Differ.format = MyCustomFormatModule diff --git a/differ.gemspec b/differ.gemspec index d59e0e5..57d1530 100644 --- a/differ.gemspec +++ b/differ.gemspec @@ -25,6 +25,7 @@ Gem::Specification.new do |s| "lib/differ/format/ascii.rb", "lib/differ/format/color.rb", "lib/differ/format/html.rb", + "lib/differ/format/patch.rb", "lib/differ/string.rb", "spec/differ/change_spec.rb", "spec/differ/diff_spec.rb", diff --git a/lib/differ.rb b/lib/differ.rb index 63a4078..916828d 100644 --- a/lib/differ.rb +++ b/lib/differ.rb @@ -3,6 +3,7 @@ require 'differ/format/ascii' require 'differ/format/color' require 'differ/format/html' +require 'differ/format/patch' module Differ class << self @@ -49,6 +50,7 @@ def format_for(f) when :ascii then Format::Ascii when :color then Format::Color when :html then Format::HTML + when :patch then Format::Patch when nil then nil else raise "Unknown format type #{f.inspect}" end @@ -80,4 +82,4 @@ def change(method, array, index) @diff.same(array.shift) end end -end \ No newline at end of file +end diff --git a/lib/differ/format/patch.rb b/lib/differ/format/patch.rb new file mode 100644 index 0000000..afaaa65 --- /dev/null +++ b/lib/differ/format/patch.rb @@ -0,0 +1,28 @@ +module Differ + module Format + module Patch + class << self + def format(change) + (change.change? && as_change(change)) || + (change.delete? && as_delete(change)) || + (change.insert? && as_insert(change)) || + '' + end + + private + + def as_insert(change) + "\033[32m+ #{change.insert}\033[0m" + end + + def as_delete(change) + "\033[31m- #{change.delete}\033[0m" + end + + def as_change(change) + [as_delete(change), as_insert(change)].join("\n") + end + end + end + end +end diff --git a/spec/differ/format/patch_spec.rb b/spec/differ/format/patch_spec.rb new file mode 100644 index 0000000..3308ffb --- /dev/null +++ b/spec/differ/format/patch_spec.rb @@ -0,0 +1,18 @@ +require 'spec_helper' + +describe Differ::Format::Patch do + it 'should format inserts well' do + @expected = "\033[32m+ SAMPLE\033[0m" + Differ::Format::Patch.format(+'SAMPLE').should == @expected + end + + it 'should format deletes well' do + @expected = "\033[31m- SAMPLE\033[0m" + Differ::Format::Patch.format(-'SAMPLE').should == @expected + end + + it 'should format changes well' do + @expected = "\033[31m- THEN\033[0m\n\033[32m+ NOW\033[0m" + Differ::Format::Patch.format('THEN' >> 'NOW').should == @expected + end +end