Module: ImportExport::ControllerMethods::InstanceMethods

Defined in:
lib/import_export/controller_methods.rb

Instance Method Summary collapse

Instance Method Details

#exportObject



25
26
27
# File 'lib/import_export/controller_methods.rb', line 25

def export
  send_data self.class.model_class.export, :type => 'text/csv; charset=iso-8859-1; header=present', :disposition => "attachment; filename=#{export_file_name}"   
end

#importObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/import_export/controller_methods.rb', line 29

def import
  @new_objects = []
  filename = upload_file_name
  context = self.class.context.clone
  context[:scoped] = self.send(context[:scoped]) if context[:scoped]

  if File.exists? filename
    begin
      @new_objects = self.class.model_class.import(filename, context)
      flash[:notice] = "Import Successful - Imported #{@new_objects.length} #{self.class.model_class.name.underscore.humanize.pluralize}"
    rescue Exception => e
      logger.error flash[:error] = "Import Failed - No records imported due to errors. #{e}"
    ensure
      File.delete(filename)
    end
  else
    @new_objects = []
  end
  render :template => "import_export/import"
end

#uploadObject



50
51
52
53
54
55
56
57
58
# File 'lib/import_export/controller_methods.rb', line 50

def upload
  if params[:csv_file] && File.extname(params[:csv_file].original_filename) == '.csv'
    FileUtils.makedirs "#{UPLOADS_PATH}"
    File.open(upload_file_name, "wb") { |f| f.write(params[:csv_file].read)}
  else
    flash[:error] = "Error! Invalid file, please select a csv file."
  end
  redirect_to "/#{self.controller_name}/import"
end