Sha256: 6c04d14b87173f5da9a254f1ec69b80ce2ad1f68143975ad36378d4bca4e5bb9

Contents?: true

Size: 1.58 KB

Versions: 19

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

begin
  require 'rainbow'
rescue LoadError
end

module Esse
  module Output
    module_function

    def formatted_runtime(number)
      colorize(sprintf('%.3f ms', number), :lightgray)
    end

    def runtime_padding(number, extra = 2)
      ' ' * (extra + sprintf('%.3f ms', number).size)
    end

    def colorize(text, *attributes)
      if defined? Rainbow
        attributes.reduce(Rainbow(text)) { |p, a| p.public_send(a) }
      else
        text
      end
    end

    def print_error(message_or_error, backtrace: false, **options)
      options[:level] ||= :error
      message = message_or_error.to_s

      print_message(message, output: :stderr, **options)

      if message_or_error.is_a?(Exception) && backtrace
        limit = backtrace.is_a?(Integer) ? backtrace : -1
        print_backtrace(message_or_error, limit: limit, level: options[:level])
      end
    end

    def print_backtrace(error, limit: -1, **options)
      return unless error.respond_to?(:backtrace)
      return if error.backtrace.nil?

      error.backtrace[0..limit].each { |frame| print_error(frame, **options) }
    end

    def print_message(message, level: :info, output: $stdout, newline: true, **fields)
      output = \
        case output
        when :stdout, 'stdout'
          $stdout
        when :stderr, 'stderr'
          $stderr
        when IO, StringIO
          output
        else
          raise ArgumentError, "Invalid output #{output.inspect}"
        end

      message = format(message, **fields)
      newline ? output.puts(message) : output.print(message)
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
esse-0.4.0.rc4 lib/esse/primitives/output.rb
esse-0.4.0.rc3 lib/esse/primitives/output.rb
esse-0.4.0.rc2 lib/esse/primitives/output.rb
esse-0.4.0.rc1 lib/esse/primitives/output.rb
esse-0.3.5 lib/esse/primitives/output.rb
esse-0.3.4 lib/esse/primitives/output.rb
esse-0.3.3 lib/esse/primitives/output.rb
esse-0.3.2 lib/esse/primitives/output.rb
esse-0.3.1 lib/esse/primitives/output.rb
esse-0.3.0 lib/esse/primitives/output.rb
esse-0.2.6 lib/esse/primitives/output.rb
esse-0.2.5 lib/esse/primitives/output.rb
esse-0.2.4 lib/esse/primitives/output.rb
esse-0.2.3 lib/esse/primitives/output.rb
esse-0.2.2 lib/esse/primitives/output.rb
esse-0.2.0 lib/esse/primitives/output.rb
esse-0.1.3 lib/esse/primitives/output.rb
esse-0.1.2 lib/esse/primitives/output.rb
esse-0.1.1 lib/esse/primitives/output.rb