Sha256: 4df57623434444294e7869df647161a7f2fd73f7d9015d621a741077eeffb21a

Contents?: true

Size: 1.55 KB

Versions: 1

Compression:

Stored size: 1.55 KB

Contents

module Flucti
  module Utilities
    class ListDisplayer
      attr_reader :options, :columns

      def initialize(options={}, &block)
        @options = options
        @columns = build_column_list(&block)
      end

      def display(entries)
        if options[:table] || entries.size > 3
          puts entries.inject(Utilities::Table.new(*columns.map { |title,| title })) { |table, entry|
            table << columns.map { |title, proc| proc.call(entry) }
          }
        else
          entries.each do |entry|
            if attribute = options[:title]
              puts_subtitle(entry.send(attribute))
            else
              title, proc = columns.first
              val = proc.call(entry)
              puts_subtitle(val.to_s =~ /^\d+$/ ? "#{title}=#{val}" : val)
            end
            display_single_entry(entry)
          end
        end
        puts "\nTotal: #{entries.size}"
      end

      def display_single_entry(entry)
        columns.each do |title, proc|
          puts "%-*s %s" % [column_width+1, "#{title}:", proc.call(entry)]
        end
      end

    private

      def build_column_list
        columns = []
        def columns.col(title, method=nil, &proc)
          push [title, proc || method.to_proc]
        end
        if attribute = options.fetch(:id, :id)
          attribute = :id if ENV['NUMERIC_ID']
          columns.col("ID", attribute)
        end
        yield columns
        return columns
      end

      def column_width
        @column_width ||= columns.map { |title,| title.to_s.length }.max
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
Flucti-flucti-cli-0.1.16 lib/flucti/utilities/list_displayer.rb