Skip to content

Instantly share code, notes, and snippets.

@ddollar
Created August 12, 2009 17:13
Show Gist options
  • Select an option

  • Save ddollar/166618 to your computer and use it in GitHub Desktop.

Select an option

Save ddollar/166618 to your computer and use it in GitHub Desktop.
class ActiveRecord::Base
def self.bulk_import(flush_after=50, &blk)
@bulk_import_columns = Set.new
@bulk_import_rows = []
@bulk_import_flush_after = flush_after
class << self
# this is essentially alias_method_chain written out for symmetry
# with the part that undoes it
alias_method :create_without_bulk_import, :create
alias_method :create, :create_with_bulk_import
yield
ensure
alias_method :create_with_bulk_import, :create
alias_method :create, :create_without_bulk_import
end
flush_bulk_import
end
def self.create_with_bulk_import(attributes=nil)
@bulk_import_columns += attributes.keys
@bulk_import_rows << attributes
if @bulk_import_rows.length >= @bulk_import_flush_after
flush_bulk_import
end
end
def self.flush_bulk_import
return unless @bulk_import_rows.length > 0
query = %{
INSERT INTO #{self.table_name}
(#{@bulk_import_columns.map { |c| connection.quote_column_name(c) }.join(',')})
VALUES
#{
@bulk_import_rows.map do |row|
"(%s)" % (@bulk_import_columns.map do |column|
quote_bound_value(row[column])
end.join(','))
end.join(',')
}
}.squish
self.connection.execute query
@bulk_import_rows = []
end
end
MyObject.bulk_import do
MyObject.create(:foo => 'bar')
MyObject.create(:foo => 'baz')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment