Sha256: e58cecf7783860f4c5d7413aa47cab67102d15e1f3b2273a3cd0f8b7ead5fe75

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 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 = map_options(contexts)
      end

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

      private

      def map_options(contexts)
        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 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.14.0 lib/cobra_commander/output/interactive_printer.rb