Sha256: 037a8d8bafa97883dd1cac425b8a37bfa6164dc5de6569b11fa3003d87e27d34

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

require "pastel"
require "tty-prompt"

module CobraCommander
  module Output
    # Runs an interactive output printer
    class InteractivePrinter
      pastel = Pastel.new
      SUCCESS = "#{pastel.green("āœ”")} %s"
      ERROR = "#{pastel.red("āœ–")} %s"
      BYE = pastel.decorate("\n\nšŸ‘‹ Bye!", :white, :on_black, :bold).freeze

      def self.run(contexts, output)
        new(contexts).run(output)
      end

      def initialize(contexts)
        @prompt = TTY::Prompt.new
        @options = contexts.sort(&method(:sort_contexts))
          .reduce({}) do |options, context|
          template = context.success? ? SUCCESS : ERROR
          options.merge format(template, context.component_name) => context
        end
      end

      def run(output)
        loop do
          context = @prompt.select("Print output?", @options)
          output.puts context.output
        end
      rescue TTY::Reader::InputInterrupt
        output.puts BYE
      end

      private

      def sort_contexts(context_a, context_b)
        if context_a.success? == context_b.success?
          context_a.component_name <=> context_b.component_name
        else
          context_a.success? ? 1 : -1
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cobra_commander-0.13.0 lib/cobra_commander/output/interactive_printer.rb