Skip to content

Instantly share code, notes, and snippets.

@alexandremcosta
Created July 29, 2016 16:23
Show Gist options
  • Save alexandremcosta/cf032126d95e8f4ffabc6bf86ebbe0db to your computer and use it in GitHub Desktop.
Save alexandremcosta/cf032126d95e8f4ffabc6bf86ebbe0db to your computer and use it in GitHub Desktop.
module MassInsertUniq
extend ActiveSupport::Concern
included do
include PluckHash
end
module ClassMethods
def mass_insert_uniq(attributes, insert_scope: -> { self })
return if attributes.blank?
attributes = Array(attributes)
existent = insert_scope.call.pluck_hash(*attributes.first.keys)
attributes = attributes - existent
if attributes.any?
connection.insert(sanitize_sql(sanitize_array(attributes)))
end
end
private
def sanitize_array(attributes)
names = attributes_name(attributes)
values = attributes_value(attributes)
["INSERT INTO #{table_name} (#{names.join(', ')}) VALUES #{value_signs(attributes)}", *values.flatten]
end
def value_signs(attributes)
Array.new(attributes.size, question_signs(attributes)).join(', ')
end
def question_signs(attributes)
total = attributes.first.size + 2
signs = Array.new(total, '?').join(', ')
"(#{signs})"
end
def attributes_name(hash_collection)
hash_collection.first.keys + %w(created_at updated_at)
end
def attributes_value(hash_collection)
time = Time.now.utc.to_s(:db)
hash_collection.map { |hash| hash.values + [time, time] }
end
end
end
module PluckHash
extend ActiveSupport::Concern
module ClassMethods
def pluck_hash(*keys)
pluck(*keys).map{|pa| Hash[keys.zip(pa)]}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment