Class: CSVFromTable

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

Instance Method Summary collapse

Instance Method Details

#ar_from_table(table_string, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/csv_from_table.rb', line 17

def ar_from_table(table_string, options={})
  @options = options
  doc = Nokogiri::HTML(table_string)
  if !doc.css("table").empty?
    @headers = table_headers(table_string)
    lines = []
    doc.css("tr").each do |node|
      cells = []
      node.css("td").each_with_index do |c, index|
        cells << c.text if include_colunm?(index)
      end
      lines << cells
    end
    lines.keep_if { |el| !el.empty? }
  else
    raise TableNotFoundInString, "The string dosen't contain a valid <table> element."
  end
end

#ar_to_csv(array) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/csv_from_table.rb', line 46

def ar_to_csv(array)
  csv_lines = []
  array.each do |el|
    csv_lines << el.join(", ")
  end
  csv_lines.join("\n")
end

#include_colunm?(index) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
# File 'lib/csv_from_table.rb', line 36

def include_colunm?(index)
  if @options[:only]
    true if @options[:only].include?(@headers[index]) || @options[:only] == @headers[index]
  elsif @options[:except]
    true unless @options[:except].include?(@headers[index]) || @options[:except] == @headers[index]
  else
    true
  end
end

#table_headers(table_string) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/csv_from_table.rb', line 54

def table_headers(table_string)
  doc = Nokogiri::HTML(table_string)
  headers = []
  doc.css("th").each do |node|
    headers << node.text
  end
  headers
end