Skip to content

Instantly share code, notes, and snippets.

@maxim

maxim/save_if.rb Secret

Created July 12, 2023 00:57
Show Gist options
  • Save maxim/3d81cceaa48cc600b40f0fa426f3eda8 to your computer and use it in GitHub Desktop.
Save maxim/3d81cceaa48cc600b40f0fa426f3eda8 to your computer and use it in GitHub Desktop.
module SaveIf
def update_if!(constraints, attributes)
if destroyed?
raise ActiveRecord::ActiveRecordError, 'cannot update a destroyed record'
end
update_if(constraints, attributes) ||
raise(ActiveRecord::StaleObjectError.new(self, 'update'))
end
def update_if(constraints, attributes)
save_if(constraints) { assign_attributes(attributes) }
end
def save_if!(constraints)
if destroyed?
raise ActiveRecord::ActiveRecordError, 'cannot update a destroyed record'
end
save_if(constraints) ||
raise(ActiveRecord::StaleObjectError.new(self, 'update'))
end
def save_if(constraints)
if new_record?
raise ActiveRecord::ActiveRecordError, 'cannot update a new record'
end
_raise_readonly_record_error if readonly?
return false if destroyed?
@_save_if_constraints = constraints.stringify_keys
with_transaction_returning_status do
yield if block_given?
_update_record == 1
end
ensure
@_save_if_constraints = nil
end
private
def _query_constraints_hash
return super unless @_save_if_constraints
@_save_if_constraints.merge(super)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment