Class: GTM::Client

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

Constant Summary collapse

@@scopes =
%w(https://www.googleapis.com/auth/tagmanager.delete.containers https://www.googleapis.com/auth/tagmanager.edit.containers https://www.googleapis.com/auth/tagmanager.edit.containerversions https://www.googleapis.com/auth/tagmanager.manage.accounts https://www.googleapis.com/auth/tagmanager.manage.users https://www.googleapis.com/auth/tagmanager.publish https://www.googleapis.com/auth/tagmanager.readonly)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



10
11
12
13
14
15
16
17
# File 'lib/gtm/client.rb', line 10

def initialize
  @client = Google::APIClient.new(
      :application_name => 'gtmclient',
      :application_version => '1.0.0'
  )
  @gtm = @client.discovered_api('tagmanager')
  @scope ||= {path: ''}
end

Instance Attribute Details

#auth_fileObject

Returns the value of attribute auth_file.



8
9
10
# File 'lib/gtm/client.rb', line 8

def auth_file
  @auth_file
end

#clientObject

Returns the value of attribute client.



8
9
10
# File 'lib/gtm/client.rb', line 8

def client
  @client
end

#containersObject

Returns the value of attribute containers.



8
9
10
# File 'lib/gtm/client.rb', line 8

def containers
  @containers
end

#gtmObject

Returns the value of attribute gtm.



8
9
10
# File 'lib/gtm/client.rb', line 8

def gtm
  @gtm
end

#scopeObject

Returns the value of attribute scope.



8
9
10
# File 'lib/gtm/client.rb', line 8

def scope
  @scope
end

Instance Method Details

#runObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/gtm/client.rb', line 28

def run
  set_auth_file
  tries = 0
  begin
    result = @client.execute(
        api_method: @gtm.accounts.list,
        parameters: {
        }
    )
    tries += 1
    raise GTM::AuthException if result.data['error'] && result.data.error['code']
    @accounts = result.data.accounts
    yield @accounts
    puts 'DONE'
  rescue AuthException
    client_secrets = Google::APIClient::ClientSecrets.load
    flow = Google::APIClient::InstalledAppFlow.new(
        client_id: client_secrets.client_id,
        client_secret: client_secrets.client_secret,
        scope: @@scopes
    )

    auth = flow.authorize
    data = Marshal.dump(auth)
    @client.authorization = auth
    File.write @auth_file, data
    retry if tries < 2
  end
end

#set_auth_fileObject



19
20
21
22
23
24
25
26
# File 'lib/gtm/client.rb', line 19

def set_auth_file
  auth_path = "#{@scope[:path]}.dump"
  FileUtils::mkdir_p auth_path
  @auth_file = "#{auth_path}/auth"
  data = File.read(@auth_file) rescue nil
  auth = Marshal.load(data) rescue nil
  @client.authorization = auth
end