Class: RenderCSV

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/render_csv.rb

Instance Method Summary collapse

Constructor Details

#initialize(object, options = {}) ⇒ RenderCSV

Returns a new instance of RenderCSV.


6
7
8
9
10
11
12
13
# File 'lib/render_csv.rb', line 6

def initialize(object, options={})
  @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

Instance Method Details

#data {|[]| ... } ⇒ Object

Yields:

  • ([])

30
31
32
# File 'lib/render_csv.rb', line 30

def data
  yield []
end

#headerObject


26
27
28
# File 'lib/render_csv.rb', line 26

def header
  nil
end

#number_to_currency(number, options = {}) ⇒ Object

XXX disable unit to avoid encoding problems, both in unit and whitespace. Also allows computations in spreadsheet.


41
42
43
# File 'lib/render_csv.rb', line 41

def number_to_currency(number, options={})
  super(number, options.merge({unit: ''}))
end

#save_tmpObject

Helper method to test pdf via rails console: OrderCsv.new(order).save_tmp


35
36
37
38
# File 'lib/render_csv.rb', line 35

def save_tmp
  encoding = @options[:encoding] || 'UTF-8'
  File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.csv", 'w') {|f| f.write(to_csv.force_encoding(encoding)) }
end

#to_csvObject


15
16
17
18
19
20
21
22
23
24
# File 'lib/render_csv.rb', line 15

def to_csv
  options = @options.select {|k| %w(col_sep row_sep).include? k.to_s}
  ret = CSV.generate options do |csv|
    if h = header
      csv << h
    end
    data {|d| csv << d}
  end
  ret.encode(@options[:encoding], invalid: :replace, undef: :replace)
end