Created
July 29, 2016 16:23
-
-
Save alexandremcosta/cf032126d95e8f4ffabc6bf86ebbe0db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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