Module: Equalshares::Pabulib::Writer
- Defined in:
- lib/equalshares/pabulib/writer.rb
Overview
Serialises an Instance back to pabulib (.pb) text. Inverse of the parser: META / PROJECTS / VOTES sections, ';'-separated, with fields containing ';', '"' or newlines quoted (and embedded '"' doubled). Parsing the result yields an equivalent Instance (round-trip safe).
Class Method Summary collapse
-
.escape(value) ⇒ Object
Inverse of the CSV field handling in Pabulib::Csv.parse_line.
- .write_file(instance, path) ⇒ Object
- .write_section(lines, header_name, rows_by_id) ⇒ Object
- .write_string(instance) ⇒ Object
Class Method Details
.escape(value) ⇒ Object
Inverse of the CSV field handling in Pabulib::Csv.parse_line.
36 37 38 39 40 41 |
# File 'lib/equalshares/pabulib/writer.rb', line 36 def escape(value) str = value.to_s return str unless str.match?(/[;"\n]/) %("#{str.gsub('"', '""')}") end |
.write_file(instance, path) ⇒ Object
20 21 22 |
# File 'lib/equalshares/pabulib/writer.rb', line 20 def write_file(instance, path) File.write(path, write_string(instance)) end |
.write_section(lines, header_name, rows_by_id) ⇒ Object
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/equalshares/pabulib/writer.rb', line 24 def write_section(lines, header_name, rows_by_id) lines << header_name return if rows_by_id.empty? header = rows_by_id.values.first.keys lines << header.map { |h| escape(h) }.join(";") rows_by_id.each_value do |row| lines << header.map { |h| escape(row[h]) }.join(";") end end |
.write_string(instance) ⇒ Object
12 13 14 15 16 17 18 |
# File 'lib/equalshares/pabulib/writer.rb', line 12 def write_string(instance) lines = ["META", "key;value"] instance..each { |key, value| lines << "#{escape(key)};#{escape(value)}" } write_section(lines, "PROJECTS", instance.projects) write_section(lines, "VOTES", instance.votes) "#{lines.join("\n")}\n" end |