From fe7594bba54e23107483469422937883beb4d4da Mon Sep 17 00:00:00 2001 From: iberianpig Date: Wed, 1 May 2024 23:07:07 +0900 Subject: [PATCH] wrap with on_load(:active_record) hook --- lib/octoball.rb | 34 ++++++++++------------------------ lib/octoball/using_shard.rb | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 24 deletions(-) create mode 100644 lib/octoball/using_shard.rb diff --git a/lib/octoball.rb b/lib/octoball.rb index b621cdf..dea60af 100644 --- a/lib/octoball.rb +++ b/lib/octoball.rb @@ -2,29 +2,15 @@ require 'active_record' require 'octoball/version' -require 'octoball/relation_proxy' -require 'octoball/connection_adapters' -require 'octoball/connection_handling' -require 'octoball/current_shard_tracker' -require 'octoball/association' -require 'octoball/association_shard_check' -require 'octoball/persistence' -require 'octoball/log_subscriber' -class Octoball - def self.using(shard, &block) - ActiveRecord::Base.connected_to(role: current_role, shard: shard&.to_sym, &block) - end - - def self.current_role - ActiveRecord::Base.current_role || ActiveRecord::Base.writing_role - end - - module UsingShard - def using(shard) - Octoball::RelationProxy.new(all, shard&.to_sym) - end - end - - ::ActiveRecord::Base.singleton_class.prepend(UsingShard) +ActiveSupport.on_load(:active_record) do + require 'octoball/relation_proxy' + require 'octoball/connection_adapters' + require 'octoball/connection_handling' + require 'octoball/current_shard_tracker' + require 'octoball/association_shard_check' + require 'octoball/persistence' + require 'octoball/association' + require 'octoball/log_subscriber' + require 'octoball/using_shard' end diff --git a/lib/octoball/using_shard.rb b/lib/octoball/using_shard.rb new file mode 100644 index 0000000..e4e8033 --- /dev/null +++ b/lib/octoball/using_shard.rb @@ -0,0 +1,17 @@ +class Octoball + def self.using(shard, &block) + ActiveRecord::Base.connected_to(role: current_role, shard: shard&.to_sym, &block) + end + + def self.current_role + ActiveRecord::Base.current_role || ActiveRecord::Base.writing_role + end + + module UsingShard + def using(shard) + Octoball::RelationProxy.new(all, shard&.to_sym) + end + end + + ::ActiveRecord::Base.singleton_class.prepend(UsingShard) +end