Class: Paperclip::XlsToCsv

Inherits:
Processor
  • Object
show all
Defined in:
lib/paperclip_processors/xls_to_csv.rb

Overview

github.com/igor-alexandrov/xls_to_csv-paperclip-processor

Example Model: class SomeCsvAttachement < ActiveRecord::Base

has_attached_file :data,
  styles: {
    converted: {
      format: "csv",
      params: "-c, -q 3"
    }
  },
  path: ":rails_root/data/some_csv_attachements/:id_partition/:basename.:extension",
  processors: [:xls_to_csv]

validates_attachment_content_type :data, content_type: ['text/csv','text/comma-separated-values','text/csv','application/csv','application/excel','application/vnd.ms-excel','application/vnd.msexcel','text/anytext','text/plain']

end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, options = {}, attachment = nil) ⇒ XlsToCsv

Returns a new instance of XlsToCsv.



21
22
23
24
25
26
27
28
29
# File 'lib/paperclip_processors/xls_to_csv.rb', line 21

def initialize(file, options = {}, attachment = nil)
  super

  @file           = file
  @params         = options[:params]
  @current_format = File.extname(@file.path)
  @basename       = File.basename(@file.path, @current_format)
  @format         = options[:format]
end

Instance Attribute Details

#fileObject

Returns the value of attribute file.



19
20
21
# File 'lib/paperclip_processors/xls_to_csv.rb', line 19

def file
  @file
end

#formatObject

Returns the value of attribute format.



19
20
21
# File 'lib/paperclip_processors/xls_to_csv.rb', line 19

def format
  @format
end

#paramsObject

Returns the value of attribute params.



19
20
21
# File 'lib/paperclip_processors/xls_to_csv.rb', line 19

def params
  @params
end

Instance Method Details

#makeObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/paperclip_processors/xls_to_csv.rb', line 31

def make
  src = @file

  if @current_format && ['.xls','xlsx'].include?(@current_format.downcase)
    dst = Tempfile.new([@basename, @format ? "#{@format}" : 'csv'].compact.join("."))
    begin
      Paperclip.run(self.command, self.parameters(src, dst))
    rescue StandardError => e
      raise "There was an error converting #{@basename} to csv: #{e.message}"
    end
    return dst
  else
    return src 
  end
end