Created
February 27, 2015 20:04
-
-
Save telagraphic/ead28c402f131f06ca5a to your computer and use it in GitHub Desktop.
roo gem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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