Class: SchemaEvolutionManager::Ask

Inherits:
Object
  • Object
show all
Defined in:
lib/schema-evolution-manager/ask.rb

Overview

Simple library to ask user for input, with easy mocakability for testing

Constant Summary collapse

TRUE_STRINGS =
['y', 'yes']

Class Method Summary collapse

Class Method Details

.for_boolean(message) ⇒ Object

Asks the user a question. Returns a boolean. Boolean is defined as matching the strings ‘y’ or ‘yes’, case insensitive



37
38
39
40
# File 'lib/schema-evolution-manager/ask.rb', line 37

def Ask.for_boolean(message)
  value = Ask.for_string("%s (y/n) " % message)
  TRUE_STRINGS.include?(value.downcase)
end

.for_password(message) ⇒ Object



42
43
44
# File 'lib/schema-evolution-manager/ask.rb', line 42

def Ask.for_password(message)
  Ask.for_string(message, :echo => false)
end

.for_string(message, opts = {}) ⇒ Object

Asks the user a question. Expects a string back.

Parameters:

  • default:

    A default value

  • echo:

    If true (the default), we echo what the user types to the screen. If false, we do NOT echo.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/schema-evolution-manager/ask.rb', line 14

def Ask.for_string(message, opts={})
  default = opts.delete(:default)
  echo = opts[:echo].nil? ? true : opts.delete(:echo)
  Preconditions.assert_empty_opts(opts)

  final_message = message.dup
  if default
    final_message << " [%s] " % default
  end

  value = nil
  while value.to_s == ""
    print final_message
    value = get_input(echo).to_s.strip
    if value.to_s == "" && default
      value = default.to_s.strip
    end
  end
  value
end

.get_input(echo) ⇒ Object

here to help with tests



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/schema-evolution-manager/ask.rb', line 47

def Ask.get_input(echo)
  if echo
    STDIN.gets
  else
    settings = `stty -g`.strip
    begin
      `stty -echo`
      input = STDIN.gets
      puts ""
    ensure
      `stty #{settings}`
    end
    input
  end
end