Sha256: a113f30195e5dade80535beed524390db3ae7416293f535d4a88c90cb01be518

Contents?: true

Size: 1.4 KB

Versions: 2

Compression:

Stored size: 1.4 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

2 entries across 2 versions & 1 rubygems

Version Path
cobra_commander-0.15.1 lib/cobra_commander/output/interactive_printer.rb
cobra_commander-0.15.0 lib/cobra_commander/output/interactive_printer.rb