The code here is a tech demo showing how to switch between databases in Rails 5, in a thread-safe manner.
The simple way to switch databases is:
ActiveRecord::Base.establish_connection :user_shard1
puts User.find(1) # this is executed on the database keyed on "user_shard1" in database.yml
ActiveRecord::Base.establish_connection :development
This should work in a single-thread environment, so it's safe to use in a single-threaded web server like Unicorn or WEBrick. However, in a multi-thread environment like Puma or Sidekiq, it will cause major bugs because ActiveRecord's state - ie which database it's using - is global for the whole process. Threads will constantly be switching this global state and then reading/writing to/from the wrong database.
The solution, as in the code example here, is to DIY pool management. Any general ActiveRecord statements will use the default database as normal (ie "development" or "production"). The pools should be established on initialisation and any code that needs to use another database should use pool.with_connection, which is a Rails method on the database pool class that will not affect global state. This is also nice from a clean-code perspective, because we don't need to reset to using the default database afterwards. It's just a block that temporarily uses a different database.