module ImportExport::ControllerMethods::InstanceMethods

Public Instance Methods

export() click to toggle source
# 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
import() click to toggle source
# 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
upload() click to toggle source
# 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

Private Instance Methods

export_file_name() click to toggle source
# File lib/import_export/controller_methods.rb, line 66
def export_file_name
  @export_file_name ||= "#{Time.now.to_formatted_s(:number)}_#{self.controller_name}_export.csv"
end
upload_file_name() click to toggle source
# File lib/import_export/controller_methods.rb, line 62
def upload_file_name
  @upload_file_name ||= "#{UPLOADS_PATH}/#{self.controller_name}_#{request.session_options[:id]}.csv"
end