def preparse(unparsed, args = [], opts = {})
        case unparsed
        when Hash  then opts.merge! unparsed
        when Array then unparsed.each { |e| preparse(e, args, opts) }
        else args << unparsed.to_s
        end
        [args, opts]
      end

def preparse ( unparsed , args = [ ] , opts = { } ) case unparsed when Hash then opts . merge! unparsed when Array then unparsed . each { | e | preparse ( e , args , opts ) } else args << unparsed . to_s end [ args , opts ] end

can't use flatten as it will flatten hashes

can t use flatten as it will flatten hashes


def to_s
      super + ":\n" +
      format_observation(result.control) + "\n" +
      result.candidates.map { |candidate| format_observation(candidate) }.join("\n") +
      "\n"
    end

def to_s super + ":\n" + format_observation ( result . control ) + "\n" + result . candidates . map { | candidate | format_observation ( candidate ) } . join ( "\n" ) + "\n" end

The default formatting is nearly unreadable, so make it useful.

 The assumption here is that errors raised in a test environment are
 printed out as strings, rather than using #inspect.

The default formatting is nearly unreadable so make it useful .


def process_url_params(url, headers)
      url_params = nil

      # find and extract/remove "params" key if the value is a Hash/ParamsArray
      headers.delete_if do |key, value|
        if key.to_s.downcase == 'params' &&
            (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray))
          if url_params
            raise ArgumentError.new("Multiple 'params' options passed")
          end
          url_params = value
          true
        else
          false
        end
      end

      # build resulting URL with query string
      if url_params && !url_params.empty?
        query_string = RestClient::Utils.encode_query_string(url_params)

        if url.include?('?')
          url + '&' + query_string
        else
          url + '?' + query_string
        end
      else
        url
      end
    end

def
process_url_params
(
url
,
headers
)
url_params
=
headers
.
delete_if
do
|
key
,
value
|
if
key
.
to_s
.
downcase
==
'params'
&&
(
value
.
is_a?
(
Hash
)
||
value
.
is_a?
(
RestClient
::
ParamsArray
)
)
if
url_params
raise
ArgumentError
.
new
(
"Multiple 'params' options passed"
)
end
url_params
=
value
true
else
false
end
end
if
url_params
&&
!
url_params
.
empty?
query_string
=
RestClient
::
Utils
.
encode_query_string
(
url_params
)
if
url
.
include?
(
'?'
)
url
+
'&'
+
query_string
else
url
+
'?'
+
query_string
end
else
url
end
end

Extract the query parameters and append them to the url

 Look through the headers hash for a :params option (case-insensitive,
 may be string or symbol). If present and the value is a Hash or
 RestClient::ParamsArray, *delete* the key/value pair from the headers
 hash and encode the value into a query string. Append this query string
 to the URL and return the resulting URL.

 @param [String] url
 @param [Hash] headers An options/headers hash to process. Mutation
   warning: the params key may be removed if present!

 @return [String] resulting url with query string


def stringify_headers headers
      headers.inject({}) do |result, (key, value)|
        if key.is_a? Symbol
          key = key.to_s.split(/_/).map(&:capitalize).join('-')
        end
        if 'CONTENT-TYPE' == key.upcase
          result[key] = maybe_convert_extension(value.to_s)
        elsif 'ACCEPT' == key.upcase
          # Accept can be composed of several comma-separated values
          if value.is_a? Array
            target_values = value
          else
            target_values = value.to_s.split ','
          end
          result[key] = target_values.map { |ext|
            maybe_convert_extension(ext.to_s.strip)
          }.join(', ')
        else
          result[key] = value.to_s
        end
        result
      end
    end

def
stringify_headers
headers
headers
.
inject
(
{
}
)
do
|
result
,
(
key
,
value
)
|
if
key
.
is_a?
Symbol
key
=
key
.
to_s
.
split
(
/
/
)
.
map
(
&
:capitalize
)
.
join
(
'-'
)
end
if
'CONTENT-TYPE'
==
key
.
upcase
result
[
key
]
=
maybe_convert_extension
(
value
.
to_s
)
elsif
'ACCEPT'
==
key
.
upcase
if
value
.
is_a?
Array
target_values
=
value
else
target_values
=
value
.
to_s
.
split
','
end
result
[
key
]
=
target_values
.
map
{
|
ext
|
maybe_convert_extension
(
ext
.
to_s
.
strip
)
}
.
join
(
', '
)
else
result
[
key
]
=
value
.
to_s
end
result
end
end

Return a hash of headers whose keys are capitalized strings

 BUG: stringify_headers does not fix the capitalization of headers that
 are already Strings. Leaving this behavior as is for now for
 backwards compatibility.
 https://github.com/rest-client/rest-client/issues/599


def maybe_convert_extension(ext)
      unless ext =~ /\A[a-zA-Z0-9_@-]+\z/
        # Don't look up strings unless they look like they could be a file
        # extension known to mime-types.
        #
        # There currently isn't any API public way to look up extensions
        # directly out of MIME::Types, but the type_for() method only strips
        # off after a period anyway.
        return ext
      end

      types = MIME::Types.type_for(ext)
      if types.empty?
        ext
      else
        types.first.content_type
      end
    end

def maybe_convert_extension ( ext ) unless ext =~ / \A \z / return ext end types = MIME :: Types . type_for ( ext ) if types . empty? ext else types . first . content_type end end

Given a MIME type or file extension, return either a MIME type or, if
 none is found, the input unchanged.

     >> maybe_convert_extension('json')
     => 'application/json'

     >> maybe_convert_extension('unknown')
     => 'unknown'

     >> maybe_convert_extension('application/xml')
     => 'application/xml'

 @param ext [String]

 @return [String]

Given a MIME type or file extension return either a MIME type or if none is found the input unchanged .


def [](suburl, &new_block)
      case
      when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block)
      when block        then self.class.new(concat_urls(url, suburl), options, &block)
      else                   self.class.new(concat_urls(url, suburl), options)
      end
    end

def [] ( suburl , & new_block ) case when block_given? then self . class . new ( concat_urls ( url , suburl ) , options , & new_block ) when block then self . class . new ( concat_urls ( url , suburl ) , options , & block ) else self . class . new ( concat_urls ( url , suburl ) , options ) end end

Construct a subresource, preserving authentication.

 Example:

   site = RestClient::Resource.new('http://example.com', 'adam', 'mypasswd')
   site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'

 This is especially useful if you wish to define your site in one place and
 call it in multiple locations:

   def orders
     RestClient::Resource.new('http://example.com/orders', 'admin', 'mypasswd')
   end

   orders.get                     # GET http://example.com/orders
   orders['1'].get                # GET http://example.com/orders/1
   orders['1/items'].delete       # DELETE http://example.com/orders/1/items

 Nest resources as far as you want:

   site = RestClient::Resource.new('http://example.com')
   posts = site['posts']
   first_post = posts['1']
   comments = first_post['comments']
   comments.post 'Hello', :content_type => 'text/plain'

Construct a subresource preserving authentication .


def cookies
      hash = {}

      cookie_jar.cookies(@request.uri).each do |cookie|
        hash[cookie.name] = cookie.value
      end

      hash
    end

def cookies hash = { } cookie_jar . cookies ( @request . uri ) . each do | cookie | hash [ cookie . name ] = cookie . value end hash end

Hash of cookies extracted from response headers.

 NB: This will return only cookies whose domain matches this request, and
 may not even return all of those cookies if there are duplicate names.
 Use the full cookie_jar for more nuanced access.

 @see #cookie_jar

 @return [Hash]

Hash of cookies extracted from response headers .


def cookie_jar
      return @cookie_jar if defined?(@cookie_jar) && @cookie_jar

      jar = @request.cookie_jar.dup
      headers.fetch(:set_cookie, []).each do |cookie|
        jar.parse(cookie, @request.uri)
      end

      @cookie_jar = jar
    end

def cookie_jar return @cookie_jar if defined? ( @cookie_jar ) && @cookie_jar jar = @request . cookie_jar . dup headers . fetch ( :set_cookie , [ ] ) . each do | cookie | jar . parse ( cookie , @request . uri ) end @cookie_jar = jar end

Cookie jar extracted from response headers.

 @return [HTTP::CookieJar]

Cookie jar extracted from response headers .


def follow_get_redirection(&block)
      new_args = request.args.dup
      new_args[:method] = :get
      new_args.delete(:payload)

      _follow_redirection(new_args, &block)
    end

def follow_get_redirection ( & block ) new_args = request . args . dup new_args [ :method ] = :get new_args . delete ( :payload ) _follow_redirection ( new_args , & block ) end

Follow a redirection response, but change the HTTP method to GET and drop
 the payload from the original request.

Follow a redirection response but change the HTTP method to GET and drop the payload from the original request .


def _follow_redirection(new_args, &block)

      # parse location header and merge into existing URL
      url = headers[:location]

      # cannot follow redirection if there is no location header
      unless url
        raise exception_with_response
      end

      # handle relative redirects
      unless url.start_with?('http')
        url = URI.parse(request.url).merge(url).to_s
      end
      new_args[:url] = url

      new_args[:password] = request.password
      new_args[:user] = request.user
      new_args[:headers] = request.headers
      new_args[:max_redirects] = request.max_redirects - 1

      # pass through our new cookie jar
      new_args[:cookies] = cookie_jar

      # prepare new request
      new_req = Request.new(new_args)

      # append self to redirection history
      new_req.redirection_history = history + [self]

      # execute redirected request
      new_req.execute(&block)
    end

def _follow_redirection ( new_args , & block ) url = headers [ :location ] unless url raise exception_with_response end unless url . start_with? ( 'http' ) url = URI . parse ( request . url ) . merge ( url ) . to_s end new_args [ :url ] = url new_args [ :password ] = request . password new_args [ :user ] = request . user new_args [ :headers ] = request . headers new_args [ :max_redirects ] = request . max_redirects - 1 new_args [ :cookies ] = cookie_jar new_req = Request . new ( new_args ) new_req . redirection_history = history + [ self ] new_req . execute ( & block ) end

Follow a redirection

 @param new_args [Hash] Start with this hash of arguments for the
   redirection request. The hash will be mutated, so be sure to dup any
   existing hash that should not be modified.


def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity
      unless env['rack.session']
        error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')
        raise(error)
      end

      @env = env
      @env['omniauth.strategy'] = self if on_auth_path?

      return mock_call!(env) if OmniAuth.config.test_mode
      return options_call if on_auth_path? && options_request?
      return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)
      return callback_call if on_callback_path?
      return other_phase if respond_to?(:other_phase)

      @app.call(env)
    end

The logic for dispatching any additional actions that need
 to be taken. For instance, calling the request phase if
 the request path is recognized.

 @param env [Hash] The Rack environment.

The logic for dispatching any additional actions that need to be taken . For instance calling the request phase if the request path is recognized .


def options_call
      OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase
      verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ')
      [200, {'Allow' => verbs}, []]
    end

def
options_call
OmniAuth
.
config
.
before_options_phase
.
call
(
env
)
if
OmniAuth
.
config
.
before_options_phase
verbs
=
OmniAuth
.
config
.
allowed_request_methods
.
collect
(
&
:to_s
)
.
collect
(
&
:upcase
)
.
join
(
', '
)
[
200
,
{
'Allow'
=>
verbs
}
,
[
]
]
end


def callback_call
      setup_phase
      log :info, 'Callback phase initiated.'
      @env['omniauth.origin'] = session.delete('omniauth.origin')
      @env['omniauth.origin'] = nil if env['omniauth.origin'] == ''
      @env['omniauth.params'] = session.delete('omniauth.params') || {}
      OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase
      callback_phase
    end

def
callback_call
setup_phase
log
:info
,
'Callback phase initiated.'
@env
[
'omniauth.origin'
]
=
session
.
delete
(
'omniauth.origin'
)
@env
[
'omniauth.origin'
]
=
if
env
[
'omniauth.origin'
]
==
''
@env
[
'omniauth.params'
]
=
session
.
delete
(
'omniauth.params'
)
||
{
}
OmniAuth
.
config
.
before_callback_phase
.
call
(
@env
)
if
OmniAuth
.
config
.
before_callback_phase
callback_phase
end

Performs the steps necessary to run the callback phase of a strategy.

Performs the steps necessary to run the callback phase of a strategy .


def mock_call!(*)
      return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)
      return mock_callback_call if on_callback_path?

      call_app!
    end

def mock_call! ( * ) return mock_request_call if on_request_path? && OmniAuth . config . allowed_request_methods . include? ( request . request_method . downcase . to_sym ) return mock_callback_call if on_callback_path? call_app! end

This is called in lieu of the normal request process
 in the event that OmniAuth has been configured to be
 in test mode.

This is called in lieu of the normal request process in the event that OmniAuth has been configured to be in test mode .


def instance_action_module
      @instance_action_module ||= Module.new do

        # Returns the <tt>GoogleAdsSavon::Client</tt> from the class instance.
        def client(&block)
          self.class.client(&block)
        end

      end.tap { |mod| include(mod) }
    end

def instance_action_module @instance_action_module ||= Module . new do def client ( & block ) self . class . client ( & block ) end end . tap { | mod | include ( mod ) } end


def soap_header_handler(auth_handler, version, header_ns, default_ns)
      auth_method = @config.read('authentication.method', :OAUTH2)
      handler_class = case auth_method
        when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT
          AdsCommon::SavonHeaders::OAuthHeaderHandler
        else
          raise AdsCommon::Errors::AuthError,
              "Unknown auth method: %s" % auth_method
        end
      return handler_class.new(@credential_handler, auth_handler, header_ns,
                                  default_ns, version)
    end

def
soap_header_handler
(
auth_handler
,
version
,
header_ns
,
default_ns
)
auth_method
=
@config
.
read
(
'authentication.method'
,
:OAUTH2
)
handler_class
=
case
auth_method
when
:OAUTH2
,
:OAUTH2_SERVICE_ACCOUNT
AdsCommon
::
SavonHeaders
::
OAuthHeaderHandler
else
raise
AdsCommon
::
Errors
::
AuthError
,
"Unknown auth method: %s"
%
auth_method
end
return
handler_class
.
new
(
@credential_handler
,
auth_handler
,
header_ns
,
default_ns
,
version
)
end

Retrieve correct soap_header_handler.

 Args:
 - auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to
   handle authentication
 - version: intended API version
 - header_ns: header namespace
 - default_ns: default namespace

 Returns:
 - SOAP header handler


def report_utils(version = nil)
      version = api_config.default_version if version.nil?
      # Check if version exists.
      if !api_config.versions.include?(version)
        raise AdsCommon::Errors::Error, "Unknown version '%s'" % version
      end
      return AdwordsApi::ReportUtils.new(self, version)
    end

def
report_utils
(
version
=
)
version
=
api_config
.
default_version
if
version
.
nil?
if
!
api_config
.
versions
.
include?
(
version
)
raise
AdsCommon
::
Errors
::
Error
,
"Unknown version '%s'"
%
version
end
return
AdwordsApi
::
ReportUtils
.
new
(
self
,
version
)
end

Returns an instance of ReportUtils object with all utilities relevant to
 the reporting.

 Args:
 - version: version of the API to use (optional).

Returns an instance of ReportUtils object with all utilities relevant to the reporting .


def batch_job_utils(version = nil)
      version = api_config.default_version if version.nil?
      # Check if version exists.
      if !api_config.versions.include?(version)
        raise AdsCommon::Errors::Error, "Unknown version '%s'" % version
      end
      return AdwordsApi::BatchJobUtils.new(self, version)
    end

def
batch_job_utils
(
version
=
)
version
=
api_config
.
default_version
if
version
.
nil?
if
!
api_config
.
versions
.
include?
(
version
)
raise
AdsCommon
::
Errors
::
Error
,
"Unknown version '%s'"
%
version
end
return
AdwordsApi
::
BatchJobUtils
.
new
(
self
,
version
)
end

Returns an instance of BatchJobUtils object with all utilities relevant
 to running batch jobs.

 Args:
 - version: version of the API to use (optional).

Returns an instance of BatchJobUtils object with all utilities relevant to running batch jobs .


def run_with_temporary_flag(flag_name, flag_value, block)
      previous = @credential_handler.instance_variable_get(flag_name)
      @credential_handler.instance_variable_set(flag_name, flag_value)
      begin
        return block.call
      ensure
        @credential_handler.instance_variable_set(flag_name, previous)
      end
    end

def run_with_temporary_flag ( flag_name , flag_value , block ) previous = @credential_handler . instance_variable_get ( flag_name ) @credential_handler . instance_variable_set ( flag_name , flag_value ) begin return block . call ensure @credential_handler . instance_variable_set ( flag_name , previous ) end end

Executes block with a temporary flag set to a given value. Returns block
 result.

Executes block with a temporary flag set to a given value . Returns block result .


def validate_arguments(args_hash, fields_list, type_ns = nil)
      check_extra_fields(args_hash, array_from_named_list(fields_list))
      add_order_key(args_hash, fields_list)
      fields_list.each do |field|
        key = field[:name]
        item = args_hash[key]
        check_required_argument_present(item, field)
        unless item.nil?
          original_name = field[:original_name]
          if original_name
            key = handle_name_override(args_hash, key, original_name)
          end

          item_type = get_full_type_signature(field[:type])
          item_ns = field[:ns] || type_ns
          key = handle_namespace_override(args_hash, key, item_ns) if item_ns

          # Separate validation for choice types as we need to inject nodes into
          # the tree. Validate as usual if not a choice type.
          unless validate_choice_argument(item, args_hash, key, item_type)
            validate_arg(item, args_hash, key, item_type)
          end
        end
      end
      return args_hash
    end

def validate_arguments ( args_hash , fields_list , type_ns = nil ) check_extra_fields ( args_hash , array_from_named_list ( fields_list ) ) add_order_key ( args_hash , fields_list ) fields_list . each do | field | key = field [ :name ] item = args_hash [ key ] check_required_argument_present ( item , field ) unless item . nil? original_name = field [ :original_name ] if original_name key = handle_name_override ( args_hash , key , original_name ) end item_type = get_full_type_signature ( field [ :type ] ) item_ns = field [ :ns ] || type_ns key = handle_namespace_override ( args_hash , key , item_ns ) if item_ns unless validate_choice_argument ( item , args_hash , key , item_type ) validate_arg ( item , args_hash , key , item_type ) end end end return args_hash end

Validates given arguments based on provided fields list.

Validates given arguments based on provided fields list .


def validate_choice_argument(item, parent, key, item_type)
      result = false
      if item_type.kind_of?(Hash) && item_type.include?(:choices)
        # If we have an array of choices, we need to go over them individually.
        # We drop original array and replace it with the generated one that's
        # nested one level more.
        if item.kind_of?(Array)
          parent[key] = []
          item.each do |sub_item|
            unless validate_choice_argument(sub_item, parent, key, item_type)
              validate_arg(sub_item, parent, key, item_type)
            end
          end
          return true
        end
        # New root needed for extra nesting we have (choice field).
        new_root = {}
        choice_items = arrayize(item)
        choice_items.each do |choice_item|
          choice_type = choice_item.delete(:xsi_type)
          choice_item_type =
              find_choice_by_xsi_type(choice_type, item_type[:choices])
          if choice_type.nil? || choice_item_type.nil?
            raise AdsCommon::Errors::TypeMismatchError.new(
              'choice subtype', choice_type, choice_item.to_s())
          end
          choice_item[:xsi_type] = choice_type
          # Note we use original name that produces a string like
          # "BasicUserList". That's needed as the name is generated out of
          # standard naming ("basicUserList") which would otherwise be produced.
          choice_key = choice_item_type[:original_name]
          new_root[choice_key] = choice_item
          type_signature = get_full_type_signature(choice_type)
          validate_arg(choice_item, new_root, choice_key, type_signature)
        end
        if parent[key].kind_of?(Array)
          parent[key] << new_root
        else
          parent[key] = new_root
        end
        result = true
      end
      return result
    end

def
validate_choice_argument
(
item
,
parent
,
key
,
item_type
)
result
=
false
if
item_type
.
kind_of?
(
Hash
)
&&
item_type
.
include?
(
:choices
)
if
item
.
kind_of?
(
Array
)
parent
[
key
]
=
[
]
item
.
each
do
|
sub_item
|
unless
validate_choice_argument
(
sub_item
,
parent
,
key
,
item_type
)
validate_arg
(
sub_item
,
parent
,
key
,
item_type
)
end
end
return
true
end
new_root
=
{
}
choice_items
=
arrayize
(
item
)
choice_items
.
each
do
|
choice_item
|
choice_type
=
choice_item
.
delete
(
:xsi_type
)
choice_item_type
=
find_choice_by_xsi_type
(
choice_type
,
item_type
[
:choices
]
)
if
choice_type
.
nil?
||
choice_item_type
.
nil?
raise
AdsCommon
::
Errors
::
TypeMismatchError
.
new
(
'choice subtype'
,
choice_type
,
choice_item
.
to_s
(
)
)
end
choice_item
[
:xsi_type
]
=
choice_type
choice_key
=
choice_item_type
[
:original_name
]
new_root
[
choice_key
]
=
choice_item
type_signature
=
get_full_type_signature
(
choice_type
)
validate_arg
(
choice_item
,
new_root
,
choice_key
,
type_signature
)
end
if
parent
[
key
]
.
kind_of?
(
Array
)
parent
[
key
]
<<
new_root
else
parent
[
key
]
=
new_root
end
result
=
true
end
return
result
end

Special handling for choice types. Goes over each item, checks xsi_type
 is set and correct and injects new node for it into the tree. After that,
 recurces with the correct item type.

Special handling for choice types . Goes over each item checks xsi_type is set and correct and injects new node for it into the tree . After that recurces with the correct item type .


def check_extra_fields(args_hash, known_fields)
      extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS
      unless extra_fields.empty?
        raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields)
      end
    end

def check_extra_fields ( args_hash , known_fields ) extra_fields = args_hash . keys - known_fields - IGNORED_HASH_KEYS unless extra_fields . empty? raise AdsCommon :: Errors :: UnexpectedParametersError . new ( extra_fields ) end end

Checks if no extra fields provided outside of known ones.

Checks if no extra fields provided outside of known ones .


def check_required_argument_present(arg, field)
      # At least one item required, none passed.
      if field[:min_occurs] > 0 and arg.nil?
        raise AdsCommon::Errors::MissingPropertyError.new(
            field[:name], field[:type])
      end
      # An object passed when an array is expected.
      if (field[:max_occurs] == :unbounded) and
          !(arg.nil? or arg.kind_of?(Array))
        raise AdsCommon::Errors::TypeMismatchError.new(
            Array, arg.class, field[:name])
      end
      # An array passed when an object is expected.
      if (field[:max_occurs] == 1) and arg.kind_of?(Array)
        raise AdsCommon::Errors::TypeMismatchError.new(
            field[:type], Array, field[:name])
      end
    end

def check_required_argument_present ( arg , field ) if field [ :min_occurs ] > 0 and arg . nil? raise AdsCommon :: Errors :: MissingPropertyError . new ( field [ :name ] , field [ :type ] ) end if ( field [ :max_occurs ] == :unbounded ) and ! ( arg . nil? or arg . kind_of? ( Array ) ) raise AdsCommon :: Errors :: TypeMismatchError . new ( Array , arg . class , field [ :name ] ) end if ( field [ :max_occurs ] == 1 ) and arg . kind_of? ( Array ) raise AdsCommon :: Errors :: TypeMismatchError . new ( field [ :type ] , Array , field [ :name ] ) end end

Checks the provided data structure matches wsdl definition.

Checks the provided data structure matches wsdl definition .


def handle_name_override(args, key, original_name)
      rename_hash_key(args, key, original_name)
      replace_array_item(args[:order!], key, original_name)
      return original_name
    end

def handle_name_override ( args , key , original_name ) rename_hash_key ( args , key , original_name ) replace_array_item ( args [ :order! ] , key , original_name ) return original_name end

Overrides non - standard name conversion .


def handle_namespace_override(args, key, ns)
      add_extra_namespace(ns)
      new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns)
      rename_hash_key(args, key, new_key)
      replace_array_item(args[:order!], key, new_key)
      return new_key
    end

def handle_namespace_override ( args , key , ns ) add_extra_namespace ( ns ) new_key = prefix_key_with_namespace ( key . to_s . lower_camelcase , ns ) rename_hash_key ( args , key , new_key ) replace_array_item ( args [ :order! ] , key , new_key ) return new_key end

Overrides non-default namespace if requested.

Overrides non - default namespace if requested .


def validate_arg(arg, parent, key, arg_type)
      result = case arg
        when Array
          validate_array_arg(arg, parent, key, arg_type)
        when Hash
          validate_hash_arg(arg, parent, key, arg_type)
        when Time
          arg = validate_time_arg(arg, parent, key)
          validate_hash_arg(arg, parent, key, arg_type)
        else
          arg
      end
      return result
    end

def validate_arg ( arg , parent , key , arg_type ) result = case arg when Array validate_array_arg ( arg , parent , key , arg_type ) when Hash validate_hash_arg ( arg , parent , key , arg_type ) when Time arg = validate_time_arg ( arg , parent , key ) validate_hash_arg ( arg , parent , key , arg_type ) else arg end return result end


def validate_array_arg(arg, parent, key, arg_type)
      result = arg.map do |item|
        validate_arg(item, parent, key, arg_type)
      end
      return result
    end

def validate_array_arg ( arg , parent , key , arg_type ) result = arg . map do | item | validate_arg ( item , parent , key , arg_type ) end return result end


def validate_hash_arg(arg, parent, key, arg_type)
      arg_type = handle_xsi_type(arg, parent, key, arg_type)
      validate_arguments(arg, arg_type[:fields], arg_type[:ns])
    end

def validate_hash_arg ( arg , parent , key , arg_type ) arg_type = handle_xsi_type ( arg , parent , key , arg_type ) validate_arguments ( arg , arg_type [ :fields ] , arg_type [ :ns ] ) end


def validate_time_arg(arg, parent, key)
      xml_value = time_to_xml_hash(arg)
      parent[key] = xml_value
      return xml_value
    end

def validate_time_arg ( arg , parent , key ) xml_value = time_to_xml_hash ( arg ) parent [ key ] = xml_value return xml_value end


def add_attribute(node, key, name, value)
      node[:attributes!] ||= {}
      node[:attributes!][key] ||= {}
      if node[:attributes!][key].include?(name)
        node[:attributes!][key][name] = arrayize(node[:attributes!][key][name])
        node[:attributes!][key][name] << value
      else
        node[:attributes!][key][name] = value
      end
    end

def add_attribute ( node , key , name , value ) node [ :attributes! ] ||= { } node [ :attributes! ] [ key ] ||= { } if node [ :attributes! ] [ key ] . include? ( name ) node [ :attributes! ] [ key ] [ name ] = arrayize ( node [ :attributes! ] [ key ] [ name ] ) node [ :attributes! ] [ key ] [ name ] << value else node [ :attributes! ] [ key ] [ name ] = value end end

Adds Savon attribute for given node, key, name and value.

Adds Savon attribute for given node key name and value .


def prefix_key_with_namespace(key, ns_index = nil)
      namespace = (ns_index.nil?) ? DEFAULT_NAMESPACE : ("ns%d" % ns_index)
      return prefix_key(key, namespace)
    end

def prefix_key_with_namespace ( key , ns_index = nil ) namespace = ( ns_index . nil? ) ? DEFAULT_NAMESPACE : ( "ns%d" % ns_index ) return prefix_key ( key , namespace ) end

Prefixes a key with a given namespace index or default namespace.

Prefixes a key with a given namespace index or default namespace .


def get_full_type_signature(type_name)
      result = (type_name.nil?) ? nil : @registry.get_type_signature(type_name)
      result[:fields] = implode_parent(result) if result and result[:base]
      return result
    end

def get_full_type_signature ( type_name ) result = ( type_name . nil? ) ? nil : @registry . get_type_signature ( type_name ) result [ :fields ] = implode_parent ( result ) if result and result [ :base ] return result end

Returns type signature with all inherited fields.

Returns type signature with all inherited fields .


def implode_parent(data_type)
      result = []
      if data_type[:base]
        parent_type = @registry.get_type_signature(data_type[:base])
        result += implode_parent(parent_type)
      end
      data_type[:fields].each do |field|
        # If the parent type includes a field with the same name, overwrite it.
        result.reject! {|parent_field| parent_field[:name].eql?(field[:name])}
        # Storing field's namespace.
        field[:ns] = data_type[:ns] if data_type[:ns]
        result << field
      end
      return result
    end

def implode_parent ( data_type ) result = [ ] if data_type [ :base ] parent_type = @registry . get_type_signature ( data_type [ :base ] ) result += implode_parent ( parent_type ) end data_type [ :fields ] . each do | field | result . reject! { | parent_field | parent_field [ :name ] . eql? ( field [ :name ] ) } field [ :ns ] = data_type [ :ns ] if data_type [ :ns ] result << field end return result end

Returns all inherited fields of superclasses for given type.

Returns all inherited fields of superclasses for given type .


def time_to_xml_hash(time)
      return {
          :hour => time.hour, :minute => time.min, :second => time.sec,
          :date => {:year => time.year, :month => time.month, :day => time.day}
      }
    end

def time_to_xml_hash ( time ) return { :hour => time . hour , :minute => time . min , :second => time . sec , :date => { :year => time . year , :month => time . month , :day => time . day } } end

Converts Time to a hash for XML marshalling.

Converts Time to a hash for XML marshalling .


def load(filename)
      begin
        new_config = YAML::load_file(filename)
        if new_config.kind_of?(Hash)
          @config = new_config
        else
          raise AdsCommon::Errors::Error,
              "Incorrect configuration file: '%s'" % filename
        end
      rescue TypeError => e
        raise AdsCommon::Errors::Error,
            "Error parsing configuration file: '%s' (%s)" % [filename, e]
      end
      return nil
    end

Reads a configuration file into instance variable as a Ruby structure with
 the complete set of keys and values.

 Args:
 - filename: config file to be read (*String*)

 Raises:
 - <b>Errno::ENOENT</b> if the file does not exist.

Reads a configuration file into instance variable as a Ruby structure with the complete set of keys and values .


def process_hash_keys(hash)
      return hash.inject({}) do |result, pair|
        key, value = pair
        result[key.to_sym] = value.is_a?(Hash) ?
            process_hash_keys(value) : value
        result
      end
    end

def process_hash_keys ( hash ) return hash . inject ( { } ) do | result , pair | key , value = pair result [ key . to_sym ] = value . is_a? ( Hash ) ? process_hash_keys ( value ) : value result end end

Auxiliary method to recurse through a hash and convert all the keys to
 symbols.

Auxiliary method to recurse through a hash and convert all the keys to symbols .


def find_value(data, path)
      return (path.nil? or data.nil?) ? nil :
          path.split('.').inject(data) do |node, section|
            break if node.nil?
            key = section.to_sym
            (node.is_a?(Hash) and node.include?(key)) ? node[key] : nil
          end
    end

def find_value ( data , path ) return ( path . nil? or data . nil? ) ? nil : path . split ( '.' ) . inject ( data ) do | node , section | break if node . nil? key = section . to_sym ( node . is_a? ( Hash ) and node . include? ( key ) ) ? node [ key ] : nil end end

Finds a value for string of format 'level1.level2.name' in a given hash.

Finds a value for string of format level1 . level2 . name in a given hash .


def initialize_url(batch_job_url)
      headers = DEFAULT_HEADERS
      headers['Content-Length'] = 0
      headers['x-goog-resumable'] = 'start'

      response = AdsCommon::Http.post_response(
          batch_job_url, '', @api.config, headers)

      return response.headers['Location']
    end

def initialize_url ( batch_job_url ) headers = DEFAULT_HEADERS headers [ 'Content-Length' ] = 0 headers [ 'x-goog-resumable' ] = 'start' response = AdsCommon :: Http . post_response ( batch_job_url , '' , @api . config , headers ) return response . headers [ 'Location' ] end

Initializes an upload URL to get the actual URL to which to upload
 operations.

 Args:
 - batch_job_url: The UploadURL provided by BatchJobService

 Returns:
 - The URL that should actually be used to upload operations.

Initializes an upload URL to get the actual URL to which to upload operations .


def put_incremental_operations(
        operations, batch_job_url, total_content_length = 0,
        is_last_request = false)
      @api.utils_reporter.batch_job_utils_used()
      headers = DEFAULT_HEADERS
      soap_operations = generate_soap_operations(operations)
      request_body = soap_operations.join
      is_first_request = (total_content_length == 0)

      if is_first_request
        request_body = (UPLOAD_XML_PREFIX % [@version]) + request_body
      end
      if is_last_request
        request_body += UPLOAD_XML_SUFFIX
      end

      request_body = add_padding(request_body)
      content_length = request_body.bytesize

      headers['Content-Length'] = content_length

      lower_bound = total_content_length
      upper_bound = total_content_length + content_length - 1
      total_bytes = is_last_request ? upper_bound + 1 : '*'
      content_range =
          "bytes %d-%d/%s" % [lower_bound, upper_bound, total_bytes]

      headers['Content-Range'] = content_range

      log_request(batch_job_url, headers, request_body)

      # The HTTPI library fails to handle the response when uploading
      # incremental requests. We're not interested in the response, so just
      # ignore the error.
      begin
        AdsCommon::Http.put_response(
            batch_job_url, request_body, @api.config, headers)
      rescue ArgumentError
      end

      total_content_length += content_length
      return total_content_length
    end

Puts the provided operations to the provided URL, allowing
 for incremental followup puts.

 Args:
 - soap_operations: An array including SOAP operations provided by
   generate_soap_operations
 - batch_job_url: The UploadURL provided by BatchJobService
 - total_content_length: The total number of bytes already uploaded
   incrementally. Set this to 0 the first time you call the method.
 - is_last_request: Whether or not this set of uploads will conclude the
   full request.

 Returns:
 - total content length, including what was just uploaded. Pass this back
   into this method on subsequent calls.

Puts the provided operations to the provided URL allowing for incremental followup puts .


def get_job_results(batch_job_url)
      @api.utils_reporter.batch_job_utils_used()
      xml_response = AdsCommon::Http.get_response(batch_job_url, @api.config)
      begin
        return sanitize_result(
            get_nori().parse(xml_response.body)[:mutate_response][:rval])
      rescue
        return nil
      end
    end

def get_job_results ( batch_job_url ) @api . utils_reporter . batch_job_utils_used ( ) xml_response = AdsCommon :: Http . get_response ( batch_job_url , @api . config ) begin return sanitize_result ( get_nori ( ) . parse ( xml_response . body ) [ :mutate_response ] [ :rval ] ) rescue return nil end end

Downloads the results of a batch job from the specified URL.

 Args:
 - batch_job_url: The URL provided by BatchJobService to fetch the results
   from

 Returns:
 - the results of the batch job, as a ruby hash, or nil if none yet exist

Downloads the results of a batch job from the specified URL .


def extract_soap_operations(full_soap_xml)
      doc = Nokogiri::XML(full_soap_xml)
      operations = doc.css('wsdl|operations')
      operations.attr('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
      operations.each do |element|
        check_xsi_type(element)
      end
      return operations.to_s
    end

Given a full SOAP xml string, extract just the operations element
 from the SOAP body as a string.

Given a full SOAP xml string extract just the operations element from the SOAP body as a string .


def sanitize_result(results)
      if results.is_a?(Array)
        ret = []
        results.each do |result|
          ret << sanitize_result(result)
        end
        return ret
      end

      if results.is_a?(Hash)
        ret = {}
        results.each do |k, v|
          v = sanitize_result(v) if v.is_a?(Hash)
          ret[k] = v unless k.to_s.start_with?('@')
        end
        return ret
      end

      return results
    end

def sanitize_result ( results ) if results . is_a? ( Array ) ret = [ ] results . each do | result | ret << sanitize_result ( result ) end return ret end if results . is_a? ( Hash ) ret = { } results . each do | k , v | v = sanitize_result ( v ) if v . is_a? ( Hash ) ret [ k ] = v unless k . to_s . start_with? ( '@' ) end return ret end return results end

Removes extraneous XML information from return hash.

Removes extraneous XML information from return hash .


def has_next_landscape_page(page)
      raise ArgumentError,
          'Cannot page through query with no LIMIT clause.' if @start_index.nil?
      return false unless page[:entries]
      total_landscape_points_in_page = 0
      page[:entries].each do |landscape|
        total_landscape_points_in_page += landscape[:landscape_points].size
      end
      return total_landscape_points_in_page >= @page_size
    end

Determining whether another page exists when dealing with bid landscapes
 is different from other types of queries. Use this method for those cases.

Determining whether another page exists when dealing with bid landscapes is different from other types of queries . Use this method for those cases .


def version_has_service(version, service)
      return service_config.include?(version) &&
          service_config[version].include?(service)
    end

def version_has_service ( version , service ) return service_config . include? ( version ) && service_config [ version ] . include? ( service ) end

Does the given version exist and contain the given service?

 Returns:
 Boolean indicating whether the given version exists and contains the
 given service


def endpoint(version, service)
      base = get_wsdl_base(version)
      if !subdir_config().nil?
        base = base.to_s + subdir_config()[[version, service]].to_s
      end
      return base.to_s + version.to_s + '/' + service.to_s
    end

def endpoint ( version , service ) base = get_wsdl_base ( version ) if ! subdir_config ( ) . nil? base = base . to_s + subdir_config ( ) [ [ version , service ] ] . to_s end return base . to_s + version . to_s + '/' + service . to_s end

Get the endpoint for a service on a given API version.

 Args:
 - version: the API version
 - service: the name of the API service

 Returns:
 The endpoint URL

Get the endpoint for a service on a given API version .


def do_require(version, service)
      filename = [api_path, version.to_s, service.to_s.snakecase].join('/')
      require filename
      return filename
    end

def do_require ( version , service ) filename = [ api_path , version . to_s , service . to_s . snakecase ] . join ( '/' ) require filename return filename end

Perform the loading of the necessary source files for a version.

 Args:
 - version: the API version
 - service: service name

 Returns:
 The filename that was loaded

Perform the loading of the necessary source files for a version .


def module_name(version, service)
      return [api_name, version.to_s.upcase, service.to_s].join('::')
    end

def module_name ( version , service ) return [ api_name , version . to_s . upcase , service . to_s ] . join ( '::' ) end

Returns the full module name for a given service.

 Args:
 - version: the API version
 - service: the service name

 Returns:
 The full module name for the given service

Returns the full module name for a given service .


def get_wsdls(version)
      res = {}
      wsdl_base = get_wsdl_base(version)
      postfix = wsdl_base.start_with?('http') ? '?wsdl' : '.wsdl'
      services(version).each do |service|
        path = wsdl_base
        if (!subdir_config().nil?)
          subdir_name = subdir(version, service);
          path = path + subdir_name if subdir_name and !subdir_name.empty?
        end
        path = path + version.to_s + '/' + service.to_s + postfix
        res[service.to_s] = path
      end
      return res
    end

def get_wsdls ( version ) res = { } wsdl_base = get_wsdl_base ( version ) postfix = wsdl_base . start_with? ( 'http' ) ? '?wsdl' : '.wsdl' services ( version ) . each do | service | path = wsdl_base if ( ! subdir_config ( ) . nil? ) subdir_name = subdir ( version , service ) ; path = path + subdir_name if subdir_name and ! subdir_name . empty? end path = path + version . to_s + '/' + service . to_s + postfix res [ service . to_s ] = path end return res end

Generates an array of WSDL URLs based on defined Services and version
 supplied. This method is used by generators to determine what service
 wrappers to generate.

 Args:
   - version: the API version.

 Returns
   hash of pairs Service => WSDL URL

Generates an array of WSDL URLs based on defined Services and version supplied . This method is used by generators to determine what service wrappers to generate .


def process(offset = 0, instance = self,  &block)
      block.arity > 0 ? yield_objects(offset, instance, &block) : evaluate(instance, &block)
    end

def process ( offset = 0 , instance = self , & block ) block . arity > 0 ? yield_objects ( offset , instance , & block ) : evaluate ( instance , & block ) end

Processes a given +block+. Yields objects if the block expects any arguments.
 Otherwise evaluates the block in the context of +instance+.

Processes a given + block + . Yields objects if the block expects any arguments . Otherwise evaluates the block in the context of + instance + .


def yield_objects(offset, instance, &block)
      to_yield = [:soap, :wsdl, :http, :wsse]
      yield *(to_yield[offset, block.arity].map { |obj_name| instance.send(obj_name) })
    end

def yield_objects ( offset , instance , & block ) to_yield = [ :soap , :wsdl , :http , :wsse ] yield * ( to_yield [ offset , block . arity ] . map { | obj_name | instance . send ( obj_name ) } ) end

Yields a number of objects to a given +block+ depending on how many arguments
 the block is expecting.

Yields a number of objects to a given + block + depending on how many arguments the block is expecting .


def evaluate(instance, &block)
      original_self = eval "self", block.binding

      # A proxy that attemps to make method calls on +instance+. If a NoMethodError is
      # raised, the call will be made on +original_self+.
      proxy = Object.new
      proxy.instance_eval do
        class << self
          attr_accessor :original_self, :instance
        end

        def method_missing(method, *args, &block)
          instance.send(method, *args, &block)
        rescue NoMethodError
          original_self.send(method, *args, &block)
        end
      end

      proxy.instance = instance
      proxy.original_self = original_self

      proxy.instance_eval &block
    end

def evaluate ( instance , & block ) original_self = eval "self" , block . binding proxy = Object . new proxy . instance_eval do class << self attr_accessor :original_self , :instance end def method_missing ( method , * args , & block ) instance . send ( method , * args , & block ) rescue NoMethodError original_self . send ( method , * args , & block ) end end proxy . instance = instance proxy . original_self = original_self proxy . instance_eval & block end

Evaluates a given +block+ inside +instance+. Stores the original block binding.

Evaluates a given + block + inside + instance + . Stores the original block binding .


def remove_blank_values(hash)
      hash.delete_if { |_, value| value.respond_to?(:empty?) ? value.empty? : !value }
    end

def remove_blank_values ( hash ) hash . delete_if { | _ , value | value . respond_to? ( :empty? ) ? value . empty? : ! value } end

Removes all blank values from a given +hash+.

Removes all blank values from a given + hash + .


def values()
      # values_array is an Ad-Manager-compliant list of values of the following
      # form: [:key => ..., :value => {:xsi_type => ..., :value => ...}]
      values_array = @values.map do |key, value|
        raise 'Missing value in StatementBuilder.' if value.nil?
        raise 'Misconfigured value in StatementBuilder.' unless value.is_a? Hash
        raise 'Value cannot be nil on StatementBuilder.' if value[:value].nil?
        raise 'Missing value type for %s.' % key if value[:xsi_type].nil?
        unless VALUE_TYPES.values.include?(value[:xsi_type])
          raise 'Unknown value type for %s.' % key
        end
        if value[:xsi_type] == 'SetValue'
          if value[:value].map {|v| v.class}.to_set.size > 1
            raise 'Cannot pass more than one type in set variable, %s.' % key
          end
        end
        if value[:xsi_type] == 'DateTimeValue'
          unless value[:value][:time_zone_id]
            raise 'Missing timezone on DateTimeValue variable, %s.' %key
          end
        end
        {:key => key.to_s(), :value => value}
      end
      return values_array
    end

Get values as an array, the format the Ad Manager API expects.

Get values as an array the format the Ad Manager API expects .


def generate_value_object(value)
      typeKeyValue = VALUE_TYPES.find {|key, val| value.is_a? key}
      dateTypes = [AdManagerApi::AdManagerDate, AdManagerApi::AdManagerDateTime]
      if dateTypes.include?(value.class)
        value = value.to_h
      end
      return value if typeKeyValue.nil?
      return {:xsi_type => typeKeyValue.last, :value => value}
    end

def generate_value_object ( value ) typeKeyValue = VALUE_TYPES . find { | key , val | value . is_a? key } dateTypes = [ AdManagerApi :: AdManagerDate , AdManagerApi :: AdManagerDateTime ] if dateTypes . include? ( value . class ) value = value . to_h end return value if typeKeyValue . nil? return { :xsi_type => typeKeyValue . last , :value => value } end

Create an individual value object by inferring the xsi_type. If the value
 type isn't recognized, return the original value parameter.

Create an individual value object by inferring the xsi_type . If the value type isn t recognized return the original value parameter .


def validate()
      if !@select.to_s.strip.empty? and @from.to_s.strip.empty?
        raise 'FROM clause is required with SELECT'
      end
      if !@from.to_s.strip.empty? and @select.to_s.strip.empty?
        raise 'SELECT clause is required with FROM'
      end
      if !@offset.nil? and @limit.nil?
        raise 'LIMIT clause is required with OFFSET'
      end
      unless @limit.is_a? Integer or @limit.nil?
        raise 'LIMIT must be an integer'
      end
      unless @offset.is_a? Integer or @offset.nil?
        raise 'OFFSET must be an integer'
      end
    end

def
validate
(
)
if
!
@select
.
to_s
.
strip
.
empty?
and
@from
.
to_s
.
strip
.
empty?
raise
'FROM clause is required with SELECT'
end
if
!
@from
.
to_s
.
strip
.
empty?
and
@select
.
to_s
.
strip
.
empty?
raise
'SELECT clause is required with FROM'
end
if
!
@offset
.
nil?
and
@limit
.
nil?
raise
'LIMIT clause is required with OFFSET'
end
unless
@limit
.
is_a?
Integer
or
@limit
.
nil?
raise
'LIMIT must be an integer'
end
unless
@offset
.
is_a?
Integer
or
@offset
.
nil?
raise
'OFFSET must be an integer'
end
end


def to_statement()
      @api.utils_reporter.statement_builder_used()
      validate()
      ordering = @ascending ? 'ASC' : 'DESC'
      pql_query = PQLQuery.new
      pql_query << SELECT % @select unless @select.to_s.empty?
      pql_query << FROM % @from unless @from.to_s.empty?
      pql_query << WHERE % @where unless @where.to_s.empty?
      pql_query << ORDER % [@order_by, ordering] unless @order_by.to_s.empty?
      pql_query << LIMIT % @limit unless @limit.nil?
      pql_query << OFFSET % @offset unless @offset.nil?
      return {:query => pql_query.to_s(), :values => @pql_values.values}
    end

def to_statement ( ) @api . utils_reporter . statement_builder_used ( ) validate ( ) ordering = @ascending ? 'ASC' : 'DESC' pql_query = PQLQuery . new pql_query << SELECT % @select unless @select . to_s . empty? pql_query << FROM % @from unless @from . to_s . empty? pql_query << WHERE % @where unless @where . to_s . empty? pql_query << ORDER % [ @order_by , ordering ] unless @order_by . to_s . empty? pql_query << LIMIT % @limit unless @limit . nil? pql_query << OFFSET % @offset unless @offset . nil? return { :query => pql_query . to_s ( ) , :values => @pql_values . values } end

Create a statement object that can be sent in a Ad Manager API request.

Create a statement object that can be sent in a Ad Manager API request .


def method_missing(name, *args, &block)
      result = @date.send(name, *args, &block)
      return self.class.new(@api, result) if result.is_a? Date
      return result
    end

def method_missing ( name , * args , & block ) result = @date . send ( name , * args , & block ) return self . class . new ( @api , result ) if result . is_a? Date return result end

When an unrecognized method is applied to AdManagerDate, pass it through
 to the internal ruby Date.

When an unrecognized method is applied to AdManagerDate pass it through to the internal ruby Date .


def to_h
      {
        :date => AdManagerApi::AdManagerDate.new(
            @api, @time.year, @time.month, @time.day
        ).to_h,
        :hour => @time.hour,
        :minute => @time.min,
        :second => @time.sec,
        :time_zone_id => @timezone.identifier
      }
    end

def to_h { :date => AdManagerApi :: AdManagerDate . new ( @api , @time . year , @time . month , @time . day ) . to_h , :hour => @time . hour , :minute => @time . min , :second => @time . sec , :time_zone_id => @timezone . identifier } end

Convert AdManagerDateTime into a hash representation which can be consumed
 by the Ad Manager API. E.g., a hash that can be passed as PQL DateTime
 variables.

 Returns:
   - ad_manager_datetime_hash: a hash representation of an
     AdManagerDateTime

Convert AdManagerDateTime into a hash representation which can be consumed by the Ad Manager API . E . g . a hash that can be passed as PQL DateTime variables .


def method_missing(name, *args, &block)
      # Restrict time zone related functions from being passed to internal ruby
      # Time attribute, since AdManagerDateTime handles timezones its own way.
      restricted_functions = [:dst?, :getgm, :getlocal, :getutc, :gmt,
          :gmtime, :gmtoff, :isdst, :localtime, :utc]
      if restricted_functions.include? name
        raise NoMethodError, 'undefined method %s for %s' % [name, self]
      end
      result = @time.send(name, *args, &block)
      if result.is_a? Time
        return self.class.new(@api, result, @timezone.identifier)
      else
        return result
      end
    end

def
method_missing
(
name
,
*
args
,
&
block
)
restricted_functions
=
[
:dst?
,
:getgm
,
:getlocal
,
:getutc
,
:gmt
,
:gmtime
,
:gmtoff
,
:isdst
,
:localtime
,
:utc
]
if
restricted_functions
.
include?
name
raise
NoMethodError
,
'undefined method %s for %s'
%
[
name
,
self
]
end
result
=
@time
.
send
(
name
,
*
args
,
&
block
)
if
result
.
is_a?
Time
return
self
.
class
.
new
(
@api
,
result
,
@timezone
.
identifier
)
else
return
result
end
end

When an unrecognized method is applied to AdManagerDateTime, pass it
 through to the internal ruby Time.

When an unrecognized method is applied to AdManagerDateTime pass it through to the internal ruby Time .


def create_savon_client(endpoint, namespace)
      client = GoogleAdsSavon::Client.new do |wsdl, httpi|
        wsdl.endpoint = endpoint
        wsdl.namespace = namespace
        AdsCommon::Http.configure_httpi(@config, httpi)
      end
      client.config.raise_errors = false
      client.config.logger.subject = NoopLogger.new
      return client
    end

def create_savon_client ( endpoint , namespace ) client = GoogleAdsSavon :: Client . new do | wsdl , httpi | wsdl . endpoint = endpoint wsdl . namespace = namespace AdsCommon :: Http . configure_httpi ( @config , httpi ) end client . config . raise_errors = false client . config . logger . subject = NoopLogger . new return client end


def get_soap_xml(action_name, args)
      registry = get_service_registry()
      validator = ParametersValidator.new(registry)
      args = validator.validate_args(action_name, args)
      return handle_soap_request(
          action_name.to_sym, true, args, validator.extra_namespaces)
    end

def get_soap_xml ( action_name , args ) registry = get_service_registry ( ) validator = ParametersValidator . new ( registry ) args = validator . validate_args ( action_name , args ) return handle_soap_request ( action_name . to_sym , true , args , validator . extra_namespaces ) end

Generates and returns SOAP XML for the specified action and args.

Generates and returns SOAP XML for the specified action and args .


def execute_action(action_name, args, &block)
      registry = get_service_registry()
      validator = ParametersValidator.new(registry)
      args = validator.validate_args(action_name, args)
      request_info, response = handle_soap_request(
          action_name.to_sym, false, args, validator.extra_namespaces)
      do_logging(action_name, request_info, response)
      handle_errors(response)
      extractor = ResultsExtractor.new(registry)
      result = extractor.extract_result(response, action_name, &block)
      run_user_block(extractor, response, result, &block) if block_given?
      return result
    end

def execute_action ( action_name , args , & block ) registry = get_service_registry ( ) validator = ParametersValidator . new ( registry ) args = validator . validate_args ( action_name , args ) request_info , response = handle_soap_request ( action_name . to_sym , false , args , validator . extra_namespaces ) do_logging ( action_name , request_info , response ) handle_errors ( response ) extractor = ResultsExtractor . new ( registry ) result = extractor . extract_result ( response , action_name , & block ) run_user_block ( extractor , response , result , & block ) if block_given? return result end

Executes SOAP action specified as a string with given arguments.

Executes SOAP action specified as a string with given arguments .


def handle_soap_request(action, xml_only, args, extra_namespaces)
      original_action_name =
          get_service_registry.get_method_signature(action)[:original_name]
      original_action_name = action if original_action_name.nil?
      request_info = nil
      response = @client.request(original_action_name) do |soap, wsdl, http|
        soap.body = args
        @header_handler.prepare_request(http, soap)
        soap.namespaces.merge!(extra_namespaces) unless extra_namespaces.nil?
        return soap.to_xml if xml_only
        request_info = RequestInfo.new(soap.to_xml, http.headers, http.url)
      end
      return request_info, response
    end

def handle_soap_request ( action , xml_only , args , extra_namespaces ) original_action_name = get_service_registry . get_method_signature ( action ) [ :original_name ] original_action_name = action if original_action_name . nil? request_info = nil response = @client . request ( original_action_name ) do | soap , wsdl , http | soap . body = args @header_handler . prepare_request ( http , soap ) soap . namespaces . merge! ( extra_namespaces ) unless extra_namespaces . nil? return soap . to_xml if xml_only request_info = RequestInfo . new ( soap . to_xml , http . headers , http . url ) end return request_info , response end

Executes the SOAP request with original SOAP name.

Executes the SOAP request with original SOAP name .


def handle_errors(response)
      if response.soap_fault?
        exception = exception_for_soap_fault(response)
        raise exception
      end
      if response.http_error?
        raise AdsCommon::Errors::HttpError,
            "HTTP Error occurred: %s" % response.http_error
      end
    end

def
handle_errors
(
response
)
if
response
.
soap_fault?
exception
=
exception_for_soap_fault
(
response
)
raise
exception
end
if
response
.
http_error?
raise
AdsCommon
::
Errors
::
HttpError
,
"HTTP Error occurred: %s"
%
response
.
http_error
end
end

Checks for errors in response and raises appropriate exception.

Checks for errors in response and raises appropriate exception .


def exception_for_soap_fault(response)
      begin
        fault = response[:fault]
        if fault[:detail] and fault[:detail][:api_exception_fault]
          exception_fault = fault[:detail][:api_exception_fault]
          exception_name = (
              exception_fault[:application_exception_type] ||
              FALLBACK_API_ERROR_EXCEPTION)
          exception_class = get_module().const_get(exception_name)
          return exception_class.new(exception_fault)
        elsif fault[:faultstring]
          fault_message = fault[:faultstring]
          return AdsCommon::Errors::ApiException.new(
              "Unknown exception with error: %s" % fault_message)
        else
          raise ArgumentError.new(fault.to_s)
        end
      rescue Exception => e
        return AdsCommon::Errors::ApiException.new(
            "Failed to resolve exception (%s), SOAP fault: %s" %
            [e.message, response.soap_fault])
      end
    end

Finds an exception object for a given response.

Finds an exception object for a given response .


def run_user_block(extractor, response, body, &block)
      header = extractor.extract_header_data(response)
      case block.arity
        when 1 then yield(header)
        when 2 then yield(header, body)
        else
          raise AdsCommon::Errors::ApiException,
              "Wrong number of block parameters: %d" % block.arity
      end
      return nil
    end

def
run_user_block
(
extractor
,
response
,
body
,
&
block
)
header
=
extractor
.
extract_header_data
(
response
)
case
block
.
arity
when
1
then
yield
(
header
)
when
2
then
yield
(
header
,
body
)
else
raise
AdsCommon
::
Errors
::
ApiException
,
"Wrong number of block parameters: %d"
%
block
.
arity
end
return
end

Yields to user-specified block with additional information such as
 headers.

Yields to user - specified block with additional information such as headers .


def do_logging(action, request, response)
      logger = get_logger()
      return unless should_log_summary(logger.level, response.soap_fault?)

      response_hash = response.hash

      soap_headers = {}
      begin
        soap_headers = response_hash[:envelope][:header][:response_header]
      rescue NoMethodError
        # If there are no headers, just ignore. We'll log what we know.
      end

      summary_message = ('ID: %s, URL: %s, Service: %s, Action: %s, Response ' +
          'time: %sms, Request ID: %s') % [@header_handler.identifier,
          request.url, self.class.to_s.split("::").last, action,
          soap_headers[:response_time], soap_headers[:request_id]]
      if soap_headers[:operations]
        summary_message += ', Operations: %s' % soap_headers[:operations]
      end
      summary_message += ', Is fault: %s' % response.soap_fault?

      request_message = nil
      response_message = nil

      if should_log_payloads(logger.level, response.soap_fault?)
        request_message = 'Outgoing request: %s %s' %
            [format_headers(request.headers), sanitize_request(request.body)]
        response_message = 'Incoming response: %s %s' %
            [format_headers(response.http.headers), response.http.body]
      end

      if response.soap_fault?
        summary_message += ', Fault message: %s' % format_fault(
            response_hash[:envelope][:body][:fault][:faultstring])
        logger.warn(summary_message)
        logger.info(request_message) unless request_message.nil?
        logger.info(response_message) unless response_message.nil?
      else
        logger.info(summary_message)
        logger.debug(request_message) unless request_message.nil?
        logger.debug(response_message) unless response_message.nil?
      end
    end

Log the request, response, and summary lines.

Log the request response and summary lines .


def format_headers(headers)
      return headers.map do |k, v|
        v = REDACTED_STR if k == 'Authorization'
        [k, v].join(': ')
      end.join(', ')
    end

def
format_headers
(
headers
)
return
headers
.
map
do
|
k
,
v
|
v
=
REDACTED_STR
if
k
==
'Authorization'
[
k
,
v
]
.
join
(
': '
)
end
.
join
(
', '
)
end

Format headers, redacting sensitive information.

Format headers redacting sensitive information .


def format_fault(message)
      if message.length > MAX_FAULT_LOG_LENGTH
        message = message[0, MAX_FAULT_LOG_LENGTH]
      end
      return message.gsub("\n", ' ')
    end

def
format_fault
(
message
)
if
message
.
length
>
MAX_FAULT_LOG_LENGTH
message
=
message
[
0
,
MAX_FAULT_LOG_LENGTH
]
end
return
message
.
gsub
(
"\n"
,
' '
)
end

Format the fault message by capping length and removing newlines.

Format the fault message by capping length and removing newlines .


def should_log_summary(level, is_fault)
      # Fault summaries log at WARN.
      return level <= Logger::WARN if is_fault
      # Success summaries log at INFO.
      return level <= Logger::INFO
    end

def should_log_summary ( level , is_fault ) return level <= Logger :: WARN if is_fault return level <= Logger :: INFO end

Check whether or not to log request summaries based on log level.

Check whether or not to log request summaries based on log level .


def should_log_payloads(level, is_fault)
      # Fault payloads log at INFO.
      return level <= Logger::INFO if is_fault
      # Success payloads log at DEBUG.
      return level <= Logger::DEBUG
    end

def should_log_payloads ( level , is_fault ) return level <= Logger :: INFO if is_fault return level <= Logger :: DEBUG end

Check whether or not to log payloads based on log level.

Check whether or not to log payloads based on log level .


def download_report_as_file(report_definition, path, cid = nil)
      report_body = download_report(report_definition, cid)
      save_to_file(report_body, path)
      return nil
    end

def download_report_as_file ( report_definition , path , cid = nil ) report_body = download_report ( report_definition , cid ) save_to_file ( report_body , path ) return nil end

Downloads a report and saves it to a file.

 Args:
 - report_definition: definition of the report in XML text or hash
 - path: path to save report to
 - cid: optional customer ID to run against

 Returns:
 - nil

 Raises:
 - AdwordsApi::Errors::InvalidReportDefinitionError if the report
   definition is invalid
 - AdwordsApi::Errors::ReportError if server-side error occurred

Downloads a report and saves it to a file .


def download_report_as_file_with_awql(report_query, format, path, cid = nil)
      report_body = download_report_with_awql(report_query, format, cid)
      save_to_file(report_body, path)
      return nil
    end

def download_report_as_file_with_awql ( report_query , format , path , cid = nil ) report_body = download_report_with_awql ( report_query , format , cid ) save_to_file ( report_body , path ) return nil end

Downloads a report with AWQL and saves it to a file.

 Args:
 - report_query: query for the report as string
 - format: format for the report as string
 - path: path to save report to
 - cid: optional customer ID to run report against

 Returns:
 - nil

 Raises:
 - AdwordsApi::Errors::ReportError if server-side error occurred

Downloads a report with AWQL and saves it to a file .


def download_report_as_stream_with_awql(
        report_query, format, cid = nil, &block)
      return get_report_response_with_awql(report_query, format, cid, &block)
    end

def download_report_as_stream_with_awql ( report_query , format , cid = nil , & block ) return get_report_response_with_awql ( report_query , format , cid , & block ) end

Streams a report with AWQL as a string to the given block.  This method
 will not do error checking on returned values.

 Args:
 - report_query: query for the report as string
 - format: format for the report as string
 - cid: optional customer ID to run report against

 Returns:
 - nil

Streams a report with AWQL as a string to the given block . This method will not do error checking on returned values .


def get_stream_helper_with_awql(report_query, format, cid = nil)
      return AdwordsApi::ReportStream.set_up_with_awql(
          self, report_query, format, cid)
    end

def get_stream_helper_with_awql ( report_query , format , cid = nil ) return AdwordsApi :: ReportStream . set_up_with_awql ( self , report_query , format , cid ) end

Returns a helper object that can manage breaking the streamed report
 results into individual lines.

 Args:
 - report_query: query for the report as string
 - format: format for the report as string
 - cid: optional customer ID to run report against

 Returns:
 - ReportStream object initialized to begin streaming.

Returns a helper object that can manage breaking the streamed report results into individual lines .


def get_report_response(report_definition, cid, &block)
      definition_text = get_report_definition_text(report_definition)
      data = '__rdxml=%s' % CGI.escape(definition_text)
      return make_adhoc_request(data, cid, &block)
    end

def get_report_response ( report_definition , cid , & block ) definition_text = get_report_definition_text ( report_definition ) data = '__rdxml=%s' % CGI . escape ( definition_text ) return make_adhoc_request ( data , cid , & block ) end

Send POST request for a report and returns Response object.

Send POST request for a report and returns Response object .


def get_report_response_with_awql(report_query, format, cid, &block)
      data = '__rdquery=%s&__fmt=%s' %
          [CGI.escape(report_query), CGI.escape(format)]
      return make_adhoc_request(data, cid, &block)
    end

def get_report_response_with_awql ( report_query , format , cid , & block ) data = '__rdquery=%s&__fmt=%s' % [ CGI . escape ( report_query ) , CGI . escape ( format ) ] return make_adhoc_request ( data , cid , & block ) end

Send POST request for a report with AWQL and returns Response object.

Send POST request for a report with AWQL and returns Response object .


def make_adhoc_request(data, cid, &block)
      @api.utils_reporter.report_utils_used()
      url = @api.api_config.adhoc_report_download_url(@version)
      headers = get_report_request_headers(url, cid)
      log_request(url, headers, data)
      # A given block indicates that we should make a stream request and yield
      # the results, rather than return a full response.
      if block_given?
        AdsCommon::Http.post_stream(url, data, @api.config, headers, &block)
        return nil
      else
        response = AdsCommon::Http.post_response(
            url, data, @api.config, headers)
        log_headers(response.headers)
        check_for_errors(response)
        return response
      end
    end

def make_adhoc_request ( data , cid , & block ) @api . utils_reporter . report_utils_used ( ) url = @api . api_config . adhoc_report_download_url ( @version ) headers = get_report_request_headers ( url , cid ) log_request ( url , headers , data ) if block_given? AdsCommon :: Http . post_stream ( url , data , @api . config , headers , & block ) return nil else response = AdsCommon :: Http . post_response ( url , data , @api . config , headers ) log_headers ( response . headers ) check_for_errors ( response ) return response end end

Makes request and AdHoc service and returns response.

Makes request and AdHoc service and returns response .


def get_report_request_headers(url, cid)
      @header_handler ||= AdwordsApi::ReportHeaderHandler.new(
          @api.credential_handler, @api.get_auth_handler(), @api.config)
      return @header_handler.headers(url, cid)
    end

def get_report_request_headers ( url , cid ) @header_handler ||= AdwordsApi :: ReportHeaderHandler . new ( @api . credential_handler , @api . get_auth_handler ( ) , @api . config ) return @header_handler . headers ( url , cid ) end


def save_to_file(data, path)
      open(path, 'wb') { |file| file.write(data) } if path
    end

def save_to_file ( data , path ) open ( path , 'wb' ) { | file | file . write ( data ) } if path end


def log_headers(headers)
      @api.logger.debug('HTTP headers: [%s]' %
          (headers.map { |k, v| [k, v].join(': ') }.join(', ')))
    end

def
log_headers
(
headers
)
@api
.
logger
.
debug
(
'HTTP headers: [%s]'
%
(
headers
.
map
{
|
k
,
v
|
[
k
,
v
]
.
join
(
': '
)
}
.
join
(
', '
)
)
)
end


def check_for_errors(response)
      # Check for error code.
      if response.code != 200
        # Check for error in body.
        report_body = response.body
        check_for_xml_error(report_body, response.code)
        # No XML error found nor raised, falling back to a default message.
        raise AdwordsApi::Errors::ReportError.new(response.code,
            'HTTP code: %d, body: %s' % [response.code, response.body])
      end
      return nil
    end

def
check_for_errors
(
response
)
if
response
.
code
!=
200
report_body
=
response
.
body
check_for_xml_error
(
report_body
,
response
.
code
)
raise
AdwordsApi
::
Errors
::
ReportError
.
new
(
response
.
code
,
'HTTP code: %d, body: %s'
%
[
response
.
code
,
response
.
body
]
)
end
return
end

Checks downloaded data for error signature. Raises ReportError if it
 detects an error.

Checks downloaded data for error signature . Raises ReportError if it detects an error .


def check_for_xml_error(report_body, response_code)
      unless report_body.nil?
        error_response = get_nori().parse(report_body)
        if error_response.include?(:report_download_error) and
            error_response[:report_download_error].include?(:api_error)
          api_error = error_response[:report_download_error][:api_error]
          raise AdwordsApi::Errors::ReportXmlError.new(response_code,
              api_error[:type], api_error[:trigger], api_error[:field_path])
        end
      end
    end

def check_for_xml_error ( report_body , response_code ) unless report_body . nil? error_response = get_nori ( ) . parse ( report_body ) if error_response . include? ( :report_download_error ) and error_response [ :report_download_error ] . include? ( :api_error ) api_error = error_response [ :report_download_error ] [ :api_error ] raise AdwordsApi :: Errors :: ReportXmlError . new ( response_code , api_error [ :type ] , api_error [ :trigger ] , api_error [ :field_path ] ) end end end

Checks for an XML error in the response body and raises an exception if
 it was found.

Checks for an XML error in the response body and raises an exception if it was found .


def report_definition_to_xml(report_definition)
      check_report_definition_hash(report_definition)
      add_report_definition_hash_order(report_definition)
      begin
        return Gyoku.xml({:report_definition => report_definition})
      rescue ArgumentError => e
        if e.message.include?("order!")
          unknown_fields =
              e.message.slice(e.message.index('['), e.message.length)
          raise AdwordsApi::Errors::InvalidReportDefinitionError,
              "Unknown report definition field(s): %s" % unknown_fields
        end
        raise e
      end
    end

Renders a report definition hash into XML text.

Renders a report definition hash into XML text .


def check_report_definition_hash(report_definition)
      # Minimal set of fields required.
      REQUIRED_FIELDS.each do |field|
        unless report_definition.include?(field)
          raise AdwordsApi::Errors::InvalidReportDefinitionError,
              "Required field '%s' is missing in the definition" % field
        end
      end
      # Fields list is also required.
      unless report_definition[:selector].include?(:fields)
        raise AdwordsApi::Errors::InvalidReportDefinitionError,
            'Fields list is required'
      end
      # 'Fields' must be an Array.
      unless report_definition[:selector][:fields].kind_of?(Array)
        raise AdwordsApi::Errors::InvalidReportDefinitionError,
            'Fields list must be an array'
      end
      # We should request at least one field.
      if report_definition[:selector][:fields].empty?
        raise AdwordsApi::Errors::InvalidReportDefinitionError,
            'At least one field needs to be requested'
      end
    end

Checks if the report definition looks correct.

Checks if the report definition looks correct .


def add_report_definition_hash_order(node, name = :root)
      def_order = REPORT_DEFINITION_ORDER[name]
      var_order = def_order.reject { |field| !node.include?(field) }
      node.keys.each do |key|
        if REPORT_DEFINITION_ORDER.include?(key)
          case node[key]
            when Hash
              add_report_definition_hash_order(node[key], key)
            when Array
              node[key].each do |item|
                add_report_definition_hash_order(item, key)
              end
          end
        end
      end
      node[:order!] = var_order
      return nil
    end

def add_report_definition_hash_order ( node , name = :root ) def_order = REPORT_DEFINITION_ORDER [ name ] var_order = def_order . reject { | field | ! node . include? ( field ) } node . keys . each do | key | if REPORT_DEFINITION_ORDER . include? ( key ) case node [ key ] when Hash add_report_definition_hash_order ( node [ key ] , key ) when Array node [ key ] . each do | item | add_report_definition_hash_order ( item , key ) end end end end node [ :order! ] = var_order return nil end

Adds fields order hint to generator based on specification.

Adds fields order hint to generator based on specification .


def headers(url, cid)
      override = (cid.nil?) ? nil : {:client_customer_id => cid}
      credentials = @credential_handler.credentials(override)
      headers = {
          'Content-Type' => 'application/x-www-form-urlencoded',
          'Authorization' => @auth_handler.auth_string(credentials),
          'User-Agent' => @credential_handler.generate_user_agent(),
          'clientCustomerId' => credentials[:client_customer_id].to_s,
          'developerToken' => credentials[:developer_token]
      }
      skip_report_header = @config.read('library.skip_report_header')
      unless skip_report_header.nil?
        headers['skipReportHeader'] = skip_report_header.to_s
      end
      skip_report_summary = @config.read('library.skip_report_summary')
      unless skip_report_summary.nil?
        headers['skipReportSummary'] = skip_report_summary.to_s
      end
      skip_column_header = @config.read('library.skip_column_header')
      unless skip_column_header.nil?
        headers['skipColumnHeader'] = skip_column_header.to_s
      end
      include_zero_impressions =
          @config.read('library.include_zero_impressions')
      unless include_zero_impressions.nil?
        headers['includeZeroImpressions'] = include_zero_impressions.to_s
      end
      use_raw_enum_values =
          @config.read('library.use_raw_enum_values')
      unless use_raw_enum_values.nil?
        headers['useRawEnumValues'] = use_raw_enum_values.to_s
      end
      return headers
    end

def headers ( url , cid ) override = ( cid . nil? ) ? nil : { :client_customer_id => cid } credentials = @credential_handler . credentials ( override ) headers = { 'Content-Type' => 'application/x-www-form-urlencoded' , 'Authorization' => @auth_handler . auth_string ( credentials ) , 'User-Agent' => @credential_handler . generate_user_agent ( ) , 'clientCustomerId' => credentials [ :client_customer_id ] . to_s , 'developerToken' => credentials [ :developer_token ] } skip_report_header = @config . read ( 'library.skip_report_header' ) unless skip_report_header . nil? headers [ 'skipReportHeader' ] = skip_report_header . to_s end skip_report_summary = @config . read ( 'library.skip_report_summary' ) unless skip_report_summary . nil? headers [ 'skipReportSummary' ] = skip_report_summary . to_s end skip_column_header = @config . read ( 'library.skip_column_header' ) unless skip_column_header . nil? headers [ 'skipColumnHeader' ] = skip_column_header . to_s end include_zero_impressions = @config . read ( 'library.include_zero_impressions' ) unless include_zero_impressions . nil? headers [ 'includeZeroImpressions' ] = include_zero_impressions . to_s end use_raw_enum_values = @config . read ( 'library.use_raw_enum_values' ) unless use_raw_enum_values . nil? headers [ 'useRawEnumValues' ] = use_raw_enum_values . to_s end return headers end

Initializes a header handler.

 Args:
  - credential_handler: a header with credential data
  - auth_handler: a header with auth data
  - config: API config

 Returns the headers set for the report request.

 Args:
  - url: URL for the report requests
  - cid: clientCustomerId to use

 Returns:
  - a Hash with HTTP headers.


def credentials(credentials_override = nil)
      credentials = @credentials.dup()
      credentials.merge!(credentials_override) unless credentials_override.nil?
      return credentials
    end

def credentials ( credentials_override = nil ) credentials = @credentials . dup ( ) credentials . merge! ( credentials_override ) unless credentials_override . nil? return credentials end

Initializes CredentialHandler.
 Returns credentials set for the next call.

Initializes CredentialHandler . Returns credentials set for the next call .


def credentials=(new_credentials)
      # Find new and changed properties.
      diff = new_credentials.inject([]) do |result, (key, value)|
        result << [key, value] if value != @credentials[key]
        result
      end

      # Find removed properties.
      diff = @credentials.inject(diff) do |result, (key, _)|
        result << [key, nil] unless new_credentials.include?(key)
        result
      end

      # Set each property.
      diff.each { |entry| set_credential(entry[0], entry[1]) }

      return nil
    end

def credentials = ( new_credentials ) diff = new_credentials . inject ( [ ] ) do | result , ( key , value ) | result << [ key , value ] if value != @credentials [ key ] result end diff = @credentials . inject ( diff ) do | result , ( key , _ ) | result << [ key , nil ] unless new_credentials . include? ( key ) result end diff . each { | entry | set_credential ( entry [ 0 ] , entry [ 1 ] ) } return nil end

Set the credentials hash to a new one. Calculate difference, and call the
 AuthHandler callback appropriately.

Set the credentials hash to a new one . Calculate difference and call the AuthHandler callback appropriately .


def generate_user_agent(extra_ids = [], agent_app = nil)
      agent_app ||= File.basename($0)
      agent_data = extra_ids
      agent_data << 'Common-Ruby/%s' % AdsCommon::ApiConfig::CLIENT_LIB_VERSION
      agent_data << 'GoogleAdsSavon/%s' % GoogleAdsSavon::VERSION
      ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
      agent_data << [ruby_engine, RUBY_VERSION].join('/')
      agent_data << 'HTTPI/%s' % HTTPI::VERSION
      agent_data << HTTPI::Adapter.use.to_s
      agent_data += get_extra_user_agents()
      return '%s (%s)' % [agent_app, agent_data.join(', ')]
    end

def
generate_user_agent
(
extra_ids
=
[
]
,
agent_app
=
)
agent_app
||=
File
.
basename
(
$0
)
agent_data
=
extra_ids
agent_data
<<
'Common-Ruby/%s'
%
AdsCommon
::
ApiConfig
::
CLIENT_LIB_VERSION
agent_data
<<
'GoogleAdsSavon/%s'
%
GoogleAdsSavon
::
VERSION
ruby_engine
=
defined?
(
RUBY_ENGINE
)
RUBY_ENGINE
:
'ruby'
agent_data
<<
[
ruby_engine
,
RUBY_VERSION
]
.
join
(
'/'
)
agent_data
<<
'HTTPI/%s'
%
HTTPI
::
VERSION
agent_data
<<
HTTPI
::
Adapter
.
use
.
to_s
agent_data
+=
get_extra_user_agents
(
)
return
'%s (%s)'
%
[
agent_app
,
agent_data
.
join
(
', '
)
]
end

Generates string for UserAgent to put into headers.

Generates string for UserAgent to put into headers .


def get_extra_user_agents()
      @extra_user_agents_lock.synchronize do
        user_agents = @extra_user_agents.collect do |k, v|
          v.nil? ? k : '%s/%s' % [k, v]
        end
        @extra_user_agents.clear
        return user_agents
      end
    end

def get_extra_user_agents ( ) @extra_user_agents_lock . synchronize do user_agents = @extra_user_agents . collect do | k , v | v . nil? ? k : '%s/%s' % [ k , v ] end @extra_user_agents . clear return user_agents end end

Generates an array of extra user agents to include in the user agent
 string.

Generates an array of extra user agents to include in the user agent string .


def extract_header_data(response)
      header_type = get_full_type_signature(:SoapResponseHeader)
      headers = response.header[:response_header].dup
      process_attributes(headers, false)
      headers = normalize_fields(headers, header_type[:fields])
      return headers
    end

def extract_header_data ( response ) header_type = get_full_type_signature ( :SoapResponseHeader ) headers = response . header [ :response_header ] . dup process_attributes ( headers , false ) headers = normalize_fields ( headers , header_type [ :fields ] ) return headers end

Extracts misc data from response header.

Extracts misc data from response header .


def extract_exception_data(soap_fault, exception_name)
      exception_type = get_full_type_signature(exception_name)
      process_attributes(soap_fault, false)
      soap_fault = normalize_fields(soap_fault, exception_type[:fields])
      return soap_fault
    end


def normalize_fields(data, fields)
      fields.each do |field|
        field_name = field[:name]
        if data.include?(field_name)
          field_data = data[field_name]
          field_data = normalize_output_field(field_data, field)
          field_data = check_array_collapse(field_data, field)
          data[field_name] = field_data unless field_data.nil?
        end
      end
      return data
    end

def normalize_fields ( data , fields ) fields . each do | field | field_name = field [ :name ] if data . include? ( field_name ) field_data = data [ field_name ] field_data = normalize_output_field ( field_data , field ) field_data = check_array_collapse ( field_data , field ) data [ field_name ] = field_data unless field_data . nil? end end return data end

Normalizes all fields for the given data based on the fields list
 provided.

Normalizes all fields for the given data based on the fields list provided .


def normalize_output_field(field_data, field_def)
      return case field_data
        when Array
          normalize_array_field(field_data, field_def)
        when Hash
          normalize_hash_field(field_data, field_def)
        else
          normalize_item(field_data, field_def)
      end
    end

Normalizes one field of a given data recursively.

 Args:
  - field_data: XML data to normalize
  - field_def: field type definition for the data

Normalizes one field of a given data recursively .


def normalize_array_field(data, field_def)
      result = data
      # Convert a specific structure to a handy hash if detected.
      if check_key_value_struct(result)
        result = convert_key_value_to_hash(result).inject({}) do |s, (k,v)|
          s[k] = normalize_output_field(v, field_def)
          s
        end
      else
        result = data.map {|item| normalize_output_field(item, field_def)}
      end
      return result
    end

def normalize_array_field ( data , field_def ) result = data if check_key_value_struct ( result ) result = convert_key_value_to_hash ( result ) . inject ( { } ) do | s , ( k , v ) | s [ k ] = normalize_output_field ( v , field_def ) s end else result = data . map { | item | normalize_output_field ( item , field_def ) } end return result end


def normalize_hash_field(field, field_def)
      process_attributes(field, true)
      field_type = field_def[:type]
      field_def = get_full_type_signature(field_type)

      # First checking for xsi:type provided.
      xsi_type_override = determine_xsi_type_override(field, field_def)
      unless xsi_type_override.nil?
        field_def = get_full_type_signature(xsi_type_override)
        return (field_def.nil?) ? field :
            normalize_fields(field, field_def[:fields])
      end

      result = field

      # Now checking for choice options from wsdl.
      choice_type_override = determine_choice_type_override(field, field_def)
      unless choice_type_override.nil?
        # For overrides we need to process sub-field and than return it
        # in the original structure.
        field_key = field.keys.first
        field_data = field[field_key]
        field_def = get_full_type_signature(choice_type_override)
        if !field_def.nil? and field_data.kind_of?(Hash)
          field_data = normalize_fields(field_data, field_def[:fields])
        end
        result = {field_key => field_data}
      else
        # Otherwise using the best we have.
        unless field_def.nil?
          result = normalize_fields(field, field_def[:fields])
        end
      end

      # Convert a single key-value hash to a proper hash if detected.
      if check_key_value_struct(result)
        result = convert_key_value_to_hash(result)
      end

      return result
    end

def normalize_hash_field ( field , field_def ) process_attributes ( field , true ) field_type = field_def [ :type ] field_def = get_full_type_signature ( field_type ) xsi_type_override = determine_xsi_type_override ( field , field_def ) unless xsi_type_override . nil? field_def = get_full_type_signature ( xsi_type_override ) return ( field_def . nil? ) ? field : normalize_fields ( field , field_def [ :fields ] ) end result = field choice_type_override = determine_choice_type_override ( field , field_def ) unless choice_type_override . nil? field_key = field . keys . first field_data = field [ field_key ] field_def = get_full_type_signature ( choice_type_override ) if ! field_def . nil? and field_data . kind_of? ( Hash ) field_data = normalize_fields ( field_data , field_def [ :fields ] ) end result = { field_key => field_data } else unless field_def . nil? result = normalize_fields ( field , field_def [ :fields ] ) end end if check_key_value_struct ( result ) result = convert_key_value_to_hash ( result ) end return result end


def determine_choice_type_override(field_data, field_def)
      result = nil
      if field_data.kind_of?(Hash) and field_def.include?(:choices)
        result = determine_choice(field_data, field_def[:choices])
      end
      return result
    end

def determine_choice_type_override ( field_data , field_def ) result = nil if field_data . kind_of? ( Hash ) and field_def . include? ( :choices ) result = determine_choice ( field_data , field_def [ :choices ] ) end return result end

Determines a choice type override for for the field. Returns nil if no
 override found.

Determines a choice type override for for the field . Returns nil if no override found .


def determine_choice(field_data, field_choices)
      result = nil
      key_name = field_data.keys.first
      unless key_name.nil?
        choice = find_named_entry(field_choices, key_name)
        result = choice[:type] unless choice.nil?
      end
      return result
    end

def determine_choice ( field_data , field_choices ) result = nil key_name = field_data . keys . first unless key_name . nil? choice = find_named_entry ( field_choices , key_name ) result = choice [ :type ] unless choice . nil? end return result end

Finds the choice option matching data provided.

Finds the choice option matching data provided .


def normalize_item(item, field_def)
      return case field_def[:type]
        when 'long', 'int' then Integer(item)
        when 'double', 'float' then Float(item)
        when 'boolean' then item.kind_of?(String) ?
            item.casecmp('true') == 0 : item
        else item
      end
    end

def normalize_item ( item , field_def ) return case field_def [ :type ] when 'long' , 'int' then Integer ( item ) when 'double' , 'float' then Float ( item ) when 'boolean' then item . kind_of? ( String ) ? item . casecmp ( 'true' ) == 0 : item else item end end

Converts one leaf item to a built-in type.

Converts one leaf item to a built - in type .


def check_array_collapse(data, field_def)
      result = data
      if !field_def[:min_occurs].nil? &&
          (field_def[:max_occurs] == :unbounded ||
              (!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&
                  !(field_def[:type] =~ /MapEntry$/)
        result = arrayize(result)
      end
      return result
    end

def check_array_collapse ( data , field_def ) result = data if ! field_def [ :min_occurs ] . nil? && ( field_def [ :max_occurs ] == :unbounded || ( ! field_def [ :max_occurs ] . nil? && field_def [ :max_occurs ] > 1 ) ) && ! ( field_def [ :type ] =~ / / ) result = arrayize ( result ) end return result end

Checks if the field signature allows an array and forces array structure
 even for a signle item.

Checks if the field signature allows an array and forces array structure even for a signle item .


def process_attributes(data, keep_xsi_type = false)
      if keep_xsi_type
        xsi_type = data.delete(:"@xsi:type")
        data[:xsi_type] = xsi_type if xsi_type
      end
      data.reject! {|key, value| key.to_s.start_with?('@')}
    end

def process_attributes ( data , keep_xsi_type = false ) if keep_xsi_type xsi_type = data . delete ( :" " ) data [ :xsi_type ] = xsi_type if xsi_type end data . reject! { | key , value | key . to_s . start_with? ( '@' ) } end

Handles attributes received from Savon .


def service(name, version = nil)
      name = name.to_sym
      version = (version.nil?) ? api_config.default_version : version.to_sym

      # Check if the combination is available.
      validate_service_request(version, name)

      # Try to re-use the service for this version if it was requested before.
      wrapper = if @wrappers.include?(version) && @wrappers[version][name]
        @wrappers[version][name]
      else
        @wrappers[version] ||= {}
        @wrappers[version][name] = prepare_wrapper(version, name)
      end
      return wrapper
    end

def service ( name , version = nil ) name = name . to_sym version = ( version . nil? ) ? api_config . default_version : version . to_sym validate_service_request ( version , name ) wrapper = if @wrappers . include? ( version ) && @wrappers [ version ] [ name ] @wrappers [ version ] [ name ] else @wrappers [ version ] ||= { } @wrappers [ version ] [ name ] = prepare_wrapper ( version , name ) end return wrapper end

Obtain an API service, given a version and its name.

 Args:
 - name: name for the intended service
 - version: intended API version.

 Returns:
 - the service wrapper for the intended service.

Obtain an API service given a version and its name .


def authorize(parameters = {}, &block)
      parameters.each_pair do |key, value|
        @credential_handler.set_credential(key, value)
      end

      auth_handler = get_auth_handler()
      token = auth_handler.get_token()

      # If token is invalid ask for a new one.
      if token.nil?
        begin
          credentials = @credential_handler.credentials
          token = auth_handler.get_token(credentials)
        rescue AdsCommon::Errors::OAuth2VerificationRequired => e
          verification_code = (block_given?) ? yield(e.oauth_url) : nil
          # Retry with verification code if one provided.
          if verification_code
            @credential_handler.set_credential(
                :oauth2_verification_code, verification_code)
            retry
          else
            raise e
          end
        end
      end
      return token
    end

def authorize ( parameters = { } , & block ) parameters . each_pair do | key , value | @credential_handler . set_credential ( key , value ) end auth_handler = get_auth_handler ( ) token = auth_handler . get_token ( ) if token . nil? begin credentials = @credential_handler . credentials token = auth_handler . get_token ( credentials ) rescue AdsCommon :: Errors :: OAuth2VerificationRequired => e verification_code = ( block_given? ) ? yield ( e . oauth_url ) : nil if verification_code @credential_handler . set_credential ( :oauth2_verification_code , verification_code ) retry else raise e end end end return token end

Authorize with specified authentication method.

 Args:
  - parameters - hash of credentials to add to configuration
  - block - code block to handle auth login url

 Returns:
  - Auth token for the method

 Throws:
  - AdsCommon::Errors::AuthError or derived if authetication error has
    occured

Authorize with specified authentication method .


def save_oauth2_token(token)
      raise AdsCommon::Errors::Error, "Can't save nil token" if token.nil?
      AdsCommon::Utils.save_oauth2_token(
          File.join(ENV['HOME'], api_config.default_config_filename), token)
    end

def
save_oauth2_token
(
token
)
raise
AdsCommon
::
Errors
::
Error
,
"Can't save nil token"
if
token
.
nil?
AdsCommon
::
Utils
.
save_oauth2_token
(
File
.
join
(
ENV
[
'HOME'
]
,
api_config
.
default_config_filename
)
,
token
)
end

Updates default configuration file to include OAuth2 token information.

Updates default configuration file to include OAuth2 token information .


def validate_service_request(version, service)
      # Check if the current config supports the requested version.
      unless api_config.has_version(version)
        raise AdsCommon::Errors::Error,
            "Version '%s' not recognized" % version.to_s
      end

      # Check if the specified version has the requested service.
      unless api_config.version_has_service(version, service)
        raise AdsCommon::Errors::Error,
            "Version '%s' does not contain service '%s'" %
            [version.to_s, service.to_s]
      end
    end

Auxiliary method to test parameters correctness for the service request.

Auxiliary method to test parameters correctness for the service request .


def create_auth_handler()
      auth_method = @config.read('authentication.method', :OAUTH2)
      return case auth_method
        when :OAUTH
          raise AdsCommon::Errors::Error,
              'OAuth authorization method is deprecated, use OAuth2 instead.'
        when :OAUTH2
          AdsCommon::Auth::OAuth2Handler.new(
              @config,
              api_config.config(:oauth_scope)
          )
        when :OAUTH2_SERVICE_ACCOUNT
          AdsCommon::Auth::OAuth2ServiceAccountHandler.new(
              @config,
              api_config.config(:oauth_scope)
          )
        else
          raise AdsCommon::Errors::Error,
              "Unknown authentication method '%s'" % auth_method
        end
    end

Auxiliary method to create an authentication handler.

 Returns:
 - auth handler

Auxiliary method to create an authentication handler .


def prepare_wrapper(version, service)
      api_config.do_require(version, service)
      endpoint = api_config.endpoint(version, service)
      interface_class_name = api_config.interface_name(version, service)

      wrapper = class_for_path(interface_class_name).new(@config, endpoint)
      auth_handler = get_auth_handler()
      header_ns = api_config.config(:header_ns) + version.to_s
      soap_handler = soap_header_handler(auth_handler, version, header_ns,
                                         wrapper.namespace)
      wrapper.header_handler = soap_handler

      return wrapper
    end

def prepare_wrapper ( version , service ) api_config . do_require ( version , service ) endpoint = api_config . endpoint ( version , service ) interface_class_name = api_config . interface_name ( version , service ) wrapper = class_for_path ( interface_class_name ) . new ( @config , endpoint ) auth_handler = get_auth_handler ( ) header_ns = api_config . config ( :header_ns ) + version . to_s soap_handler = soap_header_handler ( auth_handler , version , header_ns , wrapper . namespace ) wrapper . header_handler = soap_handler return wrapper end

Handle loading of a single service.
 Creates the wrapper, sets up handlers and creates an instance of it.

 Args:
 - version: intended API version, must be a symbol
 - service: name for the intended service

 Returns:
 - a simplified wrapper generated for the service

Handle loading of a single service . Creates the wrapper sets up handlers and creates an instance of it .


def create_default_logger()
      logger = Logger.new(STDOUT)
      logger.level = get_log_level_for_string(
          @config.read('library.log_level', 'INFO'))
      return logger
    end

def create_default_logger ( ) logger = Logger . new ( STDOUT ) logger . level = get_log_level_for_string ( @config . read ( 'library.log_level' , 'INFO' ) ) return logger end

Auxiliary method to create a default Logger.

Auxiliary method to create a default Logger .