Class: Dashes::Chart

Inherits:
Node
  • Object
show all
Defined in:
lib/dashes.rb

Instance Method Summary collapse

Constructor Details

#initializeChart

Returns a new instance of Chart.



140
141
142
143
144
145
# File 'lib/dashes.rb', line 140

def initialize
  @title = nil
  @rows = []
  @width = nil
  @max_width = nil
end

Instance Method Details

#max_width(max_width) ⇒ Object



162
163
164
165
# File 'lib/dashes.rb', line 162

def max_width(max_width)
  @max_width = max_width
  self
end

#row(label, num) ⇒ Object



152
153
154
155
# File 'lib/dashes.rb', line 152

def row(label, num)
  @rows << [label, num]
  self
end

#title(title) ⇒ Object



147
148
149
150
# File 'lib/dashes.rb', line 147

def title(title)
  @title = title
  self
end

#to_sObject



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/dashes.rb', line 167

def to_s
  return '' if @rows.empty?
  wbar, wlabel = bar_width, label_width
  wtotal = total_width - 4 # 4 for side borders and padding
  bar_space = wtotal - wlabel - 1
  bar_ratio = wbar > bar_space ? bar_space/wbar.to_f : 1

  separator = "+-#{'-'*wtotal}-+"
  format = [separator]
  if @title
    format << "| #{cell(@title, wtotal)} |"
    format << separator
  end
  @rows.each do |label, num|
    bar = '=' * (num * bar_ratio).floor
    format << "| #{cell(label, wlabel, :right)} #{cell(bar, bar_space)} |"
  end
  format << separator
  format.join("\n")
end

#total_widthObject



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/dashes.rb', line 188

def total_width
  if @rows.empty?
    0
  elsif @width
    @width
  else
    # 4 for borders/padding
    twidth = [bar_width + label_width + 1, title_width].max + 4
    @max_width ? [twidth, @max_width].min : twidth
  end
end

#width(width) ⇒ Object



157
158
159
160
# File 'lib/dashes.rb', line 157

def width(width)
  @width = width
  self
end