Sha256: 3f9f9d8facc106004afc620411c486c069c3f35280113de024769055b3aa278e

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

class InvocaGems::Presenter
  def set_task(message)
    clear_task
    @task = using_mode(:green, message)
    set_subtask('')
  end

  def clear_task(keep: true)
    if @task
      if keep
        @new_line_needed = false
        puts
      else
        print reset_line
        @new_line_needed = false
      end
      @task = nil
    end
  end

  def message(message)
    puts using_mode(:green, message)
  end

  def warning(message)
    puts using_mode(:yellow, "warning: #{message}")
  end

  def error(message)
    puts using_mode(:red, "error: #{message}")
  end

  def set_subtask(message)
    print "#{reset_line}#{@task}: #{message}"
  end

  def reset_line
    "\r\e[K"
  end

  def puts(*args)
    unless @silent
      if @new_line_needed
        super()
        @new_line_needed = false
      end
      super
    end
  end

  def print(*args)
    unless @silent
      @new_line_needed = true
      super
    end
  end

  def silence
    @silent = true
    yield
  ensure
    @silent = false
  end

  def set_mode(codes)
    "\e[#{[codes].flatten.map{ |c| COLOR_CODES[c].to_s }.join(";")}m"
  end

  def using_mode(codes, message)
    set_mode(codes) + message + set_mode(:clear)
  end

  class StopWithMessage < StandardError; end
  def stop_with_message(message)
    raise StopWithMessage, message
  end

  def self.stop_with_message(message)
    raise StopWithMessage, message
  end


  def self.with_presenter
    presenter = new
    begin
      yield presenter
    rescue StopWithMessage => ex
      presenter.error(ex.message)
    end
  end

  COLOR_CODES = {
    clear: 0,
    bright: 1,
    underline: 4,
    blink: 5,
    swap: 7,
    hide: 8,
    black: 30,
    red: 31,
    green: 32,
    yellow: 33,
    blue: 34,
    magenta: 35,
    white: 37,
    default: 39,
    black_background: 40,
    red_background: 41,
    blue_background: 40,
    green_background: 42,
    blue_background: 44,
    magenta_background: 45,
    cyan_background: 46,
    white_background: 47,
    default_background: 49
  }

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
invoca_gems-0.1.0 lib/invoca_gems/presenter.rb