File: help_formatters.rb

package info (click to toggle)
ruby-commander 4.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 360 kB
  • sloc: ruby: 1,971; makefile: 9
file content (51 lines) | stat: -rw-r--r-- 1,239 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true

module Commander
  module HelpFormatter
    autoload :Base, 'commander/help_formatters/base'
    autoload :Terminal, 'commander/help_formatters/terminal'
    autoload :TerminalCompact, 'commander/help_formatters/terminal_compact'

    class Context
      def initialize(target)
        @target = target
      end

      def get_binding
        @target.instance_eval { binding }.tap do |bind|
          decorate_binding(bind)
        end
      end

      # No-op, override in subclasses.
      def decorate_binding(_bind)
      end
    end

    class ProgramContext < Context
      def decorate_binding(bind)
        bind.eval("max_command_length = #{max_command_length(bind)}")
        bind.eval("max_aliases_length = #{max_aliases_length(bind)}")
      end

      def max_command_length(bind)
        max_key_length(bind.eval('@commands'))
      end

      def max_aliases_length(bind)
        max_key_length(bind.eval('@aliases'))
      end

      def max_key_length(hash, default = 20)
        longest = hash.keys.max_by(&:size)
        longest ? longest.size : default
      end
    end

    module_function

    def indent(amount, text)
      text.to_s.gsub("\n", "\n#{' ' * amount}")
    end
  end
end