Class: SimpleTable

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#dividerObject

Returns the value of attribute divider.



8
9
10
# File 'lib/simpletable.rb', line 8

def divider
  @divider
end

#paddingObject

Returns the value of attribute padding.



8
9
10
# File 'lib/simpletable.rb', line 8

def padding
  @padding
end

#placeholderObject

Returns the value of attribute placeholder.



8
9
10
# File 'lib/simpletable.rb', line 8

def placeholder
  @placeholder
end

Instance Method Details

#csv(separator = @separator) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/simpletable.rb', line 39

def csv(separator=@separator)
  @separator = separator if @separator != separator
  # quote strings w/ embedded separator characters
  titles = []
  @titles.each {|t| titles << (t.include?(@separator) ? t.gsub(t,"\"#{t}\"") : t)}

  # print table header
  text = titles.join(@separator) << "\n"

  # print table body
  @objects.each do |o|
    data = @methods.collect{ |m| call_method(o,m) } # collect row data
    text << data.join(@separator) << "\n"
  end
  text
end

#from_objects(objects, titles, methods, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/simpletable.rb', line 9

def from_objects( objects, titles, methods, options = {} )
  raise "Mismatched number of methods and column titles" if titles.length != methods.length
  @objects = objects
  @titles = titles
  @methods = methods
  @divider = options[:divider] || DEFAULT_DIVIDER
  @padding = options[:padding] || DEFAULT_PADDING
  @placeholder = options[:placeholder] || DEFAULT_PLACEHOLDER
  self
end

#textObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/simpletable.rb', line 20

def text
  widths = []
  # calculate column widths
  @titles.zip(@methods).each do |title,method|
    widths << @objects.collect { |o| call_method(o,method) }.push(title).group_by(&:size).max.first + @padding
  end

  # print table header
  text = row(@titles,widths)
  text << (@divider * (widths.inject(:+) - @padding)) << "\n"  # sum of column widths - padding

  # print table body
  @objects.each do |o|
    data = @methods.collect{ |m| call_method(o,m) } # collect row data
    text << row(data,widths)
  end
  text
end