Sha256: 9c8588d7731c55beb64cc789a2e1ee3f82543fbbcba51aa8b78529081cc04778

Contents?: true

Size: 1.87 KB

Versions: 14

Compression:

Stored size: 1.87 KB

Contents

module Climatic
  module Utils

    module Input

      DEFAULT_CONFIRMATION_CHOICES = {
          true => %w(Yes y),
          false => %w(No n)
      }

      def get_user_confirmation(choices: DEFAULT_CONFIRMATION_CHOICES,
                                default_choice: 'No',
                                prompt: 'Are you sure ?',
                                strict: false)

        raise Climatic::Error, 'Invalid choices !' unless choices.is_a? Hash
        values = choices.values.flatten
        raise Climatic::Error, "Invalid default choice '#{default_choice}' !" unless values.include? default_choice
        if Climatic.config[:auto]
          yield if block_given?
          return true
        end
        full_prompt = '%s (%s): ' % [prompt, choices_string(values, default_choice)]
        STDOUT.print full_prompt
        STDOUT.flush
        input = nil
        until values.include? input
          input = STDIN.gets.chomp
          input = default_choice if input.nil? || input.empty?
          unless strict
            input = default_choice unless values.include? input
          end
        end
        choices.each_pair do |res, possible_choices|
          if possible_choices.include? input
            if res and block_given?
              yield
            end
            return res
          end
        end
        raise 'Something wrong happened !'
      end


      def get_user_input(prompt, default=nil)
        full_prompt = (default.nil? or default.empty?) ? "#{prompt}: " : "#{prompt} (default: #{default}): "
        STDOUT.print full_prompt
        STDOUT.flush
        STDIN.gets.chomp
      end

      private


      def choices_string(choices, default_choice, highlight= %w([ ]))
        choices
            .map { |choice| choice == default_choice ? "#{highlight.first}#{choice}#{highlight.last}" : choice }
            .join '/'
      end

    end

  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
climatic-0.2.40 lib/climatic/utils/input.rb
climatic-0.2.39 lib/climatic/utils/input.rb
climatic-0.2.38 lib/climatic/utils/input.rb
climatic-0.2.37 lib/climatic/utils/input.rb
climatic-0.2.36 lib/climatic/utils/input.rb
climatic-0.2.35 lib/climatic/utils/input.rb
climatic-0.2.34 lib/climatic/utils/input.rb
climatic-0.2.32 lib/climatic/utils/input.rb
climatic-0.2.31 lib/climatic/utils/input.rb
climatic-0.2.30 lib/climatic/utils/input.rb
climatic-0.2.29 lib/climatic/utils/input.rb
climatic-0.2.28 lib/climatic/utils/input.rb
climatic-0.2.27 lib/climatic/utils/input.rb
climatic-0.2.26 lib/climatic/utils/input.rb