I have an external library FooModels which is just a collection of activerecord models belonging to a test-Foo, dev-Foo, or Foo database depending on the rails environment. This is easy enough to handle when my Foo project's database.yml can cover it.
The problem I'm running into is when I include them in project Bar where the default database.yml connection is to database Bar I need to specify that the Foo tables database is test-Foo in my testing environment, dev-Foo in my development env, and Foo in my prod env.
In each of my Foo models I can do:
self.table_name = 'test-Foo.table_name' if Rails.env = 'test'
self.table_name = 'dev-Foo.table_name' if Rails.env = 'development'
self.table_name = 'Foo.table_name' if Rails.env = 'production'
But this seems like a poor way to handle it. I've looked a bit into letting my class from an abstract model which inherits ActiveRecord::Base e.g:
class BaseConnection < ActiveRecord::Base
self.abstract_class = true
attr_accessor :database
@database = case Rails.env
when 'test' then 'test-Foo'
...
end
class SomeTable < BaseConnection
self.table_name = "#{@database}.some_table"
...
end
This way there would be at least less code duplication. Is there a way that I'm missing that would make this a lot easier and less messy?
Aucun commentaire:
Enregistrer un commentaire