Refactor the thread initialization and ActiveRecord.with_connection blocks

Extract Method