How to change JS, CSS and MySQL database depending on work environment?

99 Views Asked by At

In Heroku, how do I change what database my Sinatra app accesses depending on its environment?

That is: If main.rb is on my local machine, how do I get it to access localhost, but when I git push it to any branch on my Heroku repo, get it to access a live database?

Same for JS and CSS. If I'm working on my local machine, how would I set my app so that it accesses JS in dev/js/script.js, but when live it would access live/js/script.js?

2

There are 2 best solutions below

0
On BEST ANSWER

Firstly, you shouldn't usually have separate assets based on the environment you are running on. That can give you a small nightmare when you need update things.

How this usually works in Ruby land is that the server (Heroku etc) sets global environment variables when it runs your app. These variables & values are available in your app so you can check if you are running in production, testing etc.

Heroku automatically sets the DATABASE_URL environment variable and you can access it like so:

configure do
    ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'])  
end

On each server the DATABASE_URL variable will be set accordingly.

1
On

Normally you should not have separate folder for different environments for js and css, and they should be put under assets folder: If you have a good reason to do so, you can use the following code:

set :root, File.expand_path(File.dirname(__FILE__))

configure :development do   
  set :public_folder, Proc.new { "#{root}/dev/assets" }
end

configure :production do 
  set :public_folder, Proc.new { "#{root}/live/assets" }
end

Then in the view, if you put javascripts under assets/javascript, you can link to them with the path javascripts/filename.js