Created
September 24, 2019 07:02
-
-
Save wycleffsean/bd1786d5e95a08bacb3b5f6e8122cd5f to your computer and use it in GitHub Desktop.
Arel ActiveRecord extensions
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 DatabaseOperations | |
module Function | |
module_function | |
def coalesce(*args) | |
Arel::Nodes::NamedFunction.new('COALESCE', args) | |
end | |
end | |
module Atomic | |
def atomic_increment(name, count = 1) | |
col = self.class.arel_table[name] | |
increment_col = Arel::Nodes::Grouping.new( | |
Arel::Nodes::Addition.new(Function.coalesce(col, 0), count) | |
) | |
colname = self.class.connection.quote_column_name(name) | |
updates = self.class.sanitize_sql_for_assignment("#{colname} = #{increment_col.to_sql}") | |
write_attribute(name, self[name] + count) # the ol' college try | |
self.clear_attribute_changes([name]) | |
update_self(updates) | |
end | |
private | |
def update_self(*args) | |
primary_key = self.class.primary_key | |
self.class.unscoped.where(primary_key => self[primary_key]).update_all(args) | |
end | |
end | |
ActiveSupport.on_load(:active_record) do | |
include Atomic | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment