Dataset Viewer
input
stringlengths 109
5.2k
| output
stringlengths 7
509
|
---|---|
Summarize the following code: 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
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Extract the query parameters and append them to the url
|
Summarize the following code: 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
|
Return a hash of headers whose keys are capitalized strings
|
Summarize the following code: 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
|
Given a MIME type or file extension return either a MIME type or if none is found the input unchanged .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Follow a redirection
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Responds to an OPTIONS request .
|
Summarize the following code: 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
|
Performs the steps necessary to run the callback phase of a strategy .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Instance methods .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Returns an instance of ReportUtils object with all utilities relevant to the reporting .
|
Summarize the following code: 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
|
Returns an instance of BatchJobUtils object with all utilities relevant to running batch jobs .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Validates given arguments based on provided fields list .
|
Summarize the following code: 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
|
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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Checks the provided data structure matches wsdl definition .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Validates single argument .
|
Summarize the following code: 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
|
Validates Array argument .
|
Summarize the following code: 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
|
Validates Hash argument .
|
Summarize the following code: def validate_time_arg(arg, parent, key)
xml_value = time_to_xml_hash(arg)
parent[key] = xml_value
return xml_value
end
|
Validates Time argument .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Returns all inherited fields of superclasses for given type .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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?
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 + .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Evaluates a given + block + inside + instance + . Stores the original block binding .
|
Summarize the following code: 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 + .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Return a list of validation errors .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
When an unrecognized method is applied to AdManagerDateTime pass it through to the internal ruby Time .
|
Summarize the following code: 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
|
Creates and sets up Savon client .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Yields to user - specified block with additional information such as headers .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Check whether or not to log request summaries based on log level .
|
Summarize the following code: 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
|
Check whether or not to log payloads based on log level .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Makes request and AdHoc service and returns response .
|
Summarize the following code: 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
|
Prepares headers for report request .
|
Summarize the following code: def save_to_file(data, path)
open(path, 'wb') { |file| file.write(data) } if path
end
|
Saves raw data to a file .
|
Summarize the following code: def log_headers(headers)
@api.logger.debug('HTTP headers: [%s]' %
(headers.map { |k, v| [k, v].join(': ') }.join(', ')))
end
|
Logs HTTP headers on debug level .
|
Summarize the following code: 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
|
Checks downloaded data for error signature . Raises ReportError if it detects an error .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Set the credentials hash to a new one . Calculate difference and call the AuthHandler callback appropriately .
|
Summarize the following code: 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
|
Generates string for UserAgent to put into headers .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Extracts misc data from SOAP fault .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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
|
Normalizes every item of an Array .
|
Summarize the following code: 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
|
Normalizes every item of a Hash .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
Summarize the following code: 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 .
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 14