Establish a connection to another database only in a block?

后端 未结 7 1136
情书的邮戳
情书的邮戳 2020-12-29 10:17

In a rails application, I have this code in pure ruby :

class LinkCreator
  attr_accessor :animal

  def initialize(animal:)
    @animal = animal
  end

  de         


        
7条回答
  •  失恋的感觉
    2020-12-29 10:42

    You can perform some queries within a block. First, define some module which will extend ActiveRecord, as below. This is a part of code used in production to change db connection per each request as well as to temporarily switch db to perform some queries within another database.

    # RAILS_ROOT/lib/connection_switch.rb
    module ConnectionSwitch
      def with_db(connection_spec_name)
        current_conf = ActiveRecord::Base.connection_config
    
        begin
          ActiveRecord::Base.establish_connection(db_configurations[connection_spec_name]).tap do
            Rails.logger.debug "\e[1;35m [ActiveRecord::Base switched database] \e[0m #{ActiveRecord::Base.connection.current_database}"
          end if database_changed?(connection_spec_name)
    
          yield
        ensure
          ActiveRecord::Base.establish_connection(current_conf).tap do
            Rails.logger.debug "\e[1;35m [ActiveRecord::Base switched database] \e[0m #{ActiveRecord::Base.connection.current_database}"
          end if database_changed?(connection_spec_name, current_conf)
        end
    
      end
    
      private
      def database_changed?(connection_spec_name, current_conf = nil)
        current_conf = ActiveRecord::Base.connection_config unless current_conf
        current_conf[:database] != db_configurations[connection_spec_name].try(:[], :database)
      end
    
      def db_configurations
        @db_config ||= begin
          file_name =  "#{Rails.root}/config/database.yml"
          if File.exists?(file_name) || File.symlink?(file_name)
            config ||= HashWithIndifferentAccess.new(YAML.load(ERB.new(File.read(file_name)).result))
          else
            config ||= HashWithIndifferentAccess.new
          end
    
          config
        end
      end
    end
    ActiveRecord.send :extend, ConnectionSwitch
    

    Now you can use it as below:

    ActiveRecord.with_db("db_connection_name") do
      # some queries to another db
    end
    

提交回复
热议问题