We have an API in Sinatra that serves both a staging environment and a production environment. The API should talk to the staging database if the request comes from a staging server. It should talk to the the production database if the request comes from a production server.
All apps are deployed on Heroku.
We can use env['HTTP_HOST'] to find out whether the request is coming from staging or production, and then set the db_url.
However, the problem is the ActiveRecord init code that runs to connect to the db:
db = URI.parse db_url
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:port => db.port,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8'
)
Does it make sense to run this code before each request? That would probably be slow…
Another solution is to run two instances of the API. But then we need to deploy the same code twice…
Is there a better way to do this?
Standard practice and common sense says that you should keep your production app separate from your staging app. I’m not sure what you have against deploying two different apps, but that’s the only way to ensure problems in staging don’t trip up your production app.