Module: ConsoleUtils
- Defined in:
- lib/more/facets/console.rb
Overview
ConsoleUtils provides methods that are generally useful in the context of creating console output.
Class Method Summary collapse
-
.ask(question, answers = nil) ⇒ Object
Convenient method to get simple console reply.
-
.password(msg = nil) ⇒ Object
Ask for a password.
-
.print_justified(left, right, options = {}) ⇒ Object
Print a justified line with left and right entries.
- .println ⇒ Object
-
.say(statement) ⇒ Object
Convenience method for puts.
-
.screen_width(out = STDERR) ⇒ Object
Console screen width (taken from progress bar).
Class Method Details
.ask(question, answers = nil) ⇒ Object
Convenient method to get simple console reply.
25 26 27 28 29 30 |
# File 'lib/more/facets/console.rb', line 25 def ask(question, answers=nil) print "#{question}" print " [#{answers}] " if answers until inp = $stdin.gets ; sleep 1 ; end inp end |
.password(msg = nil) ⇒ Object
Ask for a password. (FIXME: only for unix so far)
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/more/facets/console.rb', line 42 def password(msg=nil) msg ||= "Enter Password: " inp = '' $stdout << msg begin system "stty -echo" inp = gets.chomp ensure system "stty echo" end return inp end |
.print_justified(left, right, options = {}) ⇒ Object
Print a justified line with left and right entries.
A fill option can be given to fill in any empty space between the two. And a ratio option can be given which defaults to 0.8 (eg. 80/20)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/more/facets/console.rb', line 83 def print_justified(left, right, ={}) fill = [:fill] || '.' fill = ' ' if fill == '' fill = fill[0,1] ratio = [:ratio] || 0.8 ratio = 1 + ratio if ratio < 0 width = (@screen_width ||= screen_width) - 1 #l = (width * ratio).to_i r = (width * (1 - ratio)).to_i l = width - r left = left[0,l] right = right[0,r] str = fill * width str[0,left.size] = left str[width-right.size,right.size] = right print str end |
.println ⇒ Object
19 20 21 |
# File 'lib/more/facets/console.rb', line 19 def println end |
.say(statement) ⇒ Object
Convenience method for puts. Use this instead of puts when the output should be supressed if the global $QUIET option is set.
36 37 38 |
# File 'lib/more/facets/console.rb', line 36 def say(statement) puts statement #unless quiet? $QUIET end |
.screen_width(out = STDERR) ⇒ Object
Console screen width (taken from progress bar)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/more/facets/console.rb', line 60 def screen_width(out=STDERR) # FIXME: I don't know how portable it is. default_width = ENV['COLUMNS'] || 80 begin tiocgwinsz = 0x5413 data = [0, 0, 0, 0].pack("SSSS") if out.ioctl(tiocgwinsz, data) >= 0 then rows, cols, xpixels, ypixels = data.unpack("SSSS") if cols >= 0 then cols else default_width end else default_width end rescue Exception default_width end end |