开发者

analytics if on production site, not a local or heroku subdomain

This question is about getting an analytics script to run in one of these three environments.

  1. mysite.heroku.com
  2. mysite-staging.heroku.com
  3. mysite.com - this is the only one I want it to run on.

This is how I plan to lay it out, but any suggestions are welcome.

In my helper

def render_analytics
  if local_request? || #on a Heroku subdomain 
     false
  else
     true
  end
end

In my layout

<%= render 'shared/analytics' if render_analytics %>

render_analytics returns a boolean: true if on mysite.com, fal开发者_如何学编程se if a local_request? or on a Heroku subdomain (ex: mysite.heroku.com || mysite-staging.heroku.com)

So how can I find out if it is coming from Heroku.


Use hostname:

if local_request? || `hostname` =~ /heroku/i

A cleaner solution is to set a constant in your environment during deployment that allows you to know whether you are on Heroku. As the Heroku deploy process is pretty opaque in terms of letting you dork around with config files, you might have your method memoize the result so you aren't doing a system call each time you render a view.

I just did something similar with a method that checks the database adapter to account for differences between my development environment and Heroku. Here's my lib/adapter.rb:

class Adapter
  cattr_reader :adapter

  def self.postgres?
    @@adapter ||= Rails.configuration.database_configuration[Rails.env]['adapter']
    adapter == 'postgresql'
  end

  def self.mysql?
    @@adapter ||= Rails.configuration.database_configuration[Rails.env]['adapter']
    adapter == 'mysql'
  end

  def self.sqlite?
    @@adapter ||= Rails.configuration.database_configuration[Rails.env]['adapter']
    adapter.include?('sqlite')
  end
end

Note that in addition to this, you have to change application.rb such that lib is added to your autoload path:

config.autoload_paths += Dir["#{config.root}/lib/**/"] # include all subdirectories
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜