Skip to content

Instantly share code, notes, and snippets.

@Marchino
Created February 17, 2012 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marchino/1853827 to your computer and use it in GitHub Desktop.
Save Marchino/1853827 to your computer and use it in GitHub Desktop.
XLS Import end export
class DataManipulation
include ActiveModel::Conversion
extend ActiveModel::Naming
ALLOWED_MODELS = [:products, :stores]
attr_accessor :file, :model_name
def initialize(options = {})
self.file = options[:file]
self.model_name = options[:model_name].try(:singularize)
end
def process
self.records.each do |record|
begin
if record[:id].present?
item = model_name.classify.constantize.find(record[:id].to_i)
item.update_attributes(record)
item.save
else
raise ActiveRecord::RecordNotFound
end
rescue
item = model_name.classify.constantize.create(record)
end
end
return true
end
def records
headers = nil
rows = []
spreadsheet = Spreadsheet.open(self.file.path)
unless spreadsheet.worksheets.empty?
spreadsheet.worksheets.first.each do |row|
if headers.nil?
headers = row.collect{|field| field.parameterize('_').strip}
d headers
else
rows << Hash[headers.zip(row.collect{|field| field.to_s.strip })].symbolize_keys
end
end
end
return rows
end
def persisted?
false
end
end
class Admin::DataManipulationsController < Admin::AdminController
def show
model_name = params[:id].to_s
if DataManipulation::ALLOWED_MODELS.include? model_name.to_sym
Mime::Type.register "application/vnd.ms-excel", :xls
@records = model_name.classify.constantize.all
columns = model_name.classify.constantize.column_names
send_data @records.to_xls(:only => columns.select{|name| not name =~ /(updated|created)_at/})
else
render :file => "#{Rails.root}/public/404.html", :status => 404
end
end
def index
@data_manipulation = DataManipulation.new()
end
def create
@data_manipulation = DataManipulation.new(params[:data_manipulation])
if @data_manipulation.process
redirect_to admin_data_manipulations_path, :notice => 'Elaborazione completata con successo!'
else
render :action => :index
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment