From 65649aa4f3da5a06ada54db97b91f1fed60cdfaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartosz=20Bonis=C5=82awski?= Date: Wed, 21 Mar 2018 17:03:33 +0100 Subject: [PATCH] Monkeypatch activerecord relations to work with rails >=5.2.0rc2 --- .travis.yml | 4 +-- lib/paranoia.rb | 1 + lib/paranoia/active_record_patches.rb | 41 +++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 lib/paranoia/active_record_patches.rb diff --git a/.travis.yml b/.travis.yml index bfde1a38..43642d8b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,7 +14,7 @@ env: - RAILS='~> 4.2.0' - RAILS='~> 5.0.0' - RAILS='~> 5.1.0' - - RAILS='~> 5.2.0.beta2' + - RAILS='~> 5.2.0.rc2' matrix: allow_failures: @@ -24,5 +24,5 @@ matrix: rvm: jruby-9.1.6.0 - env: RAILS='~> 5.1.0' rvm: jruby-9.1.6.0 - - env: RAILS='~> 5.2.0.beta2' + - env: RAILS='~> 5.2.0.rc2' rvm: jruby-9.1.6.0 diff --git a/lib/paranoia.rb b/lib/paranoia.rb index fb04d711..17b6052c 100644 --- a/lib/paranoia.rb +++ b/lib/paranoia.rb @@ -1,4 +1,5 @@ require 'active_record' unless defined? ActiveRecord +require 'paranoia/active_record_patches' module Paranoia @@default_sentinel_value = nil diff --git a/lib/paranoia/active_record_patches.rb b/lib/paranoia/active_record_patches.rb new file mode 100644 index 00000000..ec85cdc1 --- /dev/null +++ b/lib/paranoia/active_record_patches.rb @@ -0,0 +1,41 @@ +module HandleParanoiaDestroyedInBelongsToAssociation + def handle_dependency + return unless load_target + + case options[:dependent] + when :destroy + target.destroy + if defined? target.deleted? + raise ActiveRecord::Rollback unless target.deleted? + else + raise ActiveRecord::Rollback unless target.destroyed? + end + else + target.send(options[:dependent]) + end + end +end + +module HandleParanoiaDestroyedInHasOneAssociation + def delete(method = options[:dependent]) + if load_target + case method + when :delete + target.delete + when :destroy + target.destroyed_by_association = reflection + target.destroy + if defined? target.deleted? + throw(:abort) unless target.deleted? + else + throw(:abort) unless target.destroyed? + end + when :nullify + target.update_columns(reflection.foreign_key => nil) if target.persisted? + end + end + end +end + +ActiveRecord::Associations::BelongsToAssociation.prepend HandleParanoiaDestroyedInBelongsToAssociation +ActiveRecord::Associations::HasOneAssociation.prepend HandleParanoiaDestroyedInHasOneAssociation