Skip to content

Instantly share code, notes, and snippets.

@telagraphic
Created February 27, 2015 20:04
Show Gist options
  • Save telagraphic/ead28c402f131f06ca5a to your computer and use it in GitHub Desktop.
Save telagraphic/ead28c402f131f06ca5a to your computer and use it in GitHub Desktop.
roo gem
class Testcase < ActiveRecord::Base
require 'spreadsheet'
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
testcase = find_by_id(row["id"]) || new
testcase.attributes = row.to_hash.slice(*row.to_hash.keys)
testcase.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::Csv.new(file.path, nil, :ignore)
when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment