Class: MakeMenu::FieldSet

Inherits:
Object
  • Object
show all
Defined in:
lib/make_menu/field_set.rb

Overview

A set of FIELDS to display above the menu

Instance Method Summary collapse

Constructor Details

#initialize ⇒ FieldSet

Returns a new instance of FieldSet.



6
7
8
9
# File 'lib/make_menu/field_set.rb', line 6

def initialize
  @fields = []
  @max_widths = {}
end

Instance Method Details

#add(label = '', value_from_file: nil, color: :normal, none: '[none]'.dark, &block) ⇒ Object

Add a new field to the set

Parameters:

  • label (String) (defaults to: '') —

    Optional label to print to the left of the field value

  • value_from_file (String, Symbol) (defaults to: nil) —

    If set, read the field value from a file in the current directory. A String is used literally, a Symbol is assumed to be a hidden file (i.e. starts with .)

  • color (String, Symbol, Integer) (defaults to: :normal) —

    Formatting to apply to the value

  • none (String) (defaults to: '[none]'.dark) —

    Text to display if the file does not exist, or is empty

  • block (Proc) —

    Block to return the value to display



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/make_menu/field_set.rb', line 19

def add(label = '', value_from_file: nil, color: :normal, none: '[none]'.dark, &block)
  if value_from_file
    if value_from_file.is_a? Symbol
      value_from_file = ".#{value_from_file}"
    end
    block = lambda do
      if File.exist? value_from_file
        value = File.read(value_from_file).strip

        return none if value.empty?

        return value.color(color)
      else
        return none
      end
    end
  end

  @fields << {
    label: label,
    handler: block
  }
end

#display ⇒ Object

Print fields in an aligned vertical stack



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/make_menu/field_set.rb', line 44

def display
  build
  @fields.each do |field|
    label_cell = field[:label]
                   .align(
                     :right,
                     width: @max_widths[:label]
                   )

    value_cel = field[:value]
                  .align(
                    :left,
                    width: @max_widths[:value],
                    pad_right: true
                  )

    puts "#{label_cell}#{value_cel}".align(:center)
  end
  puts
end