Class: Nucleon::Util::Console

Inherits:
Object
  • Object
show all
Defined in:
lib/core/util/console.rb

Overview

  • Nucleon::Core (base UI capable object)

Constant Summary collapse

@@colors =

Color formatter map

{
  :clear  => "\e[0m",
  :black  => "\e[30m",
  :red    => "\e[31m",
  :green  => "\e[32m",
  :yellow => "\e[33m",
  :blue   => "\e[34m",
  :purple => "\e[35m",
  :cyan   => "\e[36m",
  :grey   => "\e[37m"
}
@@color_map =

Colored message map

{
  :warn    => :yellow,
  :error   => :red,
  :success => :green
}
@@quiet =

Global quiet flag to disable all output

false
@@use_colors =

Global flag to render console output in color (using color formatting)

true

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Console

Initialize a new console object

TODO: Figure out some way to make the console system pluggable?

  • Parameters

    • Hash

      options Console options

      • String

        :resource Logger resource identifier (also serves as prefix)

      • Boolean

        :color Whether or not to render messages in color (overridden by global quiet)

      • Symbol

        :printer Printer method (default :puts)

      • IO

        :input Don’t touch

      • IO

        :output Don’t touch

      • IO

        :error Don’t touch

      • ANY

        :console_delegate Delegate object that handles console operations (must implement logging interface)

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • Nucleon::Config::ensure



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/core/util/console.rb', line 97

def initialize(options = {})
  if options.is_a?(String)
    options = { :resource => options }
  end
  config = Config.ensure(options)

  @resource = config.get(:resource, '')

  @color   = config.get(:color, true)
  @printer = config.get(:printer, :puts)

  @input  = config.get(:input, $stdin)
  @output = config.get(:output, $stdout)
  @error  = config.get(:error, $stderr)

  @delegate = config.get(:console_delegate, nil)
end

Instance Attribute Details

#colorObject

Boolean

Whether or not to use color markers when rendering text

This can be overridden by the global quiet setting ::quiet, ::quiet=



142
143
144
# File 'lib/core/util/console.rb', line 142

def color
  @color
end

#delegateObject

ANY

Any class that implements this console interface



164
165
166
# File 'lib/core/util/console.rb', line 164

def delegate
  @delegate
end

#error(message, *args) ⇒ Object

Output error to an output channel unless quiet specified

  • Parameters

    • String

      message Message to render to output channel

    • Hash

      options Output options

      • #say options

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #say



160
161
162
# File 'lib/core/util/console.rb', line 160

def error
  @error
end

#inputObject

IO

Input IO object

Don’t touch unless you know what you are doing.



148
149
150
# File 'lib/core/util/console.rb', line 148

def input
  @input
end

#outputObject

IO

Output IO object (messages)

Don’t touch unless you know what you are doing.



154
155
156
# File 'lib/core/util/console.rb', line 154

def output
  @output
end

#resourceObject

String

Console resource name

This is the string identifier and default console prefix used when rendering.



136
137
138
# File 'lib/core/util/console.rb', line 136

def resource
  @resource
end

Class Method Details

.black(string) ⇒ Object

Color a given string black if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Black or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



660
661
662
# File 'lib/core/util/console.rb', line 660

def self.black(string)
  colorize(string, :black)
end

.blue(string) ⇒ Object

Color a given string blue if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Blue or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



728
729
730
# File 'lib/core/util/console.rb', line 728

def self.blue(string)
  colorize(string, :blue)
end

.colorize(string, color) ⇒ Object

Colorize a given string if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

    • String, Symbol

      color Color to use; :black, :red, :green, :yellow, :blue, :purple, :cyan, :grey

  • Returns

    • String

      Colorized or input string depending on global color flag

  • Errors

See also:

  • ::use_colors



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/core/util/console.rb', line 627

def self.colorize(string, color)
  return '' unless string
  return string.to_s unless use_colors

  color        = color.to_sym
  string       = string.to_s
  color_string = string

  if @@colors[color]
    color         = @@colors[color]
    clear_color   = @@colors[:clear]
    escaped_clear = Regexp.escape(clear_color)

    color_string  = "#{color}"
    color_string << string.gsub(/#{escaped_clear}(?!\e\[)/, "#{clear_color}#{color}")
    color_string << "#{clear_color}"
  end
  color_string
end

.cyan(string) ⇒ Object

Color a given string cyan if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Cyan or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



762
763
764
# File 'lib/core/util/console.rb', line 762

def self.cyan(string)
  colorize(string, :cyan)
end

.green(string) ⇒ Object

Color a given string green if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Green or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



694
695
696
# File 'lib/core/util/console.rb', line 694

def self.green(string)
  colorize(string, :green)
end

.grey(string) ⇒ Object

Color a given string grey if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Grey or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



779
780
781
# File 'lib/core/util/console.rb', line 779

def self.grey(string)
  colorize(string, :grey)
end

.purple(string) ⇒ Object

Color a given string purple if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Purple or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



745
746
747
# File 'lib/core/util/console.rb', line 745

def self.purple(string)
  colorize(string, :purple)
end

.quietObject

Check current global quiet flag

  • Parameters

  • Returns

    • Boolean

      Whether or not console output is disabled at the global level

  • Errors

See also:

  • ::quiet=



183
184
185
# File 'lib/core/util/console.rb', line 183

def self.quiet
  @@quiet
end

.quiet=(quiet) ⇒ Object

Set current global quiet flag

  • Parameters

    • Boolean

      quiet Whether or not console output is disabled at the global level

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • ::quiet



200
201
202
# File 'lib/core/util/console.rb', line 200

def self.quiet=quiet
  @@quiet = quiet
end

.red(string) ⇒ Object

Color a given string red if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Red or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



677
678
679
# File 'lib/core/util/console.rb', line 677

def self.red(string)
  colorize(string, :red)
end

.use_colorsObject

Check current global use colors flag

  • Parameters

  • Returns

    • Boolean

      Whether or not console output coloring is allowed at the global level

  • Errors

See also:

  • ::use_colors=



220
221
222
# File 'lib/core/util/console.rb', line 220

def self.use_colors
  @@use_colors && ! ENV['NUCLEON_NO_COLOR']
end

.use_colors=(use_colors) ⇒ Object

Set current global use colors flag

  • Parameters

    • Boolean

      use_colors Whether or not console output coloring is allowed at the global level

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • ::use_colors



237
238
239
# File 'lib/core/util/console.rb', line 237

def self.use_colors=use_colors
  @@use_colors = use_colors
end

.yellow(string) ⇒ Object

Color a given string yellow if global colors enabled, else return input string.

  • Parameters

    • String, Symbol

      string String to colorize (if colors allowed globally)

  • Returns

    • String

      Yellow or uncolored input string depending on global color flag

  • Errors

See:

  • ::colorize



711
712
713
# File 'lib/core/util/console.rb', line 711

def self.yellow(string)
  colorize(string, :yellow)
end

Instance Method Details

#ask(message, options = {}) ⇒ Object

Ask terminal user for an input value

Input text can be freely displayed or hidden as typed.

  • Parameters

    • String

      message Message to display to the user

    • Hash

      options Input options

      • Boolean

        :new_line Append new line to end of message

      • Boolean

        :prefix Render prefix before message (console resource)

      • Boolean

        :echo Whether or not to echo the input back to the screen

      • #say options (minus :quiet_override)

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #say

  • Nucleon::Config::ensure

  • Nucleon::Config#import

  • Nucleon::Config#export



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/core/util/console.rb', line 331

def ask(message, options = {})
  return @delegate.ask(message, options) if check_delegate('ask')

  options[:new_line] = false if ! options.has_key?(:new_line)
  options[:prefix] = false if ! options.has_key?(:prefix)
  options[:echo] = true if ! options.has_key?(:echo)

  user_input = nil

  say(:info, message, Config.ensure(options).import({
    :quiet_override => true,
    :new_line => false
  }).export)

  if options[:echo]
    user_input = @input.gets.chomp
  else
    require 'io/console'
    user_input = @input.noecho(&:gets).chomp
  end
  safe_puts("\n")
  user_input
end

#check_delegate(method) ⇒ Object

Check if a registered delegate exists and responds to a specified method.

  • Parameters

    • String, Symbol

      method Method to check in delegate if registered

  • Returns

    • Boolean

      Whether a delegate that responds to method exists

  • Errors



606
607
608
# File 'lib/core/util/console.rb', line 606

def check_delegate(method)
  return Util::Data.test(@delegate && @delegate.respond_to?(method.to_s))
end

#dump(data, options = {}) ⇒ Object

Dump an object to an output channel even if quiet specified

Data dumps can not be silenced.

  • Parameters

    • String

      data Serialized data object or text string

    • Hash

      options Dump options

      • Symbol

        :channel IO channel to send output to (don’t touch)

      • #safe_puts options

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #safe_puts



300
301
302
303
304
305
# File 'lib/core/util/console.rb', line 300

def dump(data, options = {})
  return @delegate.dump(data, options) if check_delegate('dump')

  options[:channel] = options.has_key?(:channel) ? options[:channel] : @error
  safe_puts(data.to_s, options)
end

#format_message(type, message, options = {}) ⇒ Object

Format a message for display.

Primary functions:

  1. Add prefix to each line if requested (:prefix)

  2. Add colors to each line if requested (global and instance color enabled)

  • Parameters

    • Symbol

      type Message type; :warn, :error, :success

    • String

      message Message to render

    • Hash

      options Format options

      • Boolean

        :color Color to use; :black, :red, :green, :yellow, :blue, :purple, :cyan, :grey

      • Boolean

        :prefix Render prefix before message

      • String

        :prefix_text Text to render within brackets [prefix_text] (default console resource)

  • Returns

    • String

      Formatted string ready for output

  • Errors

See also:

  • ::use_colors

  • ::colorize

  • #check_delegate

  • #say



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/core/util/console.rb', line 512

def format_message(type, message, options = {})
  return @delegate.format_message(type, message, options) if check_delegate('format_message')
  return '' if message.to_s.strip.empty?

  if options[:prefix]
    if prefix_text = options[:prefix_text]
      prefix = "[#{prefix_text}]"

    elsif @resource && ! @resource.empty?
      prefix = "[#{@resource}]"
    end
  end

  lines         = []
  prev_color    = nil
  escaped_clear = Regexp.escape(@@colors[:clear])

  message.split("\n").each do |line|
    line = prev_color + line if self.class.use_colors && @color && prev_color

    lines << "#{prefix} #{line}".sub(/^ /, '')

    if self.class.use_colors && @color
      # Set next previous color
      if line =~ /#{escaped_clear}$/
        prev_color = nil
      else
        line_section = line.split(/#{escaped_clear}/).pop

        if line_section
          prev_colors = line_section.scan(/\e\[[0-9][0-9]?m/)
          prev_color  = prev_colors.pop unless prev_colors.empty?
        end
      end
    end
  end

  message = lines.join("\n")

  if self.class.use_colors && @color
    if options.has_key?(:color)
      message = self.class.colorize(message, options[:color])
    else
      message = self.class.colorize(message, @@color_map[type]) if @@color_map[type]
    end
  end
  return message
end

#info(message, *args) ⇒ Object

Output information to an output channel unless quiet specified

  • Parameters

    • String

      message Message to render to output channel

    • Hash

      options Output options

      • #say options

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #say



415
416
417
418
# File 'lib/core/util/console.rb', line 415

def info(message, *args)
  return @delegate.info(message, *args) if check_delegate('info')
  say(:info, message, *args)
end

#inspectObject

Return a string reference that identifies this console object

  • Parameters

  • Returns

    • String

      Identification string

  • Errors



124
125
126
# File 'lib/core/util/console.rb', line 124

def inspect
  "#<#{self.class}: #{@resource}>"
end

#password(type, options = {}) ⇒ Object

Ask terminal user for a password

Keeps requesting until two password inputs match or user cancels the input.

TODO: Needs I18n treatment.

  • Parameters

    • String, Symbol

      type Type of password being requested (in prompt)

    • Hash

      options Input options

  • Returns

    • String

      Returns password with whitespace stripped

  • Errors

See also:

  • #check_delegate

  • #ask



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/core/util/console.rb', line 374

def password(type, options = {})
  return @delegate.password(type, options) if check_delegate('password')

  try_again = true
  password  = nil

  while try_again
    # Get and check a password from the keyboard
    password              = ask("Enter #{type} password: ", { :echo => false })
    confirmation_password = ask("Confirm #{type} password: ", { :echo => false })

    if password != confirmation_password
      choice    = ask('Passwords do not match!  Try again? (Y|N): ')
      try_again = choice.upcase == "Y"
      password  = nil unless try_again
    else
      try_again = false
    end
  end
  password = password.strip if password
  password
end

#safe_puts(message = nil, options = {}) ⇒ Object

Safely output via a printer method to an output channel unless quiet specified

  • Parameters

    • String

      message Message to render to output channel

    • Hash

      options Output options

      • Symbol

        :channel IO channel to send output to (don’t touch)

      • Symbol

        :printer Printer method to use; :puts, :print

  • Returns

    • Void

      This method does not return a value

  • Errors

    • Errno::EPIPE

      Error if sending of output to communication channel fails

See also:

  • #check_delegate



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/core/util/console.rb', line 578

def safe_puts(message = nil, options = {})
  return @delegate.safe_puts(message, options) if check_delegate('safe_puts')

  message ||= ""
  options = {
    :channel => @output,
    :printer => @printer,
  }.merge(options)

  begin
    options[:channel].send(options[:printer], message)
  rescue Errno::EPIPE
    return
  end
end

#say(type, message, options = {}) ⇒ Object

Output via a printer method to an output channel unless quiet specified

  • Parameters

    • Symbol

      type Message type; :warn, :error, :success

    • String

      message Message to render to output channel

    • Hash

      options Output options

      • Boolean

        :quiet_override Whether or not to override global quiet flag

      • Boolean

        :new_line Append new line to end of message

      • Boolean

        :prefix Render prefix before message (console resource)

      • Symbol

        :channel IO channel to send output to (don’t touch)

      • #format_message options

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #format_message

  • #safe_puts



266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/core/util/console.rb', line 266

def say(type, message, options = {})
  return if @@quiet && ! options[:quiet_override]
  return @delegate.say(type, message, options) if check_delegate('say')

  defaults = { :new_line => true, :prefix => true }
  options  = defaults.merge(options)
  printer  = options[:new_line] ? :puts : :print
  suffix   = options[:new_line] ? "\n" : ''

  puts_options           = { :printer => printer }
  puts_options[:channel] = options[:channel] if options.has_key?(:channel)

  safe_puts(format_message(type, message, options) + suffix, puts_options)
end

#success(message, *args) ⇒ Object

Output success message to an output channel unless quiet specified

  • Parameters

    • String

      message Message to render to output channel

    • Hash

      options Output options

      • #say options

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #say



478
479
480
481
# File 'lib/core/util/console.rb', line 478

def success(message, *args)
  return @delegate.success(message, *args) if check_delegate('success')
  say(:success, message, *args)
end

#warn(message, *args) ⇒ Object

Output warning to an output channel unless quiet specified

  • Parameters

    • String

      message Message to render to output channel

    • Hash

      options Output options

      • #say options

  • Returns

    • Void

      This method does not return a value

  • Errors

See also:

  • #check_delegate

  • #say



436
437
438
439
# File 'lib/core/util/console.rb', line 436

def warn(message, *args)
  return @delegate.warn(message, *args) if check_delegate('warn')
  say(:warn, message, *args)
end