I am developing a Ruby gem that will be used by a Rails application. In it, I would like to use database connection (ActiveRecord::Base.connection) that the Rails app itself uses.
The gem will be invoked either:
- Through a rake task.
- Via the Rails console
Here’s the problem: When I call ActiveRecord::Base.connection from within the gem, it raises an error:
No database connection defined
I assume this is because the gem doesn't automatically inherit the database connection setup from the Rails application.
What I Want to Achieve: I want the gem to utilize the Rails app's database connection seamlessly, without requiring additional setup from the app's side.
Example Code: Here’s a simplified example of what I’m trying to do:
My Questions: How can I configure my gem so that it automatically uses the Rails app's database connection?
Are there any best practices or pitfalls I should be aware of when developing gems that interact with Rails' database connection?
Additional Information: The Rails app is running on >= Rails 7 with ActiveRecord.
Any guidance or code examples would be greatly appreciated!