class CLIHelper::ShowTable

Show table

Attributes

default_columns[R]

Public Class Methods

new(conf = nil, ext = nil, &block) click to toggle source

Class constructor

@param conf [String] Configuration file @param ext [Helper] Cli helper information

# File lib/cli_helper.rb, line 321
def initialize(conf = nil, ext = nil, &block)
    @columns         = {}
    @default_columns = []

    @ext  = ext
    @conf = conf

    instance_eval(&block)
end

Public Instance Methods

column(name, desc, *conf, &block) click to toggle source

Fill column attributes

@param name [String] Column name @param desc [String] Column description @param conf [Array] Configutation attributes

# File lib/cli_helper.rb, line 341
def column(name, desc, *conf, &block)
    column = {}

    column[:desc] = desc
    column[:size] = 5

    conf.each do |c|
        case c
        when Symbol
            column[c] = true
        when Hash
            c.each do |key, value|
                column[key] = value
            end
        end
    end

    column[:proc] = block

    @columns[name.to_sym] = column

    @default_columns << name
end
columns_info(columns) click to toggle source

Get columns information

@param columns [Array] Array with columns information

@return [Array] Array with columns objects

# File lib/cli_helper.rb, line 484
def columns_info(columns)
    ret = []

    columns.each do |column|
        data = column.to_s.split('=')

        ret << { :name => data[0].upcase.to_sym, :prop => data[1] }
    end

    ret
end
default(*args) click to toggle source

Get default columns

@param args [Array] Array with default columns

# File lib/cli_helper.rb, line 368
def default(*args)
    args.map! {|a| a.to_sym }

    @default_columns = args
end
describe_columns() click to toggle source

Show column description

# File lib/cli_helper.rb, line 441
def describe_columns
    str = '%-20s: %-20s'

    @columns.each do |column, d|
        puts format(str, column, d[:desc])
    end
end
helper() click to toggle source

Get the helper

# File lib/cli_helper.rb, line 332
def helper
    @ext
end
max_size(index) click to toggle source

Get maximum string lenght in column

@param index [Integer] Column index to search

@return [Integer] Maximum length

# File lib/cli_helper.rb, line 454
def max_size(index)
    sizes = []

    @res_data.each do |d|
        sizes << d[index].size
    end

    sizes.max
end
print_tty_header() click to toggle source

Print tty header

show(data, options = {}, top = false) click to toggle source

Show resource

@param data [Hash/Object] Data to show @param options [Hash] Object with CLI user options @param top [Boolean] True to not update columns again

# File lib/cli_helper.rb, line 379
def show(data, options = {}, top = false)
    update_columns(options) unless top

    if options[:list]
        @cli_columns = options[:list].collect {|o| o.upcase.to_sym }
    else
        @cli_columns = @default_columns
    end

    if data.is_a? Hash
        @data = data

        @data.extend(HashWithSearch)

        pool = @data.keys.first

        return print_table(data, options) unless pool

        element = pool.split('_')[0..-2].join('_')

        pool_data = @data.dsearch("#{pool}/#{element}")

        if pool_data
            pool_data = [pool_data].flatten
        else
            pool_data = []
        end

        print_table(pool_data, options)
    else
        data ||= []

        print_table(data, options)
    end
end
top(options = {}) { || ... } click to toggle source

Show resource continuosly

@param options [Hash] Object with CLI user options

# File lib/cli_helper.rb, line 418
def top(options = {})
    delay = options[:delay] || 1
    top   = false

    begin
        loop do
            data = yield

            CLIHelper.scr_cls
            CLIHelper.scr_move(0, 0)

            show(data, options, top)

            sleep delay

            top = true
        end
    rescue SystemExit, Interrupt, StandardError => e
        CLIHelper.fail(e.message)
    end
end
total_columns_size(columns) click to toggle source

Get total size of all columns

@param columns [Array] Array with columns name

@return [Integer] Total size

# File lib/cli_helper.rb, line 469
def total_columns_size(columns)
    size = 0

    columns.each do |c|
        size += @columns[c[:name]][:size]
    end

    size
end

Private Instance Methods

config_adjust_data() click to toggle source

Get adjust information from configuration files

@return [Array] Array with columns data

# File lib/cli_helper.rb, line 670
def config_adjust_data
    ret = []

    @cli_columns.each do |column|
        next unless @columns[column][:adjust]

        ret << column.to_s.downcase
    end

    ret
end
config_expand_data() click to toggle source

Get expand information from configuration files

@return [Array] Array with columns data

# File lib/cli_helper.rb, line 649
def config_expand_data
    ret = []

    @cli_columns.each do |column|
        expand_c = @columns[column][:expand]

        next unless expand_c

        column = column.to_s.downcase

        ret << "#{column}=#{expand_c}" if expand_c.is_a? Numeric

        ret << column.to_s.downcase unless expand_c.is_a? Numeric
    end

    ret
end
data_array(data, options) click to toggle source

Get data in array format

@param data [Array] Array with data to show @param options [Hash] Object with CLI user options

@return [Array] Array with selected columns information

# File lib/cli_helper.rb, line 606
def data_array(data, options)
    # Take default table columns and desired ones by the user
    cols = @default_columns

    @cli_columns.each do |col|
        next if @default_columns.include?(col)

        @default_columns.insert(@cli_columns.index(col) + 1, col)
    end

    res_data = data.collect do |d|
        cols.collect do |c|
            @columns[c][:proc].call(d).to_s if @columns[c]
        end
    end

    filter_data!(res_data, options) if options && options[:filter]

    res_data
end
expand_columns(expand_columns, all = false) click to toggle source

Change the size of expand columns

@param expand_columns [Array] Array with expand columns names @param all [Boolean] True to expand all columns

# File lib/cli_helper.rb, line 686
def expand_columns(expand_columns, all = false)
    return if expand_columns.empty?

    if $stdout.isatty
        terminal_size = $stdout.winsize[1]
    elsif IO.console && IO.console.tty?
        terminal_size = IO.console.winsize[1]
    else
        terminal_size = nil
    end

    return if terminal_size.nil?

    default_columns = columns_info(@cli_columns)
    expand_columns  = columns_info(expand_columns)

    total_size     = total_columns_size(default_columns)
    columns_size   = total_columns_size(expand_columns)

    terminal_size -= (@cli_columns.size - 1)
    left_size      = terminal_size - total_size
    remaining_size = left_size

    return if left_size <= 0

    expand_columns.each do |c|
        column = c[:name]
        prop   = c[:prop]

        if @columns[column].nil?
            CLIHelper.fail("Unknown column #{column}")
        end

        if all
            prop = @columns[column][:size] / total_size.to_f
        elsif !prop
            prop = @columns[column][:size] / columns_size.to_f
        end

        size = (left_size * prop.to_f).round

        @columns[column][:adjust] = false
        @columns[column][:size]  += size

        remaining_size -= size
    end

    if remaining_size > 0
        # If there is some left space, add it to the last column
        @columns[expand_columns[-1][:name]][:size] += remaining_size
    end

    return if terminal_size == total_columns_size(default_columns)

    # If there is extra space, sub it from the last column
    diff = total_columns_size(default_columns) - terminal_size

    @columns[expand_columns[-1][:name]][:size] -= diff
end
filter_data!(data, options) click to toggle source

Filter data

@param data [Array] Array with data to filter @param options [Hash] Object with CLI user options

# File lib/cli_helper.rb, line 849
def filter_data!(data, options)
    operators = /(#{FILTER_OPS.join('|')})/
    filter    = options[:filter]

    if options.key?(:operator)
        log_operator = options[:operator].upcase
    else
        log_operator = 'AND'
    end

    stems = filter.map do |s|
        m = s.match(/^(.*?)#{operators}(.*?)$/)

        if m
            index = @default_columns.index(m[1].upcase.to_sym)

            if index
                {
                    :left       => m[1],
                    :operator   => m[2],
                    :right      => m[3],
                    :index      => index
                }
            else
                CLIHelper.fail("Column '#{m[1]}' not found")
            end
        else
            CLIHelper.fail("Expression '#{s}' incorrect")
        end
    end

    data.select! do |d|
        pass = true

        stems.each do |s|
            case s[:operator]
            when '='
                op = '=='
            when '~'
                op = 'include?'
            else
                op = s[:operator]
            end

            if d[s[:index]].public_send(op, s[:right])
                if log_operator == 'OR'
                    pass = true

                    break
                end
            else
                pass = false

                break if log_operator == 'AND'
            end
        end

        pass
    end
end
format_str(field, data) click to toggle source

Format data as string

@param field [Symbol] Name of the column to format @param data [String] Data to format

# File lib/cli_helper.rb, line 631
def format_str(field, data)
    if @columns[field]
        @columns[field][:left] ? minus = '-' : minus = ''
        size = @columns[field][:size]

        if @columns[field][:adjust]
            format("%#{minus}#{size}s", data.to_s)
        else
            format("%#{minus}#{size}.#{size}s", data.to_s)
        end
    else
        CLIHelper.fail("Column #{field} not defined.")
    end
end
header_str() click to toggle source

Get header in string format

# File lib/cli_helper.rb, line 506
def header_str
    @cli_columns.collect do |c|
        if @columns[c]
            format_str(c, c.to_s)
        else
            CLIHelper.fail("Column #{c} not defined.")
        end
    end.compact.join(' ')
end
print_csv_data(data, del) click to toggle source

Print data in CSV format

@param data [Array] Array with data to show @param del [Char] CSV delimiter

print_data(data, options) click to toggle source

Print data

@param data [Array] Array with data to show @param options [Hash] Object with CLI user options

print_normal_data(data, stat_column) click to toggle source

Print data in normal format

@param data [Array] Array with data to show @param stat_column [String] Name of the state column

print_table(data, options) click to toggle source

Print data in table format

@param data [Array] Array with data to show @param options [Hash] Object with CLI user options

size_columns(options) click to toggle source

Change columns size

@param options [Array] Array with size information for each column

# File lib/cli_helper.rb, line 749
def size_columns(options)
    options[:size].each do |column|
        data   = column.split('=')
        column = data[0].upcase.to_sym
        size   = data[1].to_i

        @columns[column][:adjust] = false
        @columns[column][:size]   = size
    end
end
update_columns(options) click to toggle source

Update columns information

@param options [Hash] Object with CLI user options

# File lib/cli_helper.rb, line 810
def update_columns(options)
    begin
        if @conf && File.exist?(@conf)
            config = YAML.load_file(@conf)
        else
            config = {}
        end

        default      = config.delete(:default) || {}
        default_conf = config.delete(:default_conf) || {}
        listconf     = options[:listconf]

        listconf = default_conf[listconf.to_sym] if listconf

        if !listconf && ENV['ONE_LISTCONF']
            listconf = default_conf[ENV['ONE_LISTCONF'].to_sym]
        end

        if listconf
            @default_columns = listconf
        else
            @default_columns = default unless default.empty?
        end

        # Filter show options with available columns
        @default_columns &= @columns.keys

        @columns.merge!(config) do |_key, oldval, newval|
            oldval.merge(newval)
        end
    rescue StandardError => e
        CLIHelper.fail(e.message)
    end
end
update_columns_size(options) click to toggle source

Update columns size information

@param options [Hash] Object with CLI user options

# File lib/cli_helper.rb, line 763
def update_columns_size(options)
    adjust = options[:adjust]

    if adjust
        adjust += config_adjust_data
    else
        adjust = config_adjust_data
    end

    expand_all  = (options.key? :expand) && options[:expand].nil?
    expand      = !options[:expand].nil?
    expand_data = []

    if expand_all
        expand_data = @cli_columns
    elsif expand
        expand_data += options[:expand]
    end

    expand_data += config_expand_data

    c_size = options[:size]

    # Update adjust attribute to not truncate the column
    # If expand all columns adjust is ignored
    unless expand_all
        adjust.each do |column|
            column = column.upcase.to_sym
            size   = max_size(@cli_columns.index(column))

            if size && size > @columns[column][:size]
                @columns[column][:adjust] = true
                @columns[column][:size]   = size
            end
        end
    end

    # Update size attribute if size
    size_columns(options) if c_size

    # Update size attribute if expand
    expand_columns(expand_data) unless options.key? :no_expand
end