我正在尝试设置Google Analytics,并根据环境引用不同的跟踪ID。我有一个沙盒版本的谷歌分析,其中有一个ID,在暂存环境中运行,以及一个生产版本的谷歌分析,具有另一个身份,在生产环境中运行。
我将这些ID设置为环境变量,目标是调用环境变量ENV [“GA_TRACKING_ID”]以在我的javascript文件中设置跟踪,并根据正在运行的环境自动设置id。
但是,我不断获得ReferenceError: ENV is not defined
更新
class @GoogleAnalytics
@load: ->
window._gaq = []
window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]
# other GA configuration
@analyticsId: ->
gon.ga_tracking_id
GoogleAnalytics.load()
使用接受的答案的gem和ApplicationController代码:
class ApplicationController < ActionController::Base
before_action :assign_env_variables
def assign_env_variables
gon.ga_tracking_id = ENV["GA_TRACKING_ID"]
end
end
答案 0 :(得分:1)
我非常喜欢这个用于将后端变量传递给Javascript的gem:
addOnChildAttachStateChangeListener
在application_controller.rb中,您可以添加before_action过滤器来运行一个方法,这意味着它将在每个页面上加载。使用gon,你可以使用这样的代码来分配变量:
gon.ga_tracking_id
只要在模板头中包含gon行(根据文档),您就可以在JS文件中的任何位置使用它来访问该变量:
{{1}}