lib/rubygems/comparator/report.rb in gem-compare-0.0.2 vs lib/rubygems/comparator/report.rb in gem-compare-0.0.3

- old
+ new

@@ -1,14 +1,45 @@ +require 'rubygems/comparator/report/entry' + class Gem::Comparator + + ## + # Gem::Comparator::Report can nest sections and print only those that + # contain some messages. + # + # Usage: + # report = Gem::Comparator::Report.new + # report['section1'] << "Message 1" + # report['section1']['subsection1'].set_header 'Message 2 Header' + # report['section1']['subsection1'] << "Message 2" if false + # report['section1'].section + # nest('subsection2').section + # puts "Message 3" + # end + # end + # report.print + # + # This won't print Message 2 nor its header saving a lot of if/else. + class Report + module Signs + def same + Rainbow('SAME').green.bright + end + + def different + Rainbow('DIFFERENT').red.bright + end + end + def self.new(name = 'main') Gem::Comparator::Report::NestedSection.new(name) end class NestedSection - include Gem::Comparator::Base + include Report::Signs include Gem::UserInteraction DEFAULT_INDENT = ' ' attr_reader :header, :messages, :parent_section, :level @@ -31,16 +62,23 @@ def set_header(message) @header = Entry.new(message) end def puts(message) - @messages << Entry.new(message) + case message + when String, Array + @messages << Entry.new(message) unless message.empty? + else + @messages << Entry.new(message) unless message + end end alias_method :<<, :puts def nest(name) - @sections.each { |s| if s.name == name; return s; end } + @sections.each do |s| + return s if s.name == name + end NestedSection.new(name, self) end alias_method :[], :nest def print @@ -49,20 +87,24 @@ def all_messages indent = DEFAULT_INDENT*@level if @header.empty? - @messages.map { |m| m.set_indent!(indent) } + nested_messages + @messages.map do |m| + m.set_indent!(indent) + end + nested_messages else - nested = @messages.map { |m| m.set_indent!(indent * 2) } + nested_messages + nested = @messages.map do |m| + m.set_indent!(indent * 2) + end + nested_messages return [] if nested.empty? @header.set_indent!(indent) nested.unshift(@header) end end - + def lines(line_num) all_messages[line_num].data end def nested_messages @@ -81,41 +123,8 @@ parent.sections << self @level = parent.level + 1 parent_section = parent end - end - - class Entry - include Gem::UserInteraction - - attr_accessor :data, :indent - - def initialize(data = '', indent = '') - @data = data - @indent = indent - end - - def set_indent!(indent) - @indent = indent - self - end - - def empty? - case @data - when String, Array - @data.empty? - end - end - - def print - printed = case @data - when String - "#{@indent}#{@data}" - when Array - @indent + @data.join("\n#{@indent}") - end - say printed - end end end end