2014-05-08 12:42:50 +02:00
|
|
|
require 'csv'
|
|
|
|
|
2023-01-06 16:55:40 +01:00
|
|
|
class RenderCsv
|
2014-05-08 12:42:50 +02:00
|
|
|
include ActionView::Helpers::NumberHelper
|
|
|
|
|
2021-03-01 15:27:26 +01:00
|
|
|
def initialize(object, options = {})
|
2014-05-08 12:42:50 +02:00
|
|
|
@object = object
|
|
|
|
@options = options
|
|
|
|
# defaults to please Microsoft Excel ...
|
|
|
|
@options[:col_sep] ||= FoodsoftConfig[:csv_col_sep] || ';'
|
|
|
|
@options[:row_sep] ||= FoodsoftConfig[:csv_row_sep] if FoodsoftConfig[:csv_row_sep]
|
|
|
|
@options[:encoding] ||= FoodsoftConfig[:csv_encoding] || 'ISO-8859-15'
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_csv
|
2021-03-01 15:27:26 +01:00
|
|
|
options = @options.select { |k| %w(col_sep row_sep).include? k.to_s }
|
2018-12-11 15:27:32 +01:00
|
|
|
ret = CSV.generate options do |csv|
|
2014-05-08 12:42:50 +02:00
|
|
|
if h = header
|
|
|
|
csv << h
|
|
|
|
end
|
2021-03-01 15:27:26 +01:00
|
|
|
data { |d| csv << d }
|
2014-05-08 12:42:50 +02:00
|
|
|
end
|
2018-12-11 15:27:32 +01:00
|
|
|
ret.encode(@options[:encoding], invalid: :replace, undef: :replace)
|
2014-05-08 12:42:50 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def header
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
|
|
|
|
def data
|
|
|
|
yield []
|
|
|
|
end
|
|
|
|
|
|
|
|
# Helper method to test pdf via rails console: OrderCsv.new(order).save_tmp
|
|
|
|
def save_tmp
|
|
|
|
encoding = @options[:encoding] || 'UTF-8'
|
2022-02-20 16:15:22 +01:00
|
|
|
File.write("#{Rails.root}/tmp/#{self.class.to_s.underscore}.csv", to_csv.force_encoding(encoding))
|
2014-05-08 12:42:50 +02:00
|
|
|
end
|
|
|
|
|
2014-09-03 17:36:48 +02:00
|
|
|
# XXX disable unit to avoid encoding problems, both in unit and whitespace. Also allows computations in spreadsheet.
|
2021-03-01 15:27:26 +01:00
|
|
|
def number_to_currency(number, options = {})
|
|
|
|
super(number, options.merge({ unit: '' }))
|
2014-05-08 12:42:50 +02:00
|
|
|
end
|
|
|
|
end
|