Skip to content

Instantly share code, notes, and snippets.

@wycleffsean
Created September 24, 2019 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wycleffsean/bd1786d5e95a08bacb3b5f6e8122cd5f to your computer and use it in GitHub Desktop.
Save wycleffsean/bd1786d5e95a08bacb3b5f6e8122cd5f to your computer and use it in GitHub Desktop.
Arel ActiveRecord extensions
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