Rails - 仅在生产中显示代码的最佳方式?

jyo*_*eph 27 ruby-on-rails

我有一些代码,我只想在生产中显示,例如显示disqus注释.这样做的最佳方法是什么?目前我有:

<% if RAILS_ENV.eql?('production') %>
    disqus code here
<% end %>
Run Code Online (Sandbox Code Playgroud)

但我不确定这是最好的方法,还是它?看起来非常冗长,我需要在应用程序的几个不同的地方.

Adi*_*ghi 48

有效的检查是

<% if Rails.env.production? %>
  disqus code here
<% end %>
Run Code Online (Sandbox Code Playgroud)

无需在environment.rb或初始化程序中将其作为常量.只是保持你的代码简单并使用Rails.env.production?在我的主代码库中我说.


Jac*_*kin 41

我建议在你的application_helper.rb文件中编写一个帮助方法:

def render_disqus
    return '' unless Rails.env.production?
    #render disqus stuff here...
end
Run Code Online (Sandbox Code Playgroud)

然后,在您的视图中,它变得非常简单:

<%= render_disqus %>
Run Code Online (Sandbox Code Playgroud)

  • `if not`可以改为`除非` (2认同)