repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
NCSU-Libraries/quick_search | app/controllers/quick_search/typeahead_controller.rb | QuickSearch.TypeaheadController.typeahead | def typeahead
# :searcher param expected to be name of a searcher with underscores, ie: ematrix_journal
searcher = params[:searcher]
query = params[:q] or ''
total = params[:total] or 3
if searcher.blank?
logger.error "Typeahead request: no searcher param provided"
head :bad_request
return nil
end
searcher_string = "QuickSearch::#{searcher.camelize}Searcher"
begin
klass = searcher_string.constantize
rescue NameError
logger.error "Typeahead request: searcher #{searcher} does not exist"
head :bad_request
return nil
end
if klass.method_defined? :typeahead
typeahead_result = klass.new(HTTPClient.new, query, total).typeahead
if params.has_key? 'callback'
render json: typeahead_result, callback: params['callback']
else
render json: typeahead_result
end
else
logger.error "Typeahead request: searcher #{searcher} has no typeahead method"
head :bad_request
return nil
end
end | ruby | def typeahead
# :searcher param expected to be name of a searcher with underscores, ie: ematrix_journal
searcher = params[:searcher]
query = params[:q] or ''
total = params[:total] or 3
if searcher.blank?
logger.error "Typeahead request: no searcher param provided"
head :bad_request
return nil
end
searcher_string = "QuickSearch::#{searcher.camelize}Searcher"
begin
klass = searcher_string.constantize
rescue NameError
logger.error "Typeahead request: searcher #{searcher} does not exist"
head :bad_request
return nil
end
if klass.method_defined? :typeahead
typeahead_result = klass.new(HTTPClient.new, query, total).typeahead
if params.has_key? 'callback'
render json: typeahead_result, callback: params['callback']
else
render json: typeahead_result
end
else
logger.error "Typeahead request: searcher #{searcher} has no typeahead method"
head :bad_request
return nil
end
end | [
"def",
"typeahead",
"# :searcher param expected to be name of a searcher with underscores, ie: ematrix_journal",
"searcher",
"=",
"params",
"[",
":searcher",
"]",
"query",
"=",
"params",
"[",
":q",
"]",
"or",
"''",
"total",
"=",
"params",
"[",
":total",
"]",
"or",
"3",
"if",
"searcher",
".",
"blank?",
"logger",
".",
"error",
"\"Typeahead request: no searcher param provided\"",
"head",
":bad_request",
"return",
"nil",
"end",
"searcher_string",
"=",
"\"QuickSearch::#{searcher.camelize}Searcher\"",
"begin",
"klass",
"=",
"searcher_string",
".",
"constantize",
"rescue",
"NameError",
"logger",
".",
"error",
"\"Typeahead request: searcher #{searcher} does not exist\"",
"head",
":bad_request",
"return",
"nil",
"end",
"if",
"klass",
".",
"method_defined?",
":typeahead",
"typeahead_result",
"=",
"klass",
".",
"new",
"(",
"HTTPClient",
".",
"new",
",",
"query",
",",
"total",
")",
".",
"typeahead",
"if",
"params",
".",
"has_key?",
"'callback'",
"render",
"json",
":",
"typeahead_result",
",",
"callback",
":",
"params",
"[",
"'callback'",
"]",
"else",
"render",
"json",
":",
"typeahead_result",
"end",
"else",
"logger",
".",
"error",
"\"Typeahead request: searcher #{searcher} has no typeahead method\"",
"head",
":bad_request",
"return",
"nil",
"end",
"end"
] | This method should return a list of search suggestions for a given searcher
It should return errors if there is no param called 'searcher', if the searcher does not exist
or if the searcher doesn't implement the 'typeahead' method
Otherwise, it should return the result of calling the 'typeahead' method as JSON | [
"This",
"method",
"should",
"return",
"a",
"list",
"of",
"search",
"suggestions",
"for",
"a",
"given",
"searcher",
"It",
"should",
"return",
"errors",
"if",
"there",
"is",
"no",
"param",
"called",
"searcher",
"if",
"the",
"searcher",
"does",
"not",
"exist",
"or",
"if",
"the",
"searcher",
"doesn",
"t",
"implement",
"the",
"typeahead",
"method",
"Otherwise",
"it",
"should",
"return",
"the",
"result",
"of",
"calling",
"the",
"typeahead",
"method",
"as",
"JSON"
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/typeahead_controller.rb#L10-L45 | train |
NCSU-Libraries/quick_search | app/controllers/quick_search/logging_controller.rb | QuickSearch.LoggingController.log_search | def log_search
if params[:query].present? && params[:page].present?
@session.searches.create(query: params[:query], page: params[:page])
head :ok
else
head :bad_request
end
end | ruby | def log_search
if params[:query].present? && params[:page].present?
@session.searches.create(query: params[:query], page: params[:page])
head :ok
else
head :bad_request
end
end | [
"def",
"log_search",
"if",
"params",
"[",
":query",
"]",
".",
"present?",
"&&",
"params",
"[",
":page",
"]",
".",
"present?",
"@session",
".",
"searches",
".",
"create",
"(",
"query",
":",
"params",
"[",
":query",
"]",
",",
"page",
":",
"params",
"[",
":page",
"]",
")",
"head",
":ok",
"else",
"head",
":bad_request",
"end",
"end"
] | Logs a search to the database
This is an API endpoint for logging a search. It requires that at least a search query and a page are
present in the query parameters. It returns a 200 OK HTTP status if the request was successful, or
an 400 BAD REQUEST HTTP status if any parameters are missing. | [
"Logs",
"a",
"search",
"to",
"the",
"database"
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/logging_controller.rb#L20-L27 | train |
NCSU-Libraries/quick_search | app/controllers/quick_search/logging_controller.rb | QuickSearch.LoggingController.log_event | def log_event
if params[:category].present? && params[:event_action].present? && params[:label].present?
# if an action isn't passed in, assume that it is a click
action = params.fetch(:action_type, 'click')
# create a new event on the current session
@session.events.create(category: params[:category], item: params[:event_action], query: params[:label][0..250], action: action)
if params[:ga].present? and params[:ga]
send_event_to_ga(params[:category], params[:event_action], params[:label])
end
# check whether this is a jsonp request
if params[:callback].present?
render :json => { 'response': 'success' }, :callback => params[:callback]
else
render :json => { 'response': 'success' }
end
else
head :bad_request
end
end | ruby | def log_event
if params[:category].present? && params[:event_action].present? && params[:label].present?
# if an action isn't passed in, assume that it is a click
action = params.fetch(:action_type, 'click')
# create a new event on the current session
@session.events.create(category: params[:category], item: params[:event_action], query: params[:label][0..250], action: action)
if params[:ga].present? and params[:ga]
send_event_to_ga(params[:category], params[:event_action], params[:label])
end
# check whether this is a jsonp request
if params[:callback].present?
render :json => { 'response': 'success' }, :callback => params[:callback]
else
render :json => { 'response': 'success' }
end
else
head :bad_request
end
end | [
"def",
"log_event",
"if",
"params",
"[",
":category",
"]",
".",
"present?",
"&&",
"params",
"[",
":event_action",
"]",
".",
"present?",
"&&",
"params",
"[",
":label",
"]",
".",
"present?",
"# if an action isn't passed in, assume that it is a click",
"action",
"=",
"params",
".",
"fetch",
"(",
":action_type",
",",
"'click'",
")",
"# create a new event on the current session",
"@session",
".",
"events",
".",
"create",
"(",
"category",
":",
"params",
"[",
":category",
"]",
",",
"item",
":",
"params",
"[",
":event_action",
"]",
",",
"query",
":",
"params",
"[",
":label",
"]",
"[",
"0",
"..",
"250",
"]",
",",
"action",
":",
"action",
")",
"if",
"params",
"[",
":ga",
"]",
".",
"present?",
"and",
"params",
"[",
":ga",
"]",
"send_event_to_ga",
"(",
"params",
"[",
":category",
"]",
",",
"params",
"[",
":event_action",
"]",
",",
"params",
"[",
":label",
"]",
")",
"end",
"# check whether this is a jsonp request",
"if",
"params",
"[",
":callback",
"]",
".",
"present?",
"render",
":json",
"=>",
"{",
"'response'",
":",
"'success'",
"}",
",",
":callback",
"=>",
"params",
"[",
":callback",
"]",
"else",
"render",
":json",
"=>",
"{",
"'response'",
":",
"'success'",
"}",
"end",
"else",
"head",
":bad_request",
"end",
"end"
] | Logs an event to the database. Typically, these can be clicks or serves.
This is an API endpoint for logging an event. It requires that at least a TODO are
present in the query parameters. It returns a 200 OK HTTP status if the request was successful, or
an 400 BAD REQUEST HTTP status if any parameters are missing. This endpoint supports JSONP requests. | [
"Logs",
"an",
"event",
"to",
"the",
"database",
".",
"Typically",
"these",
"can",
"be",
"clicks",
"or",
"serves",
"."
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/logging_controller.rb#L36-L57 | train |
NCSU-Libraries/quick_search | app/controllers/quick_search/logging_controller.rb | QuickSearch.LoggingController.new_session | def new_session
on_campus = on_campus?(request.remote_ip)
is_mobile = is_mobile?
session_expiry = 5.minutes.from_now
session_uuid = SecureRandom.uuid
# create session in db
@session = Session.create(session_uuid: session_uuid, expiry: session_expiry, on_campus: on_campus, is_mobile: is_mobile)
# set cookie
cookies[:session_id] = { :value => session_uuid, :expires => session_expiry }
end | ruby | def new_session
on_campus = on_campus?(request.remote_ip)
is_mobile = is_mobile?
session_expiry = 5.minutes.from_now
session_uuid = SecureRandom.uuid
# create session in db
@session = Session.create(session_uuid: session_uuid, expiry: session_expiry, on_campus: on_campus, is_mobile: is_mobile)
# set cookie
cookies[:session_id] = { :value => session_uuid, :expires => session_expiry }
end | [
"def",
"new_session",
"on_campus",
"=",
"on_campus?",
"(",
"request",
".",
"remote_ip",
")",
"is_mobile",
"=",
"is_mobile?",
"session_expiry",
"=",
"5",
".",
"minutes",
".",
"from_now",
"session_uuid",
"=",
"SecureRandom",
".",
"uuid",
"# create session in db",
"@session",
"=",
"Session",
".",
"create",
"(",
"session_uuid",
":",
"session_uuid",
",",
"expiry",
":",
"session_expiry",
",",
"on_campus",
":",
"on_campus",
",",
"is_mobile",
":",
"is_mobile",
")",
"# set cookie",
"cookies",
"[",
":session_id",
"]",
"=",
"{",
":value",
"=>",
"session_uuid",
",",
":expires",
"=>",
"session_expiry",
"}",
"end"
] | Creates a new session, and logs it in the database
A session is tracked by a UUID that is stored in a cookie, and has a 5 minute expiry time.
Sessions are stored in the database with the time they were initiated, their expiry time (or end time),
whether the request originated from a campus IP address, and whether the request originated from a mobile device | [
"Creates",
"a",
"new",
"session",
"and",
"logs",
"it",
"in",
"the",
"database"
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/logging_controller.rb#L135-L145 | train |
NCSU-Libraries/quick_search | app/controllers/quick_search/logging_controller.rb | QuickSearch.LoggingController.update_session | def update_session
# update session expiry in the database
session_id = cookies[:session_id]
@session = Session.find_by session_uuid: session_id
@session.expiry = 5.minutes.from_now
@session.save
# update session expiry on cookie
cookies[:session_id] = { :value => session_id, :expires => @session.expiry }
end | ruby | def update_session
# update session expiry in the database
session_id = cookies[:session_id]
@session = Session.find_by session_uuid: session_id
@session.expiry = 5.minutes.from_now
@session.save
# update session expiry on cookie
cookies[:session_id] = { :value => session_id, :expires => @session.expiry }
end | [
"def",
"update_session",
"# update session expiry in the database",
"session_id",
"=",
"cookies",
"[",
":session_id",
"]",
"@session",
"=",
"Session",
".",
"find_by",
"session_uuid",
":",
"session_id",
"@session",
".",
"expiry",
"=",
"5",
".",
"minutes",
".",
"from_now",
"@session",
".",
"save",
"# update session expiry on cookie",
"cookies",
"[",
":session_id",
"]",
"=",
"{",
":value",
"=>",
"session_id",
",",
":expires",
"=>",
"@session",
".",
"expiry",
"}",
"end"
] | Updates a session's expiration time on cookie and in database
When a request is made with a non-expired session, the expiration time is updated to 5 minutes from the current time.
This update is reflected in the cookie as well as in the database entry for the session. | [
"Updates",
"a",
"session",
"s",
"expiration",
"time",
"on",
"cookie",
"and",
"in",
"database"
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/logging_controller.rb#L153-L162 | train |
NCSU-Libraries/quick_search | app/searchers/quick_search/searcher.rb | QuickSearch.Searcher.no_results_link | def no_results_link(service_name, i18n_key, default_i18n_key = nil)
if (i18n_key.present? && I18n.exists?(i18n_key)) ||
(default_i18n_key.present? && I18n.exists?(default_i18n_key))
locale_result = I18n.t(i18n_key, default: I18n.t(default_i18n_key))
return locale_result if locale_result
end
begin
config_class = "QuickSearch::Engine::#{service_name.upcase}_CONFIG".constantize
config_class['no_results_link']
rescue NameError
nil
end
end | ruby | def no_results_link(service_name, i18n_key, default_i18n_key = nil)
if (i18n_key.present? && I18n.exists?(i18n_key)) ||
(default_i18n_key.present? && I18n.exists?(default_i18n_key))
locale_result = I18n.t(i18n_key, default: I18n.t(default_i18n_key))
return locale_result if locale_result
end
begin
config_class = "QuickSearch::Engine::#{service_name.upcase}_CONFIG".constantize
config_class['no_results_link']
rescue NameError
nil
end
end | [
"def",
"no_results_link",
"(",
"service_name",
",",
"i18n_key",
",",
"default_i18n_key",
"=",
"nil",
")",
"if",
"(",
"i18n_key",
".",
"present?",
"&&",
"I18n",
".",
"exists?",
"(",
"i18n_key",
")",
")",
"||",
"(",
"default_i18n_key",
".",
"present?",
"&&",
"I18n",
".",
"exists?",
"(",
"default_i18n_key",
")",
")",
"locale_result",
"=",
"I18n",
".",
"t",
"(",
"i18n_key",
",",
"default",
":",
"I18n",
".",
"t",
"(",
"default_i18n_key",
")",
")",
"return",
"locale_result",
"if",
"locale_result",
"end",
"begin",
"config_class",
"=",
"\"QuickSearch::Engine::#{service_name.upcase}_CONFIG\"",
".",
"constantize",
"config_class",
"[",
"'no_results_link'",
"]",
"rescue",
"NameError",
"nil",
"end",
"end"
] | Returns a String representing the link to use when no results are
found for a search.
This default implementation first looks for the "i18n_key" and
"default_i18n_key" in the I18N locale files. If no entry is found
the "no_results_link" from the searcher configuration is returned.
Using the I18N locale files is considered legacy behavior (but
is preferred in this method to preserve existing functionality).
Use of the searcher configuration file is preferred. | [
"Returns",
"a",
"String",
"representing",
"the",
"link",
"to",
"use",
"when",
"no",
"results",
"are",
"found",
"for",
"a",
"search",
"."
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/searchers/quick_search/searcher.rb#L38-L51 | train |
NCSU-Libraries/quick_search | app/controllers/quick_search/search_controller.rb | QuickSearch.SearchController.xhr_search | def xhr_search
endpoint = params[:endpoint]
if params[:template] == 'with_paging'
template = 'xhr_response_with_paging'
else
template = 'xhr_response'
end
@query = params_q_scrubbed
@page = page
@per_page = per_page(endpoint)
@offset = offset(@page,@per_page)
http_client = HTTPClient.new
update_searcher_timeout(http_client, endpoint, true)
benchmark "%s xhr #{endpoint}" % CGI.escape(@query.to_str) do
klass = "QuickSearch::#{endpoint.camelize}Searcher".constantize
searcher = klass.new(http_client,
extracted_query(params_q_scrubbed),
@per_page,
@offset,
@page,
on_campus?(ip),
extracted_scope(params_q_scrubbed))
searcher.search
searcher_partials = {}
searcher_cfg = searcher_config(endpoint)
unless searcher_cfg.blank?
services = searcher_cfg['services'].blank? ? [] : searcher_cfg['services']
else
services = []
end
services << endpoint
respond_to do |format|
format.html {
services.each do |service|
service_template = render_to_string(
:partial => "quick_search/search/#{template}",
:layout => false,
:locals => { module_display_name: t("#{endpoint}_search.display_name"),
searcher: searcher,
search: '',
service_name: service
})
searcher_partials[service] = service_template
end
render :json => searcher_partials
}
format.json {
# prevents openstruct object from results being nested inside tables
# See: http://stackoverflow.com/questions/7835047/collecting-hashes-into-openstruct-creates-table-entry
result_list = []
searcher.results.each do |result|
result_list << result.to_h
end
render :json => { :endpoint => endpoint,
:per_page => @per_page.to_s,
:page => @page.to_s,
:total => searcher.total,
:results => result_list
}
}
end
end
end | ruby | def xhr_search
endpoint = params[:endpoint]
if params[:template] == 'with_paging'
template = 'xhr_response_with_paging'
else
template = 'xhr_response'
end
@query = params_q_scrubbed
@page = page
@per_page = per_page(endpoint)
@offset = offset(@page,@per_page)
http_client = HTTPClient.new
update_searcher_timeout(http_client, endpoint, true)
benchmark "%s xhr #{endpoint}" % CGI.escape(@query.to_str) do
klass = "QuickSearch::#{endpoint.camelize}Searcher".constantize
searcher = klass.new(http_client,
extracted_query(params_q_scrubbed),
@per_page,
@offset,
@page,
on_campus?(ip),
extracted_scope(params_q_scrubbed))
searcher.search
searcher_partials = {}
searcher_cfg = searcher_config(endpoint)
unless searcher_cfg.blank?
services = searcher_cfg['services'].blank? ? [] : searcher_cfg['services']
else
services = []
end
services << endpoint
respond_to do |format|
format.html {
services.each do |service|
service_template = render_to_string(
:partial => "quick_search/search/#{template}",
:layout => false,
:locals => { module_display_name: t("#{endpoint}_search.display_name"),
searcher: searcher,
search: '',
service_name: service
})
searcher_partials[service] = service_template
end
render :json => searcher_partials
}
format.json {
# prevents openstruct object from results being nested inside tables
# See: http://stackoverflow.com/questions/7835047/collecting-hashes-into-openstruct-creates-table-entry
result_list = []
searcher.results.each do |result|
result_list << result.to_h
end
render :json => { :endpoint => endpoint,
:per_page => @per_page.to_s,
:page => @page.to_s,
:total => searcher.total,
:results => result_list
}
}
end
end
end | [
"def",
"xhr_search",
"endpoint",
"=",
"params",
"[",
":endpoint",
"]",
"if",
"params",
"[",
":template",
"]",
"==",
"'with_paging'",
"template",
"=",
"'xhr_response_with_paging'",
"else",
"template",
"=",
"'xhr_response'",
"end",
"@query",
"=",
"params_q_scrubbed",
"@page",
"=",
"page",
"@per_page",
"=",
"per_page",
"(",
"endpoint",
")",
"@offset",
"=",
"offset",
"(",
"@page",
",",
"@per_page",
")",
"http_client",
"=",
"HTTPClient",
".",
"new",
"update_searcher_timeout",
"(",
"http_client",
",",
"endpoint",
",",
"true",
")",
"benchmark",
"\"%s xhr #{endpoint}\"",
"%",
"CGI",
".",
"escape",
"(",
"@query",
".",
"to_str",
")",
"do",
"klass",
"=",
"\"QuickSearch::#{endpoint.camelize}Searcher\"",
".",
"constantize",
"searcher",
"=",
"klass",
".",
"new",
"(",
"http_client",
",",
"extracted_query",
"(",
"params_q_scrubbed",
")",
",",
"@per_page",
",",
"@offset",
",",
"@page",
",",
"on_campus?",
"(",
"ip",
")",
",",
"extracted_scope",
"(",
"params_q_scrubbed",
")",
")",
"searcher",
".",
"search",
"searcher_partials",
"=",
"{",
"}",
"searcher_cfg",
"=",
"searcher_config",
"(",
"endpoint",
")",
"unless",
"searcher_cfg",
".",
"blank?",
"services",
"=",
"searcher_cfg",
"[",
"'services'",
"]",
".",
"blank?",
"?",
"[",
"]",
":",
"searcher_cfg",
"[",
"'services'",
"]",
"else",
"services",
"=",
"[",
"]",
"end",
"services",
"<<",
"endpoint",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"services",
".",
"each",
"do",
"|",
"service",
"|",
"service_template",
"=",
"render_to_string",
"(",
":partial",
"=>",
"\"quick_search/search/#{template}\"",
",",
":layout",
"=>",
"false",
",",
":locals",
"=>",
"{",
"module_display_name",
":",
"t",
"(",
"\"#{endpoint}_search.display_name\"",
")",
",",
"searcher",
":",
"searcher",
",",
"search",
":",
"''",
",",
"service_name",
":",
"service",
"}",
")",
"searcher_partials",
"[",
"service",
"]",
"=",
"service_template",
"end",
"render",
":json",
"=>",
"searcher_partials",
"}",
"format",
".",
"json",
"{",
"# prevents openstruct object from results being nested inside tables",
"# See: http://stackoverflow.com/questions/7835047/collecting-hashes-into-openstruct-creates-table-entry",
"result_list",
"=",
"[",
"]",
"searcher",
".",
"results",
".",
"each",
"do",
"|",
"result",
"|",
"result_list",
"<<",
"result",
".",
"to_h",
"end",
"render",
":json",
"=>",
"{",
":endpoint",
"=>",
"endpoint",
",",
":per_page",
"=>",
"@per_page",
".",
"to_s",
",",
":page",
"=>",
"@page",
".",
"to_s",
",",
":total",
"=>",
"searcher",
".",
"total",
",",
":results",
"=>",
"result_list",
"}",
"}",
"end",
"end",
"end"
] | The following searches for individual sections of the page.
This allows us to do client-side requests in cases where the original server-side
request times out or otherwise fails. | [
"The",
"following",
"searches",
"for",
"individual",
"sections",
"of",
"the",
"page",
".",
"This",
"allows",
"us",
"to",
"do",
"client",
"-",
"side",
"requests",
"in",
"cases",
"where",
"the",
"original",
"server",
"-",
"side",
"request",
"times",
"out",
"or",
"otherwise",
"fails",
"."
] | 2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03 | https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/search_controller.rb#L46-L119 | train |
saturnflyer/surrounded | lib/surrounded/context.rb | Surrounded.Context.private_const_set | def private_const_set(name, const)
unless role_const_defined?(name)
const = const_set(name, const)
private_constant name.to_sym
end
const
end | ruby | def private_const_set(name, const)
unless role_const_defined?(name)
const = const_set(name, const)
private_constant name.to_sym
end
const
end | [
"def",
"private_const_set",
"(",
"name",
",",
"const",
")",
"unless",
"role_const_defined?",
"(",
"name",
")",
"const",
"=",
"const_set",
"(",
"name",
",",
"const",
")",
"private_constant",
"name",
".",
"to_sym",
"end",
"const",
"end"
] | Set a named constant and make it private | [
"Set",
"a",
"named",
"constant",
"and",
"make",
"it",
"private"
] | 0052932a1ce70aa01122c0efdc79b4f60578bace | https://github.com/saturnflyer/surrounded/blob/0052932a1ce70aa01122c0efdc79b4f60578bace/lib/surrounded/context.rb#L73-L79 | train |
CocoaPods/fourflusher | lib/fourflusher/executable.rb | Fourflusher.Executable.executable | def executable(name)
define_method(name) do |*command|
Executable.execute_command(name, Array(command).flatten, false)
end
define_method(name.to_s + '!') do |*command|
Executable.execute_command(name, Array(command).flatten, true)
end
end | ruby | def executable(name)
define_method(name) do |*command|
Executable.execute_command(name, Array(command).flatten, false)
end
define_method(name.to_s + '!') do |*command|
Executable.execute_command(name, Array(command).flatten, true)
end
end | [
"def",
"executable",
"(",
"name",
")",
"define_method",
"(",
"name",
")",
"do",
"|",
"*",
"command",
"|",
"Executable",
".",
"execute_command",
"(",
"name",
",",
"Array",
"(",
"command",
")",
".",
"flatten",
",",
"false",
")",
"end",
"define_method",
"(",
"name",
".",
"to_s",
"+",
"'!'",
")",
"do",
"|",
"*",
"command",
"|",
"Executable",
".",
"execute_command",
"(",
"name",
",",
"Array",
"(",
"command",
")",
".",
"flatten",
",",
"true",
")",
"end",
"end"
] | Creates the methods for the executable with the given name.
@param [Symbol] name
the name of the executable.
@return [void] | [
"Creates",
"the",
"methods",
"for",
"the",
"executable",
"with",
"the",
"given",
"name",
"."
] | 8235ee8fae34ccaf5c708987306228988cea2e43 | https://github.com/CocoaPods/fourflusher/blob/8235ee8fae34ccaf5c708987306228988cea2e43/lib/fourflusher/executable.rb#L52-L60 | train |
CocoaPods/fourflusher | lib/fourflusher/find.rb | Fourflusher.SimControl.fetch_sims | def fetch_sims
device_list = JSON.parse(list(['-j', 'devices']))['devices']
unless device_list.is_a?(Hash)
msg = "Expected devices to be of type Hash but instated found #{device_list.class}"
fail Fourflusher::Informative, msg
end
device_list.flat_map do |runtime_str, devices|
# This format changed with Xcode 10.2.
if runtime_str.start_with?('com.apple.CoreSimulator.SimRuntime.')
# Sample string: com.apple.CoreSimulator.SimRuntime.iOS-12-2
_unused, os_info = runtime_str.split 'com.apple.CoreSimulator.SimRuntime.'
os_name, os_major_version, os_minor_version = os_info.split '-'
os_version = "#{os_major_version}.#{os_minor_version}"
else
# Sample string: iOS 9.3
os_name, os_version = runtime_str.split ' '
end
devices.map do |device|
if device['availability'] == '(available)' || device['isAvailable'] == 'YES'
Simulator.new(device, os_name, os_version)
end
end
end.compact.sort(&:sim_list_compare)
end | ruby | def fetch_sims
device_list = JSON.parse(list(['-j', 'devices']))['devices']
unless device_list.is_a?(Hash)
msg = "Expected devices to be of type Hash but instated found #{device_list.class}"
fail Fourflusher::Informative, msg
end
device_list.flat_map do |runtime_str, devices|
# This format changed with Xcode 10.2.
if runtime_str.start_with?('com.apple.CoreSimulator.SimRuntime.')
# Sample string: com.apple.CoreSimulator.SimRuntime.iOS-12-2
_unused, os_info = runtime_str.split 'com.apple.CoreSimulator.SimRuntime.'
os_name, os_major_version, os_minor_version = os_info.split '-'
os_version = "#{os_major_version}.#{os_minor_version}"
else
# Sample string: iOS 9.3
os_name, os_version = runtime_str.split ' '
end
devices.map do |device|
if device['availability'] == '(available)' || device['isAvailable'] == 'YES'
Simulator.new(device, os_name, os_version)
end
end
end.compact.sort(&:sim_list_compare)
end | [
"def",
"fetch_sims",
"device_list",
"=",
"JSON",
".",
"parse",
"(",
"list",
"(",
"[",
"'-j'",
",",
"'devices'",
"]",
")",
")",
"[",
"'devices'",
"]",
"unless",
"device_list",
".",
"is_a?",
"(",
"Hash",
")",
"msg",
"=",
"\"Expected devices to be of type Hash but instated found #{device_list.class}\"",
"fail",
"Fourflusher",
"::",
"Informative",
",",
"msg",
"end",
"device_list",
".",
"flat_map",
"do",
"|",
"runtime_str",
",",
"devices",
"|",
"# This format changed with Xcode 10.2.",
"if",
"runtime_str",
".",
"start_with?",
"(",
"'com.apple.CoreSimulator.SimRuntime.'",
")",
"# Sample string: com.apple.CoreSimulator.SimRuntime.iOS-12-2",
"_unused",
",",
"os_info",
"=",
"runtime_str",
".",
"split",
"'com.apple.CoreSimulator.SimRuntime.'",
"os_name",
",",
"os_major_version",
",",
"os_minor_version",
"=",
"os_info",
".",
"split",
"'-'",
"os_version",
"=",
"\"#{os_major_version}.#{os_minor_version}\"",
"else",
"# Sample string: iOS 9.3",
"os_name",
",",
"os_version",
"=",
"runtime_str",
".",
"split",
"' '",
"end",
"devices",
".",
"map",
"do",
"|",
"device",
"|",
"if",
"device",
"[",
"'availability'",
"]",
"==",
"'(available)'",
"||",
"device",
"[",
"'isAvailable'",
"]",
"==",
"'YES'",
"Simulator",
".",
"new",
"(",
"device",
",",
"os_name",
",",
"os_version",
")",
"end",
"end",
"end",
".",
"compact",
".",
"sort",
"(",
":sim_list_compare",
")",
"end"
] | Gets the simulators and transforms the simctl json into Simulator objects | [
"Gets",
"the",
"simulators",
"and",
"transforms",
"the",
"simctl",
"json",
"into",
"Simulator",
"objects"
] | 8235ee8fae34ccaf5c708987306228988cea2e43 | https://github.com/CocoaPods/fourflusher/blob/8235ee8fae34ccaf5c708987306228988cea2e43/lib/fourflusher/find.rb#L124-L148 | train |
brandur/json_schema | lib/json_schema/validator.rb | JsonSchema.Validator.get_extra_keys | def get_extra_keys(schema, data)
extra = data.keys - schema.properties.keys
if schema.pattern_properties
schema.pattern_properties.keys.each do |pattern|
extra -= extra.select { |k| k =~ pattern }
end
end
extra
end | ruby | def get_extra_keys(schema, data)
extra = data.keys - schema.properties.keys
if schema.pattern_properties
schema.pattern_properties.keys.each do |pattern|
extra -= extra.select { |k| k =~ pattern }
end
end
extra
end | [
"def",
"get_extra_keys",
"(",
"schema",
",",
"data",
")",
"extra",
"=",
"data",
".",
"keys",
"-",
"schema",
".",
"properties",
".",
"keys",
"if",
"schema",
".",
"pattern_properties",
"schema",
".",
"pattern_properties",
".",
"keys",
".",
"each",
"do",
"|",
"pattern",
"|",
"extra",
"-=",
"extra",
".",
"select",
"{",
"|",
"k",
"|",
"k",
"=~",
"pattern",
"}",
"end",
"end",
"extra",
"end"
] | for use with additionalProperties and strictProperties | [
"for",
"use",
"with",
"additionalProperties",
"and",
"strictProperties"
] | 9c4656774a7c7d22a6f466932b34fd47d67c88dc | https://github.com/brandur/json_schema/blob/9c4656774a7c7d22a6f466932b34fd47d67c88dc/lib/json_schema/validator.rb#L60-L70 | train |
brandur/json_schema | lib/json_pointer/evaluator.rb | JsonPointer.Evaluator.split | def split(path)
parts = []
last_index = 0
while index = path.index("/", last_index)
if index == last_index
parts << ""
else
parts << path[last_index...index]
end
last_index = index + 1
end
# and also get that last segment
parts << path[last_index..-1]
# it should begin with a blank segment from the leading "/"; kill that
parts.shift
parts
end | ruby | def split(path)
parts = []
last_index = 0
while index = path.index("/", last_index)
if index == last_index
parts << ""
else
parts << path[last_index...index]
end
last_index = index + 1
end
# and also get that last segment
parts << path[last_index..-1]
# it should begin with a blank segment from the leading "/"; kill that
parts.shift
parts
end | [
"def",
"split",
"(",
"path",
")",
"parts",
"=",
"[",
"]",
"last_index",
"=",
"0",
"while",
"index",
"=",
"path",
".",
"index",
"(",
"\"/\"",
",",
"last_index",
")",
"if",
"index",
"==",
"last_index",
"parts",
"<<",
"\"\"",
"else",
"parts",
"<<",
"path",
"[",
"last_index",
"...",
"index",
"]",
"end",
"last_index",
"=",
"index",
"+",
"1",
"end",
"# and also get that last segment",
"parts",
"<<",
"path",
"[",
"last_index",
"..",
"-",
"1",
"]",
"# it should begin with a blank segment from the leading \"/\"; kill that",
"parts",
".",
"shift",
"parts",
"end"
] | custom split method to account for blank segments | [
"custom",
"split",
"method",
"to",
"account",
"for",
"blank",
"segments"
] | 9c4656774a7c7d22a6f466932b34fd47d67c88dc | https://github.com/brandur/json_schema/blob/9c4656774a7c7d22a6f466932b34fd47d67c88dc/lib/json_pointer/evaluator.rb#L53-L69 | train |
rajatthareja/ReportBuilder | lib/report_builder/builder.rb | ReportBuilder.Builder.build_report | def build_report
options = ReportBuilder.options
groups = get_groups options[:input_path]
json_report_path = options[:json_report_path] || options[:report_path]
if options[:report_types].include? 'JSON'
File.open(json_report_path + '.json', 'w') do |file|
file.write JSON.pretty_generate(groups.size > 1 ? groups : groups.first['features'])
end
end
if options[:additional_css] and Pathname.new(options[:additional_css]).file?
options[:additional_css] = File.read(options[:additional_css])
end
if options[:additional_js] and Pathname.new(options[:additional_js]).file?
options[:additional_js] = File.read(options[:additional_js])
end
html_report_path = options[:html_report_path] || options[:report_path]
if options[:report_types].include? 'HTML'
File.open(html_report_path + '.html', 'w') do |file|
file.write get(groups.size > 1 ? 'group_report' : 'report').result(binding).gsub(' ', '').gsub("\n\n", '')
end
end
retry_report_path = options[:retry_report_path] || options[:report_path]
if options[:report_types].include? 'RETRY'
File.open(retry_report_path + '.retry', 'w') do |file|
groups.each do |group|
group['features'].each do |feature|
if feature['status'] == 'broken'
feature['elements'].each do |scenario|
file.puts "#{feature['uri']}:#{scenario['line']}" if scenario['status'] == 'failed'
end
end
end
end
end
end
[json_report_path, html_report_path, retry_report_path]
end | ruby | def build_report
options = ReportBuilder.options
groups = get_groups options[:input_path]
json_report_path = options[:json_report_path] || options[:report_path]
if options[:report_types].include? 'JSON'
File.open(json_report_path + '.json', 'w') do |file|
file.write JSON.pretty_generate(groups.size > 1 ? groups : groups.first['features'])
end
end
if options[:additional_css] and Pathname.new(options[:additional_css]).file?
options[:additional_css] = File.read(options[:additional_css])
end
if options[:additional_js] and Pathname.new(options[:additional_js]).file?
options[:additional_js] = File.read(options[:additional_js])
end
html_report_path = options[:html_report_path] || options[:report_path]
if options[:report_types].include? 'HTML'
File.open(html_report_path + '.html', 'w') do |file|
file.write get(groups.size > 1 ? 'group_report' : 'report').result(binding).gsub(' ', '').gsub("\n\n", '')
end
end
retry_report_path = options[:retry_report_path] || options[:report_path]
if options[:report_types].include? 'RETRY'
File.open(retry_report_path + '.retry', 'w') do |file|
groups.each do |group|
group['features'].each do |feature|
if feature['status'] == 'broken'
feature['elements'].each do |scenario|
file.puts "#{feature['uri']}:#{scenario['line']}" if scenario['status'] == 'failed'
end
end
end
end
end
end
[json_report_path, html_report_path, retry_report_path]
end | [
"def",
"build_report",
"options",
"=",
"ReportBuilder",
".",
"options",
"groups",
"=",
"get_groups",
"options",
"[",
":input_path",
"]",
"json_report_path",
"=",
"options",
"[",
":json_report_path",
"]",
"||",
"options",
"[",
":report_path",
"]",
"if",
"options",
"[",
":report_types",
"]",
".",
"include?",
"'JSON'",
"File",
".",
"open",
"(",
"json_report_path",
"+",
"'.json'",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"JSON",
".",
"pretty_generate",
"(",
"groups",
".",
"size",
">",
"1",
"?",
"groups",
":",
"groups",
".",
"first",
"[",
"'features'",
"]",
")",
"end",
"end",
"if",
"options",
"[",
":additional_css",
"]",
"and",
"Pathname",
".",
"new",
"(",
"options",
"[",
":additional_css",
"]",
")",
".",
"file?",
"options",
"[",
":additional_css",
"]",
"=",
"File",
".",
"read",
"(",
"options",
"[",
":additional_css",
"]",
")",
"end",
"if",
"options",
"[",
":additional_js",
"]",
"and",
"Pathname",
".",
"new",
"(",
"options",
"[",
":additional_js",
"]",
")",
".",
"file?",
"options",
"[",
":additional_js",
"]",
"=",
"File",
".",
"read",
"(",
"options",
"[",
":additional_js",
"]",
")",
"end",
"html_report_path",
"=",
"options",
"[",
":html_report_path",
"]",
"||",
"options",
"[",
":report_path",
"]",
"if",
"options",
"[",
":report_types",
"]",
".",
"include?",
"'HTML'",
"File",
".",
"open",
"(",
"html_report_path",
"+",
"'.html'",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"get",
"(",
"groups",
".",
"size",
">",
"1",
"?",
"'group_report'",
":",
"'report'",
")",
".",
"result",
"(",
"binding",
")",
".",
"gsub",
"(",
"' '",
",",
"''",
")",
".",
"gsub",
"(",
"\"\\n\\n\"",
",",
"''",
")",
"end",
"end",
"retry_report_path",
"=",
"options",
"[",
":retry_report_path",
"]",
"||",
"options",
"[",
":report_path",
"]",
"if",
"options",
"[",
":report_types",
"]",
".",
"include?",
"'RETRY'",
"File",
".",
"open",
"(",
"retry_report_path",
"+",
"'.retry'",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"groups",
".",
"each",
"do",
"|",
"group",
"|",
"group",
"[",
"'features'",
"]",
".",
"each",
"do",
"|",
"feature",
"|",
"if",
"feature",
"[",
"'status'",
"]",
"==",
"'broken'",
"feature",
"[",
"'elements'",
"]",
".",
"each",
"do",
"|",
"scenario",
"|",
"file",
".",
"puts",
"\"#{feature['uri']}:#{scenario['line']}\"",
"if",
"scenario",
"[",
"'status'",
"]",
"==",
"'failed'",
"end",
"end",
"end",
"end",
"end",
"end",
"[",
"json_report_path",
",",
"html_report_path",
",",
"retry_report_path",
"]",
"end"
] | ReportBuilder Main method | [
"ReportBuilder",
"Main",
"method"
] | 58b849fb368a7d6407ab9519cbee70bb9decd908 | https://github.com/rajatthareja/ReportBuilder/blob/58b849fb368a7d6407ab9519cbee70bb9decd908/lib/report_builder/builder.rb#L19-L61 | train |
davetron5000/methadone | lib/methadone/exit_now.rb | Methadone.ExitNow.exit_now! | def exit_now!(exit_code,message=nil)
if exit_code.kind_of?(String) && message.nil?
raise Methadone::Error.new(1,exit_code)
else
raise Methadone::Error.new(exit_code,message)
end
end | ruby | def exit_now!(exit_code,message=nil)
if exit_code.kind_of?(String) && message.nil?
raise Methadone::Error.new(1,exit_code)
else
raise Methadone::Error.new(exit_code,message)
end
end | [
"def",
"exit_now!",
"(",
"exit_code",
",",
"message",
"=",
"nil",
")",
"if",
"exit_code",
".",
"kind_of?",
"(",
"String",
")",
"&&",
"message",
".",
"nil?",
"raise",
"Methadone",
"::",
"Error",
".",
"new",
"(",
"1",
",",
"exit_code",
")",
"else",
"raise",
"Methadone",
"::",
"Error",
".",
"new",
"(",
"exit_code",
",",
"message",
")",
"end",
"end"
] | Call this to exit the program immediately
with the given error code and message.
+exit_code+:: exit status you'd like to exit with
+message+:: message to display to the user explaining the problem
If +exit_code+ is a String and +message+ is omitted, +exit_code+ will be used as the message
and the actual exit code will be 1.
=== Examples
exit_now!(4,"Oh noes!")
# => exit app with status 4 and show the user "Oh noes!" on stderr
exit_now!("Oh noes!")
# => exit app with status 1 and show the user "Oh noes!" on stderr
exit_now!(4)
# => exit app with status 4 and dont' give the user a message (how rude of you) | [
"Call",
"this",
"to",
"exit",
"the",
"program",
"immediately",
"with",
"the",
"given",
"error",
"code",
"and",
"message",
"."
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/exit_now.rb#L25-L31 | train |
davetron5000/methadone | lib/methadone/cli.rb | Methadone.CLI.check_and_prepare_basedir! | def check_and_prepare_basedir!(basedir,force)
if File.exists? basedir
if force
rm_rf basedir, :verbose => true, :secure => true
else
exit_now! 1,"error: #{basedir} exists, use --force to override"
end
end
mkdir_p basedir
end | ruby | def check_and_prepare_basedir!(basedir,force)
if File.exists? basedir
if force
rm_rf basedir, :verbose => true, :secure => true
else
exit_now! 1,"error: #{basedir} exists, use --force to override"
end
end
mkdir_p basedir
end | [
"def",
"check_and_prepare_basedir!",
"(",
"basedir",
",",
"force",
")",
"if",
"File",
".",
"exists?",
"basedir",
"if",
"force",
"rm_rf",
"basedir",
",",
":verbose",
"=>",
"true",
",",
":secure",
"=>",
"true",
"else",
"exit_now!",
"1",
",",
"\"error: #{basedir} exists, use --force to override\"",
"end",
"end",
"mkdir_p",
"basedir",
"end"
] | Checks that the basedir can be used, either by
not existing, or by existing and force is true.
In that case, we clean it out entirely
+basedir+:: base directory where the user wants to create a new project
+force+:: if true, and +basedir+ exists, delete it before proceeding
This will exit the app if the dir exists and force is false | [
"Checks",
"that",
"the",
"basedir",
"can",
"be",
"used",
"either",
"by",
"not",
"existing",
"or",
"by",
"existing",
"and",
"force",
"is",
"true",
".",
"In",
"that",
"case",
"we",
"clean",
"it",
"out",
"entirely"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/cli.rb#L19-L28 | train |
davetron5000/methadone | lib/methadone/cli.rb | Methadone.CLI.add_to_file | def add_to_file(file,lines,options = {})
new_lines = []
found_line = false
File.open(file).readlines.each do |line|
line.chomp!
if options[:before] && options[:before] === line
found_line = true
new_lines += lines
end
new_lines << line
end
raise "No line matched #{options[:before]}" if options[:before] && !found_line
new_lines += lines unless options[:before]
File.open(file,'w') do |fp|
new_lines.each { |line| fp.puts line }
end
end | ruby | def add_to_file(file,lines,options = {})
new_lines = []
found_line = false
File.open(file).readlines.each do |line|
line.chomp!
if options[:before] && options[:before] === line
found_line = true
new_lines += lines
end
new_lines << line
end
raise "No line matched #{options[:before]}" if options[:before] && !found_line
new_lines += lines unless options[:before]
File.open(file,'w') do |fp|
new_lines.each { |line| fp.puts line }
end
end | [
"def",
"add_to_file",
"(",
"file",
",",
"lines",
",",
"options",
"=",
"{",
"}",
")",
"new_lines",
"=",
"[",
"]",
"found_line",
"=",
"false",
"File",
".",
"open",
"(",
"file",
")",
".",
"readlines",
".",
"each",
"do",
"|",
"line",
"|",
"line",
".",
"chomp!",
"if",
"options",
"[",
":before",
"]",
"&&",
"options",
"[",
":before",
"]",
"===",
"line",
"found_line",
"=",
"true",
"new_lines",
"+=",
"lines",
"end",
"new_lines",
"<<",
"line",
"end",
"raise",
"\"No line matched #{options[:before]}\"",
"if",
"options",
"[",
":before",
"]",
"&&",
"!",
"found_line",
"new_lines",
"+=",
"lines",
"unless",
"options",
"[",
":before",
"]",
"File",
".",
"open",
"(",
"file",
",",
"'w'",
")",
"do",
"|",
"fp",
"|",
"new_lines",
".",
"each",
"{",
"|",
"line",
"|",
"fp",
".",
"puts",
"line",
"}",
"end",
"end"
] | Add content to a file
+file+:: path to the file
+lines+:: Array of String representing the lines to add
+options+:: Hash of options:
<tt>:before</tt>:: A regexp that will appear right after the new content. i.e.
this is where to insert said content. | [
"Add",
"content",
"to",
"a",
"file"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/cli.rb#L37-L55 | train |
davetron5000/methadone | lib/methadone/cli.rb | Methadone.CLI.copy_file | def copy_file(relative_path,options = {})
options[:from] ||= :full
relative_path = File.join(relative_path.split(/\//))
template_path = File.join(template_dir(options[:from]),relative_path + ".erb")
template = ERB.new(File.open(template_path).readlines.join(''))
relative_path_parts = File.split(relative_path)
relative_path_parts[-1] = options[:as] if options[:as]
erb_binding = options[:binding] or binding
File.open(File.join(relative_path_parts),'w') do |file|
file.puts template.result(erb_binding)
file.chmod(0755) if options[:executable]
end
end | ruby | def copy_file(relative_path,options = {})
options[:from] ||= :full
relative_path = File.join(relative_path.split(/\//))
template_path = File.join(template_dir(options[:from]),relative_path + ".erb")
template = ERB.new(File.open(template_path).readlines.join(''))
relative_path_parts = File.split(relative_path)
relative_path_parts[-1] = options[:as] if options[:as]
erb_binding = options[:binding] or binding
File.open(File.join(relative_path_parts),'w') do |file|
file.puts template.result(erb_binding)
file.chmod(0755) if options[:executable]
end
end | [
"def",
"copy_file",
"(",
"relative_path",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":from",
"]",
"||=",
":full",
"relative_path",
"=",
"File",
".",
"join",
"(",
"relative_path",
".",
"split",
"(",
"/",
"\\/",
"/",
")",
")",
"template_path",
"=",
"File",
".",
"join",
"(",
"template_dir",
"(",
"options",
"[",
":from",
"]",
")",
",",
"relative_path",
"+",
"\".erb\"",
")",
"template",
"=",
"ERB",
".",
"new",
"(",
"File",
".",
"open",
"(",
"template_path",
")",
".",
"readlines",
".",
"join",
"(",
"''",
")",
")",
"relative_path_parts",
"=",
"File",
".",
"split",
"(",
"relative_path",
")",
"relative_path_parts",
"[",
"-",
"1",
"]",
"=",
"options",
"[",
":as",
"]",
"if",
"options",
"[",
":as",
"]",
"erb_binding",
"=",
"options",
"[",
":binding",
"]",
"or",
"binding",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"relative_path_parts",
")",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"puts",
"template",
".",
"result",
"(",
"erb_binding",
")",
"file",
".",
"chmod",
"(",
"0755",
")",
"if",
"options",
"[",
":executable",
"]",
"end",
"end"
] | Copies a file, running it through ERB
+relative_path+:: path to the file, relative to the project root, minus the .erb extension
You should use forward slashes to separate paths; this method
will handle making the ultimate path OS independent.
+options+:: Options to affect how the copy is done:
<tt>:from</tt>:: The name of the profile from which to find the file, "full" by default
<tt>:as</tt>:: The name the file should get if not the one in relative_path
<tt>:executable</tt>:: true if this file should be set executable
<tt>:binding</tt>:: the binding to use for the template | [
"Copies",
"a",
"file",
"running",
"it",
"through",
"ERB"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/cli.rb#L67-L84 | train |
davetron5000/methadone | lib/methadone/argv_parser.rb | Methadone.ARGVParser.parse_string_for_argv | def parse_string_for_argv(string) #:nodoc:
return [] if string.nil?
args = [] # return value we are building up
current = 0 # pointer to where we are in +string+
next_arg = '' # the next arg we are building up to ultimatley put into args
inside_quote = nil # quote character we are "inside" of
last_char = nil # the last character we saw
while current < string.length
char = string.chars.to_a[current]
case char
when /["']/
if inside_quote.nil? # eat the quote, but remember we are now "inside" one
inside_quote = char
elsif inside_quote == char # we closed the quote we were "inside"
inside_quote = nil
else # we got a different quote, so it goes in literally
next_arg << char
end
when /\s/
if last_char == "\\" # we have an escaped space, replace the escape char
next_arg[-1] = char
elsif inside_quote # we are inside a quote so keep the space
next_arg << char
else # new argument
args << next_arg
next_arg = ''
end
else
next_arg << char
end
current += 1
last_char = char
end
args << next_arg unless next_arg == ''
args
end | ruby | def parse_string_for_argv(string) #:nodoc:
return [] if string.nil?
args = [] # return value we are building up
current = 0 # pointer to where we are in +string+
next_arg = '' # the next arg we are building up to ultimatley put into args
inside_quote = nil # quote character we are "inside" of
last_char = nil # the last character we saw
while current < string.length
char = string.chars.to_a[current]
case char
when /["']/
if inside_quote.nil? # eat the quote, but remember we are now "inside" one
inside_quote = char
elsif inside_quote == char # we closed the quote we were "inside"
inside_quote = nil
else # we got a different quote, so it goes in literally
next_arg << char
end
when /\s/
if last_char == "\\" # we have an escaped space, replace the escape char
next_arg[-1] = char
elsif inside_quote # we are inside a quote so keep the space
next_arg << char
else # new argument
args << next_arg
next_arg = ''
end
else
next_arg << char
end
current += 1
last_char = char
end
args << next_arg unless next_arg == ''
args
end | [
"def",
"parse_string_for_argv",
"(",
"string",
")",
"#:nodoc:",
"return",
"[",
"]",
"if",
"string",
".",
"nil?",
"args",
"=",
"[",
"]",
"# return value we are building up",
"current",
"=",
"0",
"# pointer to where we are in +string+",
"next_arg",
"=",
"''",
"# the next arg we are building up to ultimatley put into args",
"inside_quote",
"=",
"nil",
"# quote character we are \"inside\" of",
"last_char",
"=",
"nil",
"# the last character we saw",
"while",
"current",
"<",
"string",
".",
"length",
"char",
"=",
"string",
".",
"chars",
".",
"to_a",
"[",
"current",
"]",
"case",
"char",
"when",
"/",
"/",
"if",
"inside_quote",
".",
"nil?",
"# eat the quote, but remember we are now \"inside\" one",
"inside_quote",
"=",
"char",
"elsif",
"inside_quote",
"==",
"char",
"# we closed the quote we were \"inside\"",
"inside_quote",
"=",
"nil",
"else",
"# we got a different quote, so it goes in literally",
"next_arg",
"<<",
"char",
"end",
"when",
"/",
"\\s",
"/",
"if",
"last_char",
"==",
"\"\\\\\"",
"# we have an escaped space, replace the escape char",
"next_arg",
"[",
"-",
"1",
"]",
"=",
"char",
"elsif",
"inside_quote",
"# we are inside a quote so keep the space",
"next_arg",
"<<",
"char",
"else",
"# new argument",
"args",
"<<",
"next_arg",
"next_arg",
"=",
"''",
"end",
"else",
"next_arg",
"<<",
"char",
"end",
"current",
"+=",
"1",
"last_char",
"=",
"char",
"end",
"args",
"<<",
"next_arg",
"unless",
"next_arg",
"==",
"''",
"args",
"end"
] | Parses +string+, returning an array that can be placed into ARGV or given to OptionParser | [
"Parses",
"+",
"string",
"+",
"returning",
"an",
"array",
"that",
"can",
"be",
"placed",
"into",
"ARGV",
"or",
"given",
"to",
"OptionParser"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/argv_parser.rb#L11-L48 | train |
davetron5000/methadone | lib/methadone/main.rb | Methadone.Main.go! | def go!
setup_defaults
opts.post_setup
opts.parse!
opts.check_args!
result = call_main
if result.kind_of? Integer
exit result
else
exit 0
end
rescue OptionParser::ParseError => ex
logger.error ex.message
puts
puts opts.help
exit 64 # Linux standard for bad command line
end | ruby | def go!
setup_defaults
opts.post_setup
opts.parse!
opts.check_args!
result = call_main
if result.kind_of? Integer
exit result
else
exit 0
end
rescue OptionParser::ParseError => ex
logger.error ex.message
puts
puts opts.help
exit 64 # Linux standard for bad command line
end | [
"def",
"go!",
"setup_defaults",
"opts",
".",
"post_setup",
"opts",
".",
"parse!",
"opts",
".",
"check_args!",
"result",
"=",
"call_main",
"if",
"result",
".",
"kind_of?",
"Integer",
"exit",
"result",
"else",
"exit",
"0",
"end",
"rescue",
"OptionParser",
"::",
"ParseError",
"=>",
"ex",
"logger",
".",
"error",
"ex",
".",
"message",
"puts",
"puts",
"opts",
".",
"help",
"exit",
"64",
"# Linux standard for bad command line",
"end"
] | Start your command-line app, exiting appropriately when
complete.
This *will* exit your program when it completes. If your
#main block evaluates to an integer, that value will be sent
to Kernel#exit, otherwise, this will exit with 0
If the command-line options couldn't be parsed, this
will exit with 64 and whatever message OptionParser provided.
If a required argument (see #arg) is not found, this exits with
64 and a message about that missing argument. | [
"Start",
"your",
"command",
"-",
"line",
"app",
"exiting",
"appropriately",
"when",
"complete",
"."
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/main.rb#L162-L178 | train |
davetron5000/methadone | lib/methadone/main.rb | Methadone.Main.normalize_defaults | def normalize_defaults
new_options = {}
options.each do |key,value|
unless value.nil?
new_options[key.to_s] = value
new_options[key.to_sym] = value
end
end
options.merge!(new_options)
end | ruby | def normalize_defaults
new_options = {}
options.each do |key,value|
unless value.nil?
new_options[key.to_s] = value
new_options[key.to_sym] = value
end
end
options.merge!(new_options)
end | [
"def",
"normalize_defaults",
"new_options",
"=",
"{",
"}",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"unless",
"value",
".",
"nil?",
"new_options",
"[",
"key",
".",
"to_s",
"]",
"=",
"value",
"new_options",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
"end",
"end",
"options",
".",
"merge!",
"(",
"new_options",
")",
"end"
] | Normalized all defaults to both string and symbol forms, so
the user can access them via either means just as they would for
non-defaulted options | [
"Normalized",
"all",
"defaults",
"to",
"both",
"string",
"and",
"symbol",
"forms",
"so",
"the",
"user",
"can",
"access",
"them",
"via",
"either",
"means",
"just",
"as",
"they",
"would",
"for",
"non",
"-",
"defaulted",
"options"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/main.rb#L384-L393 | train |
davetron5000/methadone | lib/methadone/main.rb | Methadone.Main.call_main | def call_main
@leak_exceptions = nil unless defined? @leak_exceptions
@main_block.call(*ARGV)
rescue Methadone::Error => ex
raise ex if ENV['DEBUG']
logger.error ex.message unless no_message? ex
ex.exit_code
rescue OptionParser::ParseError
raise
rescue => ex
raise ex if ENV['DEBUG']
raise ex if @leak_exceptions
logger.error ex.message unless no_message? ex
70 # Linux sysexit code for internal software error
end | ruby | def call_main
@leak_exceptions = nil unless defined? @leak_exceptions
@main_block.call(*ARGV)
rescue Methadone::Error => ex
raise ex if ENV['DEBUG']
logger.error ex.message unless no_message? ex
ex.exit_code
rescue OptionParser::ParseError
raise
rescue => ex
raise ex if ENV['DEBUG']
raise ex if @leak_exceptions
logger.error ex.message unless no_message? ex
70 # Linux sysexit code for internal software error
end | [
"def",
"call_main",
"@leak_exceptions",
"=",
"nil",
"unless",
"defined?",
"@leak_exceptions",
"@main_block",
".",
"call",
"(",
"ARGV",
")",
"rescue",
"Methadone",
"::",
"Error",
"=>",
"ex",
"raise",
"ex",
"if",
"ENV",
"[",
"'DEBUG'",
"]",
"logger",
".",
"error",
"ex",
".",
"message",
"unless",
"no_message?",
"ex",
"ex",
".",
"exit_code",
"rescue",
"OptionParser",
"::",
"ParseError",
"raise",
"rescue",
"=>",
"ex",
"raise",
"ex",
"if",
"ENV",
"[",
"'DEBUG'",
"]",
"raise",
"ex",
"if",
"@leak_exceptions",
"logger",
".",
"error",
"ex",
".",
"message",
"unless",
"no_message?",
"ex",
"70",
"# Linux sysexit code for internal software error",
"end"
] | Handle calling main and trapping any exceptions thrown | [
"Handle",
"calling",
"main",
"and",
"trapping",
"any",
"exceptions",
"thrown"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/main.rb#L396-L410 | train |
davetron5000/methadone | lib/methadone/main.rb | Methadone.OptionParserProxy.check_args! | def check_args!
::Hash[@args.zip(::ARGV)].each do |arg_name,arg_value|
if @arg_options[arg_name].include? :required
if arg_value.nil?
message = "'#{arg_name.to_s}' is required"
message = "at least one " + message if @arg_options[arg_name].include? :many
raise ::OptionParser::ParseError,message
end
end
end
end | ruby | def check_args!
::Hash[@args.zip(::ARGV)].each do |arg_name,arg_value|
if @arg_options[arg_name].include? :required
if arg_value.nil?
message = "'#{arg_name.to_s}' is required"
message = "at least one " + message if @arg_options[arg_name].include? :many
raise ::OptionParser::ParseError,message
end
end
end
end | [
"def",
"check_args!",
"::",
"Hash",
"[",
"@args",
".",
"zip",
"(",
"::",
"ARGV",
")",
"]",
".",
"each",
"do",
"|",
"arg_name",
",",
"arg_value",
"|",
"if",
"@arg_options",
"[",
"arg_name",
"]",
".",
"include?",
":required",
"if",
"arg_value",
".",
"nil?",
"message",
"=",
"\"'#{arg_name.to_s}' is required\"",
"message",
"=",
"\"at least one \"",
"+",
"message",
"if",
"@arg_options",
"[",
"arg_name",
"]",
".",
"include?",
":many",
"raise",
"::",
"OptionParser",
"::",
"ParseError",
",",
"message",
"end",
"end",
"end",
"end"
] | Create the proxy
+option_parser+:: An OptionParser instance
+options+:: a hash that will store the options
set via automatic setting. The caller should
retain a reference to this | [
"Create",
"the",
"proxy"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/main.rb#L442-L452 | train |
davetron5000/methadone | lib/methadone/main.rb | Methadone.OptionParserProxy.arg | def arg(arg_name,*options)
options << :optional if options.include?(:any) && !options.include?(:optional)
options << :required unless options.include? :optional
options << :one unless options.include?(:any) || options.include?(:many)
@args << arg_name
@arg_options[arg_name] = options
options.select(&STRINGS_ONLY).each do |doc|
@arg_documentation[arg_name] = doc + (options.include?(:optional) ? " (optional)" : "")
end
set_banner
end | ruby | def arg(arg_name,*options)
options << :optional if options.include?(:any) && !options.include?(:optional)
options << :required unless options.include? :optional
options << :one unless options.include?(:any) || options.include?(:many)
@args << arg_name
@arg_options[arg_name] = options
options.select(&STRINGS_ONLY).each do |doc|
@arg_documentation[arg_name] = doc + (options.include?(:optional) ? " (optional)" : "")
end
set_banner
end | [
"def",
"arg",
"(",
"arg_name",
",",
"*",
"options",
")",
"options",
"<<",
":optional",
"if",
"options",
".",
"include?",
"(",
":any",
")",
"&&",
"!",
"options",
".",
"include?",
"(",
":optional",
")",
"options",
"<<",
":required",
"unless",
"options",
".",
"include?",
":optional",
"options",
"<<",
":one",
"unless",
"options",
".",
"include?",
"(",
":any",
")",
"||",
"options",
".",
"include?",
"(",
":many",
")",
"@args",
"<<",
"arg_name",
"@arg_options",
"[",
"arg_name",
"]",
"=",
"options",
"options",
".",
"select",
"(",
"STRINGS_ONLY",
")",
".",
"each",
"do",
"|",
"doc",
"|",
"@arg_documentation",
"[",
"arg_name",
"]",
"=",
"doc",
"+",
"(",
"options",
".",
"include?",
"(",
":optional",
")",
"?",
"\" (optional)\"",
":",
"\"\"",
")",
"end",
"set_banner",
"end"
] | Sets the banner to include these arg names | [
"Sets",
"the",
"banner",
"to",
"include",
"these",
"arg",
"names"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/main.rb#L483-L493 | train |
davetron5000/methadone | lib/methadone/sh.rb | Methadone.SH.sh | def sh(command,options={},&block)
sh_logger.debug("Executing '#{command}'")
stdout,stderr,status = execution_strategy.run_command(command)
process_status = Methadone::ProcessStatus.new(status,options[:expected])
sh_logger.warn("stderr output of '#{command}': #{stderr}") unless stderr.strip.length == 0
if process_status.success?
sh_logger.debug("stdout output of '#{command}': #{stdout}") unless stdout.strip.length == 0
call_block(block,stdout,stderr,process_status.exitstatus) unless block.nil?
else
sh_logger.info("stdout output of '#{command}': #{stdout}") unless stdout.strip.length == 0
sh_logger.warn("Error running '#{command}'")
end
process_status.exitstatus
rescue *exception_meaning_command_not_found => ex
sh_logger.error("Error running '#{command}': #{ex.message}")
127
end | ruby | def sh(command,options={},&block)
sh_logger.debug("Executing '#{command}'")
stdout,stderr,status = execution_strategy.run_command(command)
process_status = Methadone::ProcessStatus.new(status,options[:expected])
sh_logger.warn("stderr output of '#{command}': #{stderr}") unless stderr.strip.length == 0
if process_status.success?
sh_logger.debug("stdout output of '#{command}': #{stdout}") unless stdout.strip.length == 0
call_block(block,stdout,stderr,process_status.exitstatus) unless block.nil?
else
sh_logger.info("stdout output of '#{command}': #{stdout}") unless stdout.strip.length == 0
sh_logger.warn("Error running '#{command}'")
end
process_status.exitstatus
rescue *exception_meaning_command_not_found => ex
sh_logger.error("Error running '#{command}': #{ex.message}")
127
end | [
"def",
"sh",
"(",
"command",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"sh_logger",
".",
"debug",
"(",
"\"Executing '#{command}'\"",
")",
"stdout",
",",
"stderr",
",",
"status",
"=",
"execution_strategy",
".",
"run_command",
"(",
"command",
")",
"process_status",
"=",
"Methadone",
"::",
"ProcessStatus",
".",
"new",
"(",
"status",
",",
"options",
"[",
":expected",
"]",
")",
"sh_logger",
".",
"warn",
"(",
"\"stderr output of '#{command}': #{stderr}\"",
")",
"unless",
"stderr",
".",
"strip",
".",
"length",
"==",
"0",
"if",
"process_status",
".",
"success?",
"sh_logger",
".",
"debug",
"(",
"\"stdout output of '#{command}': #{stdout}\"",
")",
"unless",
"stdout",
".",
"strip",
".",
"length",
"==",
"0",
"call_block",
"(",
"block",
",",
"stdout",
",",
"stderr",
",",
"process_status",
".",
"exitstatus",
")",
"unless",
"block",
".",
"nil?",
"else",
"sh_logger",
".",
"info",
"(",
"\"stdout output of '#{command}': #{stdout}\"",
")",
"unless",
"stdout",
".",
"strip",
".",
"length",
"==",
"0",
"sh_logger",
".",
"warn",
"(",
"\"Error running '#{command}'\"",
")",
"end",
"process_status",
".",
"exitstatus",
"rescue",
"exception_meaning_command_not_found",
"=>",
"ex",
"sh_logger",
".",
"error",
"(",
"\"Error running '#{command}': #{ex.message}\"",
")",
"127",
"end"
] | Run a shell command, capturing and logging its output.
If the command completed successfully, it's output is logged at DEBUG.
If not, its output as logged at INFO. In either case, its
error output is logged at WARN.
command:: the command to run as a String or Array of String. The String form is simplest, but
is open to injection. If you need to execute a command that is assembled from some portion
of user input, consider using an Array of String. This form prevents tokenization that occurs
in the String form. The first element is the command to execute,
and the remainder are the arguments. See Methadone::ExecutionStrategy::Base for more info.
options:: options to control the call. Currently responds to:
+:expected+:: an Int or Array of Int representing error codes, <b>in addition to 0</b>, that are
expected and therefore constitute success. Useful for commands that don't use
exit codes the way you'd like
block:: if provided, will be called if the command exited nonzero. The block may take 0, 1, 2, or 3 arguments.
The arguments provided are the standard output as a string, standard error as a string, and
the exitstatus as an Int.
You should be safe to pass in a lambda instead of a block, as long as your
lambda doesn't take more than three arguments
Example
sh "cp foo /tmp"
sh "ls /tmp" do |stdout|
# stdout contains the output of ls /tmp
end
sh "ls -l /tmp foobar" do |stdout,stderr|
# ...
end
Returns the exit status of the command. Note that if the command doesn't exist, this returns 127. | [
"Run",
"a",
"shell",
"command",
"capturing",
"and",
"logging",
"its",
"output",
".",
"If",
"the",
"command",
"completed",
"successfully",
"it",
"s",
"output",
"is",
"logged",
"at",
"DEBUG",
".",
"If",
"not",
"its",
"output",
"as",
"logged",
"at",
"INFO",
".",
"In",
"either",
"case",
"its",
"error",
"output",
"is",
"logged",
"at",
"WARN",
"."
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/sh.rb#L100-L120 | train |
davetron5000/methadone | lib/methadone/sh.rb | Methadone.SH.call_block | def call_block(block,stdout,stderr,exitstatus)
# blocks that take no arguments have arity -1. Or 0. Ugh.
if block.arity > 0
case block.arity
when 1
block.call(stdout)
when 2
block.call(stdout,stderr)
else
# Let it fail for lambdas
block.call(stdout,stderr,exitstatus)
end
else
block.call
end
end | ruby | def call_block(block,stdout,stderr,exitstatus)
# blocks that take no arguments have arity -1. Or 0. Ugh.
if block.arity > 0
case block.arity
when 1
block.call(stdout)
when 2
block.call(stdout,stderr)
else
# Let it fail for lambdas
block.call(stdout,stderr,exitstatus)
end
else
block.call
end
end | [
"def",
"call_block",
"(",
"block",
",",
"stdout",
",",
"stderr",
",",
"exitstatus",
")",
"# blocks that take no arguments have arity -1. Or 0. Ugh.",
"if",
"block",
".",
"arity",
">",
"0",
"case",
"block",
".",
"arity",
"when",
"1",
"block",
".",
"call",
"(",
"stdout",
")",
"when",
"2",
"block",
".",
"call",
"(",
"stdout",
",",
"stderr",
")",
"else",
"# Let it fail for lambdas",
"block",
".",
"call",
"(",
"stdout",
",",
"stderr",
",",
"exitstatus",
")",
"end",
"else",
"block",
".",
"call",
"end",
"end"
] | Safely call our block, even if the user passed in a lambda | [
"Safely",
"call",
"our",
"block",
"even",
"if",
"the",
"user",
"passed",
"in",
"a",
"lambda"
] | 2e670ac24cee3ab8658a1de62a70ff58e7806dc5 | https://github.com/davetron5000/methadone/blob/2e670ac24cee3ab8658a1de62a70ff58e7806dc5/lib/methadone/sh.rb#L206-L221 | train |
akretion/ooor | lib/ooor/associations.rb | Ooor.Associations.relationnal_result | def relationnal_result(method_name, *arguments)
self.class.reload_fields_definition(false)
if self.class.many2one_associations.has_key?(method_name)
load_m2o_association(method_name, *arguments)
elsif self.class.polymorphic_m2o_associations.has_key?(method_name)# && @associations[method_name]
load_polymorphic_m2o_association(method_name, *arguments)
# values = @associations[method_name].split(',')
# self.class.const_get(values[0]).find(values[1], arguments.extract_options!)
else # o2m or m2m
load_x2m_association(method_name, *arguments)
end
end | ruby | def relationnal_result(method_name, *arguments)
self.class.reload_fields_definition(false)
if self.class.many2one_associations.has_key?(method_name)
load_m2o_association(method_name, *arguments)
elsif self.class.polymorphic_m2o_associations.has_key?(method_name)# && @associations[method_name]
load_polymorphic_m2o_association(method_name, *arguments)
# values = @associations[method_name].split(',')
# self.class.const_get(values[0]).find(values[1], arguments.extract_options!)
else # o2m or m2m
load_x2m_association(method_name, *arguments)
end
end | [
"def",
"relationnal_result",
"(",
"method_name",
",",
"*",
"arguments",
")",
"self",
".",
"class",
".",
"reload_fields_definition",
"(",
"false",
")",
"if",
"self",
".",
"class",
".",
"many2one_associations",
".",
"has_key?",
"(",
"method_name",
")",
"load_m2o_association",
"(",
"method_name",
",",
"arguments",
")",
"elsif",
"self",
".",
"class",
".",
"polymorphic_m2o_associations",
".",
"has_key?",
"(",
"method_name",
")",
"# && @associations[method_name]",
"load_polymorphic_m2o_association",
"(",
"method_name",
",",
"arguments",
")",
"# values = @associations[method_name].split(',')",
"# self.class.const_get(values[0]).find(values[1], arguments.extract_options!)",
"else",
"# o2m or m2m",
"load_x2m_association",
"(",
"method_name",
",",
"arguments",
")",
"end",
"end"
] | fakes associations like much like ActiveRecord according to the cached OpenERP data model | [
"fakes",
"associations",
"like",
"much",
"like",
"ActiveRecord",
"according",
"to",
"the",
"cached",
"OpenERP",
"data",
"model"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/associations.rb#L28-L39 | train |
akretion/ooor | lib/ooor/type_casting.rb | Ooor.TypeCasting.cast_association | def cast_association(k)
if self.class.one2many_associations[k]
if @loaded_associations[k]
v = @loaded_associations[k].select {|i| i.changed?}
v = @associations[k] if v.empty?
else
v = @associations[k]
end
cast_o2m_association(v)
elsif self.class.many2many_associations[k]
v = @associations[k]
[[6, false, (v || []).map {|i| i.is_a?(Base) ? i.id : i}]]
elsif self.class.many2one_associations[k]
v = @associations[k] # TODO support for nested
cast_m2o_association(v)
end
end | ruby | def cast_association(k)
if self.class.one2many_associations[k]
if @loaded_associations[k]
v = @loaded_associations[k].select {|i| i.changed?}
v = @associations[k] if v.empty?
else
v = @associations[k]
end
cast_o2m_association(v)
elsif self.class.many2many_associations[k]
v = @associations[k]
[[6, false, (v || []).map {|i| i.is_a?(Base) ? i.id : i}]]
elsif self.class.many2one_associations[k]
v = @associations[k] # TODO support for nested
cast_m2o_association(v)
end
end | [
"def",
"cast_association",
"(",
"k",
")",
"if",
"self",
".",
"class",
".",
"one2many_associations",
"[",
"k",
"]",
"if",
"@loaded_associations",
"[",
"k",
"]",
"v",
"=",
"@loaded_associations",
"[",
"k",
"]",
".",
"select",
"{",
"|",
"i",
"|",
"i",
".",
"changed?",
"}",
"v",
"=",
"@associations",
"[",
"k",
"]",
"if",
"v",
".",
"empty?",
"else",
"v",
"=",
"@associations",
"[",
"k",
"]",
"end",
"cast_o2m_association",
"(",
"v",
")",
"elsif",
"self",
".",
"class",
".",
"many2many_associations",
"[",
"k",
"]",
"v",
"=",
"@associations",
"[",
"k",
"]",
"[",
"[",
"6",
",",
"false",
",",
"(",
"v",
"||",
"[",
"]",
")",
".",
"map",
"{",
"|",
"i",
"|",
"i",
".",
"is_a?",
"(",
"Base",
")",
"?",
"i",
".",
"id",
":",
"i",
"}",
"]",
"]",
"elsif",
"self",
".",
"class",
".",
"many2one_associations",
"[",
"k",
"]",
"v",
"=",
"@associations",
"[",
"k",
"]",
"# TODO support for nested",
"cast_m2o_association",
"(",
"v",
")",
"end",
"end"
] | talk OpenERP cryptic associations API | [
"talk",
"OpenERP",
"cryptic",
"associations",
"API"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/type_casting.rb#L163-L179 | train |
akretion/ooor | lib/ooor/base.rb | Ooor.Base.on_change | def on_change(on_change_method, field_name, field_value, *args)
# NOTE: OpenERP doesn't accept context systematically in on_change events unfortunately
ids = self.id ? [id] : []
result = self.class.object_service(:execute, self.class.openerp_model, on_change_method, ids, *args)
load_on_change_result(result, field_name, field_value)
end | ruby | def on_change(on_change_method, field_name, field_value, *args)
# NOTE: OpenERP doesn't accept context systematically in on_change events unfortunately
ids = self.id ? [id] : []
result = self.class.object_service(:execute, self.class.openerp_model, on_change_method, ids, *args)
load_on_change_result(result, field_name, field_value)
end | [
"def",
"on_change",
"(",
"on_change_method",
",",
"field_name",
",",
"field_value",
",",
"*",
"args",
")",
"# NOTE: OpenERP doesn't accept context systematically in on_change events unfortunately",
"ids",
"=",
"self",
".",
"id",
"?",
"[",
"id",
"]",
":",
"[",
"]",
"result",
"=",
"self",
".",
"class",
".",
"object_service",
"(",
":execute",
",",
"self",
".",
"class",
".",
"openerp_model",
",",
"on_change_method",
",",
"ids",
",",
"args",
")",
"load_on_change_result",
"(",
"result",
",",
"field_name",
",",
"field_value",
")",
"end"
] | Generic OpenERP on_change method | [
"Generic",
"OpenERP",
"on_change",
"method"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/base.rb#L100-L105 | train |
akretion/ooor | lib/ooor/base.rb | Ooor.Base.wkf_action | def wkf_action(action, context={}, reload=true)
self.class.object_service(:exec_workflow, self.class.openerp_model, action, self.id, context)
reload_fields if reload
end | ruby | def wkf_action(action, context={}, reload=true)
self.class.object_service(:exec_workflow, self.class.openerp_model, action, self.id, context)
reload_fields if reload
end | [
"def",
"wkf_action",
"(",
"action",
",",
"context",
"=",
"{",
"}",
",",
"reload",
"=",
"true",
")",
"self",
".",
"class",
".",
"object_service",
"(",
":exec_workflow",
",",
"self",
".",
"class",
".",
"openerp_model",
",",
"action",
",",
"self",
".",
"id",
",",
"context",
")",
"reload_fields",
"if",
"reload",
"end"
] | wrapper for OpenERP exec_workflow Business Process Management engine | [
"wrapper",
"for",
"OpenERP",
"exec_workflow",
"Business",
"Process",
"Management",
"engine"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/base.rb#L108-L111 | train |
akretion/ooor | lib/ooor/persistence.rb | Ooor.Persistence.load | def load(attributes)
self.class.reload_fields_definition(false)
raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
@associations ||= {}
@attributes ||= {}
@loaded_associations = {}
attributes.each do |key, value|
self.send "#{key}=", value if self.respond_to?("#{key}=")
end
self
end | ruby | def load(attributes)
self.class.reload_fields_definition(false)
raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
@associations ||= {}
@attributes ||= {}
@loaded_associations = {}
attributes.each do |key, value|
self.send "#{key}=", value if self.respond_to?("#{key}=")
end
self
end | [
"def",
"load",
"(",
"attributes",
")",
"self",
".",
"class",
".",
"reload_fields_definition",
"(",
"false",
")",
"raise",
"ArgumentError",
",",
"\"expected an attributes Hash, got #{attributes.inspect}\"",
"unless",
"attributes",
".",
"is_a?",
"(",
"Hash",
")",
"@associations",
"||=",
"{",
"}",
"@attributes",
"||=",
"{",
"}",
"@loaded_associations",
"=",
"{",
"}",
"attributes",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"self",
".",
"send",
"\"#{key}=\"",
",",
"value",
"if",
"self",
".",
"respond_to?",
"(",
"\"#{key}=\"",
")",
"end",
"self",
"end"
] | Flushes the current object and loads the +attributes+ Hash
containing the attributes and the associations into the current object | [
"Flushes",
"the",
"current",
"object",
"and",
"loads",
"the",
"+",
"attributes",
"+",
"Hash",
"containing",
"the",
"attributes",
"and",
"the",
"associations",
"into",
"the",
"current",
"object"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/persistence.rb#L86-L96 | train |
akretion/ooor | lib/ooor/persistence.rb | Ooor.Persistence.copy | def copy(defaults={}, context={})
self.class.find(rpc_execute('copy', id, defaults, context), context: context)
end | ruby | def copy(defaults={}, context={})
self.class.find(rpc_execute('copy', id, defaults, context), context: context)
end | [
"def",
"copy",
"(",
"defaults",
"=",
"{",
"}",
",",
"context",
"=",
"{",
"}",
")",
"self",
".",
"class",
".",
"find",
"(",
"rpc_execute",
"(",
"'copy'",
",",
"id",
",",
"defaults",
",",
"context",
")",
",",
"context",
":",
"context",
")",
"end"
] | OpenERP copy method, load persisted copied Object | [
"OpenERP",
"copy",
"method",
"load",
"persisted",
"copied",
"Object"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/persistence.rb#L225-L227 | train |
akretion/ooor | lib/ooor/persistence.rb | Ooor.Persistence.perform_validations | def perform_validations(options={}) # :nodoc:
if options.is_a?(Hash)
options[:validate] == false || valid?(options[:context])
else
valid?
end
end | ruby | def perform_validations(options={}) # :nodoc:
if options.is_a?(Hash)
options[:validate] == false || valid?(options[:context])
else
valid?
end
end | [
"def",
"perform_validations",
"(",
"options",
"=",
"{",
"}",
")",
"# :nodoc:",
"if",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"[",
":validate",
"]",
"==",
"false",
"||",
"valid?",
"(",
"options",
"[",
":context",
"]",
")",
"else",
"valid?",
"end",
"end"
] | Real validations happens on OpenERP side, only pre-validations can happen here eventually | [
"Real",
"validations",
"happens",
"on",
"OpenERP",
"side",
"only",
"pre",
"-",
"validations",
"can",
"happen",
"here",
"eventually"
] | f0aa6c70601cc28dbbb519ebec33af40f57b3943 | https://github.com/akretion/ooor/blob/f0aa6c70601cc28dbbb519ebec33af40f57b3943/lib/ooor/persistence.rb#L250-L256 | train |
rspec/rspec-activemodel-mocks | lib/rspec/active_model/mocks/mocks.rb | RSpec::ActiveModel::Mocks.Mocks.stub_model | def stub_model(model_class, stubs={})
model_class.new.tap do |m|
m.extend ActiveModelStubExtensions
if defined?(ActiveRecord) && model_class < ActiveRecord::Base && model_class.primary_key
m.extend ActiveRecordStubExtensions
primary_key = model_class.primary_key.to_sym
stubs = {primary_key => next_id}.merge(stubs)
stubs = {:persisted? => !!stubs[primary_key]}.merge(stubs)
else
stubs = {:id => next_id}.merge(stubs)
stubs = {:persisted? => !!stubs[:id]}.merge(stubs)
end
stubs = {:blank? => false}.merge(stubs)
stubs.each do |message, return_value|
if m.respond_to?("#{message}=")
m.__send__("#{message}=", return_value)
else
RSpec::Mocks.allow_message(m, message).and_return(return_value)
end
end
yield m if block_given?
end
end | ruby | def stub_model(model_class, stubs={})
model_class.new.tap do |m|
m.extend ActiveModelStubExtensions
if defined?(ActiveRecord) && model_class < ActiveRecord::Base && model_class.primary_key
m.extend ActiveRecordStubExtensions
primary_key = model_class.primary_key.to_sym
stubs = {primary_key => next_id}.merge(stubs)
stubs = {:persisted? => !!stubs[primary_key]}.merge(stubs)
else
stubs = {:id => next_id}.merge(stubs)
stubs = {:persisted? => !!stubs[:id]}.merge(stubs)
end
stubs = {:blank? => false}.merge(stubs)
stubs.each do |message, return_value|
if m.respond_to?("#{message}=")
m.__send__("#{message}=", return_value)
else
RSpec::Mocks.allow_message(m, message).and_return(return_value)
end
end
yield m if block_given?
end
end | [
"def",
"stub_model",
"(",
"model_class",
",",
"stubs",
"=",
"{",
"}",
")",
"model_class",
".",
"new",
".",
"tap",
"do",
"|",
"m",
"|",
"m",
".",
"extend",
"ActiveModelStubExtensions",
"if",
"defined?",
"(",
"ActiveRecord",
")",
"&&",
"model_class",
"<",
"ActiveRecord",
"::",
"Base",
"&&",
"model_class",
".",
"primary_key",
"m",
".",
"extend",
"ActiveRecordStubExtensions",
"primary_key",
"=",
"model_class",
".",
"primary_key",
".",
"to_sym",
"stubs",
"=",
"{",
"primary_key",
"=>",
"next_id",
"}",
".",
"merge",
"(",
"stubs",
")",
"stubs",
"=",
"{",
":persisted?",
"=>",
"!",
"!",
"stubs",
"[",
"primary_key",
"]",
"}",
".",
"merge",
"(",
"stubs",
")",
"else",
"stubs",
"=",
"{",
":id",
"=>",
"next_id",
"}",
".",
"merge",
"(",
"stubs",
")",
"stubs",
"=",
"{",
":persisted?",
"=>",
"!",
"!",
"stubs",
"[",
":id",
"]",
"}",
".",
"merge",
"(",
"stubs",
")",
"end",
"stubs",
"=",
"{",
":blank?",
"=>",
"false",
"}",
".",
"merge",
"(",
"stubs",
")",
"stubs",
".",
"each",
"do",
"|",
"message",
",",
"return_value",
"|",
"if",
"m",
".",
"respond_to?",
"(",
"\"#{message}=\"",
")",
"m",
".",
"__send__",
"(",
"\"#{message}=\"",
",",
"return_value",
")",
"else",
"RSpec",
"::",
"Mocks",
".",
"allow_message",
"(",
"m",
",",
"message",
")",
".",
"and_return",
"(",
"return_value",
")",
"end",
"end",
"yield",
"m",
"if",
"block_given?",
"end",
"end"
] | Creates an instance of `Model` with `to_param` stubbed using a
generated value that is unique to each object. If `Model` is an
`ActiveRecord` model, it is prohibited from accessing the database.
For each key in `stubs`, if the model has a matching attribute
(determined by `respond_to?`) it is simply assigned the submitted values.
If the model does not have a matching attribute, the key/value pair is
assigned as a stub return value using RSpec's mocking/stubbing
framework.
<tt>persisted?</tt> is overridden to return the result of !id.nil?
This means that by default persisted? will return true. If you want
the object to behave as a new record, sending it `as_new_record` will
set the id to nil. You can also explicitly set :id => nil, in which
case persisted? will return false, but using `as_new_record` makes the
example a bit more descriptive.
While you can use stub_model in any example (model, view, controller,
helper), it is especially useful in view examples, which are
inherently more state-based than interaction-based.
@example
stub_model(Person)
stub_model(Person).as_new_record
stub_model(Person, :to_param => 37)
stub_model(Person) {|person| person.first_name = "David"} | [
"Creates",
"an",
"instance",
"of",
"Model",
"with",
"to_param",
"stubbed",
"using",
"a",
"generated",
"value",
"that",
"is",
"unique",
"to",
"each",
"object",
".",
"If",
"Model",
"is",
"an",
"ActiveRecord",
"model",
"it",
"is",
"prohibited",
"from",
"accessing",
"the",
"database",
"."
] | 0338d50039cad672bbe695fff5591da1ba849308 | https://github.com/rspec/rspec-activemodel-mocks/blob/0338d50039cad672bbe695fff5591da1ba849308/lib/rspec/active_model/mocks/mocks.rb#L243-L267 | train |
tmm1/pygments.rb | lib/pygments/popen.rb | Pygments.Popen.stop | def stop(reason)
if @pid
begin
Process.kill('KILL', @pid)
Process.waitpid(@pid)
rescue Errno::ESRCH, Errno::ECHILD
end
end
@log.info "Killing pid: #{@pid.to_s}. Reason: #{reason}"
@pid = nil
end | ruby | def stop(reason)
if @pid
begin
Process.kill('KILL', @pid)
Process.waitpid(@pid)
rescue Errno::ESRCH, Errno::ECHILD
end
end
@log.info "Killing pid: #{@pid.to_s}. Reason: #{reason}"
@pid = nil
end | [
"def",
"stop",
"(",
"reason",
")",
"if",
"@pid",
"begin",
"Process",
".",
"kill",
"(",
"'KILL'",
",",
"@pid",
")",
"Process",
".",
"waitpid",
"(",
"@pid",
")",
"rescue",
"Errno",
"::",
"ESRCH",
",",
"Errno",
"::",
"ECHILD",
"end",
"end",
"@log",
".",
"info",
"\"Killing pid: #{@pid.to_s}. Reason: #{reason}\"",
"@pid",
"=",
"nil",
"end"
] | Stop the child process by issuing a kill -9.
We then call waitpid() with the pid, which waits for that particular
child and reaps it.
kill() can set errno to ESRCH if, for some reason, the file
is gone; regardless the final outcome of this method
will be to set our @pid variable to nil.
Technically, kill() can also fail with EPERM or EINVAL (wherein
the signal isn't sent); but we have permissions, and
we're not doing anything invalid here. | [
"Stop",
"the",
"child",
"process",
"by",
"issuing",
"a",
"kill",
"-",
"9",
"."
] | 926d1adad88c22f92010a0f284d2dcc10213ec1e | https://github.com/tmm1/pygments.rb/blob/926d1adad88c22f92010a0f284d2dcc10213ec1e/lib/pygments/popen.rb#L96-L106 | train |
tmm1/pygments.rb | lib/pygments/popen.rb | Pygments.Popen.mentos | def mentos(method, args=[], kwargs={}, original_code=nil)
# Open the pipe if necessary
start unless alive?
begin
# Timeout requests that take too long.
# Invalid MENTOS_TIMEOUT results in just using default.
timeout_time = Integer(ENV["MENTOS_TIMEOUT"]) rescue 8
Timeout::timeout(timeout_time) do
# For sanity checking on both sides of the pipe when highlighting, we prepend and
# append an id. mentos checks that these are 8 character ids and that they match.
# It then returns the id's back to Rubyland.
id = (0...8).map{65.+(rand(25)).chr}.join
code = add_ids(original_code, id) if original_code
# Add metadata to the header and generate it.
if code
bytesize = code.bytesize
else
bytesize = 0
end
kwargs.freeze
kwargs = kwargs.merge("fd" => @out.to_i, "id" => id, "bytes" => bytesize)
out_header = MultiJson.dump(:method => method, :args => args, :kwargs => kwargs)
# Get the size of the header itself and write that.
bits = get_fixed_bits_from_header(out_header)
@in.write(bits)
# mentos is now waiting for the header, and, potentially, code.
write_data(out_header, code)
check_for_error
# mentos will now return data to us. First it sends the header.
header = get_header
# Now handle the header, any read any more data required.
res = handle_header_and_return(header, id)
# Finally, return what we got.
return_result(res, method)
end
rescue Timeout::Error
# If we timeout, we need to clear out the pipe and start over.
@log.error "Timeout on a mentos #{method} call"
stop "Timeout on mentos #{method} call."
end
rescue Errno::EPIPE, EOFError
stop "EPIPE"
raise MentosError, "EPIPE"
end | ruby | def mentos(method, args=[], kwargs={}, original_code=nil)
# Open the pipe if necessary
start unless alive?
begin
# Timeout requests that take too long.
# Invalid MENTOS_TIMEOUT results in just using default.
timeout_time = Integer(ENV["MENTOS_TIMEOUT"]) rescue 8
Timeout::timeout(timeout_time) do
# For sanity checking on both sides of the pipe when highlighting, we prepend and
# append an id. mentos checks that these are 8 character ids and that they match.
# It then returns the id's back to Rubyland.
id = (0...8).map{65.+(rand(25)).chr}.join
code = add_ids(original_code, id) if original_code
# Add metadata to the header and generate it.
if code
bytesize = code.bytesize
else
bytesize = 0
end
kwargs.freeze
kwargs = kwargs.merge("fd" => @out.to_i, "id" => id, "bytes" => bytesize)
out_header = MultiJson.dump(:method => method, :args => args, :kwargs => kwargs)
# Get the size of the header itself and write that.
bits = get_fixed_bits_from_header(out_header)
@in.write(bits)
# mentos is now waiting for the header, and, potentially, code.
write_data(out_header, code)
check_for_error
# mentos will now return data to us. First it sends the header.
header = get_header
# Now handle the header, any read any more data required.
res = handle_header_and_return(header, id)
# Finally, return what we got.
return_result(res, method)
end
rescue Timeout::Error
# If we timeout, we need to clear out the pipe and start over.
@log.error "Timeout on a mentos #{method} call"
stop "Timeout on mentos #{method} call."
end
rescue Errno::EPIPE, EOFError
stop "EPIPE"
raise MentosError, "EPIPE"
end | [
"def",
"mentos",
"(",
"method",
",",
"args",
"=",
"[",
"]",
",",
"kwargs",
"=",
"{",
"}",
",",
"original_code",
"=",
"nil",
")",
"# Open the pipe if necessary",
"start",
"unless",
"alive?",
"begin",
"# Timeout requests that take too long.",
"# Invalid MENTOS_TIMEOUT results in just using default.",
"timeout_time",
"=",
"Integer",
"(",
"ENV",
"[",
"\"MENTOS_TIMEOUT\"",
"]",
")",
"rescue",
"8",
"Timeout",
"::",
"timeout",
"(",
"timeout_time",
")",
"do",
"# For sanity checking on both sides of the pipe when highlighting, we prepend and",
"# append an id. mentos checks that these are 8 character ids and that they match.",
"# It then returns the id's back to Rubyland.",
"id",
"=",
"(",
"0",
"...",
"8",
")",
".",
"map",
"{",
"65",
".",
"+",
"(",
"rand",
"(",
"25",
")",
")",
".",
"chr",
"}",
".",
"join",
"code",
"=",
"add_ids",
"(",
"original_code",
",",
"id",
")",
"if",
"original_code",
"# Add metadata to the header and generate it.",
"if",
"code",
"bytesize",
"=",
"code",
".",
"bytesize",
"else",
"bytesize",
"=",
"0",
"end",
"kwargs",
".",
"freeze",
"kwargs",
"=",
"kwargs",
".",
"merge",
"(",
"\"fd\"",
"=>",
"@out",
".",
"to_i",
",",
"\"id\"",
"=>",
"id",
",",
"\"bytes\"",
"=>",
"bytesize",
")",
"out_header",
"=",
"MultiJson",
".",
"dump",
"(",
":method",
"=>",
"method",
",",
":args",
"=>",
"args",
",",
":kwargs",
"=>",
"kwargs",
")",
"# Get the size of the header itself and write that.",
"bits",
"=",
"get_fixed_bits_from_header",
"(",
"out_header",
")",
"@in",
".",
"write",
"(",
"bits",
")",
"# mentos is now waiting for the header, and, potentially, code.",
"write_data",
"(",
"out_header",
",",
"code",
")",
"check_for_error",
"# mentos will now return data to us. First it sends the header.",
"header",
"=",
"get_header",
"# Now handle the header, any read any more data required.",
"res",
"=",
"handle_header_and_return",
"(",
"header",
",",
"id",
")",
"# Finally, return what we got.",
"return_result",
"(",
"res",
",",
"method",
")",
"end",
"rescue",
"Timeout",
"::",
"Error",
"# If we timeout, we need to clear out the pipe and start over.",
"@log",
".",
"error",
"\"Timeout on a mentos #{method} call\"",
"stop",
"\"Timeout on mentos #{method} call.\"",
"end",
"rescue",
"Errno",
"::",
"EPIPE",
",",
"EOFError",
"stop",
"\"EPIPE\"",
"raise",
"MentosError",
",",
"\"EPIPE\"",
"end"
] | Our 'rpc'-ish request to mentos. Requires a method name, and then optional
args, kwargs, code. | [
"Our",
"rpc",
"-",
"ish",
"request",
"to",
"mentos",
".",
"Requires",
"a",
"method",
"name",
"and",
"then",
"optional",
"args",
"kwargs",
"code",
"."
] | 926d1adad88c22f92010a0f284d2dcc10213ec1e | https://github.com/tmm1/pygments.rb/blob/926d1adad88c22f92010a0f284d2dcc10213ec1e/lib/pygments/popen.rb#L245-L299 | train |
tmm1/pygments.rb | lib/pygments/popen.rb | Pygments.Popen.handle_header_and_return | def handle_header_and_return(header, id)
if header
header = header_to_json(header)
bytes = header[:bytes]
# Read more bytes (the actual response body)
res = @out.read(bytes.to_i)
if header[:method] == "highlight"
# Make sure we have a result back; else consider this an error.
if res.nil?
@log.warn "No highlight result back from mentos."
stop "No highlight result back from mentos."
raise MentosError, "No highlight result back from mentos."
end
# Remove the newline from Python
res = res[0..-2]
@log.info "Highlight in process."
# Get the id's
start_id = res[0..7]
end_id = res[-8..-1]
# Sanity check.
if not (start_id == id and end_id == id)
@log.error "ID's did not match. Aborting."
stop "ID's did not match. Aborting."
raise MentosError, "ID's did not match. Aborting."
else
# We're good. Remove the padding
res = res[10..-11]
@log.info "Highlighting complete."
res
end
end
res
else
@log.error "No header data back."
stop "No header data back."
raise MentosError, "No header received back."
end
end | ruby | def handle_header_and_return(header, id)
if header
header = header_to_json(header)
bytes = header[:bytes]
# Read more bytes (the actual response body)
res = @out.read(bytes.to_i)
if header[:method] == "highlight"
# Make sure we have a result back; else consider this an error.
if res.nil?
@log.warn "No highlight result back from mentos."
stop "No highlight result back from mentos."
raise MentosError, "No highlight result back from mentos."
end
# Remove the newline from Python
res = res[0..-2]
@log.info "Highlight in process."
# Get the id's
start_id = res[0..7]
end_id = res[-8..-1]
# Sanity check.
if not (start_id == id and end_id == id)
@log.error "ID's did not match. Aborting."
stop "ID's did not match. Aborting."
raise MentosError, "ID's did not match. Aborting."
else
# We're good. Remove the padding
res = res[10..-11]
@log.info "Highlighting complete."
res
end
end
res
else
@log.error "No header data back."
stop "No header data back."
raise MentosError, "No header received back."
end
end | [
"def",
"handle_header_and_return",
"(",
"header",
",",
"id",
")",
"if",
"header",
"header",
"=",
"header_to_json",
"(",
"header",
")",
"bytes",
"=",
"header",
"[",
":bytes",
"]",
"# Read more bytes (the actual response body)",
"res",
"=",
"@out",
".",
"read",
"(",
"bytes",
".",
"to_i",
")",
"if",
"header",
"[",
":method",
"]",
"==",
"\"highlight\"",
"# Make sure we have a result back; else consider this an error.",
"if",
"res",
".",
"nil?",
"@log",
".",
"warn",
"\"No highlight result back from mentos.\"",
"stop",
"\"No highlight result back from mentos.\"",
"raise",
"MentosError",
",",
"\"No highlight result back from mentos.\"",
"end",
"# Remove the newline from Python",
"res",
"=",
"res",
"[",
"0",
"..",
"-",
"2",
"]",
"@log",
".",
"info",
"\"Highlight in process.\"",
"# Get the id's",
"start_id",
"=",
"res",
"[",
"0",
"..",
"7",
"]",
"end_id",
"=",
"res",
"[",
"-",
"8",
"..",
"-",
"1",
"]",
"# Sanity check.",
"if",
"not",
"(",
"start_id",
"==",
"id",
"and",
"end_id",
"==",
"id",
")",
"@log",
".",
"error",
"\"ID's did not match. Aborting.\"",
"stop",
"\"ID's did not match. Aborting.\"",
"raise",
"MentosError",
",",
"\"ID's did not match. Aborting.\"",
"else",
"# We're good. Remove the padding",
"res",
"=",
"res",
"[",
"10",
"..",
"-",
"11",
"]",
"@log",
".",
"info",
"\"Highlighting complete.\"",
"res",
"end",
"end",
"res",
"else",
"@log",
".",
"error",
"\"No header data back.\"",
"stop",
"\"No header data back.\"",
"raise",
"MentosError",
",",
"\"No header received back.\"",
"end",
"end"
] | Based on the header we receive, determine if we need
to read more bytes, and read those bytes if necessary.
Then, do a sanity check with the ids.
Returns a result — either highlighted text or metadata. | [
"Based",
"on",
"the",
"header",
"we",
"receive",
"determine",
"if",
"we",
"need",
"to",
"read",
"more",
"bytes",
"and",
"read",
"those",
"bytes",
"if",
"necessary",
"."
] | 926d1adad88c22f92010a0f284d2dcc10213ec1e | https://github.com/tmm1/pygments.rb/blob/926d1adad88c22f92010a0f284d2dcc10213ec1e/lib/pygments/popen.rb#L327-L369 | train |
tmm1/pygments.rb | lib/pygments/popen.rb | Pygments.Popen.get_header | def get_header
begin
size = @out.read(33)
size = size[0..-2]
# Sanity check the size
if not size_check(size)
@log.error "Size returned from mentos.py invalid."
stop "Size returned from mentos.py invalid."
raise MentosError, "Size returned from mentos.py invalid."
end
# Read the amount of bytes we should be expecting. We first
# convert the string of bits into an integer.
header_bytes = size.to_s.to_i(2) + 1
@log.info "Size in: #{size.to_s} (#{header_bytes.to_s})"
@out.read(header_bytes)
rescue
@log.error "Failed to get header."
stop "Failed to get header."
raise MentosError, "Failed to get header."
end
end | ruby | def get_header
begin
size = @out.read(33)
size = size[0..-2]
# Sanity check the size
if not size_check(size)
@log.error "Size returned from mentos.py invalid."
stop "Size returned from mentos.py invalid."
raise MentosError, "Size returned from mentos.py invalid."
end
# Read the amount of bytes we should be expecting. We first
# convert the string of bits into an integer.
header_bytes = size.to_s.to_i(2) + 1
@log.info "Size in: #{size.to_s} (#{header_bytes.to_s})"
@out.read(header_bytes)
rescue
@log.error "Failed to get header."
stop "Failed to get header."
raise MentosError, "Failed to get header."
end
end | [
"def",
"get_header",
"begin",
"size",
"=",
"@out",
".",
"read",
"(",
"33",
")",
"size",
"=",
"size",
"[",
"0",
"..",
"-",
"2",
"]",
"# Sanity check the size",
"if",
"not",
"size_check",
"(",
"size",
")",
"@log",
".",
"error",
"\"Size returned from mentos.py invalid.\"",
"stop",
"\"Size returned from mentos.py invalid.\"",
"raise",
"MentosError",
",",
"\"Size returned from mentos.py invalid.\"",
"end",
"# Read the amount of bytes we should be expecting. We first",
"# convert the string of bits into an integer.",
"header_bytes",
"=",
"size",
".",
"to_s",
".",
"to_i",
"(",
"2",
")",
"+",
"1",
"@log",
".",
"info",
"\"Size in: #{size.to_s} (#{header_bytes.to_s})\"",
"@out",
".",
"read",
"(",
"header_bytes",
")",
"rescue",
"@log",
".",
"error",
"\"Failed to get header.\"",
"stop",
"\"Failed to get header.\"",
"raise",
"MentosError",
",",
"\"Failed to get header.\"",
"end",
"end"
] | Read the header via the pipe.
Returns a header. | [
"Read",
"the",
"header",
"via",
"the",
"pipe",
"."
] | 926d1adad88c22f92010a0f284d2dcc10213ec1e | https://github.com/tmm1/pygments.rb/blob/926d1adad88c22f92010a0f284d2dcc10213ec1e/lib/pygments/popen.rb#L401-L423 | train |
tmm1/pygments.rb | lib/pygments/popen.rb | Pygments.Popen.return_result | def return_result(res, method)
unless method == :lexer_name_for || method == :highlight || method == :css
res = MultiJson.load(res, :symbolize_keys => true)
end
res = res.rstrip if res.class == String
res
end | ruby | def return_result(res, method)
unless method == :lexer_name_for || method == :highlight || method == :css
res = MultiJson.load(res, :symbolize_keys => true)
end
res = res.rstrip if res.class == String
res
end | [
"def",
"return_result",
"(",
"res",
",",
"method",
")",
"unless",
"method",
"==",
":lexer_name_for",
"||",
"method",
"==",
":highlight",
"||",
"method",
"==",
":css",
"res",
"=",
"MultiJson",
".",
"load",
"(",
"res",
",",
":symbolize_keys",
"=>",
"true",
")",
"end",
"res",
"=",
"res",
".",
"rstrip",
"if",
"res",
".",
"class",
"==",
"String",
"res",
"end"
] | Return the final result for the API. Return Ruby objects for the methods that
want them, text otherwise. | [
"Return",
"the",
"final",
"result",
"for",
"the",
"API",
".",
"Return",
"Ruby",
"objects",
"for",
"the",
"methods",
"that",
"want",
"them",
"text",
"otherwise",
"."
] | 926d1adad88c22f92010a0f284d2dcc10213ec1e | https://github.com/tmm1/pygments.rb/blob/926d1adad88c22f92010a0f284d2dcc10213ec1e/lib/pygments/popen.rb#L427-L433 | train |
tmm1/pygments.rb | lib/pygments/popen.rb | Pygments.Popen.header_to_json | def header_to_json(header)
@log.info "[In header: #{header} "
header = MultiJson.load(header, :symbolize_keys => true)
if header[:error]
# Raise this as a Ruby exception of the MentosError class.
# Stop so we don't leave the pipe in an inconsistent state.
@log.error "Failed to convert header to JSON."
stop header[:error]
raise MentosError, header[:error]
else
header
end
end | ruby | def header_to_json(header)
@log.info "[In header: #{header} "
header = MultiJson.load(header, :symbolize_keys => true)
if header[:error]
# Raise this as a Ruby exception of the MentosError class.
# Stop so we don't leave the pipe in an inconsistent state.
@log.error "Failed to convert header to JSON."
stop header[:error]
raise MentosError, header[:error]
else
header
end
end | [
"def",
"header_to_json",
"(",
"header",
")",
"@log",
".",
"info",
"\"[In header: #{header} \"",
"header",
"=",
"MultiJson",
".",
"load",
"(",
"header",
",",
":symbolize_keys",
"=>",
"true",
")",
"if",
"header",
"[",
":error",
"]",
"# Raise this as a Ruby exception of the MentosError class.",
"# Stop so we don't leave the pipe in an inconsistent state.",
"@log",
".",
"error",
"\"Failed to convert header to JSON.\"",
"stop",
"header",
"[",
":error",
"]",
"raise",
"MentosError",
",",
"header",
"[",
":error",
"]",
"else",
"header",
"end",
"end"
] | Convert a text header into JSON for easy access. | [
"Convert",
"a",
"text",
"header",
"into",
"JSON",
"for",
"easy",
"access",
"."
] | 926d1adad88c22f92010a0f284d2dcc10213ec1e | https://github.com/tmm1/pygments.rb/blob/926d1adad88c22f92010a0f284d2dcc10213ec1e/lib/pygments/popen.rb#L436-L449 | train |
pboling/flag_shih_tzu | lib/flag_shih_tzu.rb | FlagShihTzu.ClassMethods.sql_in_for_flag | def sql_in_for_flag(flag, colmn)
val = flag_mapping[colmn][flag]
flag_value_range_for_column(colmn).select { |bits| bits & val == val }
end | ruby | def sql_in_for_flag(flag, colmn)
val = flag_mapping[colmn][flag]
flag_value_range_for_column(colmn).select { |bits| bits & val == val }
end | [
"def",
"sql_in_for_flag",
"(",
"flag",
",",
"colmn",
")",
"val",
"=",
"flag_mapping",
"[",
"colmn",
"]",
"[",
"flag",
"]",
"flag_value_range_for_column",
"(",
"colmn",
")",
".",
"select",
"{",
"|",
"bits",
"|",
"bits",
"&",
"val",
"==",
"val",
"}",
"end"
] | returns an array of integers suitable for a SQL IN statement. | [
"returns",
"an",
"array",
"of",
"integers",
"suitable",
"for",
"a",
"SQL",
"IN",
"statement",
"."
] | 07a5b8b817d456d1a663581d4bbce37834a1795c | https://github.com/pboling/flag_shih_tzu/blob/07a5b8b817d456d1a663581d4bbce37834a1795c/lib/flag_shih_tzu.rb#L429-L432 | train |
Dynflow/dynflow | lib/dynflow/action/format.rb | Dynflow.Action::Format.input_format | def input_format(&block)
case
when block && !@input_format_block
@input_format_block = block
when !block && @input_format_block
return @input_format ||= Apipie::Params::Description.define(&@input_format_block)
when block && @input_format_block
raise "The input_format has already been defined in #{self.class}"
when !block && !@input_format_block
if superclass.respond_to? :input_format
superclass.input_format
else
raise "The input_format has not been defined yet in #{self.class}"
end
end
end | ruby | def input_format(&block)
case
when block && !@input_format_block
@input_format_block = block
when !block && @input_format_block
return @input_format ||= Apipie::Params::Description.define(&@input_format_block)
when block && @input_format_block
raise "The input_format has already been defined in #{self.class}"
when !block && !@input_format_block
if superclass.respond_to? :input_format
superclass.input_format
else
raise "The input_format has not been defined yet in #{self.class}"
end
end
end | [
"def",
"input_format",
"(",
"&",
"block",
")",
"case",
"when",
"block",
"&&",
"!",
"@input_format_block",
"@input_format_block",
"=",
"block",
"when",
"!",
"block",
"&&",
"@input_format_block",
"return",
"@input_format",
"||=",
"Apipie",
"::",
"Params",
"::",
"Description",
".",
"define",
"(",
"@input_format_block",
")",
"when",
"block",
"&&",
"@input_format_block",
"raise",
"\"The input_format has already been defined in #{self.class}\"",
"when",
"!",
"block",
"&&",
"!",
"@input_format_block",
"if",
"superclass",
".",
"respond_to?",
":input_format",
"superclass",
".",
"input_format",
"else",
"raise",
"\"The input_format has not been defined yet in #{self.class}\"",
"end",
"end",
"end"
] | we don't evaluate tbe block immediatelly, but postpone it till all the
action classes are loaded, because we can use them to reference output format | [
"we",
"don",
"t",
"evaluate",
"tbe",
"block",
"immediatelly",
"but",
"postpone",
"it",
"till",
"all",
"the",
"action",
"classes",
"are",
"loaded",
"because",
"we",
"can",
"use",
"them",
"to",
"reference",
"output",
"format"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/action/format.rb#L10-L25 | train |
Dynflow/dynflow | lib/dynflow/serializable.rb | Dynflow.Serializable.recursive_to_hash | def recursive_to_hash(*values)
if values.size == 1
value = values.first
case value
when String, Numeric, Symbol, TrueClass, FalseClass, NilClass, Time
value
when Hash
value.inject({}) { |h, (k, v)| h.update k => recursive_to_hash(v) }
when Array
value.map { |v| recursive_to_hash v }
else
value.to_hash
end
else
values.all? { |v| Type! v, Hash, NilClass }
recursive_to_hash(values.compact.reduce { |h, v| h.merge v })
end
end | ruby | def recursive_to_hash(*values)
if values.size == 1
value = values.first
case value
when String, Numeric, Symbol, TrueClass, FalseClass, NilClass, Time
value
when Hash
value.inject({}) { |h, (k, v)| h.update k => recursive_to_hash(v) }
when Array
value.map { |v| recursive_to_hash v }
else
value.to_hash
end
else
values.all? { |v| Type! v, Hash, NilClass }
recursive_to_hash(values.compact.reduce { |h, v| h.merge v })
end
end | [
"def",
"recursive_to_hash",
"(",
"*",
"values",
")",
"if",
"values",
".",
"size",
"==",
"1",
"value",
"=",
"values",
".",
"first",
"case",
"value",
"when",
"String",
",",
"Numeric",
",",
"Symbol",
",",
"TrueClass",
",",
"FalseClass",
",",
"NilClass",
",",
"Time",
"value",
"when",
"Hash",
"value",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"h",
".",
"update",
"k",
"=>",
"recursive_to_hash",
"(",
"v",
")",
"}",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"recursive_to_hash",
"v",
"}",
"else",
"value",
".",
"to_hash",
"end",
"else",
"values",
".",
"all?",
"{",
"|",
"v",
"|",
"Type!",
"v",
",",
"Hash",
",",
"NilClass",
"}",
"recursive_to_hash",
"(",
"values",
".",
"compact",
".",
"reduce",
"{",
"|",
"h",
",",
"v",
"|",
"h",
".",
"merge",
"v",
"}",
")",
"end",
"end"
] | recursively traverses hash-array structure and converts all to hashes
accepts more hashes which are then merged | [
"recursively",
"traverses",
"hash",
"-",
"array",
"structure",
"and",
"converts",
"all",
"to",
"hashes",
"accepts",
"more",
"hashes",
"which",
"are",
"then",
"merged"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/serializable.rb#L39-L56 | train |
Dynflow/dynflow | lib/dynflow/action/with_sub_plans.rb | Dynflow.Action::WithSubPlans.trigger | def trigger(action_class, *args)
if uses_concurrency_control
trigger_with_concurrency_control(action_class, *args)
else
world.trigger { world.plan_with_options(action_class: action_class, args: args, caller_action: self) }
end
end | ruby | def trigger(action_class, *args)
if uses_concurrency_control
trigger_with_concurrency_control(action_class, *args)
else
world.trigger { world.plan_with_options(action_class: action_class, args: args, caller_action: self) }
end
end | [
"def",
"trigger",
"(",
"action_class",
",",
"*",
"args",
")",
"if",
"uses_concurrency_control",
"trigger_with_concurrency_control",
"(",
"action_class",
",",
"args",
")",
"else",
"world",
".",
"trigger",
"{",
"world",
".",
"plan_with_options",
"(",
"action_class",
":",
"action_class",
",",
"args",
":",
"args",
",",
"caller_action",
":",
"self",
")",
"}",
"end",
"end"
] | Helper for creating sub plans | [
"Helper",
"for",
"creating",
"sub",
"plans"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/action/with_sub_plans.rb#L79-L85 | train |
Dynflow/dynflow | lib/dynflow/action/with_bulk_sub_plans.rb | Dynflow.Action::WithBulkSubPlans.current_batch | def current_batch
start_position = output[:planned_count]
size = start_position + batch_size > total_count ? total_count - start_position : batch_size
batch(start_position, size)
end | ruby | def current_batch
start_position = output[:planned_count]
size = start_position + batch_size > total_count ? total_count - start_position : batch_size
batch(start_position, size)
end | [
"def",
"current_batch",
"start_position",
"=",
"output",
"[",
":planned_count",
"]",
"size",
"=",
"start_position",
"+",
"batch_size",
">",
"total_count",
"?",
"total_count",
"-",
"start_position",
":",
"batch_size",
"batch",
"(",
"start_position",
",",
"size",
")",
"end"
] | Returns the items in the current batch | [
"Returns",
"the",
"items",
"in",
"the",
"current",
"batch"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/action/with_bulk_sub_plans.rb#L49-L53 | train |
Dynflow/dynflow | lib/dynflow/execution_plan/dependency_graph.rb | Dynflow.ExecutionPlan::DependencyGraph.add_dependencies | def add_dependencies(step, action)
action.required_step_ids.each do |required_step_id|
@graph[step.id] << required_step_id
end
end | ruby | def add_dependencies(step, action)
action.required_step_ids.each do |required_step_id|
@graph[step.id] << required_step_id
end
end | [
"def",
"add_dependencies",
"(",
"step",
",",
"action",
")",
"action",
".",
"required_step_ids",
".",
"each",
"do",
"|",
"required_step_id",
"|",
"@graph",
"[",
"step",
".",
"id",
"]",
"<<",
"required_step_id",
"end",
"end"
] | adds dependencies to graph that +step+ has based
on the steps referenced in its +input+ | [
"adds",
"dependencies",
"to",
"graph",
"that",
"+",
"step",
"+",
"has",
"based",
"on",
"the",
"steps",
"referenced",
"in",
"its",
"+",
"input",
"+"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/execution_plan/dependency_graph.rb#L10-L14 | train |
Dynflow/dynflow | lib/dynflow/world.rb | Dynflow.World.reload! | def reload!
# TODO what happens with newly loaded classes
@action_classes = @action_classes.map do |klass|
begin
Utils.constantize(klass.to_s)
rescue NameError
nil # ignore missing classes
end
end.compact
middleware.clear_cache!
calculate_subscription_index
end | ruby | def reload!
# TODO what happens with newly loaded classes
@action_classes = @action_classes.map do |klass|
begin
Utils.constantize(klass.to_s)
rescue NameError
nil # ignore missing classes
end
end.compact
middleware.clear_cache!
calculate_subscription_index
end | [
"def",
"reload!",
"# TODO what happens with newly loaded classes",
"@action_classes",
"=",
"@action_classes",
".",
"map",
"do",
"|",
"klass",
"|",
"begin",
"Utils",
".",
"constantize",
"(",
"klass",
".",
"to_s",
")",
"rescue",
"NameError",
"nil",
"# ignore missing classes",
"end",
"end",
".",
"compact",
"middleware",
".",
"clear_cache!",
"calculate_subscription_index",
"end"
] | reload actions classes, intended only for devel | [
"reload",
"actions",
"classes",
"intended",
"only",
"for",
"devel"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/world.rb#L117-L128 | train |
Dynflow/dynflow | lib/dynflow/action/rescue.rb | Dynflow.Action::Rescue.rescue_strategy | def rescue_strategy
suggested_strategies = []
if self.steps.compact.any? { |step| step.state == :error }
suggested_strategies << SuggestedStrategy[self, rescue_strategy_for_self]
end
self.planned_actions.each do |planned_action|
rescue_strategy = rescue_strategy_for_planned_action(planned_action)
next unless rescue_strategy # ignore actions that have no say in the rescue strategy
suggested_strategies << SuggestedStrategy[planned_action, rescue_strategy]
end
combine_suggested_strategies(suggested_strategies)
end | ruby | def rescue_strategy
suggested_strategies = []
if self.steps.compact.any? { |step| step.state == :error }
suggested_strategies << SuggestedStrategy[self, rescue_strategy_for_self]
end
self.planned_actions.each do |planned_action|
rescue_strategy = rescue_strategy_for_planned_action(planned_action)
next unless rescue_strategy # ignore actions that have no say in the rescue strategy
suggested_strategies << SuggestedStrategy[planned_action, rescue_strategy]
end
combine_suggested_strategies(suggested_strategies)
end | [
"def",
"rescue_strategy",
"suggested_strategies",
"=",
"[",
"]",
"if",
"self",
".",
"steps",
".",
"compact",
".",
"any?",
"{",
"|",
"step",
"|",
"step",
".",
"state",
"==",
":error",
"}",
"suggested_strategies",
"<<",
"SuggestedStrategy",
"[",
"self",
",",
"rescue_strategy_for_self",
"]",
"end",
"self",
".",
"planned_actions",
".",
"each",
"do",
"|",
"planned_action",
"|",
"rescue_strategy",
"=",
"rescue_strategy_for_planned_action",
"(",
"planned_action",
")",
"next",
"unless",
"rescue_strategy",
"# ignore actions that have no say in the rescue strategy",
"suggested_strategies",
"<<",
"SuggestedStrategy",
"[",
"planned_action",
",",
"rescue_strategy",
"]",
"end",
"combine_suggested_strategies",
"(",
"suggested_strategies",
")",
"end"
] | What strategy should be used for rescuing from error in
the action or its sub actions
@return Strategy
When determining the strategy, the algorithm starts from the
entry action that by default takes the strategy from #rescue_strategy_for_self
and #rescue_strategy_for_planned_actions and combines them together. | [
"What",
"strategy",
"should",
"be",
"used",
"for",
"rescuing",
"from",
"error",
"in",
"the",
"action",
"or",
"its",
"sub",
"actions"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/action/rescue.rb#L21-L35 | train |
Dynflow/dynflow | lib/dynflow/action/rescue.rb | Dynflow.Action::Rescue.combine_suggested_strategies | def combine_suggested_strategies(suggested_strategies)
if suggested_strategies.empty?
nil
else
# TODO: Find the safest rescue strategy among the suggested ones
if suggested_strategies.all? { |suggested_strategy| suggested_strategy.strategy == Skip }
return Skip
elsif suggested_strategies.all? { |suggested_strategy| suggested_strategy.strategy == Fail }
return Fail
else
return Pause # We don't know how to handle this case, so we'll just pause
end
end
end | ruby | def combine_suggested_strategies(suggested_strategies)
if suggested_strategies.empty?
nil
else
# TODO: Find the safest rescue strategy among the suggested ones
if suggested_strategies.all? { |suggested_strategy| suggested_strategy.strategy == Skip }
return Skip
elsif suggested_strategies.all? { |suggested_strategy| suggested_strategy.strategy == Fail }
return Fail
else
return Pause # We don't know how to handle this case, so we'll just pause
end
end
end | [
"def",
"combine_suggested_strategies",
"(",
"suggested_strategies",
")",
"if",
"suggested_strategies",
".",
"empty?",
"nil",
"else",
"# TODO: Find the safest rescue strategy among the suggested ones",
"if",
"suggested_strategies",
".",
"all?",
"{",
"|",
"suggested_strategy",
"|",
"suggested_strategy",
".",
"strategy",
"==",
"Skip",
"}",
"return",
"Skip",
"elsif",
"suggested_strategies",
".",
"all?",
"{",
"|",
"suggested_strategy",
"|",
"suggested_strategy",
".",
"strategy",
"==",
"Fail",
"}",
"return",
"Fail",
"else",
"return",
"Pause",
"# We don't know how to handle this case, so we'll just pause",
"end",
"end",
"end"
] | Override when different approach should be taken for combining
the suggested strategies | [
"Override",
"when",
"different",
"approach",
"should",
"be",
"taken",
"for",
"combining",
"the",
"suggested",
"strategies"
] | b52b2a91e36e34f8736200afa7a3fe5e1c94a020 | https://github.com/Dynflow/dynflow/blob/b52b2a91e36e34f8736200afa7a3fe5e1c94a020/lib/dynflow/action/rescue.rb#L51-L64 | train |
theodi/csvlint.rb | lib/csvlint/error_collector.rb | Csvlint.ErrorCollector.build_errors | def build_errors(type, category = nil, row = nil, column = nil, content = nil, constraints = {})
@errors << Csvlint::ErrorMessage.new(type, category, row, column, content, constraints)
end | ruby | def build_errors(type, category = nil, row = nil, column = nil, content = nil, constraints = {})
@errors << Csvlint::ErrorMessage.new(type, category, row, column, content, constraints)
end | [
"def",
"build_errors",
"(",
"type",
",",
"category",
"=",
"nil",
",",
"row",
"=",
"nil",
",",
"column",
"=",
"nil",
",",
"content",
"=",
"nil",
",",
"constraints",
"=",
"{",
"}",
")",
"@errors",
"<<",
"Csvlint",
"::",
"ErrorMessage",
".",
"new",
"(",
"type",
",",
"category",
",",
"row",
",",
"column",
",",
"content",
",",
"constraints",
")",
"end"
] | Creates a validation error | [
"Creates",
"a",
"validation",
"error"
] | e11a4de001d18a1de1a692a9690f7a66b1430bfb | https://github.com/theodi/csvlint.rb/blob/e11a4de001d18a1de1a692a9690f7a66b1430bfb/lib/csvlint/error_collector.rb#L5-L7 | train |
theodi/csvlint.rb | lib/csvlint/validate.rb | Csvlint.Validator.parse_contents | def parse_contents(stream, line = nil)
# parse_contents will parse one line and apply headers, formats methods and error handle as appropriate
current_line = line.present? ? line : 1
all_errors = []
@csv_options[:encoding] = @encoding
begin
row = LineCSV.parse_line(stream, @csv_options)
rescue LineCSV::MalformedCSVError => e
build_exception_messages(e, stream, current_line)
end
if row
if current_line <= 1 && @csv_header
# this conditional should be refactored somewhere
row = row.reject { |col| col.nil? || col.empty? }
validate_header(row)
@col_counts << row.size
else
build_formats(row)
@col_counts << row.reject { |col| col.nil? || col.empty? }.size
@expected_columns = row.size unless @expected_columns != 0
build_errors(:blank_rows, :structure, current_line, nil, stream.to_s) if row.reject { |c| c.nil? || c.empty? }.size == 0
# Builds errors and warnings related to the provided schema file
if @schema
@schema.validate_row(row, current_line, all_errors, @source, @validate)
@errors += @schema.errors
all_errors += @schema.errors
@warnings += @schema.warnings
else
build_errors(:ragged_rows, :structure, current_line, nil, stream.to_s) if !row.empty? && row.size != @expected_columns
end
end
end
@data << row
end | ruby | def parse_contents(stream, line = nil)
# parse_contents will parse one line and apply headers, formats methods and error handle as appropriate
current_line = line.present? ? line : 1
all_errors = []
@csv_options[:encoding] = @encoding
begin
row = LineCSV.parse_line(stream, @csv_options)
rescue LineCSV::MalformedCSVError => e
build_exception_messages(e, stream, current_line)
end
if row
if current_line <= 1 && @csv_header
# this conditional should be refactored somewhere
row = row.reject { |col| col.nil? || col.empty? }
validate_header(row)
@col_counts << row.size
else
build_formats(row)
@col_counts << row.reject { |col| col.nil? || col.empty? }.size
@expected_columns = row.size unless @expected_columns != 0
build_errors(:blank_rows, :structure, current_line, nil, stream.to_s) if row.reject { |c| c.nil? || c.empty? }.size == 0
# Builds errors and warnings related to the provided schema file
if @schema
@schema.validate_row(row, current_line, all_errors, @source, @validate)
@errors += @schema.errors
all_errors += @schema.errors
@warnings += @schema.warnings
else
build_errors(:ragged_rows, :structure, current_line, nil, stream.to_s) if !row.empty? && row.size != @expected_columns
end
end
end
@data << row
end | [
"def",
"parse_contents",
"(",
"stream",
",",
"line",
"=",
"nil",
")",
"# parse_contents will parse one line and apply headers, formats methods and error handle as appropriate",
"current_line",
"=",
"line",
".",
"present?",
"?",
"line",
":",
"1",
"all_errors",
"=",
"[",
"]",
"@csv_options",
"[",
":encoding",
"]",
"=",
"@encoding",
"begin",
"row",
"=",
"LineCSV",
".",
"parse_line",
"(",
"stream",
",",
"@csv_options",
")",
"rescue",
"LineCSV",
"::",
"MalformedCSVError",
"=>",
"e",
"build_exception_messages",
"(",
"e",
",",
"stream",
",",
"current_line",
")",
"end",
"if",
"row",
"if",
"current_line",
"<=",
"1",
"&&",
"@csv_header",
"# this conditional should be refactored somewhere",
"row",
"=",
"row",
".",
"reject",
"{",
"|",
"col",
"|",
"col",
".",
"nil?",
"||",
"col",
".",
"empty?",
"}",
"validate_header",
"(",
"row",
")",
"@col_counts",
"<<",
"row",
".",
"size",
"else",
"build_formats",
"(",
"row",
")",
"@col_counts",
"<<",
"row",
".",
"reject",
"{",
"|",
"col",
"|",
"col",
".",
"nil?",
"||",
"col",
".",
"empty?",
"}",
".",
"size",
"@expected_columns",
"=",
"row",
".",
"size",
"unless",
"@expected_columns",
"!=",
"0",
"build_errors",
"(",
":blank_rows",
",",
":structure",
",",
"current_line",
",",
"nil",
",",
"stream",
".",
"to_s",
")",
"if",
"row",
".",
"reject",
"{",
"|",
"c",
"|",
"c",
".",
"nil?",
"||",
"c",
".",
"empty?",
"}",
".",
"size",
"==",
"0",
"# Builds errors and warnings related to the provided schema file",
"if",
"@schema",
"@schema",
".",
"validate_row",
"(",
"row",
",",
"current_line",
",",
"all_errors",
",",
"@source",
",",
"@validate",
")",
"@errors",
"+=",
"@schema",
".",
"errors",
"all_errors",
"+=",
"@schema",
".",
"errors",
"@warnings",
"+=",
"@schema",
".",
"warnings",
"else",
"build_errors",
"(",
":ragged_rows",
",",
":structure",
",",
"current_line",
",",
"nil",
",",
"stream",
".",
"to_s",
")",
"if",
"!",
"row",
".",
"empty?",
"&&",
"row",
".",
"size",
"!=",
"@expected_columns",
"end",
"end",
"end",
"@data",
"<<",
"row",
"end"
] | analyses the provided csv and builds errors, warnings and info messages | [
"analyses",
"the",
"provided",
"csv",
"and",
"builds",
"errors",
"warnings",
"and",
"info",
"messages"
] | e11a4de001d18a1de1a692a9690f7a66b1430bfb | https://github.com/theodi/csvlint.rb/blob/e11a4de001d18a1de1a692a9690f7a66b1430bfb/lib/csvlint/validate.rb#L174-L210 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.create_order_reference_for_id | def create_order_reference_for_id(
id,
id_type,
inherit_shipping_address: nil,
confirm_now: nil,
amount: nil,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
store_name: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CreateOrderReferenceForId',
'SellerId' => merchant_id,
'Id' => id,
'IdType' => id_type
}
optional = {
'InheritShippingAddress' => inherit_shipping_address,
'ConfirmNow' => confirm_now,
'OrderReferenceAttributes.OrderTotal.Amount' => amount,
'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code,
'OrderReferenceAttributes.PlatformId' => platform_id,
'OrderReferenceAttributes.SellerNote' => seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def create_order_reference_for_id(
id,
id_type,
inherit_shipping_address: nil,
confirm_now: nil,
amount: nil,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
store_name: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CreateOrderReferenceForId',
'SellerId' => merchant_id,
'Id' => id,
'IdType' => id_type
}
optional = {
'InheritShippingAddress' => inherit_shipping_address,
'ConfirmNow' => confirm_now,
'OrderReferenceAttributes.OrderTotal.Amount' => amount,
'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code,
'OrderReferenceAttributes.PlatformId' => platform_id,
'OrderReferenceAttributes.SellerNote' => seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"create_order_reference_for_id",
"(",
"id",
",",
"id_type",
",",
"inherit_shipping_address",
":",
"nil",
",",
"confirm_now",
":",
"nil",
",",
"amount",
":",
"nil",
",",
"currency_code",
":",
"@currency_code",
",",
"platform_id",
":",
"nil",
",",
"seller_note",
":",
"nil",
",",
"seller_order_id",
":",
"nil",
",",
"store_name",
":",
"nil",
",",
"custom_information",
":",
"nil",
",",
"supplementary_data",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'CreateOrderReferenceForId'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'Id'",
"=>",
"id",
",",
"'IdType'",
"=>",
"id_type",
"}",
"optional",
"=",
"{",
"'InheritShippingAddress'",
"=>",
"inherit_shipping_address",
",",
"'ConfirmNow'",
"=>",
"confirm_now",
",",
"'OrderReferenceAttributes.OrderTotal.Amount'",
"=>",
"amount",
",",
"'OrderReferenceAttributes.OrderTotal.CurrencyCode'",
"=>",
"currency_code",
",",
"'OrderReferenceAttributes.PlatformId'",
"=>",
"platform_id",
",",
"'OrderReferenceAttributes.SellerNote'",
"=>",
"seller_note",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId'",
"=>",
"seller_order_id",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.StoreName'",
"=>",
"store_name",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation'",
"=>",
"custom_information",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData'",
"=>",
"supplementary_data",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Creates an order reference for the given object
@see https://pay.amazon.com/documentation/apireference/201751630#201751670
@param id [String]
@param id_type [String]
@optional inherit_shipping_address [Boolean]
@optional confirm_now [Boolean]
@optional amount [String] (required when confirm_now is set to true)
@optional currency_code [String]
@optional platform_id [String]
@optional seller_note [String]
@optional seller_order_id [String]
@optional store_name [String]
@optional custom_information [String]
@optional supplementary_data [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Creates",
"an",
"order",
"reference",
"for",
"the",
"given",
"object"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L133-L172 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.get_billing_agreement_details | def get_billing_agreement_details(
amazon_billing_agreement_id,
address_consent_token: nil,
access_token: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetBillingAgreementDetails',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
# Preseving address_consent_token for backwards compatibility
# AccessToken returns all data in AddressConsentToken plus new data
# You cannot pass both address_consent_token and access_token in
# the same call or you will encounter a 400/"AmbiguousToken" error
'AccessToken' => access_token,
'AddressConsentToken' => address_consent_token,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def get_billing_agreement_details(
amazon_billing_agreement_id,
address_consent_token: nil,
access_token: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetBillingAgreementDetails',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
# Preseving address_consent_token for backwards compatibility
# AccessToken returns all data in AddressConsentToken plus new data
# You cannot pass both address_consent_token and access_token in
# the same call or you will encounter a 400/"AmbiguousToken" error
'AccessToken' => access_token,
'AddressConsentToken' => address_consent_token,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"get_billing_agreement_details",
"(",
"amazon_billing_agreement_id",
",",
"address_consent_token",
":",
"nil",
",",
"access_token",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'GetBillingAgreementDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonBillingAgreementId'",
"=>",
"amazon_billing_agreement_id",
"}",
"optional",
"=",
"{",
"# Preseving address_consent_token for backwards compatibility",
"# AccessToken returns all data in AddressConsentToken plus new data",
"# You cannot pass both address_consent_token and access_token in",
"# the same call or you will encounter a 400/\"AmbiguousToken\" error",
"'AccessToken'",
"=>",
"access_token",
",",
"'AddressConsentToken'",
"=>",
"address_consent_token",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Returns details about the Billing Agreement object and its current state
@see https://pay.amazon.com/documentation/apireference/201751630#201751690
@param amazon_billing_agreement_id [String]
@optional address_consent_token [String]
@optional access_token [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Returns",
"details",
"about",
"the",
"Billing",
"Agreement",
"object",
"and",
"its",
"current",
"state"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L182-L207 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.set_billing_agreement_details | def set_billing_agreement_details(
amazon_billing_agreement_id,
platform_id: nil,
seller_note: nil,
seller_billing_agreement_id: nil,
custom_information: nil,
store_name: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetBillingAgreementDetails',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'BillingAgreementAttributes.PlatformId' => platform_id,
'BillingAgreementAttributes.SellerNote' => seller_note,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.SellerBillingAgreementId' => seller_billing_agreement_id,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation' => custom_information,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName' => store_name,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def set_billing_agreement_details(
amazon_billing_agreement_id,
platform_id: nil,
seller_note: nil,
seller_billing_agreement_id: nil,
custom_information: nil,
store_name: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetBillingAgreementDetails',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'BillingAgreementAttributes.PlatformId' => platform_id,
'BillingAgreementAttributes.SellerNote' => seller_note,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.SellerBillingAgreementId' => seller_billing_agreement_id,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation' => custom_information,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName' => store_name,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"set_billing_agreement_details",
"(",
"amazon_billing_agreement_id",
",",
"platform_id",
":",
"nil",
",",
"seller_note",
":",
"nil",
",",
"seller_billing_agreement_id",
":",
"nil",
",",
"custom_information",
":",
"nil",
",",
"store_name",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'SetBillingAgreementDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonBillingAgreementId'",
"=>",
"amazon_billing_agreement_id",
"}",
"optional",
"=",
"{",
"'BillingAgreementAttributes.PlatformId'",
"=>",
"platform_id",
",",
"'BillingAgreementAttributes.SellerNote'",
"=>",
"seller_note",
",",
"'BillingAgreementAttributes.SellerBillingAgreementAttributes.SellerBillingAgreementId'",
"=>",
"seller_billing_agreement_id",
",",
"'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation'",
"=>",
"custom_information",
",",
"'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName'",
"=>",
"store_name",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Sets billing agreement details such as a description of the agreement
and other information about the seller.
@see https://pay.amazon.com/documentation/apireference/201751630#201751700
@param amazon_billing_agreement_id [String]
@optional platform_id [String]
@optional seller_note [String]
@optional seller_billing_agreement_id [String]
@optional custom_information [String]
@optional store_name [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Sets",
"billing",
"agreement",
"details",
"such",
"as",
"a",
"description",
"of",
"the",
"agreement",
"and",
"other",
"information",
"about",
"the",
"seller",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L220-L247 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.confirm_billing_agreement | def confirm_billing_agreement(
amazon_billing_agreement_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ConfirmBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def confirm_billing_agreement(
amazon_billing_agreement_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ConfirmBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"confirm_billing_agreement",
"(",
"amazon_billing_agreement_id",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'ConfirmBillingAgreement'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonBillingAgreementId'",
"=>",
"amazon_billing_agreement_id",
"}",
"optional",
"=",
"{",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Confirms that the billing agreement is free of constraints and all
required information has been set on the billing agreement
@see https://pay.amazon.com/documentation/apireference/201751630#201751710
@param amazon_billing_agreement_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Confirms",
"that",
"the",
"billing",
"agreement",
"is",
"free",
"of",
"constraints",
"and",
"all",
"required",
"information",
"has",
"been",
"set",
"on",
"the",
"billing",
"agreement"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L255-L272 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.validate_billing_agreement | def validate_billing_agreement(
amazon_billing_agreement_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ValidateBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def validate_billing_agreement(
amazon_billing_agreement_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ValidateBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"validate_billing_agreement",
"(",
"amazon_billing_agreement_id",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'ValidateBillingAgreement'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonBillingAgreementId'",
"=>",
"amazon_billing_agreement_id",
"}",
"optional",
"=",
"{",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Validates the status of the BillingAgreement object and the payment
method associated with it
@see https://pay.amazon.com/documentation/apireference/201751630#201751720
@param amazon_billing_agreement_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Validates",
"the",
"status",
"of",
"the",
"BillingAgreement",
"object",
"and",
"the",
"payment",
"method",
"associated",
"with",
"it"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L280-L297 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.close_billing_agreement | def close_billing_agreement(
amazon_billing_agreement_id,
closure_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CloseBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'ClosureReason' => closure_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def close_billing_agreement(
amazon_billing_agreement_id,
closure_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CloseBillingAgreement',
'SellerId' => merchant_id,
'AmazonBillingAgreementId' => amazon_billing_agreement_id
}
optional = {
'ClosureReason' => closure_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"close_billing_agreement",
"(",
"amazon_billing_agreement_id",
",",
"closure_reason",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'CloseBillingAgreement'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonBillingAgreementId'",
"=>",
"amazon_billing_agreement_id",
"}",
"optional",
"=",
"{",
"'ClosureReason'",
"=>",
"closure_reason",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Confirms that you want to terminate the billing agreement with the buyer
and that you do not expect to create any new order references or
authorizations on this billing agreement
@see https://pay.amazon.com/documentation/apireference/201751630#201751950
@param amazon_billing_agreement_id [String]
@optional closure_reason [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Confirms",
"that",
"you",
"want",
"to",
"terminate",
"the",
"billing",
"agreement",
"with",
"the",
"buyer",
"and",
"that",
"you",
"do",
"not",
"expect",
"to",
"create",
"any",
"new",
"order",
"references",
"or",
"authorizations",
"on",
"this",
"billing",
"agreement"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L374-L393 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.list_order_reference | def list_order_reference(
query_id,
query_id_type,
created_time_range_start: nil,
created_time_range_end: nil,
sort_order: nil,
page_size: nil,
order_reference_status_list_filter: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
payment_domain = payment_domain_hash[@region]
parameters = {
'Action' => 'ListOrderReference',
'SellerId' => merchant_id,
'QueryId' => query_id,
'QueryIdType' => query_id_type
}
optional = {
'CreatedTimeRange.StartTime' => created_time_range_start,
'CreatedTimeRange.EndTime' => created_time_range_end,
'SortOrder' => sort_order,
'PageSize' => page_size,
'PaymentDomain' => payment_domain,
'MWSAuthToken' => mws_auth_token
}
if order_reference_status_list_filter
order_reference_status_list_filter.each_with_index do |val, index|
optional_key = "OrderReferenceStatusListFilter.OrderReferenceStatus.#{index + 1}"
optional[optional_key] = val
end
end
operation(parameters, optional)
end | ruby | def list_order_reference(
query_id,
query_id_type,
created_time_range_start: nil,
created_time_range_end: nil,
sort_order: nil,
page_size: nil,
order_reference_status_list_filter: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
payment_domain = payment_domain_hash[@region]
parameters = {
'Action' => 'ListOrderReference',
'SellerId' => merchant_id,
'QueryId' => query_id,
'QueryIdType' => query_id_type
}
optional = {
'CreatedTimeRange.StartTime' => created_time_range_start,
'CreatedTimeRange.EndTime' => created_time_range_end,
'SortOrder' => sort_order,
'PageSize' => page_size,
'PaymentDomain' => payment_domain,
'MWSAuthToken' => mws_auth_token
}
if order_reference_status_list_filter
order_reference_status_list_filter.each_with_index do |val, index|
optional_key = "OrderReferenceStatusListFilter.OrderReferenceStatus.#{index + 1}"
optional[optional_key] = val
end
end
operation(parameters, optional)
end | [
"def",
"list_order_reference",
"(",
"query_id",
",",
"query_id_type",
",",
"created_time_range_start",
":",
"nil",
",",
"created_time_range_end",
":",
"nil",
",",
"sort_order",
":",
"nil",
",",
"page_size",
":",
"nil",
",",
"order_reference_status_list_filter",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"payment_domain",
"=",
"payment_domain_hash",
"[",
"@region",
"]",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'ListOrderReference'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'QueryId'",
"=>",
"query_id",
",",
"'QueryIdType'",
"=>",
"query_id_type",
"}",
"optional",
"=",
"{",
"'CreatedTimeRange.StartTime'",
"=>",
"created_time_range_start",
",",
"'CreatedTimeRange.EndTime'",
"=>",
"created_time_range_end",
",",
"'SortOrder'",
"=>",
"sort_order",
",",
"'PageSize'",
"=>",
"page_size",
",",
"'PaymentDomain'",
"=>",
"payment_domain",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"if",
"order_reference_status_list_filter",
"order_reference_status_list_filter",
".",
"each_with_index",
"do",
"|",
"val",
",",
"index",
"|",
"optional_key",
"=",
"\"OrderReferenceStatusListFilter.OrderReferenceStatus.#{index + 1}\"",
"optional",
"[",
"optional_key",
"]",
"=",
"val",
"end",
"end",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Allows the search of any Amazon Pay order made using secondary
seller order IDs generated manually, a solution provider, or a custom
order fulfillment service.
@param query_id [String]
@param query_id_type [String]
@optional created_time_range_start [String]
@optional created_time_range_end [String]
@optional sort_order [String]
@optional page_size [Integer]
@optional order_reference_status_list_filter Array[String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Allows",
"the",
"search",
"of",
"any",
"Amazon",
"Pay",
"order",
"made",
"using",
"secondary",
"seller",
"order",
"IDs",
"generated",
"manually",
"a",
"solution",
"provider",
"or",
"a",
"custom",
"order",
"fulfillment",
"service",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L407-L445 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.get_merchant_account_status | def get_merchant_account_status(
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetMerchantAccountStatus',
'SellerId' => merchant_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def get_merchant_account_status(
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetMerchantAccountStatus',
'SellerId' => merchant_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"get_merchant_account_status",
"(",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'GetMerchantAccountStatus'",
",",
"'SellerId'",
"=>",
"merchant_id",
"}",
"optional",
"=",
"{",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Returns status of the merchant
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Returns",
"status",
"of",
"the",
"merchant"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L464-L479 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.get_order_reference_details | def get_order_reference_details(
amazon_order_reference_id,
address_consent_token: nil,
access_token: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetOrderReferenceDetails',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
# Preseving address_consent_token for backwards compatibility
# AccessToken returns all data in AddressConsentToken plus new data
'AccessToken' => access_token || address_consent_token,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def get_order_reference_details(
amazon_order_reference_id,
address_consent_token: nil,
access_token: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetOrderReferenceDetails',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
# Preseving address_consent_token for backwards compatibility
# AccessToken returns all data in AddressConsentToken plus new data
'AccessToken' => access_token || address_consent_token,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"get_order_reference_details",
"(",
"amazon_order_reference_id",
",",
"address_consent_token",
":",
"nil",
",",
"access_token",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'GetOrderReferenceDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonOrderReferenceId'",
"=>",
"amazon_order_reference_id",
"}",
"optional",
"=",
"{",
"# Preseving address_consent_token for backwards compatibility",
"# AccessToken returns all data in AddressConsentToken plus new data",
"'AccessToken'",
"=>",
"access_token",
"||",
"address_consent_token",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Returns details about the Order Reference object and its current state
@see https://pay.amazon.com/documentation/apireference/201751630#201751970
@param amazon_order_reference_id [String]
@optional address_consent_token [String]
@optional access_token [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Returns",
"details",
"about",
"the",
"Order",
"Reference",
"object",
"and",
"its",
"current",
"state"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L488-L510 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.set_order_reference_details | def set_order_reference_details(
amazon_order_reference_id,
amount,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
request_payment_authorization: nil,
store_name: nil,
order_item_categories: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetOrderReferenceDetails',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id,
'OrderReferenceAttributes.OrderTotal.Amount' => amount,
'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code
}
optional = {
'OrderReferenceAttributes.PlatformId' => platform_id,
'OrderReferenceAttributes.RequestPaymentAuthorization' => request_payment_authorization,
'OrderReferenceAttributes.SellerNote' => seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
if order_item_categories
optional.merge!(
get_categories_list(
'OrderReferenceAttributes',
order_item_categories
)
)
end
operation(parameters, optional)
end | ruby | def set_order_reference_details(
amazon_order_reference_id,
amount,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
request_payment_authorization: nil,
store_name: nil,
order_item_categories: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetOrderReferenceDetails',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id,
'OrderReferenceAttributes.OrderTotal.Amount' => amount,
'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code
}
optional = {
'OrderReferenceAttributes.PlatformId' => platform_id,
'OrderReferenceAttributes.RequestPaymentAuthorization' => request_payment_authorization,
'OrderReferenceAttributes.SellerNote' => seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
if order_item_categories
optional.merge!(
get_categories_list(
'OrderReferenceAttributes',
order_item_categories
)
)
end
operation(parameters, optional)
end | [
"def",
"set_order_reference_details",
"(",
"amazon_order_reference_id",
",",
"amount",
",",
"currency_code",
":",
"@currency_code",
",",
"platform_id",
":",
"nil",
",",
"seller_note",
":",
"nil",
",",
"seller_order_id",
":",
"nil",
",",
"request_payment_authorization",
":",
"nil",
",",
"store_name",
":",
"nil",
",",
"order_item_categories",
":",
"nil",
",",
"custom_information",
":",
"nil",
",",
"supplementary_data",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'SetOrderReferenceDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonOrderReferenceId'",
"=>",
"amazon_order_reference_id",
",",
"'OrderReferenceAttributes.OrderTotal.Amount'",
"=>",
"amount",
",",
"'OrderReferenceAttributes.OrderTotal.CurrencyCode'",
"=>",
"currency_code",
"}",
"optional",
"=",
"{",
"'OrderReferenceAttributes.PlatformId'",
"=>",
"platform_id",
",",
"'OrderReferenceAttributes.RequestPaymentAuthorization'",
"=>",
"request_payment_authorization",
",",
"'OrderReferenceAttributes.SellerNote'",
"=>",
"seller_note",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId'",
"=>",
"seller_order_id",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.StoreName'",
"=>",
"store_name",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation'",
"=>",
"custom_information",
",",
"'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData'",
"=>",
"supplementary_data",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"if",
"order_item_categories",
"optional",
".",
"merge!",
"(",
"get_categories_list",
"(",
"'OrderReferenceAttributes'",
",",
"order_item_categories",
")",
")",
"end",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Sets order reference details such as the order total and a description
for the order
@see https://pay.amazon.com/documentation/apireference/201751630#201751960
@param amazon_order_reference_id [String]
@param amount [String]
@optional currency_code [String]
@optional platform_id [String]
@optional seller_note [String]
@optional seller_order_id [String]
@optional request_payment_authorization [Boolean]
@optional store_name [String]
@optional order_item_categories Array[String]
@optional custom_information [String]
@optional supplementary_data [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Sets",
"order",
"reference",
"details",
"such",
"as",
"the",
"order",
"total",
"and",
"a",
"description",
"for",
"the",
"order"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L528-L573 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.set_order_attributes | def set_order_attributes(
amazon_order_reference_id,
amount: nil,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
payment_service_provider_id: nil,
payment_service_provider_order_id: nil,
request_payment_authorization: nil,
store_name: nil,
order_item_categories: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetOrderAttributes',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'OrderAttributes.OrderTotal.Amount' => amount,
'OrderAttributes.OrderTotal.CurrencyCode' => currency_code,
'OrderAttributes.PlatformId' => platform_id,
'OrderAttributes.SellerNote' => seller_note,
'OrderAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId' => payment_service_provider_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId' => payment_service_provider_order_id,
'OrderAttributes.RequestPaymentAuthorization' => request_payment_authorization,
'OrderAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
optional['OrderAttributes.OrderTotal.CurrencyCode'] = nil if amount.nil?
if order_item_categories
optional.merge!(
get_categories_list(
'OrderAttributes',
order_item_categories
)
)
end
operation(parameters, optional)
end | ruby | def set_order_attributes(
amazon_order_reference_id,
amount: nil,
currency_code: @currency_code,
platform_id: nil,
seller_note: nil,
seller_order_id: nil,
payment_service_provider_id: nil,
payment_service_provider_order_id: nil,
request_payment_authorization: nil,
store_name: nil,
order_item_categories: nil,
custom_information: nil,
supplementary_data: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'SetOrderAttributes',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'OrderAttributes.OrderTotal.Amount' => amount,
'OrderAttributes.OrderTotal.CurrencyCode' => currency_code,
'OrderAttributes.PlatformId' => platform_id,
'OrderAttributes.SellerNote' => seller_note,
'OrderAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId' => payment_service_provider_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId' => payment_service_provider_order_id,
'OrderAttributes.RequestPaymentAuthorization' => request_payment_authorization,
'OrderAttributes.SellerOrderAttributes.StoreName' => store_name,
'OrderAttributes.SellerOrderAttributes.CustomInformation' => custom_information,
'OrderAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,
'MWSAuthToken' => mws_auth_token
}
optional['OrderAttributes.OrderTotal.CurrencyCode'] = nil if amount.nil?
if order_item_categories
optional.merge!(
get_categories_list(
'OrderAttributes',
order_item_categories
)
)
end
operation(parameters, optional)
end | [
"def",
"set_order_attributes",
"(",
"amazon_order_reference_id",
",",
"amount",
":",
"nil",
",",
"currency_code",
":",
"@currency_code",
",",
"platform_id",
":",
"nil",
",",
"seller_note",
":",
"nil",
",",
"seller_order_id",
":",
"nil",
",",
"payment_service_provider_id",
":",
"nil",
",",
"payment_service_provider_order_id",
":",
"nil",
",",
"request_payment_authorization",
":",
"nil",
",",
"store_name",
":",
"nil",
",",
"order_item_categories",
":",
"nil",
",",
"custom_information",
":",
"nil",
",",
"supplementary_data",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'SetOrderAttributes'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonOrderReferenceId'",
"=>",
"amazon_order_reference_id",
"}",
"optional",
"=",
"{",
"'OrderAttributes.OrderTotal.Amount'",
"=>",
"amount",
",",
"'OrderAttributes.OrderTotal.CurrencyCode'",
"=>",
"currency_code",
",",
"'OrderAttributes.PlatformId'",
"=>",
"platform_id",
",",
"'OrderAttributes.SellerNote'",
"=>",
"seller_note",
",",
"'OrderAttributes.SellerOrderAttributes.SellerOrderId'",
"=>",
"seller_order_id",
",",
"'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId'",
"=>",
"payment_service_provider_id",
",",
"'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId'",
"=>",
"payment_service_provider_order_id",
",",
"'OrderAttributes.RequestPaymentAuthorization'",
"=>",
"request_payment_authorization",
",",
"'OrderAttributes.SellerOrderAttributes.StoreName'",
"=>",
"store_name",
",",
"'OrderAttributes.SellerOrderAttributes.CustomInformation'",
"=>",
"custom_information",
",",
"'OrderAttributes.SellerOrderAttributes.SupplementaryData'",
"=>",
"supplementary_data",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"optional",
"[",
"'OrderAttributes.OrderTotal.CurrencyCode'",
"]",
"=",
"nil",
"if",
"amount",
".",
"nil?",
"if",
"order_item_categories",
"optional",
".",
"merge!",
"(",
"get_categories_list",
"(",
"'OrderAttributes'",
",",
"order_item_categories",
")",
")",
"end",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Sets order attributes such as the order total and a description
for the order
@see https://pay.amazon.com/documentation/apireference/201751630#201751960
@param amazon_order_reference_id [String]
@optional amount [String]
@optional currency_code [String]
@optional platform_id [String]
@optional seller_note [String]
@optional seller_order_id [String]
@optional request_payment_authorization [Boolean]
@optional store_name [String]
@optional order_item_categories Array[String]
@optional custom_information [String]
@optional supplementary_data [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Sets",
"order",
"attributes",
"such",
"as",
"the",
"order",
"total",
"and",
"a",
"description",
"for",
"the",
"order"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L591-L642 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.confirm_order_reference | def confirm_order_reference(
amazon_order_reference_id,
success_url: nil,
failure_url: nil,
authorization_amount: nil,
currency_code: @currency_code,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ConfirmOrderReference',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'SuccessUrl' => success_url,
'FailureUrl' => failure_url,
'AuthorizationAmount.Amount' => authorization_amount,
'AuthorizationAmount.CurrencyCode' => currency_code,
'MWSAuthToken' => mws_auth_token
}
optional['AuthorizationAmount.CurrencyCode'] = nil if authorization_amount.nil?
operation(parameters, optional)
end | ruby | def confirm_order_reference(
amazon_order_reference_id,
success_url: nil,
failure_url: nil,
authorization_amount: nil,
currency_code: @currency_code,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'ConfirmOrderReference',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'SuccessUrl' => success_url,
'FailureUrl' => failure_url,
'AuthorizationAmount.Amount' => authorization_amount,
'AuthorizationAmount.CurrencyCode' => currency_code,
'MWSAuthToken' => mws_auth_token
}
optional['AuthorizationAmount.CurrencyCode'] = nil if authorization_amount.nil?
operation(parameters, optional)
end | [
"def",
"confirm_order_reference",
"(",
"amazon_order_reference_id",
",",
"success_url",
":",
"nil",
",",
"failure_url",
":",
"nil",
",",
"authorization_amount",
":",
"nil",
",",
"currency_code",
":",
"@currency_code",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'ConfirmOrderReference'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonOrderReferenceId'",
"=>",
"amazon_order_reference_id",
"}",
"optional",
"=",
"{",
"'SuccessUrl'",
"=>",
"success_url",
",",
"'FailureUrl'",
"=>",
"failure_url",
",",
"'AuthorizationAmount.Amount'",
"=>",
"authorization_amount",
",",
"'AuthorizationAmount.CurrencyCode'",
"=>",
"currency_code",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"optional",
"[",
"'AuthorizationAmount.CurrencyCode'",
"]",
"=",
"nil",
"if",
"authorization_amount",
".",
"nil?",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Confirms that the order reference is free of constraints and all required
information has been set on the order reference
@see https://pay.amazon.com/documentation/apireference/201751630#201751980
@param amazon_order_reference_id [String]
@optional success_url [String]
@optional failure_url [String]
@optional authorization_amount [String]
@optional currency_code [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Confirms",
"that",
"the",
"order",
"reference",
"is",
"free",
"of",
"constraints",
"and",
"all",
"required",
"information",
"has",
"been",
"set",
"on",
"the",
"order",
"reference"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L654-L681 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.cancel_order_reference | def cancel_order_reference(
amazon_order_reference_id,
cancelation_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CancelOrderReference',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'CancelationReason' => cancelation_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def cancel_order_reference(
amazon_order_reference_id,
cancelation_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CancelOrderReference',
'SellerId' => merchant_id,
'AmazonOrderReferenceId' => amazon_order_reference_id
}
optional = {
'CancelationReason' => cancelation_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"cancel_order_reference",
"(",
"amazon_order_reference_id",
",",
"cancelation_reason",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'CancelOrderReference'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonOrderReferenceId'",
"=>",
"amazon_order_reference_id",
"}",
"optional",
"=",
"{",
"'CancelationReason'",
"=>",
"cancelation_reason",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Cancels a previously confirmed order reference
@see https://pay.amazon.com/documentation/apireference/201751630#201751990
@param amazon_order_reference_id [String]
@optional cancelation_reason [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Cancels",
"a",
"previously",
"confirmed",
"order",
"reference"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L689-L708 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.get_authorization_details | def get_authorization_details(
amazon_authorization_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetAuthorizationDetails',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def get_authorization_details(
amazon_authorization_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetAuthorizationDetails',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"get_authorization_details",
"(",
"amazon_authorization_id",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'GetAuthorizationDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonAuthorizationId'",
"=>",
"amazon_authorization_id",
"}",
"optional",
"=",
"{",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Returns the status of a particular authorization and the total amount
captured on the authorization
@see https://pay.amazon.com/documentation/apireference/201751630#201752030
@param amazon_authorization_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Returns",
"the",
"status",
"of",
"a",
"particular",
"authorization",
"and",
"the",
"total",
"amount",
"captured",
"on",
"the",
"authorization"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L766-L783 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.capture | def capture(
amazon_authorization_id,
capture_reference_id,
amount,
currency_code: @currency_code,
seller_capture_note: nil,
soft_descriptor: nil,
provider_credit_details: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'Capture',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id,
'CaptureReferenceId' => capture_reference_id,
'CaptureAmount.Amount' => amount,
'CaptureAmount.CurrencyCode' => currency_code
}
optional = {
'SellerCaptureNote' => seller_capture_note,
'SoftDescriptor' => soft_descriptor,
'MWSAuthToken' => mws_auth_token
}
optional.merge!(set_provider_credit_details(provider_credit_details)) if provider_credit_details
operation(parameters, optional)
end | ruby | def capture(
amazon_authorization_id,
capture_reference_id,
amount,
currency_code: @currency_code,
seller_capture_note: nil,
soft_descriptor: nil,
provider_credit_details: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'Capture',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id,
'CaptureReferenceId' => capture_reference_id,
'CaptureAmount.Amount' => amount,
'CaptureAmount.CurrencyCode' => currency_code
}
optional = {
'SellerCaptureNote' => seller_capture_note,
'SoftDescriptor' => soft_descriptor,
'MWSAuthToken' => mws_auth_token
}
optional.merge!(set_provider_credit_details(provider_credit_details)) if provider_credit_details
operation(parameters, optional)
end | [
"def",
"capture",
"(",
"amazon_authorization_id",
",",
"capture_reference_id",
",",
"amount",
",",
"currency_code",
":",
"@currency_code",
",",
"seller_capture_note",
":",
"nil",
",",
"soft_descriptor",
":",
"nil",
",",
"provider_credit_details",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'Capture'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonAuthorizationId'",
"=>",
"amazon_authorization_id",
",",
"'CaptureReferenceId'",
"=>",
"capture_reference_id",
",",
"'CaptureAmount.Amount'",
"=>",
"amount",
",",
"'CaptureAmount.CurrencyCode'",
"=>",
"currency_code",
"}",
"optional",
"=",
"{",
"'SellerCaptureNote'",
"=>",
"seller_capture_note",
",",
"'SoftDescriptor'",
"=>",
"soft_descriptor",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"optional",
".",
"merge!",
"(",
"set_provider_credit_details",
"(",
"provider_credit_details",
")",
")",
"if",
"provider_credit_details",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Captures funds from an authorized payment instrument.
@see https://pay.amazon.com/documentation/apireference/201751630#201752040
@param amazon_authorization_id [String]
@param capture_reference_id [String]
@param amount [String]
@optional currency_code [String]
@optional seller_capture_note [String]
@optional soft_descriptor [String]
@optional provider_credit_details [Array of Hash]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Captures",
"funds",
"from",
"an",
"authorized",
"payment",
"instrument",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L796-L826 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.get_capture_details | def get_capture_details(
amazon_capture_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetCaptureDetails',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def get_capture_details(
amazon_capture_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetCaptureDetails',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"get_capture_details",
"(",
"amazon_capture_id",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'GetCaptureDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonCaptureId'",
"=>",
"amazon_capture_id",
"}",
"optional",
"=",
"{",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Returns the status of a particular capture and the total amount refunded
on the capture
@see https://pay.amazon.com/documentation/apireference/201751630#201752060
@param amazon_capture_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Returns",
"the",
"status",
"of",
"a",
"particular",
"capture",
"and",
"the",
"total",
"amount",
"refunded",
"on",
"the",
"capture"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L834-L851 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.refund | def refund(
amazon_capture_id,
refund_reference_id,
amount,
currency_code: @currency_code,
seller_refund_note: nil,
soft_descriptor: nil,
provider_credit_reversal_details: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'Refund',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id,
'RefundReferenceId' => refund_reference_id,
'RefundAmount.Amount' => amount,
'RefundAmount.CurrencyCode' => currency_code
}
optional = {
'SellerRefundNote' => seller_refund_note,
'SoftDescriptor' => soft_descriptor,
'MWSAuthToken' => mws_auth_token
}
optional.merge!(set_provider_credit_reversal_details(provider_credit_reversal_details)) if provider_credit_reversal_details
operation(parameters, optional)
end | ruby | def refund(
amazon_capture_id,
refund_reference_id,
amount,
currency_code: @currency_code,
seller_refund_note: nil,
soft_descriptor: nil,
provider_credit_reversal_details: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'Refund',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id,
'RefundReferenceId' => refund_reference_id,
'RefundAmount.Amount' => amount,
'RefundAmount.CurrencyCode' => currency_code
}
optional = {
'SellerRefundNote' => seller_refund_note,
'SoftDescriptor' => soft_descriptor,
'MWSAuthToken' => mws_auth_token
}
optional.merge!(set_provider_credit_reversal_details(provider_credit_reversal_details)) if provider_credit_reversal_details
operation(parameters, optional)
end | [
"def",
"refund",
"(",
"amazon_capture_id",
",",
"refund_reference_id",
",",
"amount",
",",
"currency_code",
":",
"@currency_code",
",",
"seller_refund_note",
":",
"nil",
",",
"soft_descriptor",
":",
"nil",
",",
"provider_credit_reversal_details",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'Refund'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonCaptureId'",
"=>",
"amazon_capture_id",
",",
"'RefundReferenceId'",
"=>",
"refund_reference_id",
",",
"'RefundAmount.Amount'",
"=>",
"amount",
",",
"'RefundAmount.CurrencyCode'",
"=>",
"currency_code",
"}",
"optional",
"=",
"{",
"'SellerRefundNote'",
"=>",
"seller_refund_note",
",",
"'SoftDescriptor'",
"=>",
"soft_descriptor",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"optional",
".",
"merge!",
"(",
"set_provider_credit_reversal_details",
"(",
"provider_credit_reversal_details",
")",
")",
"if",
"provider_credit_reversal_details",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Refunds a previously captured amount
@see https://pay.amazon.com/documentation/apireference/201751630#201752080
@param amazon_capture_id [String]
@param refund_reference_id [String]
@param amount [String]
@optional currency_code [String]
@optional seller_refund_note [String]
@optional soft_descriptor [String]
@optional provider_credit_reversal_details [Array of Hash]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Refunds",
"a",
"previously",
"captured",
"amount"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L864-L894 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.get_refund_details | def get_refund_details(
amazon_refund_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetRefundDetails',
'SellerId' => merchant_id,
'AmazonRefundId' => amazon_refund_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def get_refund_details(
amazon_refund_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetRefundDetails',
'SellerId' => merchant_id,
'AmazonRefundId' => amazon_refund_id
}
optional = {
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"get_refund_details",
"(",
"amazon_refund_id",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'GetRefundDetails'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonRefundId'",
"=>",
"amazon_refund_id",
"}",
"optional",
"=",
"{",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Returns the status of a particular refund
@see https://pay.amazon.com/documentation/apireference/201751630#201752100
@param amazon_refund_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Returns",
"the",
"status",
"of",
"a",
"particular",
"refund"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L901-L918 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.close_authorization | def close_authorization(
amazon_authorization_id,
closure_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CloseAuthorization',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id
}
optional = {
'ClosureReason' => closure_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | ruby | def close_authorization(
amazon_authorization_id,
closure_reason: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'CloseAuthorization',
'SellerId' => merchant_id,
'AmazonAuthorizationId' => amazon_authorization_id
}
optional = {
'ClosureReason' => closure_reason,
'MWSAuthToken' => mws_auth_token
}
operation(parameters, optional)
end | [
"def",
"close_authorization",
"(",
"amazon_authorization_id",
",",
"closure_reason",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"parameters",
"=",
"{",
"'Action'",
"=>",
"'CloseAuthorization'",
",",
"'SellerId'",
"=>",
"merchant_id",
",",
"'AmazonAuthorizationId'",
"=>",
"amazon_authorization_id",
"}",
"optional",
"=",
"{",
"'ClosureReason'",
"=>",
"closure_reason",
",",
"'MWSAuthToken'",
"=>",
"mws_auth_token",
"}",
"operation",
"(",
"parameters",
",",
"optional",
")",
"end"
] | Closes an authorization
@see https://pay.amazon.com/documentation/apireference/201751630#201752070
@param amazon_authorization_id [String]
@optional closure_reason [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"Closes",
"an",
"authorization"
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L926-L945 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.set_provider_credit_details | def set_provider_credit_details(provider_credit_details)
member_details = {}
provider_credit_details.each_with_index do |val, index|
member = index + 1
member_details["ProviderCreditList.member.#{member}.ProviderId"] = val[:provider_id]
member_details["ProviderCreditList.member.#{member}.CreditAmount.Amount"] = val[:amount]
member_details["ProviderCreditList.member.#{member}.CreditAmount.CurrencyCode"] = val[:currency_code]
end
member_details
end | ruby | def set_provider_credit_details(provider_credit_details)
member_details = {}
provider_credit_details.each_with_index do |val, index|
member = index + 1
member_details["ProviderCreditList.member.#{member}.ProviderId"] = val[:provider_id]
member_details["ProviderCreditList.member.#{member}.CreditAmount.Amount"] = val[:amount]
member_details["ProviderCreditList.member.#{member}.CreditAmount.CurrencyCode"] = val[:currency_code]
end
member_details
end | [
"def",
"set_provider_credit_details",
"(",
"provider_credit_details",
")",
"member_details",
"=",
"{",
"}",
"provider_credit_details",
".",
"each_with_index",
"do",
"|",
"val",
",",
"index",
"|",
"member",
"=",
"index",
"+",
"1",
"member_details",
"[",
"\"ProviderCreditList.member.#{member}.ProviderId\"",
"]",
"=",
"val",
"[",
":provider_id",
"]",
"member_details",
"[",
"\"ProviderCreditList.member.#{member}.CreditAmount.Amount\"",
"]",
"=",
"val",
"[",
":amount",
"]",
"member_details",
"[",
"\"ProviderCreditList.member.#{member}.CreditAmount.CurrencyCode\"",
"]",
"=",
"val",
"[",
":currency_code",
"]",
"end",
"member_details",
"end"
] | This method builds the provider credit details hash
that will be combined with either the authorize or capture
API call. | [
"This",
"method",
"builds",
"the",
"provider",
"credit",
"details",
"hash",
"that",
"will",
"be",
"combined",
"with",
"either",
"the",
"authorize",
"or",
"capture",
"API",
"call",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L1081-L1091 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client.rb | AmazonPay.Client.set_provider_credit_reversal_details | def set_provider_credit_reversal_details(provider_credit_reversal_details)
member_details = {}
provider_credit_reversal_details.each_with_index do |val, index|
member = index + 1
member_details["ProviderCreditReversalList.member.#{member}.ProviderId"] = val[:provider_id]
member_details["ProviderCreditReversalList.member.#{member}.CreditReversalAmount.Amount"] = val[:amount]
member_details["ProviderCreditReversalList.member.#{member}.CreditReversalAmount.CurrencyCode"] = val[:currency_code]
end
member_details
end | ruby | def set_provider_credit_reversal_details(provider_credit_reversal_details)
member_details = {}
provider_credit_reversal_details.each_with_index do |val, index|
member = index + 1
member_details["ProviderCreditReversalList.member.#{member}.ProviderId"] = val[:provider_id]
member_details["ProviderCreditReversalList.member.#{member}.CreditReversalAmount.Amount"] = val[:amount]
member_details["ProviderCreditReversalList.member.#{member}.CreditReversalAmount.CurrencyCode"] = val[:currency_code]
end
member_details
end | [
"def",
"set_provider_credit_reversal_details",
"(",
"provider_credit_reversal_details",
")",
"member_details",
"=",
"{",
"}",
"provider_credit_reversal_details",
".",
"each_with_index",
"do",
"|",
"val",
",",
"index",
"|",
"member",
"=",
"index",
"+",
"1",
"member_details",
"[",
"\"ProviderCreditReversalList.member.#{member}.ProviderId\"",
"]",
"=",
"val",
"[",
":provider_id",
"]",
"member_details",
"[",
"\"ProviderCreditReversalList.member.#{member}.CreditReversalAmount.Amount\"",
"]",
"=",
"val",
"[",
":amount",
"]",
"member_details",
"[",
"\"ProviderCreditReversalList.member.#{member}.CreditReversalAmount.CurrencyCode\"",
"]",
"=",
"val",
"[",
":currency_code",
"]",
"end",
"member_details",
"end"
] | This method builds the provider credit reversal
details hash that will be combined with the refund
API call. | [
"This",
"method",
"builds",
"the",
"provider",
"credit",
"reversal",
"details",
"hash",
"that",
"will",
"be",
"combined",
"with",
"the",
"refund",
"API",
"call",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client.rb#L1096-L1106 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/request.rb | AmazonPay.Request.build_post_url | def build_post_url
@optional.map { |k, v| @parameters[k] = v unless v.nil? }
@parameters['Timestamp'] = Time.now.utc.iso8601 unless @parameters.key?('Timestamp')
@parameters = @default_hash.merge(@parameters)
post_url = @parameters.sort.map { |k, v| "#{k}=#{custom_escape(v)}" }.join('&')
post_body = ['POST', @mws_endpoint.to_s, "/#{@sandbox_str}/#{AmazonPay::API_VERSION}", post_url].join("\n")
post_url += '&Signature=' + sign(post_body)
if @log_enabled
data = AmazonPay::Sanitize.new(post_url)
@logger.debug("request/Post: #{data.sanitize_request_data}")
end
post_url
end | ruby | def build_post_url
@optional.map { |k, v| @parameters[k] = v unless v.nil? }
@parameters['Timestamp'] = Time.now.utc.iso8601 unless @parameters.key?('Timestamp')
@parameters = @default_hash.merge(@parameters)
post_url = @parameters.sort.map { |k, v| "#{k}=#{custom_escape(v)}" }.join('&')
post_body = ['POST', @mws_endpoint.to_s, "/#{@sandbox_str}/#{AmazonPay::API_VERSION}", post_url].join("\n")
post_url += '&Signature=' + sign(post_body)
if @log_enabled
data = AmazonPay::Sanitize.new(post_url)
@logger.debug("request/Post: #{data.sanitize_request_data}")
end
post_url
end | [
"def",
"build_post_url",
"@optional",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"@parameters",
"[",
"k",
"]",
"=",
"v",
"unless",
"v",
".",
"nil?",
"}",
"@parameters",
"[",
"'Timestamp'",
"]",
"=",
"Time",
".",
"now",
".",
"utc",
".",
"iso8601",
"unless",
"@parameters",
".",
"key?",
"(",
"'Timestamp'",
")",
"@parameters",
"=",
"@default_hash",
".",
"merge",
"(",
"@parameters",
")",
"post_url",
"=",
"@parameters",
".",
"sort",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}=#{custom_escape(v)}\"",
"}",
".",
"join",
"(",
"'&'",
")",
"post_body",
"=",
"[",
"'POST'",
",",
"@mws_endpoint",
".",
"to_s",
",",
"\"/#{@sandbox_str}/#{AmazonPay::API_VERSION}\"",
",",
"post_url",
"]",
".",
"join",
"(",
"\"\\n\"",
")",
"post_url",
"+=",
"'&Signature='",
"+",
"sign",
"(",
"post_body",
")",
"if",
"@log_enabled",
"data",
"=",
"AmazonPay",
"::",
"Sanitize",
".",
"new",
"(",
"post_url",
")",
"@logger",
".",
"debug",
"(",
"\"request/Post: #{data.sanitize_request_data}\"",
")",
"end",
"post_url",
"end"
] | This method combines the required and optional
parameters to sign the post body and generate
the post url. | [
"This",
"method",
"combines",
"the",
"required",
"and",
"optional",
"parameters",
"to",
"sign",
"the",
"post",
"body",
"and",
"generate",
"the",
"post",
"url",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/request.rb#L65-L78 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/request.rb | AmazonPay.Request.sign | def sign(post_body)
custom_escape(Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, @secret_key, post_body)))
end | ruby | def sign(post_body)
custom_escape(Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, @secret_key, post_body)))
end | [
"def",
"sign",
"(",
"post_body",
")",
"custom_escape",
"(",
"Base64",
".",
"strict_encode64",
"(",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
",",
"@secret_key",
",",
"post_body",
")",
")",
")",
"end"
] | This method signs the post body that is being sent
using the secret key provided. | [
"This",
"method",
"signs",
"the",
"post",
"body",
"that",
"is",
"being",
"sent",
"using",
"the",
"secret",
"key",
"provided",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/request.rb#L82-L84 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/request.rb | AmazonPay.Request.post | def post(mws_endpoint, sandbox_str, post_url)
uri = URI("https://#{mws_endpoint}/#{sandbox_str}/#{AmazonPay::API_VERSION}")
https = Net::HTTP.new(uri.host, uri.port, @proxy_addr, @proxy_port, @proxy_user, @proxy_pass)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
user_agent = { 'User-Agent' => "#{AmazonPay::SDK_NAME}/#{AmazonPay::VERSION}; (#{@application_name + '/' if @application_name}#{@application_version.to_s + ';' if @application_version} #{RUBY_VERSION}; #{RUBY_PLATFORM})" }
tries = 0
begin
response = https.post(uri.path, post_url, user_agent)
if @log_enabled
data = AmazonPay::Sanitize.new(response.body)
@logger.debug("response: #{data.sanitize_response_data}")
end
if @throttle.eql?(true)
raise 'InternalServerError' if response.code.eql?('500')
raise 'ServiceUnavailable or RequestThrottled' if response.code.eql?('503')
end
AmazonPay::Response.new(response)
rescue StandardError => error
tries += 1
sleep(get_seconds_for_try_count(tries))
retry if tries <= MAX_RETRIES
raise error.message
end
end | ruby | def post(mws_endpoint, sandbox_str, post_url)
uri = URI("https://#{mws_endpoint}/#{sandbox_str}/#{AmazonPay::API_VERSION}")
https = Net::HTTP.new(uri.host, uri.port, @proxy_addr, @proxy_port, @proxy_user, @proxy_pass)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
user_agent = { 'User-Agent' => "#{AmazonPay::SDK_NAME}/#{AmazonPay::VERSION}; (#{@application_name + '/' if @application_name}#{@application_version.to_s + ';' if @application_version} #{RUBY_VERSION}; #{RUBY_PLATFORM})" }
tries = 0
begin
response = https.post(uri.path, post_url, user_agent)
if @log_enabled
data = AmazonPay::Sanitize.new(response.body)
@logger.debug("response: #{data.sanitize_response_data}")
end
if @throttle.eql?(true)
raise 'InternalServerError' if response.code.eql?('500')
raise 'ServiceUnavailable or RequestThrottled' if response.code.eql?('503')
end
AmazonPay::Response.new(response)
rescue StandardError => error
tries += 1
sleep(get_seconds_for_try_count(tries))
retry if tries <= MAX_RETRIES
raise error.message
end
end | [
"def",
"post",
"(",
"mws_endpoint",
",",
"sandbox_str",
",",
"post_url",
")",
"uri",
"=",
"URI",
"(",
"\"https://#{mws_endpoint}/#{sandbox_str}/#{AmazonPay::API_VERSION}\"",
")",
"https",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
",",
"@proxy_addr",
",",
"@proxy_port",
",",
"@proxy_user",
",",
"@proxy_pass",
")",
"https",
".",
"use_ssl",
"=",
"true",
"https",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
"user_agent",
"=",
"{",
"'User-Agent'",
"=>",
"\"#{AmazonPay::SDK_NAME}/#{AmazonPay::VERSION}; (#{@application_name + '/' if @application_name}#{@application_version.to_s + ';' if @application_version} #{RUBY_VERSION}; #{RUBY_PLATFORM})\"",
"}",
"tries",
"=",
"0",
"begin",
"response",
"=",
"https",
".",
"post",
"(",
"uri",
".",
"path",
",",
"post_url",
",",
"user_agent",
")",
"if",
"@log_enabled",
"data",
"=",
"AmazonPay",
"::",
"Sanitize",
".",
"new",
"(",
"response",
".",
"body",
")",
"@logger",
".",
"debug",
"(",
"\"response: #{data.sanitize_response_data}\"",
")",
"end",
"if",
"@throttle",
".",
"eql?",
"(",
"true",
")",
"raise",
"'InternalServerError'",
"if",
"response",
".",
"code",
".",
"eql?",
"(",
"'500'",
")",
"raise",
"'ServiceUnavailable or RequestThrottled'",
"if",
"response",
".",
"code",
".",
"eql?",
"(",
"'503'",
")",
"end",
"AmazonPay",
"::",
"Response",
".",
"new",
"(",
"response",
")",
"rescue",
"StandardError",
"=>",
"error",
"tries",
"+=",
"1",
"sleep",
"(",
"get_seconds_for_try_count",
"(",
"tries",
")",
")",
"retry",
"if",
"tries",
"<=",
"MAX_RETRIES",
"raise",
"error",
".",
"message",
"end",
"end"
] | This method performs the post to the MWS endpoint.
It will retry three times after the initial post if
the status code comes back as either 500 or 503. | [
"This",
"method",
"performs",
"the",
"post",
"to",
"the",
"MWS",
"endpoint",
".",
"It",
"will",
"retry",
"three",
"times",
"after",
"the",
"initial",
"post",
"if",
"the",
"status",
"code",
"comes",
"back",
"as",
"either",
"500",
"or",
"503",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/request.rb#L89-L115 | train |
amzn/amazon-pay-sdk-ruby | lib/amazon_pay/client_helper.rb | AmazonPay.Client.charge | def charge(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code: @currency_code,
charge_note: nil,
charge_order_id: nil,
store_name: nil,
custom_information: nil,
soft_descriptor: nil,
platform_id: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
if order_reference?(amazon_reference_id)
call_order_reference_api(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code,
charge_note,
charge_order_id,
store_name,
custom_information,
soft_descriptor,
platform_id,
merchant_id,
mws_auth_token
)
elsif billing_agreement?(amazon_reference_id)
call_billing_agreement_api(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code,
charge_note,
charge_order_id,
store_name,
custom_information,
soft_descriptor,
platform_id,
merchant_id,
mws_auth_token
)
end
end | ruby | def charge(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code: @currency_code,
charge_note: nil,
charge_order_id: nil,
store_name: nil,
custom_information: nil,
soft_descriptor: nil,
platform_id: nil,
merchant_id: @merchant_id,
mws_auth_token: nil
)
if order_reference?(amazon_reference_id)
call_order_reference_api(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code,
charge_note,
charge_order_id,
store_name,
custom_information,
soft_descriptor,
platform_id,
merchant_id,
mws_auth_token
)
elsif billing_agreement?(amazon_reference_id)
call_billing_agreement_api(
amazon_reference_id,
authorization_reference_id,
charge_amount,
charge_currency_code,
charge_note,
charge_order_id,
store_name,
custom_information,
soft_descriptor,
platform_id,
merchant_id,
mws_auth_token
)
end
end | [
"def",
"charge",
"(",
"amazon_reference_id",
",",
"authorization_reference_id",
",",
"charge_amount",
",",
"charge_currency_code",
":",
"@currency_code",
",",
"charge_note",
":",
"nil",
",",
"charge_order_id",
":",
"nil",
",",
"store_name",
":",
"nil",
",",
"custom_information",
":",
"nil",
",",
"soft_descriptor",
":",
"nil",
",",
"platform_id",
":",
"nil",
",",
"merchant_id",
":",
"@merchant_id",
",",
"mws_auth_token",
":",
"nil",
")",
"if",
"order_reference?",
"(",
"amazon_reference_id",
")",
"call_order_reference_api",
"(",
"amazon_reference_id",
",",
"authorization_reference_id",
",",
"charge_amount",
",",
"charge_currency_code",
",",
"charge_note",
",",
"charge_order_id",
",",
"store_name",
",",
"custom_information",
",",
"soft_descriptor",
",",
"platform_id",
",",
"merchant_id",
",",
"mws_auth_token",
")",
"elsif",
"billing_agreement?",
"(",
"amazon_reference_id",
")",
"call_billing_agreement_api",
"(",
"amazon_reference_id",
",",
"authorization_reference_id",
",",
"charge_amount",
",",
"charge_currency_code",
",",
"charge_note",
",",
"charge_order_id",
",",
"store_name",
",",
"custom_information",
",",
"soft_descriptor",
",",
"platform_id",
",",
"merchant_id",
",",
"mws_auth_token",
")",
"end",
"end"
] | This method combines multiple API calls to perform
a complete transaction with minimum requirements.
@param amazon_reference_id [String]
@param authorization_reference_id [String]
@param charge_amount [String]
@optional charge_currency_code [String]
@optional charge_note [String]
@optional charge_order [String]
@optional store_name [String]
@optional custom_information [String]
@optional soft_descriptor [String]
@optional platform_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | [
"This",
"method",
"combines",
"multiple",
"API",
"calls",
"to",
"perform",
"a",
"complete",
"transaction",
"with",
"minimum",
"requirements",
"."
] | 6321994cc10b5614630b6743da8d1eb79b2bc1ed | https://github.com/amzn/amazon-pay-sdk-ruby/blob/6321994cc10b5614630b6743da8d1eb79b2bc1ed/lib/amazon_pay/client_helper.rb#L21-L67 | train |
AlexWayfer/flame | lib/flame/router.rb | Flame.Router.add | def add(routes_refine)
routes.deep_merge! routes_refine.routes
reverse_routes.merge! routes_refine.reverse_routes
end | ruby | def add(routes_refine)
routes.deep_merge! routes_refine.routes
reverse_routes.merge! routes_refine.reverse_routes
end | [
"def",
"add",
"(",
"routes_refine",
")",
"routes",
".",
"deep_merge!",
"routes_refine",
".",
"routes",
"reverse_routes",
".",
"merge!",
"routes_refine",
".",
"reverse_routes",
"end"
] | Add RoutesRefine to Router
@param routes_refine [Flame::Router::RoutesRefine] refined routes | [
"Add",
"RoutesRefine",
"to",
"Router"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/router.rb#L36-L39 | train |
AlexWayfer/flame | lib/flame/router.rb | Flame.Router.find_nearest_route | def find_nearest_route(path)
path_parts = path.parts.dup
loop do
route = routes.navigate(*path_parts)&.values&.grep(Route)&.first
break route if route || path_parts.pop.nil?
end
end | ruby | def find_nearest_route(path)
path_parts = path.parts.dup
loop do
route = routes.navigate(*path_parts)&.values&.grep(Route)&.first
break route if route || path_parts.pop.nil?
end
end | [
"def",
"find_nearest_route",
"(",
"path",
")",
"path_parts",
"=",
"path",
".",
"parts",
".",
"dup",
"loop",
"do",
"route",
"=",
"routes",
".",
"navigate",
"(",
"path_parts",
")",
"&.",
"values",
"&.",
"grep",
"(",
"Route",
")",
"&.",
"first",
"break",
"route",
"if",
"route",
"||",
"path_parts",
".",
"pop",
".",
"nil?",
"end",
"end"
] | Find the nearest route by path
@param path [Flame::Path] path for route finding
@return [Flame::Route, nil] return the found nearest route or `nil` | [
"Find",
"the",
"nearest",
"route",
"by",
"path"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/router.rb#L44-L50 | train |
AlexWayfer/flame | lib/flame/router.rb | Flame.Router.path_of | def path_of(route_or_controller, action = nil)
if route_or_controller.is_a?(Flame::Router::Route)
route = route_or_controller
controller = route.controller
action = route.action
else
controller = route_or_controller
end
reverse_routes.dig(controller.to_s, action)
end | ruby | def path_of(route_or_controller, action = nil)
if route_or_controller.is_a?(Flame::Router::Route)
route = route_or_controller
controller = route.controller
action = route.action
else
controller = route_or_controller
end
reverse_routes.dig(controller.to_s, action)
end | [
"def",
"path_of",
"(",
"route_or_controller",
",",
"action",
"=",
"nil",
")",
"if",
"route_or_controller",
".",
"is_a?",
"(",
"Flame",
"::",
"Router",
"::",
"Route",
")",
"route",
"=",
"route_or_controller",
"controller",
"=",
"route",
".",
"controller",
"action",
"=",
"route",
".",
"action",
"else",
"controller",
"=",
"route_or_controller",
"end",
"reverse_routes",
".",
"dig",
"(",
"controller",
".",
"to_s",
",",
"action",
")",
"end"
] | Find the path of route
@param route_or_controller [Flame::Router::Route, Flame::Controller]
route or controller
@param action [Symbol, nil] action (or not for route)
@return [Flame::Path] mounted path to action of controller | [
"Find",
"the",
"path",
"of",
"route"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/router.rb#L57-L66 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.render | def render(cache: true, &block)
@cache = cache
## Compile Tilt to instance hash
return unless @filename
tilt = compile_file
## Render Tilt from instance hash with new options
layout_render tilt.render(@scope, @locals, &block)
end | ruby | def render(cache: true, &block)
@cache = cache
## Compile Tilt to instance hash
return unless @filename
tilt = compile_file
## Render Tilt from instance hash with new options
layout_render tilt.render(@scope, @locals, &block)
end | [
"def",
"render",
"(",
"cache",
":",
"true",
",",
"&",
"block",
")",
"@cache",
"=",
"cache",
"## Compile Tilt to instance hash",
"return",
"unless",
"@filename",
"tilt",
"=",
"compile_file",
"## Render Tilt from instance hash with new options",
"layout_render",
"tilt",
".",
"render",
"(",
"@scope",
",",
"@locals",
",",
"block",
")",
"end"
] | Create a new instance from controller, by path and with options
@param controller [Flame::Controller]
controller for default scope, views directory and cache
@param path [Symbol, String] path (full or the last part) for view search
@param options [Hash] options for template
@option options [Object] :scope (controller)
scope of visibility in rendering
@option options [Symbol, String, false] :layout ('layout.*')
name of the layout file
@option options [Hash] :tilt options for Tilt
@option options [Hash] :locals ({}) local variables for rendering
Render template with layout
@param cache [Boolean] cache compiles or not
@return [String] compiled template | [
"Create",
"a",
"new",
"instance",
"from",
"controller",
"by",
"path",
"and",
"with",
"options"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L51-L59 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.compile_file | def compile_file(filename = @filename)
cached = @controller.cached_tilts[filename]
return cached if @cache && cached
compiled = Tilt.new(filename, nil, @tilt_options)
@controller.cached_tilts[filename] ||= compiled if @cache
compiled
end | ruby | def compile_file(filename = @filename)
cached = @controller.cached_tilts[filename]
return cached if @cache && cached
compiled = Tilt.new(filename, nil, @tilt_options)
@controller.cached_tilts[filename] ||= compiled if @cache
compiled
end | [
"def",
"compile_file",
"(",
"filename",
"=",
"@filename",
")",
"cached",
"=",
"@controller",
".",
"cached_tilts",
"[",
"filename",
"]",
"return",
"cached",
"if",
"@cache",
"&&",
"cached",
"compiled",
"=",
"Tilt",
".",
"new",
"(",
"filename",
",",
"nil",
",",
"@tilt_options",
")",
"@controller",
".",
"cached_tilts",
"[",
"filename",
"]",
"||=",
"compiled",
"if",
"@cache",
"compiled",
"end"
] | Compile file with Tilt engine
@param filename [String] filename | [
"Compile",
"file",
"with",
"Tilt",
"engine"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L69-L76 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.find_file | def find_file(path)
caller_path = caller_locations(4..4).first.path
caller_dir =
begin
File.dirname(caller_path).sub(views_dir, '') if Tilt[caller_path]
rescue LoadError
nil
end
find_files(path, controller_dirs | Array(caller_dir))
.find { |file| Tilt[file] }
end | ruby | def find_file(path)
caller_path = caller_locations(4..4).first.path
caller_dir =
begin
File.dirname(caller_path).sub(views_dir, '') if Tilt[caller_path]
rescue LoadError
nil
end
find_files(path, controller_dirs | Array(caller_dir))
.find { |file| Tilt[file] }
end | [
"def",
"find_file",
"(",
"path",
")",
"caller_path",
"=",
"caller_locations",
"(",
"4",
"..",
"4",
")",
".",
"first",
".",
"path",
"caller_dir",
"=",
"begin",
"File",
".",
"dirname",
"(",
"caller_path",
")",
".",
"sub",
"(",
"views_dir",
",",
"''",
")",
"if",
"Tilt",
"[",
"caller_path",
"]",
"rescue",
"LoadError",
"nil",
"end",
"find_files",
"(",
"path",
",",
"controller_dirs",
"|",
"Array",
"(",
"caller_dir",
")",
")",
".",
"find",
"{",
"|",
"file",
"|",
"Tilt",
"[",
"file",
"]",
"}",
"end"
] | Find template-file by path | [
"Find",
"template",
"-",
"file",
"by",
"path"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L97-L109 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.find_layouts | def find_layouts(path)
find_files(path, layout_dirs)
.select { |file| Tilt[file] }
.sort! { |a, b| b.split('/').size <=> a.split('/').size }
end | ruby | def find_layouts(path)
find_files(path, layout_dirs)
.select { |file| Tilt[file] }
.sort! { |a, b| b.split('/').size <=> a.split('/').size }
end | [
"def",
"find_layouts",
"(",
"path",
")",
"find_files",
"(",
"path",
",",
"layout_dirs",
")",
".",
"select",
"{",
"|",
"file",
"|",
"Tilt",
"[",
"file",
"]",
"}",
".",
"sort!",
"{",
"|",
"a",
",",
"b",
"|",
"b",
".",
"split",
"(",
"'/'",
")",
".",
"size",
"<=>",
"a",
".",
"split",
"(",
"'/'",
")",
".",
"size",
"}",
"end"
] | Find layout-files by path | [
"Find",
"layout",
"-",
"files",
"by",
"path"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L112-L116 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.controller_dirs | def controller_dirs
parts = @controller.class.underscore.split('/').map do |part|
%w[_controller _ctrl]
.find { |suffix| part.chomp! suffix }
part
## Alternative, but slower by ~50%:
# part.sub(/_(controller|ctrl)$/, '')
end
combine_parts(parts).map! { |path| path.join('/') }
end | ruby | def controller_dirs
parts = @controller.class.underscore.split('/').map do |part|
%w[_controller _ctrl]
.find { |suffix| part.chomp! suffix }
part
## Alternative, but slower by ~50%:
# part.sub(/_(controller|ctrl)$/, '')
end
combine_parts(parts).map! { |path| path.join('/') }
end | [
"def",
"controller_dirs",
"parts",
"=",
"@controller",
".",
"class",
".",
"underscore",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"do",
"|",
"part",
"|",
"%w[",
"_controller",
"_ctrl",
"]",
".",
"find",
"{",
"|",
"suffix",
"|",
"part",
".",
"chomp!",
"suffix",
"}",
"part",
"## Alternative, but slower by ~50%:",
"# part.sub(/_(controller|ctrl)$/, '')",
"end",
"combine_parts",
"(",
"parts",
")",
".",
"map!",
"{",
"|",
"path",
"|",
"path",
".",
"join",
"(",
"'/'",
")",
"}",
"end"
] | Find possible directories for the controller | [
"Find",
"possible",
"directories",
"for",
"the",
"controller"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L121-L130 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.combine_parts | def combine_parts(parts)
parts.size.downto(1).with_object([]) do |i, arr|
arr.push(*parts.combination(i).to_a)
end
# variants.uniq!.reject!(&:empty?)
end | ruby | def combine_parts(parts)
parts.size.downto(1).with_object([]) do |i, arr|
arr.push(*parts.combination(i).to_a)
end
# variants.uniq!.reject!(&:empty?)
end | [
"def",
"combine_parts",
"(",
"parts",
")",
"parts",
".",
"size",
".",
"downto",
"(",
"1",
")",
".",
"with_object",
"(",
"[",
"]",
")",
"do",
"|",
"i",
",",
"arr",
"|",
"arr",
".",
"push",
"(",
"parts",
".",
"combination",
"(",
"i",
")",
".",
"to_a",
")",
"end",
"# variants.uniq!.reject!(&:empty?)",
"end"
] | Make combinations in order with different sizes
@example Make parts for ['project', 'namespace', 'controller']
# => [
['project', 'namespace', 'controller'],
['project', 'namespace'],
['namespace', 'controller'],
['namespace']
] | [
"Make",
"combinations",
"in",
"order",
"with",
"different",
"sizes"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L140-L145 | train |
AlexWayfer/flame | lib/flame/render.rb | Flame.Render.layout_render | def layout_render(content)
return content unless @layout
layout_files = find_layouts(@layout)
return content if layout_files.empty?
layout_files.each_with_object(content.dup) do |layout_file, result|
layout = compile_file(layout_file)
result.replace layout.render(@scope, @locals) { result }
end
end | ruby | def layout_render(content)
return content unless @layout
layout_files = find_layouts(@layout)
return content if layout_files.empty?
layout_files.each_with_object(content.dup) do |layout_file, result|
layout = compile_file(layout_file)
result.replace layout.render(@scope, @locals) { result }
end
end | [
"def",
"layout_render",
"(",
"content",
")",
"return",
"content",
"unless",
"@layout",
"layout_files",
"=",
"find_layouts",
"(",
"@layout",
")",
"return",
"content",
"if",
"layout_files",
".",
"empty?",
"layout_files",
".",
"each_with_object",
"(",
"content",
".",
"dup",
")",
"do",
"|",
"layout_file",
",",
"result",
"|",
"layout",
"=",
"compile_file",
"(",
"layout_file",
")",
"result",
".",
"replace",
"layout",
".",
"render",
"(",
"@scope",
",",
"@locals",
")",
"{",
"result",
"}",
"end",
"end"
] | Render the layout with template
@param result [String] result of template rendering | [
"Render",
"the",
"layout",
"with",
"template"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/render.rb#L158-L168 | train |
AlexWayfer/flame | lib/flame/path.rb | Flame.Path.adapt | def adapt(ctrl, action)
parameters = ctrl.instance_method(action).parameters
parameters.map! do |parameter|
parameter_type, parameter_name = parameter
path_part = self.class::Part.new parameter_name, arg: parameter_type
path_part unless parts.include? path_part
end
self.class.new @path.empty? ? "/#{action}" : self, *parameters.compact
end | ruby | def adapt(ctrl, action)
parameters = ctrl.instance_method(action).parameters
parameters.map! do |parameter|
parameter_type, parameter_name = parameter
path_part = self.class::Part.new parameter_name, arg: parameter_type
path_part unless parts.include? path_part
end
self.class.new @path.empty? ? "/#{action}" : self, *parameters.compact
end | [
"def",
"adapt",
"(",
"ctrl",
",",
"action",
")",
"parameters",
"=",
"ctrl",
".",
"instance_method",
"(",
"action",
")",
".",
"parameters",
"parameters",
".",
"map!",
"do",
"|",
"parameter",
"|",
"parameter_type",
",",
"parameter_name",
"=",
"parameter",
"path_part",
"=",
"self",
".",
"class",
"::",
"Part",
".",
"new",
"parameter_name",
",",
"arg",
":",
"parameter_type",
"path_part",
"unless",
"parts",
".",
"include?",
"path_part",
"end",
"self",
".",
"class",
".",
"new",
"@path",
".",
"empty?",
"?",
"\"/#{action}\"",
":",
"self",
",",
"parameters",
".",
"compact",
"end"
] | Compare by parts count and the first arg position
@param other [Flame::Path] other path
@return [-1, 0, 1] result of comparing
Compare with other path by parts
@param other [Flame::Path, String] other path
@return [true, false] equal or not
Complete path for the action of controller
@param ctrl [Flame::Controller] to which controller adapt
@param action [Symbol] to which action of controller adapt
@return [Flame::Path] adapted path
@todo Add :arg:type support (:id:num, :name:str, etc.) | [
"Compare",
"by",
"parts",
"count",
"and",
"the",
"first",
"arg",
"position"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/path.rb#L80-L88 | train |
AlexWayfer/flame | lib/flame/path.rb | Flame.Path.to_routes_with_endpoint | def to_routes_with_endpoint
endpoint =
parts.reduce(result = Flame::Router::Routes.new) do |hash, part|
hash[part] ||= Flame::Router::Routes.new
end
[result, endpoint]
end | ruby | def to_routes_with_endpoint
endpoint =
parts.reduce(result = Flame::Router::Routes.new) do |hash, part|
hash[part] ||= Flame::Router::Routes.new
end
[result, endpoint]
end | [
"def",
"to_routes_with_endpoint",
"endpoint",
"=",
"parts",
".",
"reduce",
"(",
"result",
"=",
"Flame",
"::",
"Router",
"::",
"Routes",
".",
"new",
")",
"do",
"|",
"hash",
",",
"part",
"|",
"hash",
"[",
"part",
"]",
"||=",
"Flame",
"::",
"Router",
"::",
"Routes",
".",
"new",
"end",
"[",
"result",
",",
"endpoint",
"]",
"end"
] | Path parts as keys of nested Hashes
@return [Array(Flame::Router::Routes, Flame::Router::Routes)]
whole Routes (parent) and the endpoint (most nested Routes) | [
"Path",
"parts",
"as",
"keys",
"of",
"nested",
"Hashes"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/path.rb#L113-L119 | train |
AlexWayfer/flame | lib/flame/path.rb | Flame.Path.assign_argument | def assign_argument(part, args = {})
## Not argument
return part unless part.arg?
## Not required argument
return args.delete(part[2..-1].to_sym) if part.opt_arg?
## Required argument
param = args.delete(part[1..-1].to_sym)
## Required argument is nil
error = Errors::ArgumentNotAssignedError.new(@path, part)
raise error if param.nil?
## All is ok
param
end | ruby | def assign_argument(part, args = {})
## Not argument
return part unless part.arg?
## Not required argument
return args.delete(part[2..-1].to_sym) if part.opt_arg?
## Required argument
param = args.delete(part[1..-1].to_sym)
## Required argument is nil
error = Errors::ArgumentNotAssignedError.new(@path, part)
raise error if param.nil?
## All is ok
param
end | [
"def",
"assign_argument",
"(",
"part",
",",
"args",
"=",
"{",
"}",
")",
"## Not argument",
"return",
"part",
"unless",
"part",
".",
"arg?",
"## Not required argument",
"return",
"args",
".",
"delete",
"(",
"part",
"[",
"2",
"..",
"-",
"1",
"]",
".",
"to_sym",
")",
"if",
"part",
".",
"opt_arg?",
"## Required argument",
"param",
"=",
"args",
".",
"delete",
"(",
"part",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
")",
"## Required argument is nil",
"error",
"=",
"Errors",
"::",
"ArgumentNotAssignedError",
".",
"new",
"(",
"@path",
",",
"part",
")",
"raise",
"error",
"if",
"param",
".",
"nil?",
"## All is ok",
"param",
"end"
] | Helpers for `assign_arguments` | [
"Helpers",
"for",
"assign_arguments"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/path.rb#L124-L138 | train |
AlexWayfer/flame | lib/flame/dispatcher.rb | Flame.Dispatcher.status | def status(value = nil)
response.status ||= 200
response.headers['X-Cascade'] = 'pass' if value == 404
value ? response.status = value : response.status
end | ruby | def status(value = nil)
response.status ||= 200
response.headers['X-Cascade'] = 'pass' if value == 404
value ? response.status = value : response.status
end | [
"def",
"status",
"(",
"value",
"=",
"nil",
")",
"response",
".",
"status",
"||=",
"200",
"response",
".",
"headers",
"[",
"'X-Cascade'",
"]",
"=",
"'pass'",
"if",
"value",
"==",
"404",
"value",
"?",
"response",
".",
"status",
"=",
"value",
":",
"response",
".",
"status",
"end"
] | Acccess to the status of response
@param value [Ineger, nil] integer value for new status
@return [Integer] current status
@example Set status value
status 200 | [
"Acccess",
"to",
"the",
"status",
"of",
"response"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/dispatcher.rb#L56-L60 | train |
AlexWayfer/flame | lib/flame/dispatcher.rb | Flame.Dispatcher.params | def params
@params ||=
begin
request.params.symbolize_keys(deep: true)
rescue ArgumentError => e
raise unless e.message.include?('invalid %-encoding')
{}
end
end | ruby | def params
@params ||=
begin
request.params.symbolize_keys(deep: true)
rescue ArgumentError => e
raise unless e.message.include?('invalid %-encoding')
{}
end
end | [
"def",
"params",
"@params",
"||=",
"begin",
"request",
".",
"params",
".",
"symbolize_keys",
"(",
"deep",
":",
"true",
")",
"rescue",
"ArgumentError",
"=>",
"e",
"raise",
"unless",
"e",
".",
"message",
".",
"include?",
"(",
"'invalid %-encoding'",
")",
"{",
"}",
"end",
"end"
] | Parameters of the request | [
"Parameters",
"of",
"the",
"request"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/dispatcher.rb#L74-L83 | train |
AlexWayfer/flame | lib/flame/dispatcher.rb | Flame.Dispatcher.dump_error | def dump_error(error)
error_message = [
"#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} - " \
"#{error.class} - #{error.message}:",
*error.backtrace
].join("\n\t")
@env[Rack::RACK_ERRORS].puts(error_message)
end | ruby | def dump_error(error)
error_message = [
"#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} - " \
"#{error.class} - #{error.message}:",
*error.backtrace
].join("\n\t")
@env[Rack::RACK_ERRORS].puts(error_message)
end | [
"def",
"dump_error",
"(",
"error",
")",
"error_message",
"=",
"[",
"\"#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} - \"",
"\"#{error.class} - #{error.message}:\"",
",",
"error",
".",
"backtrace",
"]",
".",
"join",
"(",
"\"\\n\\t\"",
")",
"@env",
"[",
"Rack",
"::",
"RACK_ERRORS",
"]",
".",
"puts",
"(",
"error_message",
")",
"end"
] | Add error's backtrace to @env['rack.errors'] (terminal or file)
@param error [Exception] exception for class, message and backtrace | [
"Add",
"error",
"s",
"backtrace",
"to"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/dispatcher.rb#L125-L132 | train |
AlexWayfer/flame | lib/flame/dispatcher.rb | Flame.Dispatcher.try_options | def try_options
return unless request.http_method == :OPTIONS
allow = available_endpoint&.allow
halt 404 unless allow
response.headers['Allow'] = allow
end | ruby | def try_options
return unless request.http_method == :OPTIONS
allow = available_endpoint&.allow
halt 404 unless allow
response.headers['Allow'] = allow
end | [
"def",
"try_options",
"return",
"unless",
"request",
".",
"http_method",
"==",
":OPTIONS",
"allow",
"=",
"available_endpoint",
"&.",
"allow",
"halt",
"404",
"unless",
"allow",
"response",
".",
"headers",
"[",
"'Allow'",
"]",
"=",
"allow",
"end"
] | Return response if HTTP-method is OPTIONS | [
"Return",
"response",
"if",
"HTTP",
"-",
"method",
"is",
"OPTIONS"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/dispatcher.rb#L157-L163 | train |
AlexWayfer/flame | lib/flame/controller.rb | Flame.Controller.redirect | def redirect(*args)
args[0] = args.first.to_s if args.first.is_a? URI
unless args.first.is_a? String
path_to_args_range = 0..(args.last.is_a?(Integer) ? -2 : -1)
args[path_to_args_range] = path_to(*args[path_to_args_range])
end
response.redirect(*args)
status
end | ruby | def redirect(*args)
args[0] = args.first.to_s if args.first.is_a? URI
unless args.first.is_a? String
path_to_args_range = 0..(args.last.is_a?(Integer) ? -2 : -1)
args[path_to_args_range] = path_to(*args[path_to_args_range])
end
response.redirect(*args)
status
end | [
"def",
"redirect",
"(",
"*",
"args",
")",
"args",
"[",
"0",
"]",
"=",
"args",
".",
"first",
".",
"to_s",
"if",
"args",
".",
"first",
".",
"is_a?",
"URI",
"unless",
"args",
".",
"first",
".",
"is_a?",
"String",
"path_to_args_range",
"=",
"0",
"..",
"(",
"args",
".",
"last",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"-",
"2",
":",
"-",
"1",
")",
"args",
"[",
"path_to_args_range",
"]",
"=",
"path_to",
"(",
"args",
"[",
"path_to_args_range",
"]",
")",
"end",
"response",
".",
"redirect",
"(",
"args",
")",
"status",
"end"
] | Redirect for response
@overload redirect(path, status)
Redirect to the string path
@param path [String] path
@param status [Ingeter, nil] HTTP status
@return [nil]
@example Redirect to '/hello'
redirect '/hello'
@example Redirect to '/hello' with status 301
redirect '/hello', 301
@overload redirect(uri, status)
Redirect to the URI location
@param uri [URI] URI object
@param status [Ingeter, nil] HTTP status
@return [nil]
@example Redirect to 'http://example.com'
redirect URI::HTTP.build(host: 'example.com')
@example Redirect to 'http://example.com' with status 301
redirect URI::HTTP.build(host: 'example.com'), 301
@overload redirect(*args, status)
Redirect to the path of `path_to` method
@param args arguments for `path_to` method
@param status [Ingeter, nil] HTTP status
@return [nil]
@example Redirect to `show` method of `ArticlesController` with id = 2
redirect ArticlesController, :show, id: 2
@example Redirect to method of controller with status 301
redirect ArticlesController, :show, { id: 2 }, 301 | [
"Redirect",
"for",
"response"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/controller.rb#L90-L98 | train |
AlexWayfer/flame | lib/flame/controller.rb | Flame.Controller.attachment | def attachment(filename = nil, disposition = :attachment)
content_dis = 'Content-Disposition'
response[content_dis] = disposition.to_s
return unless filename
response[content_dis] << "; filename=\"#{File.basename(filename)}\""
ext = File.extname(filename)
response.content_type = ext unless ext.empty?
end | ruby | def attachment(filename = nil, disposition = :attachment)
content_dis = 'Content-Disposition'
response[content_dis] = disposition.to_s
return unless filename
response[content_dis] << "; filename=\"#{File.basename(filename)}\""
ext = File.extname(filename)
response.content_type = ext unless ext.empty?
end | [
"def",
"attachment",
"(",
"filename",
"=",
"nil",
",",
"disposition",
"=",
":attachment",
")",
"content_dis",
"=",
"'Content-Disposition'",
"response",
"[",
"content_dis",
"]",
"=",
"disposition",
".",
"to_s",
"return",
"unless",
"filename",
"response",
"[",
"content_dis",
"]",
"<<",
"\"; filename=\\\"#{File.basename(filename)}\\\"\"",
"ext",
"=",
"File",
".",
"extname",
"(",
"filename",
")",
"response",
".",
"content_type",
"=",
"ext",
"unless",
"ext",
".",
"empty?",
"end"
] | Set the Content-Disposition to "attachment" with the specified filename,
instructing the user agents to prompt to save,
and set Content-Type by filename.
@param filename [String, nil] filename of attachment
@param disposition [Symbol, String] main content for Content-Disposition
@example Set Content-Disposition header without filename
attachment
@example Set Content-Disposition header with filename and Content-Type
attachment 'style.css' | [
"Set",
"the",
"Content",
"-",
"Disposition",
"to",
"attachment",
"with",
"the",
"specified",
"filename",
"instructing",
"the",
"user",
"agents",
"to",
"prompt",
"to",
"save",
"and",
"set",
"Content",
"-",
"Type",
"by",
"filename",
"."
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/controller.rb#L109-L117 | train |
AlexWayfer/flame | lib/flame/controller.rb | Flame.Controller.reroute | def reroute(*args)
add_controller_class(args)
ctrl, action = args[0..1]
ctrl_object = ctrl == self.class ? self : ctrl.new(@dispatcher)
ctrl_object.send :execute, action
body
end | ruby | def reroute(*args)
add_controller_class(args)
ctrl, action = args[0..1]
ctrl_object = ctrl == self.class ? self : ctrl.new(@dispatcher)
ctrl_object.send :execute, action
body
end | [
"def",
"reroute",
"(",
"*",
"args",
")",
"add_controller_class",
"(",
"args",
")",
"ctrl",
",",
"action",
"=",
"args",
"[",
"0",
"..",
"1",
"]",
"ctrl_object",
"=",
"ctrl",
"==",
"self",
".",
"class",
"?",
"self",
":",
"ctrl",
".",
"new",
"(",
"@dispatcher",
")",
"ctrl_object",
".",
"send",
":execute",
",",
"action",
"body",
"end"
] | Execute any action from any controller
@example Execute `new` action of `ArticlesController`
reroute ArticlesController, :new
@example Execute `index` action of `ArticlesController`
reroute ArticlesController
@example Execute `foo` action of current controller
reroute :foo | [
"Execute",
"any",
"action",
"from",
"any",
"controller"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/controller.rb#L163-L169 | train |
AlexWayfer/flame | lib/flame/application.rb | Flame.Application.call | def call(env)
@app.call(env) if @app.respond_to? :call
Flame::Dispatcher.new(self.class, env).run!
end | ruby | def call(env)
@app.call(env) if @app.respond_to? :call
Flame::Dispatcher.new(self.class, env).run!
end | [
"def",
"call",
"(",
"env",
")",
"@app",
".",
"call",
"(",
"env",
")",
"if",
"@app",
".",
"respond_to?",
":call",
"Flame",
"::",
"Dispatcher",
".",
"new",
"(",
"self",
".",
"class",
",",
"env",
")",
".",
"run!",
"end"
] | Request recieving method | [
"Request",
"recieving",
"method"
] | aecb2bb22b43abf4d99a36ea580d67923e3a6564 | https://github.com/AlexWayfer/flame/blob/aecb2bb22b43abf4d99a36ea580d67923e3a6564/lib/flame/application.rb#L151-L154 | train |
avinashbot/redd | lib/redd/client.rb | Redd.Client.request | def request(verb, path, options = {})
# puts "#{verb.to_s.upcase} #{path}", ' ' + options.inspect
response = connection.request(verb, path, **options)
Response.new(response.status.code, response.headers, response.body.to_s)
end | ruby | def request(verb, path, options = {})
# puts "#{verb.to_s.upcase} #{path}", ' ' + options.inspect
response = connection.request(verb, path, **options)
Response.new(response.status.code, response.headers, response.body.to_s)
end | [
"def",
"request",
"(",
"verb",
",",
"path",
",",
"options",
"=",
"{",
"}",
")",
"# puts \"#{verb.to_s.upcase} #{path}\", ' ' + options.inspect",
"response",
"=",
"connection",
".",
"request",
"(",
"verb",
",",
"path",
",",
"**",
"options",
")",
"Response",
".",
"new",
"(",
"response",
".",
"status",
".",
"code",
",",
"response",
".",
"headers",
",",
"response",
".",
"body",
".",
"to_s",
")",
"end"
] | Create a new client.
@param endpoint [String] the base endpoint to make all requests from
@param user_agent [String] a user agent string
Make an HTTP request.
@param verb [:get, :post, :put, :patch, :delete] the HTTP verb to use
@param path [String] the path relative to the endpoint
@param options [Hash] the request parameters
@option options [Hash] :params the parameters to supply with the url
@option options [Hash] :form the parameters to supply in the body
@option options [Hash] :body the direct body contents
@return [Response] the response | [
"Create",
"a",
"new",
"client",
"."
] | 3b1519a2d121efd18de59b935da6e652757eee90 | https://github.com/avinashbot/redd/blob/3b1519a2d121efd18de59b935da6e652757eee90/lib/redd/client.rb#L35-L39 | train |
avinashbot/redd | lib/redd/middleware.rb | Redd.Middleware.redirect_to_reddit! | def redirect_to_reddit!
state = SecureRandom.urlsafe_base64
url = Redd.url(
client_id: @client_id,
redirect_uri: @redirect_uri,
scope: @scope,
duration: @duration,
state: state
)
@request.session[:redd_state] = state
[302, { 'Location' => url }, []]
end | ruby | def redirect_to_reddit!
state = SecureRandom.urlsafe_base64
url = Redd.url(
client_id: @client_id,
redirect_uri: @redirect_uri,
scope: @scope,
duration: @duration,
state: state
)
@request.session[:redd_state] = state
[302, { 'Location' => url }, []]
end | [
"def",
"redirect_to_reddit!",
"state",
"=",
"SecureRandom",
".",
"urlsafe_base64",
"url",
"=",
"Redd",
".",
"url",
"(",
"client_id",
":",
"@client_id",
",",
"redirect_uri",
":",
"@redirect_uri",
",",
"scope",
":",
"@scope",
",",
"duration",
":",
"@duration",
",",
"state",
":",
"state",
")",
"@request",
".",
"session",
"[",
":redd_state",
"]",
"=",
"state",
"[",
"302",
",",
"{",
"'Location'",
"=>",
"url",
"}",
",",
"[",
"]",
"]",
"end"
] | Creates a unique state and redirects the user to reddit for authentication. | [
"Creates",
"a",
"unique",
"state",
"and",
"redirects",
"the",
"user",
"to",
"reddit",
"for",
"authentication",
"."
] | 3b1519a2d121efd18de59b935da6e652757eee90 | https://github.com/avinashbot/redd/blob/3b1519a2d121efd18de59b935da6e652757eee90/lib/redd/middleware.rb#L58-L69 | train |
avinashbot/redd | lib/redd/middleware.rb | Redd.Middleware.after_call | def after_call
env_session = @request.env['redd.session']
if env_session && env_session.client.access
# Make sure to flush any changes made to the Session client to the browser.
@request.session[:redd_session] = env_session.client.access.to_h
else
# Clear the session if the app explicitly set 'redd.session' to nil.
@request.session.delete(:redd_session)
end
end | ruby | def after_call
env_session = @request.env['redd.session']
if env_session && env_session.client.access
# Make sure to flush any changes made to the Session client to the browser.
@request.session[:redd_session] = env_session.client.access.to_h
else
# Clear the session if the app explicitly set 'redd.session' to nil.
@request.session.delete(:redd_session)
end
end | [
"def",
"after_call",
"env_session",
"=",
"@request",
".",
"env",
"[",
"'redd.session'",
"]",
"if",
"env_session",
"&&",
"env_session",
".",
"client",
".",
"access",
"# Make sure to flush any changes made to the Session client to the browser.",
"@request",
".",
"session",
"[",
":redd_session",
"]",
"=",
"env_session",
".",
"client",
".",
"access",
".",
"to_h",
"else",
"# Clear the session if the app explicitly set 'redd.session' to nil.",
"@request",
".",
"session",
".",
"delete",
"(",
":redd_session",
")",
"end",
"end"
] | Do any cleanup or changes after calling the application. | [
"Do",
"any",
"cleanup",
"or",
"changes",
"after",
"calling",
"the",
"application",
"."
] | 3b1519a2d121efd18de59b935da6e652757eee90 | https://github.com/avinashbot/redd/blob/3b1519a2d121efd18de59b935da6e652757eee90/lib/redd/middleware.rb#L82-L91 | train |
avinashbot/redd | lib/redd/middleware.rb | Redd.Middleware.handle_token_error | def handle_token_error
message = nil
message = 'invalid_state' if @request.GET['state'] != @request.session[:redd_state]
message = @request.GET['error'] if @request.GET['error']
raise Errors::TokenRetrievalError, message if message
end | ruby | def handle_token_error
message = nil
message = 'invalid_state' if @request.GET['state'] != @request.session[:redd_state]
message = @request.GET['error'] if @request.GET['error']
raise Errors::TokenRetrievalError, message if message
end | [
"def",
"handle_token_error",
"message",
"=",
"nil",
"message",
"=",
"'invalid_state'",
"if",
"@request",
".",
"GET",
"[",
"'state'",
"]",
"!=",
"@request",
".",
"session",
"[",
":redd_state",
"]",
"message",
"=",
"@request",
".",
"GET",
"[",
"'error'",
"]",
"if",
"@request",
".",
"GET",
"[",
"'error'",
"]",
"raise",
"Errors",
"::",
"TokenRetrievalError",
",",
"message",
"if",
"message",
"end"
] | Assigns a single string representing a reddit authentication errors. | [
"Assigns",
"a",
"single",
"string",
"representing",
"a",
"reddit",
"authentication",
"errors",
"."
] | 3b1519a2d121efd18de59b935da6e652757eee90 | https://github.com/avinashbot/redd/blob/3b1519a2d121efd18de59b935da6e652757eee90/lib/redd/middleware.rb#L94-L99 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.