Class: MakeMenu::FieldSet

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

Instance Method Summary collapse

Constructor Details

#initializeFieldSet



3
4
5
6
# File 'lib/make_menu/field_set.rb', line 3

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

Instance Method Details

#add(label = nil, label_color: :normal, value_color: :normal, &block) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/make_menu/field_set.rb', line 43

def add(label = nil, label_color: :normal, value_color: :normal, &block)
  @fields << {
    label: label || '',
    label_color: label_color,
    value_color: value_color,
    handler: block
  }
end

#buildObject



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/make_menu/field_set.rb', line 29

def build
  @max_widths[:label] = 0
  @max_widths[:value] = 0

  @fields.each do |field|
    label = field[:label]
    value = field[:value] = field[:handler].call
    label_width = label.decolor.size
    value_width = value.decolor.size
    @max_widths[:label] = label_width if label_width > @max_widths[:label]
    @max_widths[:value] = value_width if value_width > @max_widths[:value]
  end
end

#displayObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/make_menu/field_set.rb', line 8

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

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

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