I have several models that need to call a method that takes a particular hash as input. Where should I declare this hash to keep things DRY, and how can I then use it in multiple models?
The hash will be the same for all uses. Specifically, it’s just a hash of connection details that I want to pass to a call to establish_connection. I realize that that method takes a URL, though I’m still on rails 3.1, and that method was not made available until a little later.
Instead of repeating the following in five models, I just want to call something like establish_connection(legacy_db_connection_hash).
establish_connection(
:adapter => 'mysql',
:host => ENV['LEGACY_DATABASE_HOST'],
:username => ENV['LEGACY_DATABASE_USERNAME'],
:password => ENV['LEGACY_DATABASE_PASSWORD'],
:database => ENV['LEGACY_DATABASE_NAME']
)
I was thinking that perhaps there’s a way to do it via /lib, but I’m really not sure how to go about it.
Thank you for your time!
It should go into a
module.For example, declare a module
Fooin the filelib/foo.rb(and don’t forgetself.in front of the method name):Foo.settingswill be available when youinclude Fooin your models.Also, make sure to add the
libdirectory toconfig.autoload_pathsinconfig/application.rb, so thatlib/foo.rbis read and its containedFoomodule is loaded: