Michael Samoylov
Michael Samoylov

Reputation: 3089

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.

Upvotes: 14

Views: 4100

Answers (2)

FriscoTony
FriscoTony

Reputation: 21

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

Upvotes: 2

lucapette
lucapette

Reputation: 20724

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 %>

Upvotes: 30

Related Questions