Module: Prompt

Included in:
BunchFinder, BunchURLGenerator, Menu
Defined in:
lib/bunch/url_generator.rb

Overview

CLI Prompt utilities

Instance Method Summary collapse

Instance Method Details

#choose_number(query = '->', max) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/bunch/url_generator.rb', line 48

def choose_number(query = '->', max)
  stty_save = `stty -g`.chomp
  sel = nil
  begin
    while !sel =~ /^\d+$/ || sel.to_i <= 0 || sel.to_i > max
      sel = Readline.readline("#{query}", true)
      return nil if sel =~ /^\s*$/
    end
  rescue Interrupt
    system('stty', stty_save) # Restore
    exit
  end
  sel ? sel.to_i : nil
end

#get_line(query = '->') ⇒ Object



63
64
65
66
67
68
69
70
71
72
# File 'lib/bunch/url_generator.rb', line 63

def get_line(query = '->')
  stty_save = `stty -g`.chomp
  begin
    line = Readline.readline("#{query}: ", true)
  rescue Interrupt
    system('stty', stty_save) # Restore
    exit
  end
  line.chomp
end

#get_text(query = 'Enter text, ^d to end') ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/bunch/url_generator.rb', line 74

def get_text(query = 'Enter text, ^d to end')
  stty_save = `stty -g`.chomp
  lines = []
  puts query
  begin
    while (line = Readline.readline)
      lines << line
    end
  rescue Interrupt
    system('stty', stty_save) # Restore
    exit
  end
  lines.join("\n").chomp
end

#url_encode_textObject



122
123
124
125
126
# File 'lib/bunch/url_generator.rb', line 122

def url_encode_text
  text = get_text
  puts
  CGI.escape(text).gsub(/\+/, '%20')
end

#yn(question, default_response: false) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/bunch/url_generator.rb', line 89

def yn(question, default_response: false)
  default = default_response || 'n'

  # if this isn't an interactive shell, answer default
  return default.downcase == 'y' unless $stdout.isatty

  # clear the buffer
  if ARGV&.length
    ARGV.length.times do
      ARGV.shift
    end
  end
  system 'stty cbreak'

  options = if default
              default =~ /y/i ? '[Y/n]' : '[y/N]'
            else
              '[y/n]'
            end

  $stdout.syswrite "#{question.sub(/\?$/, '')} #{options}? "
  res = $stdin.sysread 1
  puts
  system 'stty cooked'

  res.chomp!
  res.downcase!

  res = default.downcase if res == ''

  res =~ /y/i
end