Sha256: 7ddbb8a96f3180a9873e810b858b46f7a8df94526c88b0ee6d1be1a5df1d03c7

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

require "dye"

require "cliprompt/version"
require "cliprompt/optionset"

module Cliprompt

  module_function

  CUSTOM_STYLES = {
    error: [ :bold, :red ],
    ok:    [ :bold, :green ]
  }
  define_dye_method CUSTOM_STYLES

  MSG_MANDATORY_TEXT = Dye.dye("Sorry you need to fill that information.", [ :bold, :red ])
  MSG_YES_OR_NO = Dye.dye("You need to answer by yes, no, y or n.", [ :bold, :red ])
  MSG_CHOSE_IN_LIST = Dye.dye("You need to chose between the available options.", [ :bold, :red ])

  def ask(question, *options)
    if options[0].class == Optionset
      opts = options[0]
    else
      opts = Optionset.new *options
    end
    output.print "#{question} #{opts.display} "
    answer = input.gets.chomp
    output.flush
    check(answer, question, opts)
  end

  def check(answer, question, opts)
    if answer == ''
      if !opts.default.nil?
        answer = opts.default
      else
        output.puts MSG_MANDATORY_TEXT
        ask(question, opts)
      end
    else
      if opts.boolean
        if /^(y(es)?|n(o)?)$/.match(answer.downcase)
          answer = !/^y(es)?$/.match(answer.downcase).nil?
        else
          output.puts MSG_YES_OR_NO
          ask(question, opts)
        end
      elsif opts.choices.count > 0 && !opts.choices.include?(answer)
        output.puts MSG_CHOSE_IN_LIST
        ask(question, opts)
      else
        answer
      end
    end
  end

  def setio(input, output)
    @@input = input
    @@output = output
  end

  def input
    @@input ||= STDIN
  end

  def output
    @@output ||= STDOUT
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cliprompt-0.0.1 lib/cliprompt.rb