Skip to content

Instantly share code, notes, and snippets.

@regedarek
Last active December 20, 2015 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save regedarek/6172861 to your computer and use it in GitHub Desktop.
Save regedarek/6172861 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

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