Class: ProgressBar::Format::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-progressbar/format/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format_string) ⇒ Base

Returns a new instance of Base.



6
7
8
9
# File 'lib/ruby-progressbar/format/base.rb', line 6

def initialize(format_string)
  @format_string = format_string
  @molecules     = parse(format_string)
end

Instance Attribute Details

#moleculesObject (readonly)

Returns the value of attribute molecules.



4
5
6
# File 'lib/ruby-progressbar/format/base.rb', line 4

def molecules
  @molecules
end

Instance Method Details

#process(environment) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ruby-progressbar/format/base.rb', line 11

def process(environment)
  processed_string = @format_string.dup
  ansi_sgr_codes   = %r{\e\[[\d;]+m}

  non_bar_molecules.each do |molecule|
    processed_string.gsub!("%#{molecule.key}", environment.send(molecule.method_name).to_s)
  end

  remaining_molecules = bar_molecules.size
  placeholder_length  = remaining_molecules * 2

  processed_string.gsub! '%%', '%'

  processed_string_length = processed_string.gsub(ansi_sgr_codes, '').length
  leftover_bar_length     = environment.send(:length) - processed_string_length + placeholder_length
  leftover_bar_length     = leftover_bar_length < 0 ? 0 : leftover_bar_length

  bar_molecules.each do |molecule|
    processed_string.gsub!("%#{molecule.key}", environment.send(molecule.method_name, leftover_bar_length).to_s)
  end

  processed_string
end