Sha256: 62e01910e94af41ff32397a50227966b305e691b7f91e6708827f2875624b624

Contents?: true

Size: 1.53 KB

Versions: 4

Compression:

Stored size: 1.53 KB

Contents

# PP subclass for streaming inspect output in color.
class Pry
  class ColorPrinter < ::PP
    OBJ_COLOR = begin
      code = CodeRay::Encoders::Terminal::TOKEN_COLORS[:keyword]
      if code.start_with? "\e"
        code
      else
        "\e[0m\e[0;#{code}m"
      end
    end

    CodeRay::Encoders::Terminal::TOKEN_COLORS[:comment][:self] = "\e[1;34m"

    def self.pp(obj, out = $>, width = 79)
      q = ColorPrinter.new(out, width)
      q.guard_inspect_key { q.pp obj }
      q.flush
      out << "\n"
    end

    def text(str, width = str.length)
      # Don't recolorize output with color [Issue #751]
      if str.include?("\e[")
        super "#{str}\e[0m", width
      elsif str.start_with?('#<') || str == '=' || str == '>'
        super highlight_object_literal(str), width
      else
        super CodeRay.scan(str, :ruby).term, width
      end
    end

    def pp(obj)
      super
    rescue => e
      raise if e.is_a? Pry::Pager::StopPaging
      begin
        str = obj.inspect
      rescue Exception 
        # Read the class name off of the singleton class to provide a default
        # inspect.
        singleton = class << obj; self; end
        ancestors = Pry::Method.safe_send(singleton, :ancestors)
        klass  = ancestors.reject { |k| k == singleton }.first
        obj_id = obj.__id__.to_s(16) rescue 0
        str    = "#<#{klass}:0x#{obj_id}>"
      end

      text highlight_object_literal(str)
    end

    private

    def highlight_object_literal(object_literal)
      "#{OBJ_COLOR}#{object_literal}\e[0m"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
pry-0.11.0.pre2 lib/pry/color_printer.rb
pry-0.11.0.pre2-java lib/pry/color_printer.rb
pry-0.11.0.pre lib/pry/color_printer.rb
pry-0.11.0.pre-java lib/pry/color_printer.rb