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
@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