Class: GtmOnRails::DataLayer

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::TagHelper
Defined in:
lib/gtm_on_rails/models/data_layer.rb

Defined Under Namespace

Classes: Ecommerce, Event, Object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ DataLayer

Returns a new instance of DataLayer.



8
9
10
11
# File 'lib/gtm_on_rails/models/data_layer.rb', line 8

def initialize(*args)
  options  = args.extract_options!
  @objects = [args].flatten # @objects are instances of GTM::DataLayerObject
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/gtm_on_rails/models/data_layer.rb', line 47

def method_missing(method, *args, &block)
  if @objects.respond_to?(method)
    @objects.send(method, *args, &block)
  else
    super
  end
end

Instance Attribute Details

#objectsObject

Returns the value of attribute objects.



6
7
8
# File 'lib/gtm_on_rails/models/data_layer.rb', line 6

def objects
  @objects
end

Instance Method Details



43
44
45
# File 'lib/gtm_on_rails/models/data_layer.rb', line 43

def print_on_html
  (:script, self.to_js)
end

#push(args) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/gtm_on_rails/models/data_layer.rb', line 13

def push(args)
  args = [args].flatten
  args.each do |object|
    case object
    when Hash
      @objects << GtmOnRails::DataLayer::Object.new(object)
    when GtmOnRails::DataLayer::Object
      @objects << object
    end
  end
end

#respond_to?(method, include_all = false) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/gtm_on_rails/models/data_layer.rb', line 55

def respond_to?(method, include_all=false)
  Array.new.respond_to?(method, include_all) || super
end

#to_jsObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/gtm_on_rails/models/data_layer.rb', line 25

def to_js
  js_codes = []

  js_codes << "var dataLayer = dataLayer || [];"
  @objects.each do |data_layer_object|
    # dataLayer size limit exception
    size = data_layer_object.to_json.bytesize
    if size > GtmOnRails.config.data_layer_limit_byte_size
      Rails.logger.warn("DataLayer bytesize is over limit #{GtmOnRails.config.data_layer_limit_byte_size} bytes. Size is #{size} bytes.")
      next
    end

    js_codes << data_layer_object.to_js
  end

  return js_codes.join.html_safe
end