Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional rendering with Rails depending on the environment

Is there any proper way to detect the environment (development or production) in the application layout? Say, I don't want to render the GA code in my local sandbox.

In Django we use {% if not debug %}{% include '_ga.html' %}{% endif %}. What should I use in Rails? Thanks.

like image 659
Michael Samoylov Avatar asked Jan 31 '12 12:01

Michael Samoylov


2 Answers

You can use:

Rails.env.production?
#or
Rails.env.development?
#or
Rails.env.test?

See docs for further information. So, you could do something like:

<% if Rails.env.development? %>
  <p>Dev Mode</p>
<% else %>
  <p>Production or test mode</p>
<% end %>
like image 67
lucapette Avatar answered Oct 27 '22 08:10

lucapette


I recognize this question is old, but I just came across it looking for something similar myself. I think slightly better practice is not to ask "what environment am I in?" but rather to set configuration based on what you're trying to do. So if you wanted to add a custom debug footer in development, you could add the following to config/application.rb:

config.show_debug_footer = false

That sets the default behavior. Then in config/environments/development.rb you add:

config.show_debug_footer = true

And then in your code, where you need to change the behavior, you can check:

if Rails.configuration.show_debug_footer
  [...]
end

This is a very flexible way to have custom configuration that changes depending on your environment, and it keeps your code highly readable.

See Rails documentation for Custom Configuration

like image 41
FriscoTony Avatar answered Oct 27 '22 09:10

FriscoTony