Last active
December 20, 2015 17:59
-
-
Save regedarek/6172861 to your computer and use it in GitHub Desktop.
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 Importer | |
CONN = ActiveRecord::Base.connection | |
F = "00F" | |
I = "00I" | |
def extract_to_database(collection) # collection is a file | |
add = true | |
tmp = [] | |
type = F | |
inserts = [] | |
f = [] | |
collection.each_with_index do |line, i| | |
_type = line.strip | |
_changed = [F,I].include? _type | |
if _changed && i > 0 | |
case type | |
when F then f << tmp | |
when I | |
inserts.push "(#{tmp[1]},'#{tmp[2]}','#{tmp[3]}')" | |
end | |
tmp = [] | |
type = _type | |
end | |
tmp << line | |
end | |
sql = "INSERT INTO products (`code`, `name`, `price`) VALUES #{inserts.join(", ")}" | |
CONN.execute sql | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check a refactor in my fork of the gist. Note that "f" is not used anywhere so I removed it. I used a model Product, if you are using AR it makes no sense to use raw SQL. The key to make it functional is using each_slice.