Module: AdsenseHelper

Defined in:
lib/adsense_helper/version.rb,
lib/adsense_helper/adsense_helper.rb

Overview

Google Adsense Helper

Constant Summary collapse

VERSION =
'0.1.0'

Instance Method Summary collapse

Instance Method Details

#adsense_tag(options = {}) ⇒ Object

Parameters:

client

16 digits

slot

10 digits

dimension

“#widthx#height”, default is 336x280

Example:

adsense_tag(client: 0000000000000000, slot: 1111111111, dimension: '336x280')

Generated code:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:336px;height:280px"
     data-ad-client="ca-pub-0000000000000000"
     data-ad-slot="1111111111"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/adsense_helper/adsense_helper.rb', line 24

def adsense_tag(options = {})
  defaults = { dimension: '336x280' }
  options = options.to_h.reverse_merge(defaults).with_indifferent_access
  width, height = options[:dimension].split('x').to_a
  
  raise 'Invalid ad client, should be 16 digits' unless options[:client].to_s[/^\d{16}$/]
  raise 'Invalid ad slot, should be 10 digits' unless options[:slot].to_s[/^\d{10}$/]
  raise 'Invalid ad dimension, should be "#{width}x#{height}"' unless width.to_s[/^\d+$/] && height.to_s[/^\d+$/]
  
  tags = [
    ('script', '', async: '', src: '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'),
    ('ins', '', class: 'adsbygoogle', style: "display:inline-block;width:#{width}px;height:#{height}px", 'data-ad-client' => "ca-pub-#{options[:client]}", 'data-ad-slot' => options[:slot]),
    ('script', '(adsbygoogle = window.adsbygoogle || []).push({});'),
  ]
  safe_join(tags)
end