Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@regedarek

This comment has been minimized.

Copy link
Owner Author

@regedarek regedarek commented Aug 7, 2013

Code  | Name  | Price
00106 | Water | 9.99
00107 | Onion | 8.99

Which is coded in GES file like below:

  • 00F means column header
  • 00I means insert a row
    there are also others like(00D for delete row or 00U for update)
00F
0101
02Code
031
00F
0102
02Name
031
00F
0103
02Price
030
00I
0100106
02Water
030999
00I
0100107
02Onion
030899
@tokland

This comment has been minimized.

Copy link

@tokland tokland commented Aug 9, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment