Skip to content

Instantly share code, notes, and snippets.

@chopmo
Created January 5, 2012 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chopmo/1565178 to your computer and use it in GitHub Desktop.
Save chopmo/1565178 to your computer and use it in GitHub Desktop.
module RCat
class LinePrinter
def print_line(line)
print line
end
end
class PrinterDecorator
def initialize(printer)
@printer = printer
end
def print_line(line)
@printer.print_line(line)
end
def blank_line?(line)
line.chomp.empty?
end
end
class ExtraNewlineSqueezer < PrinterDecorator
def print_line(line)
super unless @prev_line_blank && blank_line?(line)
@prev_line_blank = blank_line?(line)
end
end
class LineNumberer < PrinterDecorator
def initialize(printer, options = {})
super(printer)
@mode = options[:mode]
@line_number = 1
end
def only_significant?
@mode == :significant_lines
end
def print_line(line)
formatted_line = line
unless blank_line?(line) && only_significant?
formatted_line = "#{@line_number.to_s.rjust(6)}\t#{formatted_line}"
@line_number += 1
end
super(formatted_line)
end
end
class Display
def initialize(params)
@line_numbering_style = params[:line_numbering_style]
@squeeze_extra_newlines = params[:squeeze_extra_newlines]
end
def create_printer
printer = LinePrinter.new
printer = LineNumberer.new(printer, :mode => @line_numbering_style) if @line_numbering_style
printer = ExtraNewlineSqueezer.new(printer) if @squeeze_extra_newlines
printer
end
def render(data)
printer = create_printer
data.lines.each do |line|
printer.print_line(line)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment