jyoseph
jyoseph

Reputation: 5455

Rails - best way to display code only in production?

I have a few pieces of code that I would like to display only in production, for instance, the showing of disqus comments. What is the best way to go about doing that? Currently I have:

<% if RAILS_ENV.eql?('production') %>
    disqus code here
<% end %>

But I am not sure if that's the best method, or is that it? Seems pretty verbose and I would need this in a few different places in the application.

Upvotes: 30

Views: 10693

Answers (3)

stevec
stevec

Reputation: 52308

If you want to display something in production, but not on a certain page(s), you can do something like this:

<% if !current_page?(controller: 'home', action: 'dashboard') %>
  <% if Rails.env.production? %>
    <!-- contant go here -->
  <% end %>
<% end %>

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163258

I'd suggest writing a helper method in your application_helper.rb file:

def render_disqus
    return '' unless Rails.env.production?
    #render disqus stuff here...
end

Then, in your view it gets really simple:

<%= render_disqus %>

Upvotes: 41

Aditya Sanghi
Aditya Sanghi

Reputation: 13433

The effective check is

<% if Rails.env.production? %>
  disqus code here
<% end %>

There is no need to put it as a constant in your environment.rb or an initializer. Just keep your code simple and use Rails.env.production? in your main code base I say.

Upvotes: 52

Related Questions