From 99b970ede6e4dc247447114e8a2535b3c119a435 Mon Sep 17 00:00:00 2001 From: Daniel Sinn Date: Mon, 30 Aug 2021 00:53:46 -0400 Subject: [PATCH] Switch to `Module#prepend` in `ActiveRecord::Relation` patch `alias_method` breaks when the parameters for the function we're patching changes, as it did in rails/rails@caa178c178468f7adcc5f4c597280e6362d9e175 Closes #34. --- lib/standby/active_record/relation.rb | 25 +++++++++++++------------ spec/slavery_spec.rb | 6 ++++++ spec/spec_helper.rb | 3 ++- standby.gemspec | 1 + 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/lib/standby/active_record/relation.rb b/lib/standby/active_record/relation.rb index fef0f9f..37a9e09 100644 --- a/lib/standby/active_record/relation.rb +++ b/lib/standby/active_record/relation.rb @@ -1,19 +1,18 @@ +module ExecQueriesWithStandbyTarget + # Supports queries like User.on_standby.to_a + def exec_queries + if standby_target + Standby.on_standby(standby_target) { super } + else + super + end + end +end + module ActiveRecord class Relation attr_accessor :standby_target - # Supports queries like User.on_standby.to_a - alias_method :exec_queries_without_standby, :exec_queries - - def exec_queries - if standby_target - Standby.on_standby(standby_target) { exec_queries_without_standby } - else - exec_queries_without_standby - end - end - - # Supports queries like User.on_standby.count alias_method :calculate_without_standby, :calculate @@ -26,3 +25,5 @@ def calculate(*args) end end end + +ActiveRecord::Relation.prepend(ExecQueriesWithStandbyTarget) diff --git a/spec/slavery_spec.rb b/spec/slavery_spec.rb index 9355ded..ec3eb15 100644 --- a/spec/slavery_spec.rb +++ b/spec/slavery_spec.rb @@ -104,4 +104,10 @@ class ActiveRecord::Relation expect(User.on_standby(:two).where(nil).to_a.size).to be 0 expect(User.on_standby.where(nil).to_a.size).to be 1 end + + it 'does not interfere with setting inverses' do + user = User.first + user.update(name: 'a different name') + expect(user.items.first.user.name).to eq('a different name') + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f4a7bbb..b77be9b 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -15,10 +15,11 @@ # Prepare databases class User < ActiveRecord::Base has_many :items + attr_accessor :name end class Item < ActiveRecord::Base - belongs_to :user + belongs_to :user, inverse_of: :items end class Seeder diff --git a/standby.gemspec b/standby.gemspec index 31c9f56..b30de61 100644 --- a/standby.gemspec +++ b/standby.gemspec @@ -16,6 +16,7 @@ Gem::Specification.new do |gem| gem.executables = gem.files.grep(%r{^exe/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ['lib'] + gem.required_ruby_version = '>= 2.0' gem.add_runtime_dependency 'activerecord', '>= 3.0.0'