Class: Google::Analytics::Code

Inherits:
Object
  • Object
show all
Defined in:
lib/google_analytics.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Code

Returns a new instance of Code.



28
29
30
31
32
# File 'lib/google_analytics.rb', line 28

def initialize(config)
  @config = config
  @options = []
  @extra_option = ''
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



26
27
28
# File 'lib/google_analytics.rb', line 26

def config
  @config
end

#extra_optionObject

Returns the value of attribute extra_option.



26
27
28
# File 'lib/google_analytics.rb', line 26

def extra_option
  @extra_option
end

#optionsObject

Returns the value of attribute options.



26
27
28
# File 'lib/google_analytics.rb', line 26

def options
  @options
end

Instance Method Details

#enabled?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/google_analytics.rb', line 34

def enabled?
  @config.environments.include?(Rails.env)
end

#options_to_sObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/google_analytics.rb', line 46

def options_to_s
  option_string = ''

  @options.each do |option|
    if option.class == Hash
      key = option.keys.first
      values = option[key]

      if values.respond_to?(:join)
        value_string = values.join("', '")
        option_string << "_gaq.push(['#{key}', '#{value_string}'])\n"
      elsif !values.nil? && !values.empty?
        option_string << "_gaq.push(['#{key}', '#{values}'])\n"
      end
    else
      option_string << "_gaq.push(['#{option}'])\n"
    end
  end

  option_string
end

#push(options = {}) ⇒ Object



38
39
40
# File 'lib/google_analytics.rb', line 38

def push(options={})
  @options.push(options)
end

#push_code(code) ⇒ Object



42
43
44
# File 'lib/google_analytics.rb', line 42

def push_code(code)
  @extra_option << code
end

#to_sObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/google_analytics.rb', line 68

def to_s
  return unless enabled?

  <<-HTML
  <script type="text/javascript">
    try{
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', '#{@config.tracker_id}']);
      _gaq.push(['_setDomainName', '#{@config.domain_name}']);
      #{options_to_s}
      _gaq.push(['_trackPageview']);

      #{@extra_code}

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
      })();
    } catch(err) {}
  </script>
  HTML
end