Class: GtmOnRails::DataLayerObject

Inherits:
Object
  • Object
show all
Defined in:
lib/gtm_on_rails/models/data_layer_object.rb

Direct Known Subclasses

DataLayerEvent

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**args) ⇒ DataLayerObject

Returns a new instance of DataLayerObject.



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

def initialize(**args)
  @data = args.with_indifferent_access
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/gtm_on_rails/models/data_layer_object.rb', line 22

def method_missing(method, *args, &block)
  if method.to_s.end_with?('=')
    key     = method.to_s.chop.to_sym
    _method = :[]=
    _args   = [key] + args
  else
    key     = method
    _method = :[]
    _args   = [key]
  end

  if @data.has_key?(key)
    @data.send(_method, *_args)
  else
    super
  end
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



4
5
6
# File 'lib/gtm_on_rails/models/data_layer_object.rb', line 4

def data
  @data
end

Instance Method Details

#add(**hash) ⇒ Object



10
11
12
# File 'lib/gtm_on_rails/models/data_layer_object.rb', line 10

def add(**hash)
  @data.merge!(hash)
end

#to_jsObject



18
19
20
# File 'lib/gtm_on_rails/models/data_layer_object.rb', line 18

def to_js
  "dataLayer.push(#{self.to_json});"
end

#to_jsonObject



14
15
16
# File 'lib/gtm_on_rails/models/data_layer_object.rb', line 14

def to_json
  @data.to_json
end