Class: Clive::Formatter::Plain

Inherits:
Clive::Formatter show all
Defined in:
lib/clive/formatter/plain.rb

Direct Known Subclasses

Colour

Constant Summary collapse

DEFAULTS =
{
  :padding   => 2,
  :width     => Output.terminal_width,
  :min_ratio => 0.2,
  :max_ratio => 0.5
}

Instance Attribute Summary

Attributes inherited from Clive::Formatter

#commands, #footer, #header, #options

Instance Method Summary collapse

Methods inherited from Clive::Formatter

#inspect

Constructor Details

#initialize(opts = {}) ⇒ Plain

Returns a new instance of Plain.

Parameters:

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :width (Integer)

    Total width of screen to use

  • :padding (Integer)

    Amount of padding to use

  • :min_ratio (Float)

    Minimum proportion of screen the left side can use

  • :max_ratio (Float)

    Maximum proportion of screen the left side can use



22
23
24
25
26
27
28
29
30
31
# File 'lib/clive/formatter/plain.rb', line 22

def initialize(opts={})
  @opts = DEFAULTS.merge(opts)

  if @opts[:min_ratio] > @opts[:max_ratio]
    @opts[:max_ratio] = @opts[:min_ratio]
  end

  @header, @footer = "", ""
  @commands, @options = [], []
end

Instance Method Details

#to_sString

Builds the help string. Formatted like:

Usage: the header

  Commands:
    command            # Description

  Options:
    -a, --abc <arg>    # Description

A footer

Returns:



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/clive/formatter/plain.rb', line 46

def to_s
  groups = (@options + @commands).group_by {|i| i.config[:group] }

  # So no groups were created, let's create some nice defaults
  if groups.size == 1 && groups.keys.first == nil
    # Use an array so that the order is always correct
    groups = [['Commands', @commands.sort], ['Options', @options.sort]]
  end

  r = @header.dup << "\n\n"

  groups.each do |name, group|
    unless group.empty?
      r << (name ? "#{padding}#{name}:\n" : '')
      group.sort.sort_by {|i| i.instance_of?(Command) ? 0 : 1 }.each do |opt|
        r << build_option_string(opt)
      end
      r << "\n"
    end
  end

  r << @footer
  r.split("\n").map {|i| i.rstrip }.join("\n")
end