database_helper.rb 514 B

123456789101112131415161718192021222324
  1. # frozen_string_literal: true
  2. module DatabaseHelper
  3. def replica_enabled?
  4. ENV['REPLICA_DB_NAME'] || ENV.fetch('REPLICA_DATABASE_URL', nil)
  5. end
  6. module_function :replica_enabled?
  7. def with_read_replica(&block)
  8. if replica_enabled?
  9. ApplicationRecord.connected_to(role: :reading, prevent_writes: true, &block)
  10. else
  11. yield
  12. end
  13. end
  14. def with_primary(&block)
  15. if replica_enabled?
  16. ApplicationRecord.connected_to(role: :writing, &block)
  17. else
  18. yield
  19. end
  20. end
  21. end