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 |
---|---|---|---|---|---|---|---|---|---|---|---|
danger/danger | lib/danger/ci_source/circle_api.rb | Danger.CircleAPI.fetch_build | def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
json = JSON.parse(response.body, symbolize_names: true)
json
end | ruby | def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
json = JSON.parse(response.body, symbolize_names: true)
json
end | [
"def",
"fetch_build",
"(",
"repo_slug",
",",
"build_number",
",",
"token",
")",
"url",
"=",
"\"project/#{repo_slug}/#{build_number}\"",
"params",
"=",
"{",
"\"circle-token\"",
"=>",
"token",
"}",
"response",
"=",
"client",
".",
"get",
"url",
",",
"params",
",",
"accept",
":",
"\"application/json\"",
"json",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"symbolize_names",
":",
"true",
")",
"json",
"end"
] | Make the API call, and parse the JSON | [
"Make",
"the",
"API",
"call",
"and",
"parse",
"the",
"JSON"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/ci_source/circle_api.rb#L43-L49 | train |
danger/danger | lib/danger/danger_core/plugins/dangerfile_danger_plugin.rb | Danger.DangerfileDangerPlugin.validate_file_contains_plugin! | def validate_file_contains_plugin!(file)
plugin_count_was = Danger::Plugin.all_plugins.length
yield
if Danger::Plugin.all_plugins.length == plugin_count_was
raise("#{file} doesn't contain any valid danger plugins.")
end
end | ruby | def validate_file_contains_plugin!(file)
plugin_count_was = Danger::Plugin.all_plugins.length
yield
if Danger::Plugin.all_plugins.length == plugin_count_was
raise("#{file} doesn't contain any valid danger plugins.")
end
end | [
"def",
"validate_file_contains_plugin!",
"(",
"file",
")",
"plugin_count_was",
"=",
"Danger",
"::",
"Plugin",
".",
"all_plugins",
".",
"length",
"yield",
"if",
"Danger",
"::",
"Plugin",
".",
"all_plugins",
".",
"length",
"==",
"plugin_count_was",
"raise",
"(",
"\"#{file} doesn't contain any valid danger plugins.\"",
")",
"end",
"end"
] | Raises an error when the given block does not register a plugin. | [
"Raises",
"an",
"error",
"when",
"the",
"given",
"block",
"does",
"not",
"register",
"a",
"plugin",
"."
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/plugins/dangerfile_danger_plugin.rb#L220-L227 | train |
danger/danger | lib/danger/danger_core/dangerfile.rb | Danger.Dangerfile.print_known_info | def print_known_info
rows = []
rows += method_values_for_plugin_hashes(core_dsl_attributes)
rows << ["---", "---"]
rows += method_values_for_plugin_hashes(external_dsl_attributes)
rows << ["---", "---"]
rows << ["SCM", env.scm.class]
rows << ["Source", env.ci_source.class]
rows << ["Requests", env.request_source.class]
rows << ["Base Commit", env.meta_info_for_base]
rows << ["Head Commit", env.meta_info_for_head]
params = {}
params[:rows] = rows.each { |current| current[0] = current[0].yellow }
params[:title] = "Danger v#{Danger::VERSION}\nDSL Attributes".green
ui.section("Info:") do
ui.puts
table = Terminal::Table.new(params)
table.align_column(0, :right)
ui.puts table
ui.puts
end
end | ruby | def print_known_info
rows = []
rows += method_values_for_plugin_hashes(core_dsl_attributes)
rows << ["---", "---"]
rows += method_values_for_plugin_hashes(external_dsl_attributes)
rows << ["---", "---"]
rows << ["SCM", env.scm.class]
rows << ["Source", env.ci_source.class]
rows << ["Requests", env.request_source.class]
rows << ["Base Commit", env.meta_info_for_base]
rows << ["Head Commit", env.meta_info_for_head]
params = {}
params[:rows] = rows.each { |current| current[0] = current[0].yellow }
params[:title] = "Danger v#{Danger::VERSION}\nDSL Attributes".green
ui.section("Info:") do
ui.puts
table = Terminal::Table.new(params)
table.align_column(0, :right)
ui.puts table
ui.puts
end
end | [
"def",
"print_known_info",
"rows",
"=",
"[",
"]",
"rows",
"+=",
"method_values_for_plugin_hashes",
"(",
"core_dsl_attributes",
")",
"rows",
"<<",
"[",
"\"---\"",
",",
"\"---\"",
"]",
"rows",
"+=",
"method_values_for_plugin_hashes",
"(",
"external_dsl_attributes",
")",
"rows",
"<<",
"[",
"\"---\"",
",",
"\"---\"",
"]",
"rows",
"<<",
"[",
"\"SCM\"",
",",
"env",
".",
"scm",
".",
"class",
"]",
"rows",
"<<",
"[",
"\"Source\"",
",",
"env",
".",
"ci_source",
".",
"class",
"]",
"rows",
"<<",
"[",
"\"Requests\"",
",",
"env",
".",
"request_source",
".",
"class",
"]",
"rows",
"<<",
"[",
"\"Base Commit\"",
",",
"env",
".",
"meta_info_for_base",
"]",
"rows",
"<<",
"[",
"\"Head Commit\"",
",",
"env",
".",
"meta_info_for_head",
"]",
"params",
"=",
"{",
"}",
"params",
"[",
":rows",
"]",
"=",
"rows",
".",
"each",
"{",
"|",
"current",
"|",
"current",
"[",
"0",
"]",
"=",
"current",
"[",
"0",
"]",
".",
"yellow",
"}",
"params",
"[",
":title",
"]",
"=",
"\"Danger v#{Danger::VERSION}\\nDSL Attributes\"",
".",
"green",
"ui",
".",
"section",
"(",
"\"Info:\"",
")",
"do",
"ui",
".",
"puts",
"table",
"=",
"Terminal",
"::",
"Table",
".",
"new",
"(",
"params",
")",
"table",
".",
"align_column",
"(",
"0",
",",
":right",
")",
"ui",
".",
"puts",
"table",
"ui",
".",
"puts",
"end",
"end"
] | Iterates through the DSL's attributes, and table's the output | [
"Iterates",
"through",
"the",
"DSL",
"s",
"attributes",
"and",
"table",
"s",
"the",
"output"
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/dangerfile.rb#L147-L170 | train |
danger/danger | lib/danger/danger_core/standard_error.rb | Danger.DSLError.message | def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end | ruby | def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end | [
"def",
"message",
"@message",
"||=",
"begin",
"description",
",",
"stacktrace",
"=",
"parse",
".",
"values_at",
"(",
":description",
",",
":stacktrace",
")",
"msg",
"=",
"description",
"msg",
"=",
"msg",
".",
"red",
"if",
"msg",
".",
"respond_to?",
"(",
":red",
")",
"msg",
"<<",
"stacktrace",
"if",
"stacktrace",
"msg",
"end",
"end"
] | The message of the exception reports the content of podspec for the
line that generated the original exception.
@example Output
Invalid podspec at `RestKit.podspec` - undefined method
`exclude_header_search_paths=' for #<Pod::Specification for
`RestKit/Network (0.9.3)`>
from spec-repos/master/RestKit/0.9.3/RestKit.podspec:36
-------------------------------------------
# because it would break: #import <CoreData/CoreData.h>
> ns.exclude_header_search_paths = 'Code/RestKit.h'
end
-------------------------------------------
@return [String] the message of the exception. | [
"The",
"message",
"of",
"the",
"exception",
"reports",
"the",
"content",
"of",
"podspec",
"for",
"the",
"line",
"that",
"generated",
"the",
"original",
"exception",
"."
] | 0d6d09f2d949c287fe75202d947374042b0679f4 | https://github.com/danger/danger/blob/0d6d09f2d949c287fe75202d947374042b0679f4/lib/danger/danger_core/standard_error.rb#L63-L72 | train |
airbnb/synapse | lib/synapse.rb | Synapse.Synapse.run | def run
log.info "synapse: starting..."
statsd_increment('synapse.start')
# start all the watchers
statsd_time('synapse.watchers.start.time') do
@service_watchers.map do |watcher|
begin
watcher.start
statsd_increment("synapse.watcher.start", ['start_result:success', "watcher_name:#{watcher.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.start", ['start_result:fail', "watcher_name:#{watcher.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
end
statsd_time('synapse.main_loop.elapsed_time') do
# main loop
loops = 0
loop do
@service_watchers.each do |w|
alive = w.ping?
statsd_increment('synapse.watcher.ping.count', ["watcher_name:#{w.name}", "ping_result:#{alive ? "success" : "failure"}"])
raise "synapse: service watcher #{w.name} failed ping!" unless alive
end
if @config_updated
@config_updated = false
statsd_increment('synapse.config.update')
@config_generators.each do |config_generator|
log.info "synapse: configuring #{config_generator.name}"
begin
config_generator.update_config(@service_watchers)
rescue StandardError => e
statsd_increment("synapse.config.update_failed", ["config_name:#{config_generator.name}"])
log.error "synapse: update config failed for config #{config_generator.name} with exception #{e}"
raise e
end
end
end
sleep 1
@config_generators.each do |config_generator|
config_generator.tick(@service_watchers)
end
loops += 1
log.debug "synapse: still running at #{Time.now}" if (loops % 60) == 0
end
end
rescue StandardError => e
statsd_increment('synapse.stop', ['stop_avenue:abort', 'stop_location:main_loop', "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
log.error "synapse: encountered unexpected exception #{e.inspect} in main thread"
raise e
ensure
log.warn "synapse: exiting; sending stop signal to all watchers"
# stop all the watchers
@service_watchers.map do |w|
begin
w.stop
statsd_increment("synapse.watcher.stop", ['stop_avenue:clean', 'stop_location:main_loop', "watcher_name:#{w.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.stop", ['stop_avenue:exception', 'stop_location:main_loop', "watcher_name:#{w.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
statsd_increment('synapse.stop', ['stop_avenue:clean', 'stop_location:main_loop'])
end | ruby | def run
log.info "synapse: starting..."
statsd_increment('synapse.start')
# start all the watchers
statsd_time('synapse.watchers.start.time') do
@service_watchers.map do |watcher|
begin
watcher.start
statsd_increment("synapse.watcher.start", ['start_result:success', "watcher_name:#{watcher.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.start", ['start_result:fail', "watcher_name:#{watcher.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
end
statsd_time('synapse.main_loop.elapsed_time') do
# main loop
loops = 0
loop do
@service_watchers.each do |w|
alive = w.ping?
statsd_increment('synapse.watcher.ping.count', ["watcher_name:#{w.name}", "ping_result:#{alive ? "success" : "failure"}"])
raise "synapse: service watcher #{w.name} failed ping!" unless alive
end
if @config_updated
@config_updated = false
statsd_increment('synapse.config.update')
@config_generators.each do |config_generator|
log.info "synapse: configuring #{config_generator.name}"
begin
config_generator.update_config(@service_watchers)
rescue StandardError => e
statsd_increment("synapse.config.update_failed", ["config_name:#{config_generator.name}"])
log.error "synapse: update config failed for config #{config_generator.name} with exception #{e}"
raise e
end
end
end
sleep 1
@config_generators.each do |config_generator|
config_generator.tick(@service_watchers)
end
loops += 1
log.debug "synapse: still running at #{Time.now}" if (loops % 60) == 0
end
end
rescue StandardError => e
statsd_increment('synapse.stop', ['stop_avenue:abort', 'stop_location:main_loop', "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
log.error "synapse: encountered unexpected exception #{e.inspect} in main thread"
raise e
ensure
log.warn "synapse: exiting; sending stop signal to all watchers"
# stop all the watchers
@service_watchers.map do |w|
begin
w.stop
statsd_increment("synapse.watcher.stop", ['stop_avenue:clean', 'stop_location:main_loop', "watcher_name:#{w.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.stop", ['stop_avenue:exception', 'stop_location:main_loop', "watcher_name:#{w.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
statsd_increment('synapse.stop', ['stop_avenue:clean', 'stop_location:main_loop'])
end | [
"def",
"run",
"log",
".",
"info",
"\"synapse: starting...\"",
"statsd_increment",
"(",
"'synapse.start'",
")",
"# start all the watchers",
"statsd_time",
"(",
"'synapse.watchers.start.time'",
")",
"do",
"@service_watchers",
".",
"map",
"do",
"|",
"watcher",
"|",
"begin",
"watcher",
".",
"start",
"statsd_increment",
"(",
"\"synapse.watcher.start\"",
",",
"[",
"'start_result:success'",
",",
"\"watcher_name:#{watcher.name}\"",
"]",
")",
"rescue",
"Exception",
"=>",
"e",
"statsd_increment",
"(",
"\"synapse.watcher.start\"",
",",
"[",
"'start_result:fail'",
",",
"\"watcher_name:#{watcher.name}\"",
",",
"\"exception_name:#{e.class.name}\"",
",",
"\"exception_message:#{e.message}\"",
"]",
")",
"raise",
"e",
"end",
"end",
"end",
"statsd_time",
"(",
"'synapse.main_loop.elapsed_time'",
")",
"do",
"# main loop",
"loops",
"=",
"0",
"loop",
"do",
"@service_watchers",
".",
"each",
"do",
"|",
"w",
"|",
"alive",
"=",
"w",
".",
"ping?",
"statsd_increment",
"(",
"'synapse.watcher.ping.count'",
",",
"[",
"\"watcher_name:#{w.name}\"",
",",
"\"ping_result:#{alive ? \"success\" : \"failure\"}\"",
"]",
")",
"raise",
"\"synapse: service watcher #{w.name} failed ping!\"",
"unless",
"alive",
"end",
"if",
"@config_updated",
"@config_updated",
"=",
"false",
"statsd_increment",
"(",
"'synapse.config.update'",
")",
"@config_generators",
".",
"each",
"do",
"|",
"config_generator",
"|",
"log",
".",
"info",
"\"synapse: configuring #{config_generator.name}\"",
"begin",
"config_generator",
".",
"update_config",
"(",
"@service_watchers",
")",
"rescue",
"StandardError",
"=>",
"e",
"statsd_increment",
"(",
"\"synapse.config.update_failed\"",
",",
"[",
"\"config_name:#{config_generator.name}\"",
"]",
")",
"log",
".",
"error",
"\"synapse: update config failed for config #{config_generator.name} with exception #{e}\"",
"raise",
"e",
"end",
"end",
"end",
"sleep",
"1",
"@config_generators",
".",
"each",
"do",
"|",
"config_generator",
"|",
"config_generator",
".",
"tick",
"(",
"@service_watchers",
")",
"end",
"loops",
"+=",
"1",
"log",
".",
"debug",
"\"synapse: still running at #{Time.now}\"",
"if",
"(",
"loops",
"%",
"60",
")",
"==",
"0",
"end",
"end",
"rescue",
"StandardError",
"=>",
"e",
"statsd_increment",
"(",
"'synapse.stop'",
",",
"[",
"'stop_avenue:abort'",
",",
"'stop_location:main_loop'",
",",
"\"exception_name:#{e.class.name}\"",
",",
"\"exception_message:#{e.message}\"",
"]",
")",
"log",
".",
"error",
"\"synapse: encountered unexpected exception #{e.inspect} in main thread\"",
"raise",
"e",
"ensure",
"log",
".",
"warn",
"\"synapse: exiting; sending stop signal to all watchers\"",
"# stop all the watchers",
"@service_watchers",
".",
"map",
"do",
"|",
"w",
"|",
"begin",
"w",
".",
"stop",
"statsd_increment",
"(",
"\"synapse.watcher.stop\"",
",",
"[",
"'stop_avenue:clean'",
",",
"'stop_location:main_loop'",
",",
"\"watcher_name:#{w.name}\"",
"]",
")",
"rescue",
"Exception",
"=>",
"e",
"statsd_increment",
"(",
"\"synapse.watcher.stop\"",
",",
"[",
"'stop_avenue:exception'",
",",
"'stop_location:main_loop'",
",",
"\"watcher_name:#{w.name}\"",
",",
"\"exception_name:#{e.class.name}\"",
",",
"\"exception_message:#{e.message}\"",
"]",
")",
"raise",
"e",
"end",
"end",
"statsd_increment",
"(",
"'synapse.stop'",
",",
"[",
"'stop_avenue:clean'",
",",
"'stop_location:main_loop'",
"]",
")",
"end"
] | start all the watchers and enable haproxy configuration | [
"start",
"all",
"the",
"watchers",
"and",
"enable",
"haproxy",
"configuration"
] | 8d1f38236db1fc5ae1b3bf141090dddde42ccdbc | https://github.com/airbnb/synapse/blob/8d1f38236db1fc5ae1b3bf141090dddde42ccdbc/lib/synapse.rb#L42-L112 | train |
ankane/ahoy | lib/ahoy/database_store.rb | Ahoy.DatabaseStore.visit_or_create | def visit_or_create(started_at: nil)
ahoy.track_visit(started_at: started_at) if !visit && Ahoy.server_side_visits
visit
end | ruby | def visit_or_create(started_at: nil)
ahoy.track_visit(started_at: started_at) if !visit && Ahoy.server_side_visits
visit
end | [
"def",
"visit_or_create",
"(",
"started_at",
":",
"nil",
")",
"ahoy",
".",
"track_visit",
"(",
"started_at",
":",
"started_at",
")",
"if",
"!",
"visit",
"&&",
"Ahoy",
".",
"server_side_visits",
"visit",
"end"
] | if we don't have a visit, let's try to create one first | [
"if",
"we",
"don",
"t",
"have",
"a",
"visit",
"let",
"s",
"try",
"to",
"create",
"one",
"first"
] | 514e4f9aed4ff87be791e4d8b73b0f2788233ba8 | https://github.com/ankane/ahoy/blob/514e4f9aed4ff87be791e4d8b73b0f2788233ba8/lib/ahoy/database_store.rb#L62-L65 | train |
ankane/ahoy | lib/ahoy/tracker.rb | Ahoy.Tracker.track | def track(name, properties = {}, options = {})
if exclude?
debug "Event excluded"
elsif missing_params?
debug "Missing required parameters"
else
data = {
visit_token: visit_token,
user_id: user.try(:id),
name: name.to_s,
properties: properties,
time: trusted_time(options[:time]),
event_id: options[:id] || generate_id
}.select { |_, v| v }
@store.track_event(data)
end
true
rescue => e
report_exception(e)
end | ruby | def track(name, properties = {}, options = {})
if exclude?
debug "Event excluded"
elsif missing_params?
debug "Missing required parameters"
else
data = {
visit_token: visit_token,
user_id: user.try(:id),
name: name.to_s,
properties: properties,
time: trusted_time(options[:time]),
event_id: options[:id] || generate_id
}.select { |_, v| v }
@store.track_event(data)
end
true
rescue => e
report_exception(e)
end | [
"def",
"track",
"(",
"name",
",",
"properties",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
")",
"if",
"exclude?",
"debug",
"\"Event excluded\"",
"elsif",
"missing_params?",
"debug",
"\"Missing required parameters\"",
"else",
"data",
"=",
"{",
"visit_token",
":",
"visit_token",
",",
"user_id",
":",
"user",
".",
"try",
"(",
":id",
")",
",",
"name",
":",
"name",
".",
"to_s",
",",
"properties",
":",
"properties",
",",
"time",
":",
"trusted_time",
"(",
"options",
"[",
":time",
"]",
")",
",",
"event_id",
":",
"options",
"[",
":id",
"]",
"||",
"generate_id",
"}",
".",
"select",
"{",
"|",
"_",
",",
"v",
"|",
"v",
"}",
"@store",
".",
"track_event",
"(",
"data",
")",
"end",
"true",
"rescue",
"=>",
"e",
"report_exception",
"(",
"e",
")",
"end"
] | can't use keyword arguments here | [
"can",
"t",
"use",
"keyword",
"arguments",
"here"
] | 514e4f9aed4ff87be791e4d8b73b0f2788233ba8 | https://github.com/ankane/ahoy/blob/514e4f9aed4ff87be791e4d8b73b0f2788233ba8/lib/ahoy/tracker.rb#L18-L38 | train |
activerecord-hackery/ransack | lib/ransack/adapters/active_record/ransack/constants.rb | Ransack.Constants.escape_wildcards | def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL and MySQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end | ruby | def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL and MySQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end | [
"def",
"escape_wildcards",
"(",
"unescaped",
")",
"case",
"ActiveRecord",
"::",
"Base",
".",
"connection",
".",
"adapter_name",
"when",
"\"Mysql2\"",
".",
"freeze",
",",
"\"PostgreSQL\"",
".",
"freeze",
"# Necessary for PostgreSQL and MySQL",
"unescaped",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\\\",
"/",
",",
"'\\\\\\\\\\\\1'",
")",
"else",
"unescaped",
"end",
"end"
] | replace % \ to \% \\ | [
"replace",
"%",
"\\",
"to",
"\\",
"%",
"\\\\"
] | d44bfe6fe21ab374ceea9d060267d0d38b09ef28 | https://github.com/activerecord-hackery/ransack/blob/d44bfe6fe21ab374ceea9d060267d0d38b09ef28/lib/ransack/adapters/active_record/ransack/constants.rb#L103-L111 | train |
aasm/aasm | lib/aasm/base.rb | AASM.Base.attribute_name | def attribute_name(column_name=nil)
if column_name
@state_machine.config.column = column_name.to_sym
else
@state_machine.config.column ||= :aasm_state
end
@state_machine.config.column
end | ruby | def attribute_name(column_name=nil)
if column_name
@state_machine.config.column = column_name.to_sym
else
@state_machine.config.column ||= :aasm_state
end
@state_machine.config.column
end | [
"def",
"attribute_name",
"(",
"column_name",
"=",
"nil",
")",
"if",
"column_name",
"@state_machine",
".",
"config",
".",
"column",
"=",
"column_name",
".",
"to_sym",
"else",
"@state_machine",
".",
"config",
".",
"column",
"||=",
":aasm_state",
"end",
"@state_machine",
".",
"config",
".",
"column",
"end"
] | This method is both a getter and a setter | [
"This",
"method",
"is",
"both",
"a",
"getter",
"and",
"a",
"setter"
] | 6a1000b489c6b2e205a7b142478a4b4e207c3dbd | https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/base.rb#L68-L75 | train |
aasm/aasm | lib/aasm/localizer.rb | AASM.Localizer.i18n_klass | def i18n_klass(klass)
klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore
end | ruby | def i18n_klass(klass)
klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore
end | [
"def",
"i18n_klass",
"(",
"klass",
")",
"klass",
".",
"model_name",
".",
"respond_to?",
"(",
":i18n_key",
")",
"?",
"klass",
".",
"model_name",
".",
"i18n_key",
":",
"klass",
".",
"name",
".",
"underscore",
"end"
] | added for rails < 3.0.3 compatibility | [
"added",
"for",
"rails",
"<",
"3",
".",
"0",
".",
"3",
"compatibility"
] | 6a1000b489c6b2e205a7b142478a4b4e207c3dbd | https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/localizer.rb#L44-L46 | train |
aasm/aasm | lib/aasm/aasm.rb | AASM.ClassMethods.aasm | def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
end
AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name))
# use a default despite the DSL configuration default.
# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.
aasm_klass = options[:with_klass] || AASM::Base
raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base)
@aasm ||= Concurrent::Map.new
if @aasm[state_machine_name]
# make sure to use provided options
options.each do |key, value|
@aasm[state_machine_name].state_machine.config.send("#{key}=", value)
end
else
# create a new base
@aasm[state_machine_name] = aasm_klass.new(
self,
state_machine_name,
AASM::StateMachineStore.fetch(self, true).machine(state_machine_name),
options
)
end
@aasm[state_machine_name].instance_eval(&block) if block # new DSL
@aasm[state_machine_name]
end | ruby | def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
end
AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name))
# use a default despite the DSL configuration default.
# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.
aasm_klass = options[:with_klass] || AASM::Base
raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base)
@aasm ||= Concurrent::Map.new
if @aasm[state_machine_name]
# make sure to use provided options
options.each do |key, value|
@aasm[state_machine_name].state_machine.config.send("#{key}=", value)
end
else
# create a new base
@aasm[state_machine_name] = aasm_klass.new(
self,
state_machine_name,
AASM::StateMachineStore.fetch(self, true).machine(state_machine_name),
options
)
end
@aasm[state_machine_name].instance_eval(&block) if block # new DSL
@aasm[state_machine_name]
end | [
"def",
"aasm",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"args",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"args",
"[",
"0",
"]",
".",
"is_a?",
"(",
"String",
")",
"# using custom name",
"state_machine_name",
"=",
"args",
"[",
"0",
"]",
".",
"to_sym",
"options",
"=",
"args",
"[",
"1",
"]",
"||",
"{",
"}",
"else",
"# using the default state_machine_name",
"state_machine_name",
"=",
":default",
"options",
"=",
"args",
"[",
"0",
"]",
"||",
"{",
"}",
"end",
"AASM",
"::",
"StateMachineStore",
".",
"fetch",
"(",
"self",
",",
"true",
")",
".",
"register",
"(",
"state_machine_name",
",",
"AASM",
"::",
"StateMachine",
".",
"new",
"(",
"state_machine_name",
")",
")",
"# use a default despite the DSL configuration default.",
"# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.",
"aasm_klass",
"=",
"options",
"[",
":with_klass",
"]",
"||",
"AASM",
"::",
"Base",
"raise",
"ArgumentError",
",",
"\"The class #{aasm_klass} must inherit from AASM::Base!\"",
"unless",
"aasm_klass",
".",
"ancestors",
".",
"include?",
"(",
"AASM",
"::",
"Base",
")",
"@aasm",
"||=",
"Concurrent",
"::",
"Map",
".",
"new",
"if",
"@aasm",
"[",
"state_machine_name",
"]",
"# make sure to use provided options",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"@aasm",
"[",
"state_machine_name",
"]",
".",
"state_machine",
".",
"config",
".",
"send",
"(",
"\"#{key}=\"",
",",
"value",
")",
"end",
"else",
"# create a new base",
"@aasm",
"[",
"state_machine_name",
"]",
"=",
"aasm_klass",
".",
"new",
"(",
"self",
",",
"state_machine_name",
",",
"AASM",
"::",
"StateMachineStore",
".",
"fetch",
"(",
"self",
",",
"true",
")",
".",
"machine",
"(",
"state_machine_name",
")",
",",
"options",
")",
"end",
"@aasm",
"[",
"state_machine_name",
"]",
".",
"instance_eval",
"(",
"block",
")",
"if",
"block",
"# new DSL",
"@aasm",
"[",
"state_machine_name",
"]",
"end"
] | this is the entry point for all state and event definitions | [
"this",
"is",
"the",
"entry",
"point",
"for",
"all",
"state",
"and",
"event",
"definitions"
] | 6a1000b489c6b2e205a7b142478a4b4e207c3dbd | https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/aasm.rb#L28-L64 | train |
aasm/aasm | lib/aasm/core/event.rb | AASM::Core.Event.may_fire? | def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end | ruby | def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end | [
"def",
"may_fire?",
"(",
"obj",
",",
"to_state",
"=",
"::",
"AASM",
"::",
"NO_VALUE",
",",
"*",
"args",
")",
"_fire",
"(",
"obj",
",",
"{",
":test_only",
"=>",
"true",
"}",
",",
"to_state",
",",
"args",
")",
"# true indicates test firing",
"end"
] | a neutered version of fire - it doesn't actually fire the event, it just
executes the transition guards to determine if a transition is even
an option given current conditions. | [
"a",
"neutered",
"version",
"of",
"fire",
"-",
"it",
"doesn",
"t",
"actually",
"fire",
"the",
"event",
"it",
"just",
"executes",
"the",
"transition",
"guards",
"to",
"determine",
"if",
"a",
"transition",
"is",
"even",
"an",
"option",
"given",
"current",
"conditions",
"."
] | 6a1000b489c6b2e205a7b142478a4b4e207c3dbd | https://github.com/aasm/aasm/blob/6a1000b489c6b2e205a7b142478a4b4e207c3dbd/lib/aasm/core/event.rb#L45-L47 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/config.rb | SymmetricEncryption.Config.config | def config
@config ||= begin
raise(ConfigError, "Cannot find config file: #{file_name}") unless File.exist?(file_name)
env_config = YAML.load(ERB.new(File.new(file_name).read).result)[env]
raise(ConfigError, "Cannot find environment: #{env} in config file: #{file_name}") unless env_config
env_config = self.class.send(:deep_symbolize_keys, env_config)
self.class.send(:migrate_old_formats!, env_config)
end
end | ruby | def config
@config ||= begin
raise(ConfigError, "Cannot find config file: #{file_name}") unless File.exist?(file_name)
env_config = YAML.load(ERB.new(File.new(file_name).read).result)[env]
raise(ConfigError, "Cannot find environment: #{env} in config file: #{file_name}") unless env_config
env_config = self.class.send(:deep_symbolize_keys, env_config)
self.class.send(:migrate_old_formats!, env_config)
end
end | [
"def",
"config",
"@config",
"||=",
"begin",
"raise",
"(",
"ConfigError",
",",
"\"Cannot find config file: #{file_name}\"",
")",
"unless",
"File",
".",
"exist?",
"(",
"file_name",
")",
"env_config",
"=",
"YAML",
".",
"load",
"(",
"ERB",
".",
"new",
"(",
"File",
".",
"new",
"(",
"file_name",
")",
".",
"read",
")",
".",
"result",
")",
"[",
"env",
"]",
"raise",
"(",
"ConfigError",
",",
"\"Cannot find environment: #{env} in config file: #{file_name}\"",
")",
"unless",
"env_config",
"env_config",
"=",
"self",
".",
"class",
".",
"send",
"(",
":deep_symbolize_keys",
",",
"env_config",
")",
"self",
".",
"class",
".",
"send",
"(",
":migrate_old_formats!",
",",
"env_config",
")",
"end",
"end"
] | Load the Encryption Configuration from a YAML file.
See: `.load!` for parameters.
Returns [Hash] the configuration for the supplied environment. | [
"Load",
"the",
"Encryption",
"Configuration",
"from",
"a",
"YAML",
"file",
"."
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/config.rb#L73-L83 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/writer.rb | SymmetricEncryption.Writer.close | def close(close_child_stream = true)
return if closed?
if size.positive?
final = @stream_cipher.final
@ios.write(final) unless final.empty?
end
@ios.close if close_child_stream
@closed = true
end | ruby | def close(close_child_stream = true)
return if closed?
if size.positive?
final = @stream_cipher.final
@ios.write(final) unless final.empty?
end
@ios.close if close_child_stream
@closed = true
end | [
"def",
"close",
"(",
"close_child_stream",
"=",
"true",
")",
"return",
"if",
"closed?",
"if",
"size",
".",
"positive?",
"final",
"=",
"@stream_cipher",
".",
"final",
"@ios",
".",
"write",
"(",
"final",
")",
"unless",
"final",
".",
"empty?",
"end",
"@ios",
".",
"close",
"if",
"close_child_stream",
"@closed",
"=",
"true",
"end"
] | Encrypt data before writing to the supplied stream
Close the IO Stream.
Notes:
* Flushes any unwritten data.
* Once an EncryptionWriter has been closed a new instance must be
created before writing again.
* Closes the passed in io stream or file.
* `close` must be called _before_ the supplied stream is closed.
It is recommended to call Symmetric::EncryptedStream.open
rather than creating an instance of Symmetric::Writer directly to
ensure that the encrypted stream is closed before the stream itself is closed. | [
"Encrypt",
"data",
"before",
"writing",
"to",
"the",
"supplied",
"stream",
"Close",
"the",
"IO",
"Stream",
"."
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/writer.rb#L143-L152 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/cipher.rb | SymmetricEncryption.Cipher.encrypt | def encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
str = str.to_s
return str if str.empty?
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end | ruby | def encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
str = str.to_s
return str if str.empty?
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end | [
"def",
"encrypt",
"(",
"str",
",",
"random_iv",
":",
"SymmetricEncryption",
".",
"randomize_iv?",
",",
"compress",
":",
"false",
",",
"header",
":",
"always_add_header",
")",
"return",
"if",
"str",
".",
"nil?",
"str",
"=",
"str",
".",
"to_s",
"return",
"str",
"if",
"str",
".",
"empty?",
"encrypted",
"=",
"binary_encrypt",
"(",
"str",
",",
"random_iv",
":",
"random_iv",
",",
"compress",
":",
"compress",
",",
"header",
":",
"header",
")",
"encode",
"(",
"encrypted",
")",
"end"
] | Encrypt and then encode a string
Returns data encrypted and then encoded according to the encoding setting
of this cipher
Returns nil if str is nil
Returns "" str is empty
Parameters
str [String]
String to be encrypted. If str is not a string, #to_s will be called on it
to convert it to a string
random_iv [true|false]
Whether the encypted value should use a random IV every time the
field is encrypted.
Notes:
* Setting random_iv to true will result in a different encrypted output for
the same input string.
* It is recommended to set this to true, except if it will be used as a lookup key.
* Only set to true if the field will never be used as a lookup key, since
the encrypted value needs to be same every time in this case.
* When random_iv is true it adds the random IV string to the header.
Default: false
Highly Recommended where feasible: true
compress [true|false]
Whether to compress str before encryption.
Default: false
Notes:
* Should only be used for large strings since compression overhead and
the overhead of adding the encryption header may exceed any benefits of
compression | [
"Encrypt",
"and",
"then",
"encode",
"a",
"string"
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/cipher.rb#L134-L142 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/cipher.rb | SymmetricEncryption.Cipher.decrypt | def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING) unless decrypted.force_encoding(SymmetricEncryption::UTF8_ENCODING).valid_encoding?
decrypted
end | ruby | def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING) unless decrypted.force_encoding(SymmetricEncryption::UTF8_ENCODING).valid_encoding?
decrypted
end | [
"def",
"decrypt",
"(",
"str",
")",
"decoded",
"=",
"decode",
"(",
"str",
")",
"return",
"unless",
"decoded",
"return",
"decoded",
"if",
"decoded",
".",
"empty?",
"decrypted",
"=",
"binary_decrypt",
"(",
"decoded",
")",
"# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary",
"decrypted",
".",
"force_encoding",
"(",
"SymmetricEncryption",
"::",
"BINARY_ENCODING",
")",
"unless",
"decrypted",
".",
"force_encoding",
"(",
"SymmetricEncryption",
"::",
"UTF8_ENCODING",
")",
".",
"valid_encoding?",
"decrypted",
"end"
] | Decode and Decrypt string
Returns a decrypted string after decoding it first according to the
encoding setting of this cipher
Returns nil if encrypted_string is nil
Returns '' if encrypted_string == ''
Parameters
encrypted_string [String]
Binary encrypted string to decrypt
Reads the header if present for key, iv, cipher_name and compression
encrypted_string must be in raw binary form when calling this method
Creates a new OpenSSL::Cipher with every call so that this call
is thread-safe and can be called concurrently by multiple threads with
the same instance of Cipher | [
"Decode",
"and",
"Decrypt",
"string",
"Returns",
"a",
"decrypted",
"string",
"after",
"decoding",
"it",
"first",
"according",
"to",
"the",
"encoding",
"setting",
"of",
"this",
"cipher",
"Returns",
"nil",
"if",
"encrypted_string",
"is",
"nil",
"Returns",
"if",
"encrypted_string",
"=="
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/cipher.rb#L161-L173 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/cipher.rb | SymmetricEncryption.Cipher.binary_encrypt | def binary_encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: compress) if header || random_iv || compress
# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.
openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
openssl_cipher.encrypt
openssl_cipher.key = @key
result =
if header
if random_iv
openssl_cipher.iv = header.iv = openssl_cipher.random_iv
elsif iv
openssl_cipher.iv = iv
end
header.to_s + openssl_cipher.update(compress ? Zlib::Deflate.deflate(string) : string)
else
openssl_cipher.iv = iv if iv
openssl_cipher.update(string)
end
result << openssl_cipher.final
end | ruby | def binary_encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: compress) if header || random_iv || compress
# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.
openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
openssl_cipher.encrypt
openssl_cipher.key = @key
result =
if header
if random_iv
openssl_cipher.iv = header.iv = openssl_cipher.random_iv
elsif iv
openssl_cipher.iv = iv
end
header.to_s + openssl_cipher.update(compress ? Zlib::Deflate.deflate(string) : string)
else
openssl_cipher.iv = iv if iv
openssl_cipher.update(string)
end
result << openssl_cipher.final
end | [
"def",
"binary_encrypt",
"(",
"str",
",",
"random_iv",
":",
"SymmetricEncryption",
".",
"randomize_iv?",
",",
"compress",
":",
"false",
",",
"header",
":",
"always_add_header",
")",
"return",
"if",
"str",
".",
"nil?",
"string",
"=",
"str",
".",
"to_s",
"return",
"string",
"if",
"string",
".",
"empty?",
"# Header required when adding a random_iv or compressing",
"header",
"=",
"Header",
".",
"new",
"(",
"version",
":",
"version",
",",
"compress",
":",
"compress",
")",
"if",
"header",
"||",
"random_iv",
"||",
"compress",
"# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.",
"openssl_cipher",
"=",
"::",
"OpenSSL",
"::",
"Cipher",
".",
"new",
"(",
"cipher_name",
")",
"openssl_cipher",
".",
"encrypt",
"openssl_cipher",
".",
"key",
"=",
"@key",
"result",
"=",
"if",
"header",
"if",
"random_iv",
"openssl_cipher",
".",
"iv",
"=",
"header",
".",
"iv",
"=",
"openssl_cipher",
".",
"random_iv",
"elsif",
"iv",
"openssl_cipher",
".",
"iv",
"=",
"iv",
"end",
"header",
".",
"to_s",
"+",
"openssl_cipher",
".",
"update",
"(",
"compress",
"?",
"Zlib",
"::",
"Deflate",
".",
"deflate",
"(",
"string",
")",
":",
"string",
")",
"else",
"openssl_cipher",
".",
"iv",
"=",
"iv",
"if",
"iv",
"openssl_cipher",
".",
"update",
"(",
"string",
")",
"end",
"result",
"<<",
"openssl_cipher",
".",
"final",
"end"
] | Advanced use only
Returns a Binary encrypted string without applying Base64, or any other encoding.
str [String]
String to be encrypted. If str is not a string, #to_s will be called on it
to convert it to a string
random_iv [true|false]
Whether the encypted value should use a random IV every time the
field is encrypted.
Notes:
* Setting random_iv to true will result in a different encrypted output for
the same input string.
* It is recommended to set this to true, except if it will be used as a lookup key.
* Only set to true if the field will never be used as a lookup key, since
the encrypted value needs to be same every time in this case.
* When random_iv is true it adds the random IV string to the header.
Default: false
Highly Recommended where feasible: true
compress [true|false]
Whether to compress str before encryption.
Default: false
Notes:
* Should only be used for large strings since compression overhead and
the overhead of adding the encryption header may exceed any benefits of
compression
header [true|false]
Whether to add a header to the encrypted string.
Default: `always_add_header`
See #encrypt to encrypt and encode the result as a string. | [
"Advanced",
"use",
"only"
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/cipher.rb#L249-L276 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/header.rb | SymmetricEncryption.Header.read_string | def read_string(buffer, offset)
# TODO: Length check
# Exception when
# - offset exceeds length of buffer
# byteslice truncates when too long, but returns nil when start is beyond end of buffer
len = buffer.byteslice(offset, 2).unpack('v').first
offset += 2
out = buffer.byteslice(offset, len)
[out, offset + len]
end | ruby | def read_string(buffer, offset)
# TODO: Length check
# Exception when
# - offset exceeds length of buffer
# byteslice truncates when too long, but returns nil when start is beyond end of buffer
len = buffer.byteslice(offset, 2).unpack('v').first
offset += 2
out = buffer.byteslice(offset, len)
[out, offset + len]
end | [
"def",
"read_string",
"(",
"buffer",
",",
"offset",
")",
"# TODO: Length check",
"# Exception when",
"# - offset exceeds length of buffer",
"# byteslice truncates when too long, but returns nil when start is beyond end of buffer",
"len",
"=",
"buffer",
".",
"byteslice",
"(",
"offset",
",",
"2",
")",
".",
"unpack",
"(",
"'v'",
")",
".",
"first",
"offset",
"+=",
"2",
"out",
"=",
"buffer",
".",
"byteslice",
"(",
"offset",
",",
"len",
")",
"[",
"out",
",",
"offset",
"+",
"len",
"]",
"end"
] | Extracts a string from the supplied buffer.
The buffer starts with a 2 byte length indicator in little endian format.
Parameters
buffer [String]
offset [Integer]
Start position within the buffer.
Returns [string, offset]
string [String]
The string copied from the buffer.
offset [Integer]
The new offset within the buffer. | [
"Extracts",
"a",
"string",
"from",
"the",
"supplied",
"buffer",
".",
"The",
"buffer",
"starts",
"with",
"a",
"2",
"byte",
"length",
"indicator",
"in",
"little",
"endian",
"format",
"."
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/header.rb#L256-L265 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/reader.rb | SymmetricEncryption.Reader.gets | def gets(sep_string, length = nil)
return read(length) if sep_string.nil?
# Read more data until we get the sep_string
while (index = @read_buffer.index(sep_string)).nil? && [email protected]?
break if length && @read_buffer.length >= length
read_block
end
index ||= -1
data = @read_buffer.slice!(0..index)
@pos += data.length
return nil if data.empty? && eof?
data
end | ruby | def gets(sep_string, length = nil)
return read(length) if sep_string.nil?
# Read more data until we get the sep_string
while (index = @read_buffer.index(sep_string)).nil? && [email protected]?
break if length && @read_buffer.length >= length
read_block
end
index ||= -1
data = @read_buffer.slice!(0..index)
@pos += data.length
return nil if data.empty? && eof?
data
end | [
"def",
"gets",
"(",
"sep_string",
",",
"length",
"=",
"nil",
")",
"return",
"read",
"(",
"length",
")",
"if",
"sep_string",
".",
"nil?",
"# Read more data until we get the sep_string",
"while",
"(",
"index",
"=",
"@read_buffer",
".",
"index",
"(",
"sep_string",
")",
")",
".",
"nil?",
"&&",
"!",
"@ios",
".",
"eof?",
"break",
"if",
"length",
"&&",
"@read_buffer",
".",
"length",
">=",
"length",
"read_block",
"end",
"index",
"||=",
"-",
"1",
"data",
"=",
"@read_buffer",
".",
"slice!",
"(",
"0",
"..",
"index",
")",
"@pos",
"+=",
"data",
".",
"length",
"return",
"nil",
"if",
"data",
".",
"empty?",
"&&",
"eof?",
"data",
"end"
] | Reads a single decrypted line from the file up to and including the optional sep_string.
A sep_string of nil reads the entire contents of the file
Returns nil on eof
The stream must be opened for reading or an IOError will be raised. | [
"Reads",
"a",
"single",
"decrypted",
"line",
"from",
"the",
"file",
"up",
"to",
"and",
"including",
"the",
"optional",
"sep_string",
".",
"A",
"sep_string",
"of",
"nil",
"reads",
"the",
"entire",
"contents",
"of",
"the",
"file",
"Returns",
"nil",
"on",
"eof",
"The",
"stream",
"must",
"be",
"opened",
"for",
"reading",
"or",
"an",
"IOError",
"will",
"be",
"raised",
"."
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/reader.rb#L219-L234 | train |
rocketjob/symmetric-encryption | lib/symmetric_encryption/reader.rb | SymmetricEncryption.Reader.read_header | def read_header
@pos = 0
# Read first block and check for the header
buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)
# Use cipher specified in header, or global cipher if it has no header
iv, key, cipher_name, cipher = nil
header = Header.new
if header.parse!(buf)
@header_present = true
@compressed = header.compressed?
@version = header.version
cipher = header.cipher
cipher_name = header.cipher_name || cipher.cipher_name
key = header.key
iv = header.iv
else
@header_present = false
@compressed = nil
cipher = SymmetricEncryption.cipher(@version)
cipher_name = cipher.cipher_name
end
@stream_cipher = ::OpenSSL::Cipher.new(cipher_name)
@stream_cipher.decrypt
@stream_cipher.key = key || cipher.send(:key)
@stream_cipher.iv = iv || cipher.iv
decrypt(buf)
end | ruby | def read_header
@pos = 0
# Read first block and check for the header
buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)
# Use cipher specified in header, or global cipher if it has no header
iv, key, cipher_name, cipher = nil
header = Header.new
if header.parse!(buf)
@header_present = true
@compressed = header.compressed?
@version = header.version
cipher = header.cipher
cipher_name = header.cipher_name || cipher.cipher_name
key = header.key
iv = header.iv
else
@header_present = false
@compressed = nil
cipher = SymmetricEncryption.cipher(@version)
cipher_name = cipher.cipher_name
end
@stream_cipher = ::OpenSSL::Cipher.new(cipher_name)
@stream_cipher.decrypt
@stream_cipher.key = key || cipher.send(:key)
@stream_cipher.iv = iv || cipher.iv
decrypt(buf)
end | [
"def",
"read_header",
"@pos",
"=",
"0",
"# Read first block and check for the header",
"buf",
"=",
"@ios",
".",
"read",
"(",
"@buffer_size",
",",
"@output_buffer",
"||=",
"''",
".",
"b",
")",
"# Use cipher specified in header, or global cipher if it has no header",
"iv",
",",
"key",
",",
"cipher_name",
",",
"cipher",
"=",
"nil",
"header",
"=",
"Header",
".",
"new",
"if",
"header",
".",
"parse!",
"(",
"buf",
")",
"@header_present",
"=",
"true",
"@compressed",
"=",
"header",
".",
"compressed?",
"@version",
"=",
"header",
".",
"version",
"cipher",
"=",
"header",
".",
"cipher",
"cipher_name",
"=",
"header",
".",
"cipher_name",
"||",
"cipher",
".",
"cipher_name",
"key",
"=",
"header",
".",
"key",
"iv",
"=",
"header",
".",
"iv",
"else",
"@header_present",
"=",
"false",
"@compressed",
"=",
"nil",
"cipher",
"=",
"SymmetricEncryption",
".",
"cipher",
"(",
"@version",
")",
"cipher_name",
"=",
"cipher",
".",
"cipher_name",
"end",
"@stream_cipher",
"=",
"::",
"OpenSSL",
"::",
"Cipher",
".",
"new",
"(",
"cipher_name",
")",
"@stream_cipher",
".",
"decrypt",
"@stream_cipher",
".",
"key",
"=",
"key",
"||",
"cipher",
".",
"send",
"(",
":key",
")",
"@stream_cipher",
".",
"iv",
"=",
"iv",
"||",
"cipher",
".",
"iv",
"decrypt",
"(",
"buf",
")",
"end"
] | Read the header from the file if present | [
"Read",
"the",
"header",
"from",
"the",
"file",
"if",
"present"
] | 064ba8d57ffac44a3ed80f5e76fa1a54d660ff98 | https://github.com/rocketjob/symmetric-encryption/blob/064ba8d57ffac44a3ed80f5e76fa1a54d660ff98/lib/symmetric_encryption/reader.rb#L309-L339 | train |
braintree/braintree_ruby | lib/braintree/resource_collection.rb | Braintree.ResourceCollection.each | def each(&block)
@ids.each_slice(@page_size) do |page_of_ids|
resources = @paging_block.call(page_of_ids)
resources.each(&block)
end
end | ruby | def each(&block)
@ids.each_slice(@page_size) do |page_of_ids|
resources = @paging_block.call(page_of_ids)
resources.each(&block)
end
end | [
"def",
"each",
"(",
"&",
"block",
")",
"@ids",
".",
"each_slice",
"(",
"@page_size",
")",
"do",
"|",
"page_of_ids",
"|",
"resources",
"=",
"@paging_block",
".",
"call",
"(",
"page_of_ids",
")",
"resources",
".",
"each",
"(",
"block",
")",
"end",
"end"
] | Yields each item | [
"Yields",
"each",
"item"
] | 6e56c7099ea55bcdc4073cbea60b2688cef69663 | https://github.com/braintree/braintree_ruby/blob/6e56c7099ea55bcdc4073cbea60b2688cef69663/lib/braintree/resource_collection.rb#L14-L19 | train |
collectiveidea/audited | lib/audited/audit.rb | Audited.Audit.revision | def revision
clazz = auditable_type.constantize
(clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
end
end | ruby | def revision
clazz = auditable_type.constantize
(clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
end
end | [
"def",
"revision",
"clazz",
"=",
"auditable_type",
".",
"constantize",
"(",
"clazz",
".",
"find_by_id",
"(",
"auditable_id",
")",
"||",
"clazz",
".",
"new",
")",
".",
"tap",
"do",
"|",
"m",
"|",
"self",
".",
"class",
".",
"assign_revision_attributes",
"(",
"m",
",",
"self",
".",
"class",
".",
"reconstruct_attributes",
"(",
"ancestors",
")",
".",
"merge",
"(",
"audit_version",
":",
"version",
")",
")",
"end",
"end"
] | Return an instance of what the object looked like at this revision. If
the object has been destroyed, this will be a new record. | [
"Return",
"an",
"instance",
"of",
"what",
"the",
"object",
"looked",
"like",
"at",
"this",
"revision",
".",
"If",
"the",
"object",
"has",
"been",
"destroyed",
"this",
"will",
"be",
"a",
"new",
"record",
"."
] | af5d51b45368eabb0e727d064faf29f4af6e1458 | https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L65-L70 | train |
collectiveidea/audited | lib/audited/audit.rb | Audited.Audit.new_attributes | def new_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = values.is_a?(Array) ? values.last : values
attrs
end
end | ruby | def new_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = values.is_a?(Array) ? values.last : values
attrs
end
end | [
"def",
"new_attributes",
"(",
"audited_changes",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"{",
"}",
".",
"with_indifferent_access",
")",
"do",
"|",
"attrs",
",",
"(",
"attr",
",",
"values",
")",
"|",
"attrs",
"[",
"attr",
"]",
"=",
"values",
".",
"is_a?",
"(",
"Array",
")",
"?",
"values",
".",
"last",
":",
"values",
"attrs",
"end",
"end"
] | Returns a hash of the changed attributes with the new values | [
"Returns",
"a",
"hash",
"of",
"the",
"changed",
"attributes",
"with",
"the",
"new",
"values"
] | af5d51b45368eabb0e727d064faf29f4af6e1458 | https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L73-L78 | train |
collectiveidea/audited | lib/audited/audit.rb | Audited.Audit.old_attributes | def old_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = Array(values).first
attrs
end
end | ruby | def old_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = Array(values).first
attrs
end
end | [
"def",
"old_attributes",
"(",
"audited_changes",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"{",
"}",
".",
"with_indifferent_access",
")",
"do",
"|",
"attrs",
",",
"(",
"attr",
",",
"values",
")",
"|",
"attrs",
"[",
"attr",
"]",
"=",
"Array",
"(",
"values",
")",
".",
"first",
"attrs",
"end",
"end"
] | Returns a hash of the changed attributes with the old values | [
"Returns",
"a",
"hash",
"of",
"the",
"changed",
"attributes",
"with",
"the",
"old",
"values"
] | af5d51b45368eabb0e727d064faf29f4af6e1458 | https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L81-L87 | train |
collectiveidea/audited | lib/audited/audit.rb | Audited.Audit.undo | def undo
case action
when 'create'
# destroys a newly created record
auditable.destroy!
when 'destroy'
# creates a new record with the destroyed record attributes
auditable_type.constantize.create!(audited_changes)
when 'update'
# changes back attributes
auditable.update_attributes!(audited_changes.transform_values(&:first))
else
raise StandardError, "invalid action given #{action}"
end
end | ruby | def undo
case action
when 'create'
# destroys a newly created record
auditable.destroy!
when 'destroy'
# creates a new record with the destroyed record attributes
auditable_type.constantize.create!(audited_changes)
when 'update'
# changes back attributes
auditable.update_attributes!(audited_changes.transform_values(&:first))
else
raise StandardError, "invalid action given #{action}"
end
end | [
"def",
"undo",
"case",
"action",
"when",
"'create'",
"# destroys a newly created record",
"auditable",
".",
"destroy!",
"when",
"'destroy'",
"# creates a new record with the destroyed record attributes",
"auditable_type",
".",
"constantize",
".",
"create!",
"(",
"audited_changes",
")",
"when",
"'update'",
"# changes back attributes",
"auditable",
".",
"update_attributes!",
"(",
"audited_changes",
".",
"transform_values",
"(",
":first",
")",
")",
"else",
"raise",
"StandardError",
",",
"\"invalid action given #{action}\"",
"end",
"end"
] | Allows user to undo changes | [
"Allows",
"user",
"to",
"undo",
"changes"
] | af5d51b45368eabb0e727d064faf29f4af6e1458 | https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L90-L104 | train |
collectiveidea/audited | lib/audited/audit.rb | Audited.Audit.user_as_string= | def user_as_string=(user)
# reset both either way
self.user_as_model = self.username = nil
user.is_a?(::ActiveRecord::Base) ?
self.user_as_model = user :
self.username = user
end | ruby | def user_as_string=(user)
# reset both either way
self.user_as_model = self.username = nil
user.is_a?(::ActiveRecord::Base) ?
self.user_as_model = user :
self.username = user
end | [
"def",
"user_as_string",
"=",
"(",
"user",
")",
"# reset both either way",
"self",
".",
"user_as_model",
"=",
"self",
".",
"username",
"=",
"nil",
"user",
".",
"is_a?",
"(",
"::",
"ActiveRecord",
"::",
"Base",
")",
"?",
"self",
".",
"user_as_model",
"=",
"user",
":",
"self",
".",
"username",
"=",
"user",
"end"
] | Allows user to be set to either a string or an ActiveRecord object
@private | [
"Allows",
"user",
"to",
"be",
"set",
"to",
"either",
"a",
"string",
"or",
"an",
"ActiveRecord",
"object"
] | af5d51b45368eabb0e727d064faf29f4af6e1458 | https://github.com/collectiveidea/audited/blob/af5d51b45368eabb0e727d064faf29f4af6e1458/lib/audited/audit.rb#L108-L114 | train |
TrestleAdmin/trestle | app/helpers/trestle/table_helper.rb | Trestle.TableHelper.table | def table(name=nil, options={}, &block)
if block_given?
if name.is_a?(Hash)
options = name
else
collection = name
end
table = Table::Builder.build(options, &block)
elsif name.is_a?(Trestle::Table)
table = name
else
table = admin.tables.fetch(name) { raise ArgumentError, "Unable to find table named #{name.inspect}" }
end
collection ||= options[:collection] || table.options[:collection]
collection = collection.call if collection.respond_to?(:call)
render "trestle/table/table", table: table, collection: collection
end | ruby | def table(name=nil, options={}, &block)
if block_given?
if name.is_a?(Hash)
options = name
else
collection = name
end
table = Table::Builder.build(options, &block)
elsif name.is_a?(Trestle::Table)
table = name
else
table = admin.tables.fetch(name) { raise ArgumentError, "Unable to find table named #{name.inspect}" }
end
collection ||= options[:collection] || table.options[:collection]
collection = collection.call if collection.respond_to?(:call)
render "trestle/table/table", table: table, collection: collection
end | [
"def",
"table",
"(",
"name",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"if",
"block_given?",
"if",
"name",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"name",
"else",
"collection",
"=",
"name",
"end",
"table",
"=",
"Table",
"::",
"Builder",
".",
"build",
"(",
"options",
",",
"block",
")",
"elsif",
"name",
".",
"is_a?",
"(",
"Trestle",
"::",
"Table",
")",
"table",
"=",
"name",
"else",
"table",
"=",
"admin",
".",
"tables",
".",
"fetch",
"(",
"name",
")",
"{",
"raise",
"ArgumentError",
",",
"\"Unable to find table named #{name.inspect}\"",
"}",
"end",
"collection",
"||=",
"options",
"[",
":collection",
"]",
"||",
"table",
".",
"options",
"[",
":collection",
"]",
"collection",
"=",
"collection",
".",
"call",
"if",
"collection",
".",
"respond_to?",
"(",
":call",
")",
"render",
"\"trestle/table/table\"",
",",
"table",
":",
"table",
",",
"collection",
":",
"collection",
"end"
] | Renders an existing named table or builds and renders a custom table if a block is provided.
name - The (optional) name of the table to render (as a Symbol), or the actual Trestle::Table instance itself.
options - Hash of options that will be passed to the table builder (default: {}):
:collection - The collection that should be rendered within the table. It should be an
Array-like object, but will most likely be an ActiveRecord scope. It can
also be a callable object (i.e. a Proc) in which case the result of calling
the block will be used as the collection.
See Trestle::Table::Builder for additional options.
block - An optional block that is passed to Trestle::Table::Builder to define a custom table.
One of either the name or block must be provided, but not both.
Examples
<%= table collection: -> { Account.all }, admin: :accounts do %>
<% column(:name) %>
<% column(:balance) { |account| account.balance.format } %>
<% column(:created_at, align: :center)
<% end %>
<%= table :accounts %>
Returns the HTML representation of the table as a HTML-safe String. | [
"Renders",
"an",
"existing",
"named",
"table",
"or",
"builds",
"and",
"renders",
"a",
"custom",
"table",
"if",
"a",
"block",
"is",
"provided",
"."
] | fd5b8aeb5077e13d539cb5ddd99db1dd279f19ca | https://github.com/TrestleAdmin/trestle/blob/fd5b8aeb5077e13d539cb5ddd99db1dd279f19ca/app/helpers/trestle/table_helper.rb#L26-L45 | train |
TrestleAdmin/trestle | app/helpers/trestle/pagination_helper.rb | Trestle.PaginationHelper.page_entries_info | def page_entries_info(collection, options = {})
entry_name = options[:entry_name] || "entry"
entry_name = entry_name.pluralize unless collection.total_count == 1
if collection.total_pages < 2
t('trestle.helpers.page_entries_info.one_page.display_entries', entry_name: entry_name, count: collection.total_count, default: "Displaying <strong>all %{count}</strong> %{entry_name}")
else
first = number_with_delimiter(collection.offset_value + 1)
last = number_with_delimiter((sum = collection.offset_value + collection.limit_value) > collection.total_count ? collection.total_count : sum)
total = number_with_delimiter(collection.total_count)
t('trestle.helpers.page_entries_info.more_pages.display_entries', entry_name: entry_name, first: first, last: last, total: total, default: "Displaying %{entry_name} <strong>%{first} - %{last}</strong> of <b>%{total}</b>")
end.html_safe
end | ruby | def page_entries_info(collection, options = {})
entry_name = options[:entry_name] || "entry"
entry_name = entry_name.pluralize unless collection.total_count == 1
if collection.total_pages < 2
t('trestle.helpers.page_entries_info.one_page.display_entries', entry_name: entry_name, count: collection.total_count, default: "Displaying <strong>all %{count}</strong> %{entry_name}")
else
first = number_with_delimiter(collection.offset_value + 1)
last = number_with_delimiter((sum = collection.offset_value + collection.limit_value) > collection.total_count ? collection.total_count : sum)
total = number_with_delimiter(collection.total_count)
t('trestle.helpers.page_entries_info.more_pages.display_entries', entry_name: entry_name, first: first, last: last, total: total, default: "Displaying %{entry_name} <strong>%{first} - %{last}</strong> of <b>%{total}</b>")
end.html_safe
end | [
"def",
"page_entries_info",
"(",
"collection",
",",
"options",
"=",
"{",
"}",
")",
"entry_name",
"=",
"options",
"[",
":entry_name",
"]",
"||",
"\"entry\"",
"entry_name",
"=",
"entry_name",
".",
"pluralize",
"unless",
"collection",
".",
"total_count",
"==",
"1",
"if",
"collection",
".",
"total_pages",
"<",
"2",
"t",
"(",
"'trestle.helpers.page_entries_info.one_page.display_entries'",
",",
"entry_name",
":",
"entry_name",
",",
"count",
":",
"collection",
".",
"total_count",
",",
"default",
":",
"\"Displaying <strong>all %{count}</strong> %{entry_name}\"",
")",
"else",
"first",
"=",
"number_with_delimiter",
"(",
"collection",
".",
"offset_value",
"+",
"1",
")",
"last",
"=",
"number_with_delimiter",
"(",
"(",
"sum",
"=",
"collection",
".",
"offset_value",
"+",
"collection",
".",
"limit_value",
")",
">",
"collection",
".",
"total_count",
"?",
"collection",
".",
"total_count",
":",
"sum",
")",
"total",
"=",
"number_with_delimiter",
"(",
"collection",
".",
"total_count",
")",
"t",
"(",
"'trestle.helpers.page_entries_info.more_pages.display_entries'",
",",
"entry_name",
":",
"entry_name",
",",
"first",
":",
"first",
",",
"last",
":",
"last",
",",
"total",
":",
"total",
",",
"default",
":",
"\"Displaying %{entry_name} <strong>%{first} - %{last}</strong> of <b>%{total}</b>\"",
")",
"end",
".",
"html_safe",
"end"
] | Custom version of Kaminari's page_entries_info helper to use a
Trestle-scoped I18n key and add a delimiter to the total count. | [
"Custom",
"version",
"of",
"Kaminari",
"s",
"page_entries_info",
"helper",
"to",
"use",
"a",
"Trestle",
"-",
"scoped",
"I18n",
"key",
"and",
"add",
"a",
"delimiter",
"to",
"the",
"total",
"count",
"."
] | fd5b8aeb5077e13d539cb5ddd99db1dd279f19ca | https://github.com/TrestleAdmin/trestle/blob/fd5b8aeb5077e13d539cb5ddd99db1dd279f19ca/app/helpers/trestle/pagination_helper.rb#L5-L18 | train |
TrestleAdmin/trestle | lib/trestle/configuration.rb | Trestle.Configuration.hook | def hook(name, options={}, &block)
hooks[name.to_s] << Hook.new(name.to_s, options, &block)
end | ruby | def hook(name, options={}, &block)
hooks[name.to_s] << Hook.new(name.to_s, options, &block)
end | [
"def",
"hook",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"hooks",
"[",
"name",
".",
"to_s",
"]",
"<<",
"Hook",
".",
"new",
"(",
"name",
".",
"to_s",
",",
"options",
",",
"block",
")",
"end"
] | Register an extension hook | [
"Register",
"an",
"extension",
"hook"
] | fd5b8aeb5077e13d539cb5ddd99db1dd279f19ca | https://github.com/TrestleAdmin/trestle/blob/fd5b8aeb5077e13d539cb5ddd99db1dd279f19ca/lib/trestle/configuration.rb#L90-L92 | train |
Shopify/shipit-engine | app/models/shipit/deploy.rb | Shipit.Deploy.trigger_rollback | def trigger_rollback(user = AnonymousUser.new, env: nil, force: false)
rollback = build_rollback(user, env: env, force: force)
rollback.save!
rollback.enqueue
lock_reason = "A rollback for #{rollback.since_commit.sha} has been triggered. " \
"Please make sure the reason for the rollback has been addressed before deploying again."
stack.update!(lock_reason: lock_reason, lock_author_id: user.id)
rollback
end | ruby | def trigger_rollback(user = AnonymousUser.new, env: nil, force: false)
rollback = build_rollback(user, env: env, force: force)
rollback.save!
rollback.enqueue
lock_reason = "A rollback for #{rollback.since_commit.sha} has been triggered. " \
"Please make sure the reason for the rollback has been addressed before deploying again."
stack.update!(lock_reason: lock_reason, lock_author_id: user.id)
rollback
end | [
"def",
"trigger_rollback",
"(",
"user",
"=",
"AnonymousUser",
".",
"new",
",",
"env",
":",
"nil",
",",
"force",
":",
"false",
")",
"rollback",
"=",
"build_rollback",
"(",
"user",
",",
"env",
":",
"env",
",",
"force",
":",
"force",
")",
"rollback",
".",
"save!",
"rollback",
".",
"enqueue",
"lock_reason",
"=",
"\"A rollback for #{rollback.since_commit.sha} has been triggered. \"",
"\"Please make sure the reason for the rollback has been addressed before deploying again.\"",
"stack",
".",
"update!",
"(",
"lock_reason",
":",
"lock_reason",
",",
"lock_author_id",
":",
"user",
".",
"id",
")",
"rollback",
"end"
] | Rolls the stack back to this deploy | [
"Rolls",
"the",
"stack",
"back",
"to",
"this",
"deploy"
] | f6b93d8a242962016e0f82e99c2eb223bdc75003 | https://github.com/Shopify/shipit-engine/blob/f6b93d8a242962016e0f82e99c2eb223bdc75003/app/models/shipit/deploy.rb#L76-L86 | train |
realm/jazzy | lib/jazzy/podspec_documenter.rb | Jazzy.PodspecDocumenter.compiler_swift_version | def compiler_swift_version(user_version)
return LATEST_SWIFT_VERSION unless user_version
LONG_SWIFT_VERSIONS.select do |version|
user_version.start_with?(version)
end.last || "#{user_version[0]}.0"
end | ruby | def compiler_swift_version(user_version)
return LATEST_SWIFT_VERSION unless user_version
LONG_SWIFT_VERSIONS.select do |version|
user_version.start_with?(version)
end.last || "#{user_version[0]}.0"
end | [
"def",
"compiler_swift_version",
"(",
"user_version",
")",
"return",
"LATEST_SWIFT_VERSION",
"unless",
"user_version",
"LONG_SWIFT_VERSIONS",
".",
"select",
"do",
"|",
"version",
"|",
"user_version",
".",
"start_with?",
"(",
"version",
")",
"end",
".",
"last",
"||",
"\"#{user_version[0]}.0\"",
"end"
] | Go from a full Swift version like 4.2.1 to
something valid for SWIFT_VERSION. | [
"Go",
"from",
"a",
"full",
"Swift",
"version",
"like",
"4",
".",
"2",
".",
"1",
"to",
"something",
"valid",
"for",
"SWIFT_VERSION",
"."
] | e8744dbdb78814b237e8d57a82d40953560e9143 | https://github.com/realm/jazzy/blob/e8744dbdb78814b237e8d57a82d40953560e9143/lib/jazzy/podspec_documenter.rb#L109-L115 | train |
cerebris/jsonapi-resources | lib/jsonapi/resource_id_tree.rb | JSONAPI.ResourceIdTree.fetch_related_resource_id_tree | def fetch_related_resource_id_tree(relationship)
relationship_name = relationship.name.to_sym
@related_resource_id_trees[relationship_name] ||= RelatedResourceIdTree.new(relationship, self)
end | ruby | def fetch_related_resource_id_tree(relationship)
relationship_name = relationship.name.to_sym
@related_resource_id_trees[relationship_name] ||= RelatedResourceIdTree.new(relationship, self)
end | [
"def",
"fetch_related_resource_id_tree",
"(",
"relationship",
")",
"relationship_name",
"=",
"relationship",
".",
"name",
".",
"to_sym",
"@related_resource_id_trees",
"[",
"relationship_name",
"]",
"||=",
"RelatedResourceIdTree",
".",
"new",
"(",
"relationship",
",",
"self",
")",
"end"
] | Gets the related Resource Id Tree for a relationship, and creates it first if it does not exist
@param relationship [JSONAPI::Relationship]
@return [JSONAPI::RelatedResourceIdTree] the new or existing resource id tree for the requested relationship | [
"Gets",
"the",
"related",
"Resource",
"Id",
"Tree",
"for",
"a",
"relationship",
"and",
"creates",
"it",
"first",
"if",
"it",
"does",
"not",
"exist"
] | 1ac6bba777e364eaa36706f888792b99b63d8d1a | https://github.com/cerebris/jsonapi-resources/blob/1ac6bba777e364eaa36706f888792b99b63d8d1a/lib/jsonapi/resource_id_tree.rb#L15-L18 | train |
cerebris/jsonapi-resources | lib/jsonapi/resource_id_tree.rb | JSONAPI.PrimaryResourceIdTree.add_resource_fragment | def add_resource_fragment(fragment, include_related)
fragment.primary = true
init_included_relationships(fragment, include_related)
@fragments[fragment.identity] = fragment
end | ruby | def add_resource_fragment(fragment, include_related)
fragment.primary = true
init_included_relationships(fragment, include_related)
@fragments[fragment.identity] = fragment
end | [
"def",
"add_resource_fragment",
"(",
"fragment",
",",
"include_related",
")",
"fragment",
".",
"primary",
"=",
"true",
"init_included_relationships",
"(",
"fragment",
",",
"include_related",
")",
"@fragments",
"[",
"fragment",
".",
"identity",
"]",
"=",
"fragment",
"end"
] | Adds a Resource Fragment to the Resources hash
@param fragment [JSONAPI::ResourceFragment]
@param include_related [Hash]
@return [null] | [
"Adds",
"a",
"Resource",
"Fragment",
"to",
"the",
"Resources",
"hash"
] | 1ac6bba777e364eaa36706f888792b99b63d8d1a | https://github.com/cerebris/jsonapi-resources/blob/1ac6bba777e364eaa36706f888792b99b63d8d1a/lib/jsonapi/resource_id_tree.rb#L55-L61 | train |
cerebris/jsonapi-resources | lib/jsonapi/resource_id_tree.rb | JSONAPI.RelatedResourceIdTree.add_resource_fragment | def add_resource_fragment(fragment, include_related)
init_included_relationships(fragment, include_related)
fragment.related_from.each do |rid|
@source_resource_id_tree.fragments[rid].add_related_identity(parent_relationship.name, fragment.identity)
end
@fragments[fragment.identity] = fragment
end | ruby | def add_resource_fragment(fragment, include_related)
init_included_relationships(fragment, include_related)
fragment.related_from.each do |rid|
@source_resource_id_tree.fragments[rid].add_related_identity(parent_relationship.name, fragment.identity)
end
@fragments[fragment.identity] = fragment
end | [
"def",
"add_resource_fragment",
"(",
"fragment",
",",
"include_related",
")",
"init_included_relationships",
"(",
"fragment",
",",
"include_related",
")",
"fragment",
".",
"related_from",
".",
"each",
"do",
"|",
"rid",
"|",
"@source_resource_id_tree",
".",
"fragments",
"[",
"rid",
"]",
".",
"add_related_identity",
"(",
"parent_relationship",
".",
"name",
",",
"fragment",
".",
"identity",
")",
"end",
"@fragments",
"[",
"fragment",
".",
"identity",
"]",
"=",
"fragment",
"end"
] | Adds a Resource Fragment to the fragments hash
@param fragment [JSONAPI::ResourceFragment]
@param include_related [Hash]
@return [null] | [
"Adds",
"a",
"Resource",
"Fragment",
"to",
"the",
"fragments",
"hash"
] | 1ac6bba777e364eaa36706f888792b99b63d8d1a | https://github.com/cerebris/jsonapi-resources/blob/1ac6bba777e364eaa36706f888792b99b63d8d1a/lib/jsonapi/resource_id_tree.rb#L102-L110 | train |
googleapis/google-cloud-ruby | google-cloud-error_reporting/lib/google-cloud-error_reporting.rb | Google.Cloud.error_reporting | def error_reporting scope: nil, timeout: nil, client_config: nil
Google::Cloud.error_reporting @project, @keyfile,
scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | ruby | def error_reporting scope: nil, timeout: nil, client_config: nil
Google::Cloud.error_reporting @project, @keyfile,
scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | [
"def",
"error_reporting",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"error_reporting",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
"end"
] | Create a new object for connecting to the Stackdriver Error Reporting
service. Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/cloud-platform`
@param [Integer] timeout Default timeout to use in requests. Optional.
@param [Hash] client_config A hash of values to override the default
behavior of the API client. Optional.
@return [Google::Cloud::ErrorReporting::Project]
@example
require "google/cloud/error_reporting"
gcloud = Google::Cloud.new "GCP_Project_ID",
"/path/to/gcp/secretkey.json"
error_reporting = gcloud.error_reporting
error_event = error_reporting.error_event "Error with Backtrace",
event_time: Time.now,
service_name: "my_app_name",
service_version: "v8"
error_reporting.report error_event | [
"Create",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Stackdriver",
"Error",
"Reporting",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-error_reporting/lib/google-cloud-error_reporting.rb#L62-L67 | train |
googleapis/google-cloud-ruby | google-cloud-dns/lib/google-cloud-dns.rb | Google.Cloud.dns | def dns scope: nil, retries: nil, timeout: nil
Google::Cloud.dns @project, @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | ruby | def dns scope: nil, retries: nil, timeout: nil
Google::Cloud.dns @project, @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | [
"def",
"dns",
"scope",
":",
"nil",
",",
"retries",
":",
"nil",
",",
"timeout",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"dns",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"retries",
":",
"(",
"retries",
"||",
"@retries",
")",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
"end"
] | Creates a new object for connecting to the DNS service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/ndev.clouddns.readwrite`
@param [Integer] retries Number of times to retry requests on server
error. The default value is `3`. Optional.
@param [Integer] timeout Default timeout to use in requests. Optional.
@return [Google::Cloud::Dns::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
dns = gcloud.dns
zone = dns.zone "example-com"
zone.records.each do |record|
puts record.name
end
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
dns_readonly = "https://www.googleapis.com/auth/ndev.clouddns.readonly"
dns = gcloud.dns scope: dns_readonly | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"DNS",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-dns/lib/google-cloud-dns.rb#L66-L70 | train |
googleapis/google-cloud-ruby | google-cloud-spanner/lib/google-cloud-spanner.rb | Google.Cloud.spanner | def spanner scope: nil, timeout: nil, client_config: nil
Google::Cloud.spanner @project, @keyfile, scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | ruby | def spanner scope: nil, timeout: nil, client_config: nil
Google::Cloud.spanner @project, @keyfile, scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | [
"def",
"spanner",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"spanner",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
"end"
] | Creates a new object for connecting to the Spanner service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scopes are:
* `https://www.googleapis.com/auth/spanner`
* `https://www.googleapis.com/auth/spanner.data`
@param [Integer] timeout Default timeout to use in requests. Optional.
@param [Hash] client_config A hash of values to override the default
behavior of the API client. Optional.
@return [Google::Cloud::Spanner::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
spanner = gcloud.spanner
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
platform_scope = "https://www.googleapis.com/auth/cloud-platform"
spanner = gcloud.spanner scope: platform_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Spanner",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-spanner/lib/google-cloud-spanner.rb#L64-L68 | train |
googleapis/google-cloud-ruby | google-cloud-logging/lib/google-cloud-logging.rb | Google.Cloud.logging | def logging scope: nil, timeout: nil, client_config: nil
timeout ||= @timeout
Google::Cloud.logging @project, @keyfile, scope: scope,
timeout: timeout,
client_config: client_config
end | ruby | def logging scope: nil, timeout: nil, client_config: nil
timeout ||= @timeout
Google::Cloud.logging @project, @keyfile, scope: scope,
timeout: timeout,
client_config: client_config
end | [
"def",
"logging",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"timeout",
"||=",
"@timeout",
"Google",
"::",
"Cloud",
".",
"logging",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"timeout",
",",
"client_config",
":",
"client_config",
"end"
] | Creates a new object for connecting to the Stackdriver Logging service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/logging.admin`
@param [Integer] timeout Default timeout to use in requests. Optional.
@param [Hash] client_config A hash of values to override the default
behavior of the API client. Optional.
@return [Google::Cloud::Logging::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
logging = gcloud.logging
entries = logging.entries
entries.each do |e|
puts "[#{e.timestamp}] #{e.log_name} #{e.payload.inspect}"
end
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
platform_scope = "https://www.googleapis.com/auth/cloud-platform"
logging = gcloud.logging scope: platform_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Stackdriver",
"Logging",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-logging/lib/google-cloud-logging.rb#L69-L74 | train |
googleapis/google-cloud-ruby | google-cloud-bigquery/lib/google-cloud-bigquery.rb | Google.Cloud.bigquery | def bigquery scope: nil, retries: nil, timeout: nil
Google::Cloud.bigquery @project, @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | ruby | def bigquery scope: nil, retries: nil, timeout: nil
Google::Cloud.bigquery @project, @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | [
"def",
"bigquery",
"scope",
":",
"nil",
",",
"retries",
":",
"nil",
",",
"timeout",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"bigquery",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"retries",
":",
"(",
"retries",
"||",
"@retries",
")",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
"end"
] | Creates a new object for connecting to the BigQuery service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/bigquery`
@param [Integer] retries Number of times to retry requests on server
error. The default value is `5`. Optional.
@param [Integer] timeout Default request timeout in seconds. Optional.
@return [Google::Cloud::Bigquery::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
bigquery = gcloud.bigquery
dataset = bigquery.dataset "my_dataset"
table = dataset.table "my_table"
table.data.each do |row|
puts row
end
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
platform_scope = "https://www.googleapis.com/auth/cloud-platform"
bigquery = gcloud.bigquery scope: platform_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"BigQuery",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-bigquery/lib/google-cloud-bigquery.rb#L67-L71 | train |
googleapis/google-cloud-ruby | google-cloud-debugger/lib/google-cloud-debugger.rb | Google.Cloud.debugger | def debugger service_name: nil, service_version: nil, scope: nil,
timeout: nil, client_config: nil
Google::Cloud.debugger @project, @keyfile,
service_name: service_name,
service_version: service_version,
scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | ruby | def debugger service_name: nil, service_version: nil, scope: nil,
timeout: nil, client_config: nil
Google::Cloud.debugger @project, @keyfile,
service_name: service_name,
service_version: service_version,
scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | [
"def",
"debugger",
"service_name",
":",
"nil",
",",
"service_version",
":",
"nil",
",",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"debugger",
"@project",
",",
"@keyfile",
",",
"service_name",
":",
"service_name",
",",
"service_version",
":",
"service_version",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
"end"
] | Creates a new debugger object for instrumenting Stackdriver Debugger for
an application. Each call creates a new debugger agent with independent
connection service.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String] service_name Name for the debuggee application. Optional.
@param [String] service_version Version identifier for the debuggee
application. Optional.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/cloud_debugger`
* `https://www.googleapis.com/auth/logging.admin`
@param [Integer] timeout Default timeout to use in requests. Optional.
@param [Hash] client_config A hash of values to override the default
behavior of the API client. Optional.
@return [Google::Cloud::Debugger::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
debugger = gcloud.debugger
debugger.start
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
platform_scope = "https://www.googleapis.com/auth/cloud-platform"
debugger = gcloud.debugger scope: platform_scope | [
"Creates",
"a",
"new",
"debugger",
"object",
"for",
"instrumenting",
"Stackdriver",
"Debugger",
"for",
"an",
"application",
".",
"Each",
"call",
"creates",
"a",
"new",
"debugger",
"agent",
"with",
"independent",
"connection",
"service",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-debugger/lib/google-cloud-debugger.rb#L71-L79 | train |
googleapis/google-cloud-ruby | google-cloud-datastore/lib/google-cloud-datastore.rb | Google.Cloud.datastore | def datastore scope: nil, timeout: nil, client_config: nil
Google::Cloud.datastore @project, @keyfile,
scope: scope, timeout: (timeout || @timeout),
client_config: client_config
end | ruby | def datastore scope: nil, timeout: nil, client_config: nil
Google::Cloud.datastore @project, @keyfile,
scope: scope, timeout: (timeout || @timeout),
client_config: client_config
end | [
"def",
"datastore",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"datastore",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
"end"
] | Creates a new object for connecting to the Datastore service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/datastore`
@param [Integer] timeout Default timeout to use in requests. Optional.
@param [Hash] client_config A hash of values to override the default
behavior of the API client. See Google::Gax::CallSettings. Optional.
@return [Google::Cloud::Datastore::Dataset]
@example
require "google/cloud"
gcloud = Google::Cloud.new
datastore = gcloud.datastore
task = datastore.entity "Task" do |t|
t["type"] = "Personal"
t["done"] = false
t["priority"] = 4
t["description"] = "Learn Cloud Datastore"
end
datastore.save task
@example You shouldn't need to override the default scope, but you can:
require "google/cloud"
gcloud = Google::Cloud.new
platform_scope = "https://www.googleapis.com/auth/cloud-platform"
datastore = gcloud.datastore scope: platform_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Datastore",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-datastore/lib/google-cloud-datastore.rb#L72-L76 | train |
googleapis/google-cloud-ruby | google-cloud-resource_manager/lib/google-cloud-resource_manager.rb | Google.Cloud.resource_manager | def resource_manager scope: nil, retries: nil, timeout: nil
Google::Cloud.resource_manager @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | ruby | def resource_manager scope: nil, retries: nil, timeout: nil
Google::Cloud.resource_manager @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | [
"def",
"resource_manager",
"scope",
":",
"nil",
",",
"retries",
":",
"nil",
",",
"timeout",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"resource_manager",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"retries",
":",
"(",
"retries",
"||",
"@retries",
")",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
"end"
] | Creates a new object for connecting to the Resource Manager service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/cloud-platform`
@param [Integer] retries Number of times to retry requests on server
error. The default value is `3`. Optional.
@param [Integer] timeout Default timeout to use in requests. Optional.
@return [Google::Cloud::ResourceManager::Manager]
@example
require "google/cloud"
gcloud = Google::Cloud.new
resource_manager = gcloud.resource_manager
resource_manager.projects.each do |project|
puts projects.project_id
end
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
readonly_scope = \
"https://www.googleapis.com/auth/cloudresourcemanager.readonly"
resource_manager = gcloud.resource_manager scope: readonly_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Resource",
"Manager",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-resource_manager/lib/google-cloud-resource_manager.rb#L67-L71 | train |
googleapis/google-cloud-ruby | google-cloud-storage/lib/google-cloud-storage.rb | Google.Cloud.storage | def storage scope: nil, retries: nil, timeout: nil
Google::Cloud.storage @project, @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | ruby | def storage scope: nil, retries: nil, timeout: nil
Google::Cloud.storage @project, @keyfile, scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | [
"def",
"storage",
"scope",
":",
"nil",
",",
"retries",
":",
"nil",
",",
"timeout",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"storage",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"retries",
":",
"(",
"retries",
"||",
"@retries",
")",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
"end"
] | Creates a new object for connecting to the Storage service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@see https://cloud.google.com/storage/docs/authentication#oauth Storage
OAuth 2.0 Authentication
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/devstorage.full_control`
@param [Integer] retries Number of times to retry requests on server
error. The default value is `3`. Optional.
@param [Integer] timeout Default timeout to use in requests. Optional.
@return [Google::Cloud::Storage::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
storage = gcloud.storage
bucket = storage.bucket "my-bucket"
file = bucket.file "path/to/my-file.ext"
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
readonly_scope = "https://www.googleapis.com/auth/devstorage.read_only"
readonly_storage = gcloud.storage scope: readonly_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Storage",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-storage/lib/google-cloud-storage.rb#L67-L71 | train |
googleapis/google-cloud-ruby | google-cloud-translate/lib/google-cloud-translate.rb | Google.Cloud.translate | def translate key = nil, scope: nil, retries: nil, timeout: nil
Google::Cloud.translate key, project_id: @project, credentials: @keyfile,
scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | ruby | def translate key = nil, scope: nil, retries: nil, timeout: nil
Google::Cloud.translate key, project_id: @project, credentials: @keyfile,
scope: scope,
retries: (retries || @retries),
timeout: (timeout || @timeout)
end | [
"def",
"translate",
"key",
"=",
"nil",
",",
"scope",
":",
"nil",
",",
"retries",
":",
"nil",
",",
"timeout",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"translate",
"key",
",",
"project_id",
":",
"@project",
",",
"credentials",
":",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"retries",
":",
"(",
"retries",
"||",
"@retries",
")",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
"end"
] | Creates a new object for connecting to the Cloud Translation API. Each
call creates a new connection.
Like other Cloud Platform services, Google Cloud Translation API supports
authentication using a project ID and OAuth 2.0 credentials. In addition,
it supports authentication using a public API access key. (If both the API
key and the project and OAuth 2.0 credentials are provided, the API key
will be used.) Instructions and configuration options are covered in the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String] key a public API access key (not an OAuth 2.0 token)
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/cloud-platform`
@param [Integer] retries Number of times to retry requests on server
error. The default value is `3`. Optional.
@param [Integer] timeout Default timeout to use in requests. Optional.
@return [Google::Cloud::Translate::Api]
@example
require "google/cloud"
gcloud = Google::Cloud.new
translate = gcloud.translate "api-key-abc123XYZ789"
translation = translate.translate "Hello world!", to: "la"
translation.text #=> "Salve mundi!"
@example Using API Key from the environment variable.
require "google/cloud"
ENV["TRANSLATE_KEY"] = "api-key-abc123XYZ789"
gcloud = Google::Cloud.new
translate = gcloud.translate
translation = translate.translate "Hello world!", to: "la"
translation.text #=> "Salve mundi!" | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Cloud",
"Translation",
"API",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-translate/lib/google-cloud-translate.rb#L74-L79 | train |
googleapis/google-cloud-ruby | google-cloud-firestore/lib/google-cloud-firestore.rb | Google.Cloud.firestore | def firestore scope: nil, timeout: nil, client_config: nil
Google::Cloud.firestore @project, @keyfile,
scope: scope, timeout: (timeout || @timeout),
client_config: client_config
end | ruby | def firestore scope: nil, timeout: nil, client_config: nil
Google::Cloud.firestore @project, @keyfile,
scope: scope, timeout: (timeout || @timeout),
client_config: client_config
end | [
"def",
"firestore",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"firestore",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
"end"
] | Creates a new object for connecting to the Firestore service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/datastore`
@param [Integer] timeout Default timeout to use in requests. Optional.
@param [Hash] client_config A hash of values to override the default
behavior of the API client. Optional.
@return [Google::Cloud::Firestore::Client]
@example
require "google/cloud"
gcloud = Google::Cloud.new
firestore = gcloud.firestore
@example The default scope can be overridden with the `scope` option:
require "google/cloud"
gcloud = Google::Cloud.new
platform_scope = "https://www.googleapis.com/auth/cloud-platform"
firestore = gcloud.firestore scope: platform_scope | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Firestore",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-firestore/lib/google-cloud-firestore.rb#L63-L67 | train |
googleapis/google-cloud-ruby | google-cloud-trace/lib/google-cloud-trace.rb | Google.Cloud.trace | def trace scope: nil, timeout: nil, client_config: nil
Google::Cloud.trace @project, @keyfile, scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | ruby | def trace scope: nil, timeout: nil, client_config: nil
Google::Cloud.trace @project, @keyfile, scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
end | [
"def",
"trace",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"trace",
"@project",
",",
"@keyfile",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
"end"
] | Creates a new object for connecting to the Stackdriver Trace service.
Each call creates a new connection.
For more information on connecting to Google Cloud see the
{file:AUTHENTICATION.md Authentication Guide}.
@param [String, Array<String>] scope The OAuth 2.0 scopes controlling the
set of resources and operations that the connection can access. See
[Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The default scope is:
* `https://www.googleapis.com/auth/cloud-platform`
@param [Integer] timeout Default timeout to use in requests. Optional.
@return [Google::Cloud::Trace::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
trace_client = gcloud.trace
traces = trace_client.list_traces Time.now - 3600, Time.now
traces.each do |trace|
puts "Retrieved trace ID: #{trace.trace_id}"
end | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Stackdriver",
"Trace",
"service",
".",
"Each",
"call",
"creates",
"a",
"new",
"connection",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-trace/lib/google-cloud-trace.rb#L60-L64 | train |
googleapis/google-cloud-ruby | google-cloud-bigtable/lib/google-cloud-bigtable.rb | Google.Cloud.bigtable | def bigtable scope: nil, timeout: nil, credentials: nil, client_config: nil
Google::Cloud.bigtable(
project_id: @project,
credentials: (credentials || @keyfile),
scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
)
end | ruby | def bigtable scope: nil, timeout: nil, credentials: nil, client_config: nil
Google::Cloud.bigtable(
project_id: @project,
credentials: (credentials || @keyfile),
scope: scope,
timeout: (timeout || @timeout),
client_config: client_config
)
end | [
"def",
"bigtable",
"scope",
":",
"nil",
",",
"timeout",
":",
"nil",
",",
"credentials",
":",
"nil",
",",
"client_config",
":",
"nil",
"Google",
"::",
"Cloud",
".",
"bigtable",
"(",
"project_id",
":",
"@project",
",",
"credentials",
":",
"(",
"credentials",
"||",
"@keyfile",
")",
",",
"scope",
":",
"scope",
",",
"timeout",
":",
"(",
"timeout",
"||",
"@timeout",
")",
",",
"client_config",
":",
"client_config",
")",
"end"
] | Creates a new object for connecting to the Cloud Bigtable service.
For more information on connecting to Google Cloud Platform, see the
{file:AUTHENTICATION.md Authentication Guide}.
@param scope [Array<String>]
The OAuth 2.0 scopes controlling the set of resources and operations
that the connection can access. See [Using OAuth 2.0 to Access Google
APIs](https://developers.google.com/identity/protocols/OAuth2).
The OAuth scopes for this service. This parameter is ignored if an
updater_proc is supplied.
@param timeout [Integer]
The default timeout, in seconds, for calls made through this client.
@param credentials [Google::Auth::Credentials, String, Hash, GRPC::Core::Channel, GRPC::Core::ChannelCredentials, Proc]
Provides the means for authenticating requests made by the client. This parameter can
be one of the following types.
`Google::Auth::Credentials` uses the properties of its represented keyfile for
authenticating requests made by this client.
`String` will be treated as the path to the keyfile to use to construct
credentials for this client.
`Hash` will be treated as the contents of a keyfile to use to construct
credentials for this client.
`GRPC::Core::Channel` will be used to make calls through.
`GRPC::Core::ChannelCredentials` will be used to set up the gRPC client. The channel credentials
should already be composed with a `GRPC::Core::CallCredentials` object.
`Proc` will be used as an updater_proc for the gRPC channel. The proc transforms the
metadata for requests, generally, to give OAuth credentials.
@param client_config [Hash]
A hash for call options for each method.
See Google::Gax#construct_settings for the structure of
this data. Falls back to the default config if not specified
or the specified config is missing data points.
@return [Google::Cloud::Bigtable::Project]
@example
require "google/cloud"
gcloud = Google::Cloud.new
bigtable = gcloud.bigtable | [
"Creates",
"a",
"new",
"object",
"for",
"connecting",
"to",
"the",
"Cloud",
"Bigtable",
"service",
"."
] | 846c1a57250ac860ef4de1b54853a480ab2ff702 | https://github.com/googleapis/google-cloud-ruby/blob/846c1a57250ac860ef4de1b54853a480ab2ff702/google-cloud-bigtable/lib/google-cloud-bigtable.rb#L71-L79 | train |
bblimke/webmock | lib/webmock/request_pattern.rb | WebMock.BodyPattern.matching_body_hashes? | def matching_body_hashes?(query_parameters, pattern, content_type)
return false unless query_parameters.is_a?(Hash)
return false unless query_parameters.keys.sort == pattern.keys.sort
query_parameters.each do |key, actual|
expected = pattern[key]
if actual.is_a?(Hash) && expected.is_a?(Hash)
return false unless matching_body_hashes?(actual, expected, content_type)
else
expected = WebMock::Util::ValuesStringifier.stringify_values(expected) if url_encoded_body?(content_type)
return false unless expected === actual
end
end
true
end | ruby | def matching_body_hashes?(query_parameters, pattern, content_type)
return false unless query_parameters.is_a?(Hash)
return false unless query_parameters.keys.sort == pattern.keys.sort
query_parameters.each do |key, actual|
expected = pattern[key]
if actual.is_a?(Hash) && expected.is_a?(Hash)
return false unless matching_body_hashes?(actual, expected, content_type)
else
expected = WebMock::Util::ValuesStringifier.stringify_values(expected) if url_encoded_body?(content_type)
return false unless expected === actual
end
end
true
end | [
"def",
"matching_body_hashes?",
"(",
"query_parameters",
",",
"pattern",
",",
"content_type",
")",
"return",
"false",
"unless",
"query_parameters",
".",
"is_a?",
"(",
"Hash",
")",
"return",
"false",
"unless",
"query_parameters",
".",
"keys",
".",
"sort",
"==",
"pattern",
".",
"keys",
".",
"sort",
"query_parameters",
".",
"each",
"do",
"|",
"key",
",",
"actual",
"|",
"expected",
"=",
"pattern",
"[",
"key",
"]",
"if",
"actual",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"expected",
".",
"is_a?",
"(",
"Hash",
")",
"return",
"false",
"unless",
"matching_body_hashes?",
"(",
"actual",
",",
"expected",
",",
"content_type",
")",
"else",
"expected",
"=",
"WebMock",
"::",
"Util",
"::",
"ValuesStringifier",
".",
"stringify_values",
"(",
"expected",
")",
"if",
"url_encoded_body?",
"(",
"content_type",
")",
"return",
"false",
"unless",
"expected",
"===",
"actual",
"end",
"end",
"true",
"end"
] | Compare two hashes for equality
For two hashes to match they must have the same length and all
values must match when compared using `#===`.
The following hashes are examples of matches:
{a: /\d+/} and {a: '123'}
{a: '123'} and {a: '123'}
{a: {b: /\d+/}} and {a: {b: '123'}}
{a: {b: 'wow'}} and {a: {b: 'wow'}}
@param [Hash] query_parameters typically the result of parsing
JSON, XML or URL encoded parameters.
@param [Hash] pattern which contains keys with a string, hash or
regular expression value to use for comparison.
@return [Boolean] true if the paramaters match the comparison
hash, false if not. | [
"Compare",
"two",
"hashes",
"for",
"equality"
] | c0bcc09af372286cd110ec4159112ce583007951 | https://github.com/bblimke/webmock/blob/c0bcc09af372286cd110ec4159112ce583007951/lib/webmock/request_pattern.rb#L310-L324 | train |
jch/html-pipeline | lib/html/pipeline.rb | HTML.Pipeline.call | def call(html, context = {}, result = nil)
context = @default_context.merge(context)
context = context.freeze
result ||= @result_class.new
payload = default_payload filters: @filters.map(&:name),
context: context, result: result
instrument 'call_pipeline.html_pipeline', payload do
result[:output] =
@filters.inject(html) do |doc, filter|
perform_filter(filter, doc, context, result)
end
end
result
end | ruby | def call(html, context = {}, result = nil)
context = @default_context.merge(context)
context = context.freeze
result ||= @result_class.new
payload = default_payload filters: @filters.map(&:name),
context: context, result: result
instrument 'call_pipeline.html_pipeline', payload do
result[:output] =
@filters.inject(html) do |doc, filter|
perform_filter(filter, doc, context, result)
end
end
result
end | [
"def",
"call",
"(",
"html",
",",
"context",
"=",
"{",
"}",
",",
"result",
"=",
"nil",
")",
"context",
"=",
"@default_context",
".",
"merge",
"(",
"context",
")",
"context",
"=",
"context",
".",
"freeze",
"result",
"||=",
"@result_class",
".",
"new",
"payload",
"=",
"default_payload",
"filters",
":",
"@filters",
".",
"map",
"(",
":name",
")",
",",
"context",
":",
"context",
",",
"result",
":",
"result",
"instrument",
"'call_pipeline.html_pipeline'",
",",
"payload",
"do",
"result",
"[",
":output",
"]",
"=",
"@filters",
".",
"inject",
"(",
"html",
")",
"do",
"|",
"doc",
",",
"filter",
"|",
"perform_filter",
"(",
"filter",
",",
"doc",
",",
"context",
",",
"result",
")",
"end",
"end",
"result",
"end"
] | Apply all filters in the pipeline to the given HTML.
html - A String containing HTML or a DocumentFragment object.
context - The context hash passed to each filter. See the Filter docs
for more info on possible values. This object MUST NOT be modified
in place by filters. Use the Result for passing state back.
result - The result Hash passed to each filter for modification. This
is where Filters store extracted information from the content.
Returns the result Hash after being filtered by this Pipeline. Contains an
:output key with the DocumentFragment or String HTML markup based on the
output of the last filter in the pipeline. | [
"Apply",
"all",
"filters",
"in",
"the",
"pipeline",
"to",
"the",
"given",
"HTML",
"."
] | f1bbce4858876dc2619c61a8b18637b5d3321b1c | https://github.com/jch/html-pipeline/blob/f1bbce4858876dc2619c61a8b18637b5d3321b1c/lib/html/pipeline.rb#L107-L120 | train |
jch/html-pipeline | lib/html/pipeline.rb | HTML.Pipeline.to_document | def to_document(input, context = {}, result = nil)
result = call(input, context, result)
HTML::Pipeline.parse(result[:output])
end | ruby | def to_document(input, context = {}, result = nil)
result = call(input, context, result)
HTML::Pipeline.parse(result[:output])
end | [
"def",
"to_document",
"(",
"input",
",",
"context",
"=",
"{",
"}",
",",
"result",
"=",
"nil",
")",
"result",
"=",
"call",
"(",
"input",
",",
"context",
",",
"result",
")",
"HTML",
"::",
"Pipeline",
".",
"parse",
"(",
"result",
"[",
":output",
"]",
")",
"end"
] | Like call but guarantee the value returned is a DocumentFragment.
Pipelines may return a DocumentFragment or a String. Callers that need a
DocumentFragment should use this method. | [
"Like",
"call",
"but",
"guarantee",
"the",
"value",
"returned",
"is",
"a",
"DocumentFragment",
".",
"Pipelines",
"may",
"return",
"a",
"DocumentFragment",
"or",
"a",
"String",
".",
"Callers",
"that",
"need",
"a",
"DocumentFragment",
"should",
"use",
"this",
"method",
"."
] | f1bbce4858876dc2619c61a8b18637b5d3321b1c | https://github.com/jch/html-pipeline/blob/f1bbce4858876dc2619c61a8b18637b5d3321b1c/lib/html/pipeline.rb#L138-L141 | train |
jch/html-pipeline | lib/html/pipeline.rb | HTML.Pipeline.to_html | def to_html(input, context = {}, result = nil)
result = call(input, context, result = nil)
output = result[:output]
if output.respond_to?(:to_html)
output.to_html
else
output.to_s
end
end | ruby | def to_html(input, context = {}, result = nil)
result = call(input, context, result = nil)
output = result[:output]
if output.respond_to?(:to_html)
output.to_html
else
output.to_s
end
end | [
"def",
"to_html",
"(",
"input",
",",
"context",
"=",
"{",
"}",
",",
"result",
"=",
"nil",
")",
"result",
"=",
"call",
"(",
"input",
",",
"context",
",",
"result",
"=",
"nil",
")",
"output",
"=",
"result",
"[",
":output",
"]",
"if",
"output",
".",
"respond_to?",
"(",
":to_html",
")",
"output",
".",
"to_html",
"else",
"output",
".",
"to_s",
"end",
"end"
] | Like call but guarantee the value returned is a string of HTML markup. | [
"Like",
"call",
"but",
"guarantee",
"the",
"value",
"returned",
"is",
"a",
"string",
"of",
"HTML",
"markup",
"."
] | f1bbce4858876dc2619c61a8b18637b5d3321b1c | https://github.com/jch/html-pipeline/blob/f1bbce4858876dc2619c61a8b18637b5d3321b1c/lib/html/pipeline.rb#L144-L152 | train |
kaminari/kaminari | kaminari-core/lib/kaminari/models/page_scope_methods.rb | Kaminari.PageScopeMethods.total_pages | def total_pages
count_without_padding = total_count
count_without_padding -= @_padding if defined?(@_padding) && @_padding
count_without_padding = 0 if count_without_padding < 0
total_pages_count = (count_without_padding.to_f / limit_value).ceil
max_pages && (max_pages < total_pages_count) ? max_pages : total_pages_count
rescue FloatDomainError
raise ZeroPerPageOperation, "The number of total pages was incalculable. Perhaps you called .per(0)?"
end | ruby | def total_pages
count_without_padding = total_count
count_without_padding -= @_padding if defined?(@_padding) && @_padding
count_without_padding = 0 if count_without_padding < 0
total_pages_count = (count_without_padding.to_f / limit_value).ceil
max_pages && (max_pages < total_pages_count) ? max_pages : total_pages_count
rescue FloatDomainError
raise ZeroPerPageOperation, "The number of total pages was incalculable. Perhaps you called .per(0)?"
end | [
"def",
"total_pages",
"count_without_padding",
"=",
"total_count",
"count_without_padding",
"-=",
"@_padding",
"if",
"defined?",
"(",
"@_padding",
")",
"&&",
"@_padding",
"count_without_padding",
"=",
"0",
"if",
"count_without_padding",
"<",
"0",
"total_pages_count",
"=",
"(",
"count_without_padding",
".",
"to_f",
"/",
"limit_value",
")",
".",
"ceil",
"max_pages",
"&&",
"(",
"max_pages",
"<",
"total_pages_count",
")",
"?",
"max_pages",
":",
"total_pages_count",
"rescue",
"FloatDomainError",
"raise",
"ZeroPerPageOperation",
",",
"\"The number of total pages was incalculable. Perhaps you called .per(0)?\"",
"end"
] | Total number of pages | [
"Total",
"number",
"of",
"pages"
] | e2078ce46b145b811423dc8b5993e4bc87dc88b8 | https://github.com/kaminari/kaminari/blob/e2078ce46b145b811423dc8b5993e4bc87dc88b8/kaminari-core/lib/kaminari/models/page_scope_methods.rb#L35-L44 | train |
kaminari/kaminari | kaminari-core/lib/kaminari/models/page_scope_methods.rb | Kaminari.PageScopeMethods.current_page | def current_page
offset_without_padding = offset_value
offset_without_padding -= @_padding if defined?(@_padding) && @_padding
offset_without_padding = 0 if offset_without_padding < 0
(offset_without_padding / limit_value) + 1
rescue ZeroDivisionError
raise ZeroPerPageOperation, "Current page was incalculable. Perhaps you called .per(0)?"
end | ruby | def current_page
offset_without_padding = offset_value
offset_without_padding -= @_padding if defined?(@_padding) && @_padding
offset_without_padding = 0 if offset_without_padding < 0
(offset_without_padding / limit_value) + 1
rescue ZeroDivisionError
raise ZeroPerPageOperation, "Current page was incalculable. Perhaps you called .per(0)?"
end | [
"def",
"current_page",
"offset_without_padding",
"=",
"offset_value",
"offset_without_padding",
"-=",
"@_padding",
"if",
"defined?",
"(",
"@_padding",
")",
"&&",
"@_padding",
"offset_without_padding",
"=",
"0",
"if",
"offset_without_padding",
"<",
"0",
"(",
"offset_without_padding",
"/",
"limit_value",
")",
"+",
"1",
"rescue",
"ZeroDivisionError",
"raise",
"ZeroPerPageOperation",
",",
"\"Current page was incalculable. Perhaps you called .per(0)?\"",
"end"
] | Current page number | [
"Current",
"page",
"number"
] | e2078ce46b145b811423dc8b5993e4bc87dc88b8 | https://github.com/kaminari/kaminari/blob/e2078ce46b145b811423dc8b5993e4bc87dc88b8/kaminari-core/lib/kaminari/models/page_scope_methods.rb#L47-L55 | train |
kaminari/kaminari | kaminari-activerecord/lib/kaminari/activerecord/active_record_relation_methods.rb | Kaminari.ActiveRecordRelationMethods.entry_name | def entry_name(options = {})
default = options[:count] == 1 ? model_name.human : model_name.human.pluralize
model_name.human(options.reverse_merge(default: default))
end | ruby | def entry_name(options = {})
default = options[:count] == 1 ? model_name.human : model_name.human.pluralize
model_name.human(options.reverse_merge(default: default))
end | [
"def",
"entry_name",
"(",
"options",
"=",
"{",
"}",
")",
"default",
"=",
"options",
"[",
":count",
"]",
"==",
"1",
"?",
"model_name",
".",
"human",
":",
"model_name",
".",
"human",
".",
"pluralize",
"model_name",
".",
"human",
"(",
"options",
".",
"reverse_merge",
"(",
"default",
":",
"default",
")",
")",
"end"
] | Used for page_entry_info | [
"Used",
"for",
"page_entry_info"
] | e2078ce46b145b811423dc8b5993e4bc87dc88b8 | https://github.com/kaminari/kaminari/blob/e2078ce46b145b811423dc8b5993e4bc87dc88b8/kaminari-activerecord/lib/kaminari/activerecord/active_record_relation_methods.rb#L7-L10 | train |
guard/guard | lib/guard/watcher.rb | Guard.Watcher.call_action | def call_action(matches)
@action.arity > 0 ? @action.call(matches) : @action.call
rescue => ex
UI.error "Problem with watch action!\n#{ex.message}"
UI.error ex.backtrace.join("\n")
end | ruby | def call_action(matches)
@action.arity > 0 ? @action.call(matches) : @action.call
rescue => ex
UI.error "Problem with watch action!\n#{ex.message}"
UI.error ex.backtrace.join("\n")
end | [
"def",
"call_action",
"(",
"matches",
")",
"@action",
".",
"arity",
">",
"0",
"?",
"@action",
".",
"call",
"(",
"matches",
")",
":",
"@action",
".",
"call",
"rescue",
"=>",
"ex",
"UI",
".",
"error",
"\"Problem with watch action!\\n#{ex.message}\"",
"UI",
".",
"error",
"ex",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Executes a watcher action.
@param [String, MatchData] matches the matched path or the match from the
Regex
@return [String] the final paths | [
"Executes",
"a",
"watcher",
"action",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/watcher.rb#L81-L86 | train |
guard/guard | lib/guard/cli.rb | Guard.CLI.start | def start
if defined?(JRUBY_VERSION)
unless options[:no_interactions]
abort "\nSorry, JRuby and interactive mode are incompatible.\n"\
"As a workaround, use the '-i' option instead.\n\n"\
"More info: \n"\
" * https://github.com/guard/guard/issues/754\n"\
" * https://github.com/jruby/jruby/issues/2383\n\n"
end
end
exit(Cli::Environments::Valid.new(options).start_guard)
end | ruby | def start
if defined?(JRUBY_VERSION)
unless options[:no_interactions]
abort "\nSorry, JRuby and interactive mode are incompatible.\n"\
"As a workaround, use the '-i' option instead.\n\n"\
"More info: \n"\
" * https://github.com/guard/guard/issues/754\n"\
" * https://github.com/jruby/jruby/issues/2383\n\n"
end
end
exit(Cli::Environments::Valid.new(options).start_guard)
end | [
"def",
"start",
"if",
"defined?",
"(",
"JRUBY_VERSION",
")",
"unless",
"options",
"[",
":no_interactions",
"]",
"abort",
"\"\\nSorry, JRuby and interactive mode are incompatible.\\n\"",
"\"As a workaround, use the '-i' option instead.\\n\\n\"",
"\"More info: \\n\"",
"\" * https://github.com/guard/guard/issues/754\\n\"",
"\" * https://github.com/jruby/jruby/issues/2383\\n\\n\"",
"end",
"end",
"exit",
"(",
"Cli",
"::",
"Environments",
"::",
"Valid",
".",
"new",
"(",
"options",
")",
".",
"start_guard",
")",
"end"
] | Start Guard by initializing the defined Guard plugins and watch the file
system.
This is the default task, so calling `guard` is the same as calling
`guard start`.
@see Guard.start | [
"Start",
"Guard",
"by",
"initializing",
"the",
"defined",
"Guard",
"plugins",
"and",
"watch",
"the",
"file",
"system",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/cli.rb#L112-L123 | train |
guard/guard | lib/guard/cli.rb | Guard.CLI.notifiers | def notifiers
Cli::Environments::EvaluateOnly.new(options).evaluate
# TODO: pass the data directly to the notifiers?
DslDescriber.new.notifiers
end | ruby | def notifiers
Cli::Environments::EvaluateOnly.new(options).evaluate
# TODO: pass the data directly to the notifiers?
DslDescriber.new.notifiers
end | [
"def",
"notifiers",
"Cli",
"::",
"Environments",
"::",
"EvaluateOnly",
".",
"new",
"(",
"options",
")",
".",
"evaluate",
"# TODO: pass the data directly to the notifiers?",
"DslDescriber",
".",
"new",
".",
"notifiers",
"end"
] | List the Notifiers for use in your system.
@see Guard::DslDescriber.notifiers | [
"List",
"the",
"Notifiers",
"for",
"use",
"in",
"your",
"system",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/cli.rb#L143-L147 | train |
guard/guard | lib/guard/cli.rb | Guard.CLI.init | def init(*plugin_names)
env = Cli::Environments::Valid.new(options)
exitcode = env.initialize_guardfile(plugin_names)
exit(exitcode)
end | ruby | def init(*plugin_names)
env = Cli::Environments::Valid.new(options)
exitcode = env.initialize_guardfile(plugin_names)
exit(exitcode)
end | [
"def",
"init",
"(",
"*",
"plugin_names",
")",
"env",
"=",
"Cli",
"::",
"Environments",
"::",
"Valid",
".",
"new",
"(",
"options",
")",
"exitcode",
"=",
"env",
".",
"initialize_guardfile",
"(",
"plugin_names",
")",
"exit",
"(",
"exitcode",
")",
"end"
] | Initializes the templates of all installed Guard plugins and adds them
to the `Guardfile` when no Guard name is passed. When passing
Guard plugin names it does the same but only for those Guard plugins.
@see Guard::Guardfile.initialize_template
@see Guard::Guardfile.initialize_all_templates
@param [Array<String>] plugin_names the name of the Guard plugins to
initialize | [
"Initializes",
"the",
"templates",
"of",
"all",
"installed",
"Guard",
"plugins",
"and",
"adds",
"them",
"to",
"the",
"Guardfile",
"when",
"no",
"Guard",
"name",
"is",
"passed",
".",
"When",
"passing",
"Guard",
"plugin",
"names",
"it",
"does",
"the",
"same",
"but",
"only",
"for",
"those",
"Guard",
"plugins",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/cli.rb#L181-L185 | train |
guard/guard | lib/guard/cli.rb | Guard.CLI.show | def show
Cli::Environments::EvaluateOnly.new(options).evaluate
DslDescriber.new.show
end | ruby | def show
Cli::Environments::EvaluateOnly.new(options).evaluate
DslDescriber.new.show
end | [
"def",
"show",
"Cli",
"::",
"Environments",
"::",
"EvaluateOnly",
".",
"new",
"(",
"options",
")",
".",
"evaluate",
"DslDescriber",
".",
"new",
".",
"show",
"end"
] | Shows all Guard plugins and their options that are defined in
the `Guardfile`
@see Guard::DslDescriber.show | [
"Shows",
"all",
"Guard",
"plugins",
"and",
"their",
"options",
"that",
"are",
"defined",
"in",
"the",
"Guardfile"
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/cli.rb#L195-L198 | train |
guard/guard | lib/guard/plugin_util.rb | Guard.PluginUtil.add_to_guardfile | def add_to_guardfile
klass = plugin_class # call here to avoid failing later
require_relative "guardfile/evaluator"
# TODO: move this to Generator?
options = Guard.state.session.evaluator_options
evaluator = Guardfile::Evaluator.new(options)
begin
evaluator.evaluate
rescue Guard::Guardfile::Evaluator::NoPluginsError
end
if evaluator.guardfile_include?(name)
UI.info "Guardfile already includes #{ name } guard"
else
content = File.read("Guardfile")
File.open("Guardfile", "wb") do |f|
f.puts(content)
f.puts("")
f.puts(klass.template(plugin_location))
end
UI.info INFO_ADDED_GUARD_TO_GUARDFILE % name
end
end | ruby | def add_to_guardfile
klass = plugin_class # call here to avoid failing later
require_relative "guardfile/evaluator"
# TODO: move this to Generator?
options = Guard.state.session.evaluator_options
evaluator = Guardfile::Evaluator.new(options)
begin
evaluator.evaluate
rescue Guard::Guardfile::Evaluator::NoPluginsError
end
if evaluator.guardfile_include?(name)
UI.info "Guardfile already includes #{ name } guard"
else
content = File.read("Guardfile")
File.open("Guardfile", "wb") do |f|
f.puts(content)
f.puts("")
f.puts(klass.template(plugin_location))
end
UI.info INFO_ADDED_GUARD_TO_GUARDFILE % name
end
end | [
"def",
"add_to_guardfile",
"klass",
"=",
"plugin_class",
"# call here to avoid failing later",
"require_relative",
"\"guardfile/evaluator\"",
"# TODO: move this to Generator?",
"options",
"=",
"Guard",
".",
"state",
".",
"session",
".",
"evaluator_options",
"evaluator",
"=",
"Guardfile",
"::",
"Evaluator",
".",
"new",
"(",
"options",
")",
"begin",
"evaluator",
".",
"evaluate",
"rescue",
"Guard",
"::",
"Guardfile",
"::",
"Evaluator",
"::",
"NoPluginsError",
"end",
"if",
"evaluator",
".",
"guardfile_include?",
"(",
"name",
")",
"UI",
".",
"info",
"\"Guardfile already includes #{ name } guard\"",
"else",
"content",
"=",
"File",
".",
"read",
"(",
"\"Guardfile\"",
")",
"File",
".",
"open",
"(",
"\"Guardfile\"",
",",
"\"wb\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"puts",
"(",
"content",
")",
"f",
".",
"puts",
"(",
"\"\"",
")",
"f",
".",
"puts",
"(",
"klass",
".",
"template",
"(",
"plugin_location",
")",
")",
"end",
"UI",
".",
"info",
"INFO_ADDED_GUARD_TO_GUARDFILE",
"%",
"name",
"end",
"end"
] | Adds a plugin's template to the Guardfile. | [
"Adds",
"a",
"plugin",
"s",
"template",
"to",
"the",
"Guardfile",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/plugin_util.rb#L126-L150 | train |
guard/guard | lib/guard/plugin_util.rb | Guard.PluginUtil._plugin_constant | def _plugin_constant
@_plugin_constant ||= Guard.constants.detect do |c|
c.to_s.casecmp(_constant_name.downcase).zero?
end
end | ruby | def _plugin_constant
@_plugin_constant ||= Guard.constants.detect do |c|
c.to_s.casecmp(_constant_name.downcase).zero?
end
end | [
"def",
"_plugin_constant",
"@_plugin_constant",
"||=",
"Guard",
".",
"constants",
".",
"detect",
"do",
"|",
"c",
"|",
"c",
".",
"to_s",
".",
"casecmp",
"(",
"_constant_name",
".",
"downcase",
")",
".",
"zero?",
"end",
"end"
] | Returns the constant for the current plugin.
@example Returns the constant for a plugin
> Guard::PluginUtil.new('rspec').send(:_plugin_constant)
=> Guard::RSpec | [
"Returns",
"the",
"constant",
"for",
"the",
"current",
"plugin",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/plugin_util.rb#L160-L164 | train |
guard/guard | lib/guard/dsl.rb | Guard.Dsl.interactor | def interactor(options)
# TODO: remove dependency on Interactor (let session handle this)
case options
when :off
Interactor.enabled = false
when Hash
Interactor.options = options
end
end | ruby | def interactor(options)
# TODO: remove dependency on Interactor (let session handle this)
case options
when :off
Interactor.enabled = false
when Hash
Interactor.options = options
end
end | [
"def",
"interactor",
"(",
"options",
")",
"# TODO: remove dependency on Interactor (let session handle this)",
"case",
"options",
"when",
":off",
"Interactor",
".",
"enabled",
"=",
"false",
"when",
"Hash",
"Interactor",
".",
"options",
"=",
"options",
"end",
"end"
] | Sets the interactor options or disable the interactor.
@example Pass options to the interactor
interactor option1: 'value1', option2: 'value2'
@example Turn off interactions
interactor :off
@param [Symbol, Hash] options either `:off` or a Hash with interactor
options | [
"Sets",
"the",
"interactor",
"options",
"or",
"disable",
"the",
"interactor",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl.rb#L90-L98 | train |
guard/guard | lib/guard/dsl.rb | Guard.Dsl.guard | def guard(name, options = {})
@plugin_options = options.merge(watchers: [], callbacks: [])
yield if block_given?
@current_groups ||= []
groups = @current_groups && @current_groups.last || [:default]
groups.each do |group|
opts = @plugin_options.merge(group: group)
# TODO: let plugins be added *after* evaluation
Guard.state.session.plugins.add(name, opts)
end
@plugin_options = nil
end | ruby | def guard(name, options = {})
@plugin_options = options.merge(watchers: [], callbacks: [])
yield if block_given?
@current_groups ||= []
groups = @current_groups && @current_groups.last || [:default]
groups.each do |group|
opts = @plugin_options.merge(group: group)
# TODO: let plugins be added *after* evaluation
Guard.state.session.plugins.add(name, opts)
end
@plugin_options = nil
end | [
"def",
"guard",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"@plugin_options",
"=",
"options",
".",
"merge",
"(",
"watchers",
":",
"[",
"]",
",",
"callbacks",
":",
"[",
"]",
")",
"yield",
"if",
"block_given?",
"@current_groups",
"||=",
"[",
"]",
"groups",
"=",
"@current_groups",
"&&",
"@current_groups",
".",
"last",
"||",
"[",
":default",
"]",
"groups",
".",
"each",
"do",
"|",
"group",
"|",
"opts",
"=",
"@plugin_options",
".",
"merge",
"(",
"group",
":",
"group",
")",
"# TODO: let plugins be added *after* evaluation",
"Guard",
".",
"state",
".",
"session",
".",
"plugins",
".",
"add",
"(",
"name",
",",
"opts",
")",
"end",
"@plugin_options",
"=",
"nil",
"end"
] | Declares a Guard plugin to be used when running `guard start`.
The name parameter is usually the name of the gem without
the 'guard-' prefix.
The available options are different for each Guard implementation.
@example Declare a Guard without `watch` patterns
guard :rspec
@example Declare a Guard with a `watch` pattern
guard :rspec do
watch %r{.*_spec.rb}
end
@param [String] name the Guard plugin name
@param [Hash] options the options accepted by the Guard plugin
@yield a block where you can declare several watch patterns and actions
@see Plugin
@see Guard.add_plugin
@see #watch
@see #group | [
"Declares",
"a",
"Guard",
"plugin",
"to",
"be",
"used",
"when",
"running",
"guard",
"start",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl.rb#L175-L189 | train |
guard/guard | lib/guard/dsl.rb | Guard.Dsl.watch | def watch(pattern, &action)
# Allow watches in the global scope (to execute arbitrary commands) by
# building a generic Guard::Plugin.
@plugin_options ||= nil
return guard(:plugin) { watch(pattern, &action) } unless @plugin_options
@plugin_options[:watchers] << Watcher.new(pattern, action)
end | ruby | def watch(pattern, &action)
# Allow watches in the global scope (to execute arbitrary commands) by
# building a generic Guard::Plugin.
@plugin_options ||= nil
return guard(:plugin) { watch(pattern, &action) } unless @plugin_options
@plugin_options[:watchers] << Watcher.new(pattern, action)
end | [
"def",
"watch",
"(",
"pattern",
",",
"&",
"action",
")",
"# Allow watches in the global scope (to execute arbitrary commands) by",
"# building a generic Guard::Plugin.",
"@plugin_options",
"||=",
"nil",
"return",
"guard",
"(",
":plugin",
")",
"{",
"watch",
"(",
"pattern",
",",
"action",
")",
"}",
"unless",
"@plugin_options",
"@plugin_options",
"[",
":watchers",
"]",
"<<",
"Watcher",
".",
"new",
"(",
"pattern",
",",
"action",
")",
"end"
] | Defines a pattern to be watched in order to run actions on file
modification.
@example Declare watchers for a Guard
guard :rspec do
watch('spec/spec_helper.rb')
watch(%r{^.+_spec.rb})
watch(%r{^app/controllers/(.+).rb}) do |m|
'spec/acceptance/#{m[1]}s_spec.rb'
end
end
@example Declare global watchers outside of a Guard
watch(%r{^(.+)$}) { |m| puts "#{m[1]} changed." }
@param [String, Regexp] pattern the pattern that Guard must watch for
modification
@yield a block to be run when the pattern is matched
@yieldparam [MatchData] m matches of the pattern
@yieldreturn a directory, a filename, an array of
directories / filenames, or nothing (can be an arbitrary command)
@see Guard::Watcher
@see #guard | [
"Defines",
"a",
"pattern",
"to",
"be",
"watched",
"in",
"order",
"to",
"run",
"actions",
"on",
"file",
"modification",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl.rb#L217-L224 | train |
guard/guard | lib/guard/dsl.rb | Guard.Dsl.callback | def callback(*args, &block)
@plugin_options ||= nil
fail "callback must be called within a guard block" unless @plugin_options
block, events = if args.size > 1
# block must be the first argument in that case, the
# yielded block is ignored
args
else
[block, args[0]]
end
@plugin_options[:callbacks] << { events: events, listener: block }
end | ruby | def callback(*args, &block)
@plugin_options ||= nil
fail "callback must be called within a guard block" unless @plugin_options
block, events = if args.size > 1
# block must be the first argument in that case, the
# yielded block is ignored
args
else
[block, args[0]]
end
@plugin_options[:callbacks] << { events: events, listener: block }
end | [
"def",
"callback",
"(",
"*",
"args",
",",
"&",
"block",
")",
"@plugin_options",
"||=",
"nil",
"fail",
"\"callback must be called within a guard block\"",
"unless",
"@plugin_options",
"block",
",",
"events",
"=",
"if",
"args",
".",
"size",
">",
"1",
"# block must be the first argument in that case, the",
"# yielded block is ignored",
"args",
"else",
"[",
"block",
",",
"args",
"[",
"0",
"]",
"]",
"end",
"@plugin_options",
"[",
":callbacks",
"]",
"<<",
"{",
"events",
":",
"events",
",",
"listener",
":",
"block",
"}",
"end"
] | Defines a callback to execute arbitrary code before or after any of
the `start`, `stop`, `reload`, `run_all`, `run_on_changes`,
`run_on_additions`, `run_on_modifications` and `run_on_removals` plugin
method.
@example Add callback before the `reload` action.
callback(:reload_begin) { puts "Let's reload!" }
@example Add callback before the `start` and `stop` actions.
my_lambda = lambda do |plugin, event, *args|
puts "Let's #{event} #{plugin} with #{args}!"
end
callback(my_lambda, [:start_begin, :start_end])
@param [Array] args the callback arguments
@yield a callback block | [
"Defines",
"a",
"callback",
"to",
"execute",
"arbitrary",
"code",
"before",
"or",
"after",
"any",
"of",
"the",
"start",
"stop",
"reload",
"run_all",
"run_on_changes",
"run_on_additions",
"run_on_modifications",
"and",
"run_on_removals",
"plugin",
"method",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl.rb#L245-L257 | train |
guard/guard | lib/guard/dsl.rb | Guard.Dsl.logger | def logger(options)
if options[:level]
options[:level] = options[:level].to_sym
unless [:debug, :info, :warn, :error].include? options[:level]
UI.warning(format(WARN_INVALID_LOG_LEVEL, options[:level]))
options.delete :level
end
end
if options[:only] && options[:except]
UI.warning WARN_INVALID_LOG_OPTIONS
options.delete :only
options.delete :except
end
# Convert the :only and :except options to a regular expression
[:only, :except].each do |name|
next unless options[name]
list = [].push(options[name]).flatten.map do |plugin|
Regexp.escape(plugin.to_s)
end
options[name] = Regexp.new(list.join("|"), Regexp::IGNORECASE)
end
UI.options = UI.options.merge(options)
end | ruby | def logger(options)
if options[:level]
options[:level] = options[:level].to_sym
unless [:debug, :info, :warn, :error].include? options[:level]
UI.warning(format(WARN_INVALID_LOG_LEVEL, options[:level]))
options.delete :level
end
end
if options[:only] && options[:except]
UI.warning WARN_INVALID_LOG_OPTIONS
options.delete :only
options.delete :except
end
# Convert the :only and :except options to a regular expression
[:only, :except].each do |name|
next unless options[name]
list = [].push(options[name]).flatten.map do |plugin|
Regexp.escape(plugin.to_s)
end
options[name] = Regexp.new(list.join("|"), Regexp::IGNORECASE)
end
UI.options = UI.options.merge(options)
end | [
"def",
"logger",
"(",
"options",
")",
"if",
"options",
"[",
":level",
"]",
"options",
"[",
":level",
"]",
"=",
"options",
"[",
":level",
"]",
".",
"to_sym",
"unless",
"[",
":debug",
",",
":info",
",",
":warn",
",",
":error",
"]",
".",
"include?",
"options",
"[",
":level",
"]",
"UI",
".",
"warning",
"(",
"format",
"(",
"WARN_INVALID_LOG_LEVEL",
",",
"options",
"[",
":level",
"]",
")",
")",
"options",
".",
"delete",
":level",
"end",
"end",
"if",
"options",
"[",
":only",
"]",
"&&",
"options",
"[",
":except",
"]",
"UI",
".",
"warning",
"WARN_INVALID_LOG_OPTIONS",
"options",
".",
"delete",
":only",
"options",
".",
"delete",
":except",
"end",
"# Convert the :only and :except options to a regular expression",
"[",
":only",
",",
":except",
"]",
".",
"each",
"do",
"|",
"name",
"|",
"next",
"unless",
"options",
"[",
"name",
"]",
"list",
"=",
"[",
"]",
".",
"push",
"(",
"options",
"[",
"name",
"]",
")",
".",
"flatten",
".",
"map",
"do",
"|",
"plugin",
"|",
"Regexp",
".",
"escape",
"(",
"plugin",
".",
"to_s",
")",
"end",
"options",
"[",
"name",
"]",
"=",
"Regexp",
".",
"new",
"(",
"list",
".",
"join",
"(",
"\"|\"",
")",
",",
"Regexp",
"::",
"IGNORECASE",
")",
"end",
"UI",
".",
"options",
"=",
"UI",
".",
"options",
".",
"merge",
"(",
"options",
")",
"end"
] | Configures the Guard logger.
* Log level must be either `:debug`, `:info`, `:warn` or `:error`.
* Template supports the following placeholders: `:time`, `:severity`,
`:progname`, `:pid`, `:unit_of_work_id` and `:message`.
* Time format directives are the same as `Time#strftime` or
`:milliseconds`.
* The `:only` and `:except` options must be a `RegExp`.
@example Set the log level
logger level: :warn
@example Set a custom log template
logger template: '[Guard - :severity - :progname - :time] :message'
@example Set a custom time format
logger time_format: '%h'
@example Limit logging to a Guard plugin
logger only: :jasmine
@example Log all but not the messages from a specific Guard plugin
logger except: :jasmine
@param [Hash] options the log options
@option options [String, Symbol] level the log level
@option options [String] template the logger template
@option options [String, Symbol] time_format the time format
@option options [Regexp] only show only messages from the matching Guard
plugin
@option options [Regexp] except does not show messages from the matching
Guard plugin | [
"Configures",
"the",
"Guard",
"logger",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl.rb#L324-L353 | train |
guard/guard | lib/guard/dsl.rb | Guard.Dsl.directories | def directories(directories)
directories.each do |dir|
fail "Directory #{dir.inspect} does not exist!" unless Dir.exist?(dir)
end
Guard.state.session.watchdirs = directories
end | ruby | def directories(directories)
directories.each do |dir|
fail "Directory #{dir.inspect} does not exist!" unless Dir.exist?(dir)
end
Guard.state.session.watchdirs = directories
end | [
"def",
"directories",
"(",
"directories",
")",
"directories",
".",
"each",
"do",
"|",
"dir",
"|",
"fail",
"\"Directory #{dir.inspect} does not exist!\"",
"unless",
"Dir",
".",
"exist?",
"(",
"dir",
")",
"end",
"Guard",
".",
"state",
".",
"session",
".",
"watchdirs",
"=",
"directories",
"end"
] | Sets the directories to pass to Listen
@example watch only given directories
directories %w(lib specs)
@param [Array] directories directories for Listen to watch | [
"Sets",
"the",
"directories",
"to",
"pass",
"to",
"Listen"
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl.rb#L393-L398 | train |
guard/guard | lib/guard/commander.rb | Guard.Commander.start | def start(options = {})
setup(options)
UI.debug "Guard starts all plugins"
Runner.new.run(:start)
listener.start
watched = Guard.state.session.watchdirs.join("', '")
UI.info "Guard is now watching at '#{ watched }'"
exitcode = 0
begin
while interactor.foreground != :exit
Guard.queue.process while Guard.queue.pending?
end
rescue Interrupt
rescue SystemExit => e
exitcode = e.status
end
exitcode
ensure
stop
end | ruby | def start(options = {})
setup(options)
UI.debug "Guard starts all plugins"
Runner.new.run(:start)
listener.start
watched = Guard.state.session.watchdirs.join("', '")
UI.info "Guard is now watching at '#{ watched }'"
exitcode = 0
begin
while interactor.foreground != :exit
Guard.queue.process while Guard.queue.pending?
end
rescue Interrupt
rescue SystemExit => e
exitcode = e.status
end
exitcode
ensure
stop
end | [
"def",
"start",
"(",
"options",
"=",
"{",
"}",
")",
"setup",
"(",
"options",
")",
"UI",
".",
"debug",
"\"Guard starts all plugins\"",
"Runner",
".",
"new",
".",
"run",
"(",
":start",
")",
"listener",
".",
"start",
"watched",
"=",
"Guard",
".",
"state",
".",
"session",
".",
"watchdirs",
".",
"join",
"(",
"\"', '\"",
")",
"UI",
".",
"info",
"\"Guard is now watching at '#{ watched }'\"",
"exitcode",
"=",
"0",
"begin",
"while",
"interactor",
".",
"foreground",
"!=",
":exit",
"Guard",
".",
"queue",
".",
"process",
"while",
"Guard",
".",
"queue",
".",
"pending?",
"end",
"rescue",
"Interrupt",
"rescue",
"SystemExit",
"=>",
"e",
"exitcode",
"=",
"e",
".",
"status",
"end",
"exitcode",
"ensure",
"stop",
"end"
] | Start Guard by evaluating the `Guardfile`, initializing declared Guard
plugins and starting the available file change listener.
Main method for Guard that is called from the CLI when Guard starts.
- Setup Guard internals
- Evaluate the `Guardfile`
- Configure Notifiers
- Initialize the declared Guard plugins
- Start the available file change listener
@option options [Boolean] clear if auto clear the UI should be done
@option options [Boolean] notify if system notifications should be shown
@option options [Boolean] debug if debug output should be shown
@option options [Array<String>] group the list of groups to start
@option options [String] watchdir the director to watch
@option options [String] guardfile the path to the Guardfile
@see CLI#start | [
"Start",
"Guard",
"by",
"evaluating",
"the",
"Guardfile",
"initializing",
"declared",
"Guard",
"plugins",
"and",
"starting",
"the",
"available",
"file",
"change",
"listener",
".",
"Main",
"method",
"for",
"Guard",
"that",
"is",
"called",
"from",
"the",
"CLI",
"when",
"Guard",
"starts",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/commander.rb#L31-L53 | train |
guard/guard | lib/guard/commander.rb | Guard.Commander.run_all | def run_all(scopes = {})
UI.clear(force: true)
UI.action_with_scopes("Run", scopes)
Runner.new.run(:run_all, scopes)
end | ruby | def run_all(scopes = {})
UI.clear(force: true)
UI.action_with_scopes("Run", scopes)
Runner.new.run(:run_all, scopes)
end | [
"def",
"run_all",
"(",
"scopes",
"=",
"{",
"}",
")",
"UI",
".",
"clear",
"(",
"force",
":",
"true",
")",
"UI",
".",
"action_with_scopes",
"(",
"\"Run\"",
",",
"scopes",
")",
"Runner",
".",
"new",
".",
"run",
"(",
":run_all",
",",
"scopes",
")",
"end"
] | Trigger `run_all` on all Guard plugins currently enabled.
@param [Hash] scopes hash with a Guard plugin or a group scope | [
"Trigger",
"run_all",
"on",
"all",
"Guard",
"plugins",
"currently",
"enabled",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/commander.rb#L80-L84 | train |
guard/guard | lib/guard/commander.rb | Guard.Commander.pause | def pause(expected = nil)
paused = listener.paused?
states = { paused: true, unpaused: false, toggle: !paused }
pause = states[expected || :toggle]
fail ArgumentError, "invalid mode: #{expected.inspect}" if pause.nil?
return if pause == paused
listener.public_send(pause ? :pause : :start)
UI.info "File event handling has been #{pause ? 'paused' : 'resumed'}"
end | ruby | def pause(expected = nil)
paused = listener.paused?
states = { paused: true, unpaused: false, toggle: !paused }
pause = states[expected || :toggle]
fail ArgumentError, "invalid mode: #{expected.inspect}" if pause.nil?
return if pause == paused
listener.public_send(pause ? :pause : :start)
UI.info "File event handling has been #{pause ? 'paused' : 'resumed'}"
end | [
"def",
"pause",
"(",
"expected",
"=",
"nil",
")",
"paused",
"=",
"listener",
".",
"paused?",
"states",
"=",
"{",
"paused",
":",
"true",
",",
"unpaused",
":",
"false",
",",
"toggle",
":",
"!",
"paused",
"}",
"pause",
"=",
"states",
"[",
"expected",
"||",
":toggle",
"]",
"fail",
"ArgumentError",
",",
"\"invalid mode: #{expected.inspect}\"",
"if",
"pause",
".",
"nil?",
"return",
"if",
"pause",
"==",
"paused",
"listener",
".",
"public_send",
"(",
"pause",
"?",
":pause",
":",
":start",
")",
"UI",
".",
"info",
"\"File event handling has been #{pause ? 'paused' : 'resumed'}\"",
"end"
] | Pause Guard listening to file changes. | [
"Pause",
"Guard",
"listening",
"to",
"file",
"changes",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/commander.rb#L88-L97 | train |
guard/guard | lib/guard/dsl_describer.rb | Guard.DslDescriber.show | def show
# collect metadata
groups = Guard.state.session.groups.all
objects = []
empty_plugin = OpenStruct.new
empty_plugin.options = [["", nil]]
groups.each do |group|
plugins = Array(Guard.state.session.plugins.all(group: group.name))
plugins = [empty_plugin] if plugins.empty?
plugins.each do |plugin|
options = plugin.options
options = [["", nil]] if options.empty?
options.each do |option, raw_value|
value = raw_value.nil? ? "" : raw_value.inspect
objects << [group.title, plugin.title, option.to_s, value]
end
end
end
# presentation
rows = []
prev_group = prev_plugin = prev_option = prev_value = nil
objects.each do |group, plugin, option, value|
group_changed = prev_group != group
plugin_changed = (prev_plugin != plugin || group_changed)
rows << :split if group_changed || plugin_changed
rows << {
Group: group_changed ? group : "",
Plugin: plugin_changed ? plugin : "",
Option: option,
Value: value
}
prev_group = group
prev_plugin = plugin
prev_option = option
prev_value = value
end
# render
Formatador.display_compact_table(
rows.drop(1),
[:Group, :Plugin, :Option, :Value]
)
end | ruby | def show
# collect metadata
groups = Guard.state.session.groups.all
objects = []
empty_plugin = OpenStruct.new
empty_plugin.options = [["", nil]]
groups.each do |group|
plugins = Array(Guard.state.session.plugins.all(group: group.name))
plugins = [empty_plugin] if plugins.empty?
plugins.each do |plugin|
options = plugin.options
options = [["", nil]] if options.empty?
options.each do |option, raw_value|
value = raw_value.nil? ? "" : raw_value.inspect
objects << [group.title, plugin.title, option.to_s, value]
end
end
end
# presentation
rows = []
prev_group = prev_plugin = prev_option = prev_value = nil
objects.each do |group, plugin, option, value|
group_changed = prev_group != group
plugin_changed = (prev_plugin != plugin || group_changed)
rows << :split if group_changed || plugin_changed
rows << {
Group: group_changed ? group : "",
Plugin: plugin_changed ? plugin : "",
Option: option,
Value: value
}
prev_group = group
prev_plugin = plugin
prev_option = option
prev_value = value
end
# render
Formatador.display_compact_table(
rows.drop(1),
[:Group, :Plugin, :Option, :Value]
)
end | [
"def",
"show",
"# collect metadata",
"groups",
"=",
"Guard",
".",
"state",
".",
"session",
".",
"groups",
".",
"all",
"objects",
"=",
"[",
"]",
"empty_plugin",
"=",
"OpenStruct",
".",
"new",
"empty_plugin",
".",
"options",
"=",
"[",
"[",
"\"\"",
",",
"nil",
"]",
"]",
"groups",
".",
"each",
"do",
"|",
"group",
"|",
"plugins",
"=",
"Array",
"(",
"Guard",
".",
"state",
".",
"session",
".",
"plugins",
".",
"all",
"(",
"group",
":",
"group",
".",
"name",
")",
")",
"plugins",
"=",
"[",
"empty_plugin",
"]",
"if",
"plugins",
".",
"empty?",
"plugins",
".",
"each",
"do",
"|",
"plugin",
"|",
"options",
"=",
"plugin",
".",
"options",
"options",
"=",
"[",
"[",
"\"\"",
",",
"nil",
"]",
"]",
"if",
"options",
".",
"empty?",
"options",
".",
"each",
"do",
"|",
"option",
",",
"raw_value",
"|",
"value",
"=",
"raw_value",
".",
"nil?",
"?",
"\"\"",
":",
"raw_value",
".",
"inspect",
"objects",
"<<",
"[",
"group",
".",
"title",
",",
"plugin",
".",
"title",
",",
"option",
".",
"to_s",
",",
"value",
"]",
"end",
"end",
"end",
"# presentation",
"rows",
"=",
"[",
"]",
"prev_group",
"=",
"prev_plugin",
"=",
"prev_option",
"=",
"prev_value",
"=",
"nil",
"objects",
".",
"each",
"do",
"|",
"group",
",",
"plugin",
",",
"option",
",",
"value",
"|",
"group_changed",
"=",
"prev_group",
"!=",
"group",
"plugin_changed",
"=",
"(",
"prev_plugin",
"!=",
"plugin",
"||",
"group_changed",
")",
"rows",
"<<",
":split",
"if",
"group_changed",
"||",
"plugin_changed",
"rows",
"<<",
"{",
"Group",
":",
"group_changed",
"?",
"group",
":",
"\"\"",
",",
"Plugin",
":",
"plugin_changed",
"?",
"plugin",
":",
"\"\"",
",",
"Option",
":",
"option",
",",
"Value",
":",
"value",
"}",
"prev_group",
"=",
"group",
"prev_plugin",
"=",
"plugin",
"prev_option",
"=",
"option",
"prev_value",
"=",
"value",
"end",
"# render",
"Formatador",
".",
"display_compact_table",
"(",
"rows",
".",
"drop",
"(",
"1",
")",
",",
"[",
":Group",
",",
":Plugin",
",",
":Option",
",",
":Value",
"]",
")",
"end"
] | Shows all Guard plugins and their options that are defined in
the `Guardfile`.
@see CLI#show | [
"Shows",
"all",
"Guard",
"plugins",
"and",
"their",
"options",
"that",
"are",
"defined",
"in",
"the",
"Guardfile",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl_describer.rb#L53-L102 | train |
guard/guard | lib/guard/dsl_describer.rb | Guard.DslDescriber.notifiers | def notifiers
supported = Notifier.supported
Notifier.connect(notify: true, silent: true)
detected = Notifier.detected
Notifier.disconnect
detected_names = detected.map { |item| item[:name] }
final_rows = supported.each_with_object([]) do |(name, _), rows|
available = detected_names.include?(name) ? "✔" : "✘"
notifier = detected.detect { |n| n[:name] == name }
used = notifier ? "✔" : "✘"
options = notifier ? notifier[:options] : {}
if options.empty?
rows << :split
_add_row(rows, name, available, used, "", "")
else
options.each_with_index do |(option, value), index|
if index == 0
rows << :split
_add_row(rows, name, available, used, option.to_s, value.inspect)
else
_add_row(rows, "", "", "", option.to_s, value.inspect)
end
end
end
rows
end
Formatador.display_compact_table(
final_rows.drop(1),
[:Name, :Available, :Used, :Option, :Value]
)
end | ruby | def notifiers
supported = Notifier.supported
Notifier.connect(notify: true, silent: true)
detected = Notifier.detected
Notifier.disconnect
detected_names = detected.map { |item| item[:name] }
final_rows = supported.each_with_object([]) do |(name, _), rows|
available = detected_names.include?(name) ? "✔" : "✘"
notifier = detected.detect { |n| n[:name] == name }
used = notifier ? "✔" : "✘"
options = notifier ? notifier[:options] : {}
if options.empty?
rows << :split
_add_row(rows, name, available, used, "", "")
else
options.each_with_index do |(option, value), index|
if index == 0
rows << :split
_add_row(rows, name, available, used, option.to_s, value.inspect)
else
_add_row(rows, "", "", "", option.to_s, value.inspect)
end
end
end
rows
end
Formatador.display_compact_table(
final_rows.drop(1),
[:Name, :Available, :Used, :Option, :Value]
)
end | [
"def",
"notifiers",
"supported",
"=",
"Notifier",
".",
"supported",
"Notifier",
".",
"connect",
"(",
"notify",
":",
"true",
",",
"silent",
":",
"true",
")",
"detected",
"=",
"Notifier",
".",
"detected",
"Notifier",
".",
"disconnect",
"detected_names",
"=",
"detected",
".",
"map",
"{",
"|",
"item",
"|",
"item",
"[",
":name",
"]",
"}",
"final_rows",
"=",
"supported",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"(",
"name",
",",
"_",
")",
",",
"rows",
"|",
"available",
"=",
"detected_names",
".",
"include?",
"(",
"name",
")",
"?",
"\"✔\" :",
"\"",
"\"",
"notifier",
"=",
"detected",
".",
"detect",
"{",
"|",
"n",
"|",
"n",
"[",
":name",
"]",
"==",
"name",
"}",
"used",
"=",
"notifier",
"?",
"\"✔\" :",
"\"",
"\"",
"options",
"=",
"notifier",
"?",
"notifier",
"[",
":options",
"]",
":",
"{",
"}",
"if",
"options",
".",
"empty?",
"rows",
"<<",
":split",
"_add_row",
"(",
"rows",
",",
"name",
",",
"available",
",",
"used",
",",
"\"\"",
",",
"\"\"",
")",
"else",
"options",
".",
"each_with_index",
"do",
"|",
"(",
"option",
",",
"value",
")",
",",
"index",
"|",
"if",
"index",
"==",
"0",
"rows",
"<<",
":split",
"_add_row",
"(",
"rows",
",",
"name",
",",
"available",
",",
"used",
",",
"option",
".",
"to_s",
",",
"value",
".",
"inspect",
")",
"else",
"_add_row",
"(",
"rows",
",",
"\"\"",
",",
"\"\"",
",",
"\"\"",
",",
"option",
".",
"to_s",
",",
"value",
".",
"inspect",
")",
"end",
"end",
"end",
"rows",
"end",
"Formatador",
".",
"display_compact_table",
"(",
"final_rows",
".",
"drop",
"(",
"1",
")",
",",
"[",
":Name",
",",
":Available",
",",
":Used",
",",
":Option",
",",
":Value",
"]",
")",
"end"
] | Shows all notifiers and their options that are defined in
the `Guardfile`.
@see CLI#show | [
"Shows",
"all",
"notifiers",
"and",
"their",
"options",
"that",
"are",
"defined",
"in",
"the",
"Guardfile",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/dsl_describer.rb#L109-L146 | train |
guard/guard | lib/guard/runner.rb | Guard.Runner.run | def run(task, scope_hash = {})
Lumberjack.unit_of_work do
items = Guard.state.scope.grouped_plugins(scope_hash || {})
items.each do |_group, plugins|
_run_group_plugins(plugins) do |plugin|
_supervise(plugin, task) if plugin.respond_to?(task)
end
end
end
end | ruby | def run(task, scope_hash = {})
Lumberjack.unit_of_work do
items = Guard.state.scope.grouped_plugins(scope_hash || {})
items.each do |_group, plugins|
_run_group_plugins(plugins) do |plugin|
_supervise(plugin, task) if plugin.respond_to?(task)
end
end
end
end | [
"def",
"run",
"(",
"task",
",",
"scope_hash",
"=",
"{",
"}",
")",
"Lumberjack",
".",
"unit_of_work",
"do",
"items",
"=",
"Guard",
".",
"state",
".",
"scope",
".",
"grouped_plugins",
"(",
"scope_hash",
"||",
"{",
"}",
")",
"items",
".",
"each",
"do",
"|",
"_group",
",",
"plugins",
"|",
"_run_group_plugins",
"(",
"plugins",
")",
"do",
"|",
"plugin",
"|",
"_supervise",
"(",
"plugin",
",",
"task",
")",
"if",
"plugin",
".",
"respond_to?",
"(",
"task",
")",
"end",
"end",
"end",
"end"
] | Runs a Guard-task on all registered plugins.
@param [Symbol] task the task to run
@param [Hash] scope_hash either the Guard plugin or the group to run the task
on | [
"Runs",
"a",
"Guard",
"-",
"task",
"on",
"all",
"registered",
"plugins",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/runner.rb#L17-L26 | train |
guard/guard | lib/guard/runner.rb | Guard.Runner.run_on_changes | def run_on_changes(modified, added, removed)
types = {
MODIFICATION_TASKS => modified,
ADDITION_TASKS => added,
REMOVAL_TASKS => removed
}
UI.clearable
Guard.state.scope.grouped_plugins.each do |_group, plugins|
_run_group_plugins(plugins) do |plugin|
UI.clear
types.each do |tasks, unmatched_paths|
next if unmatched_paths.empty?
match_result = Watcher.match_files(plugin, unmatched_paths)
next if match_result.empty?
task = tasks.detect { |meth| plugin.respond_to?(meth) }
_supervise(plugin, task, match_result) if task
end
end
end
end | ruby | def run_on_changes(modified, added, removed)
types = {
MODIFICATION_TASKS => modified,
ADDITION_TASKS => added,
REMOVAL_TASKS => removed
}
UI.clearable
Guard.state.scope.grouped_plugins.each do |_group, plugins|
_run_group_plugins(plugins) do |plugin|
UI.clear
types.each do |tasks, unmatched_paths|
next if unmatched_paths.empty?
match_result = Watcher.match_files(plugin, unmatched_paths)
next if match_result.empty?
task = tasks.detect { |meth| plugin.respond_to?(meth) }
_supervise(plugin, task, match_result) if task
end
end
end
end | [
"def",
"run_on_changes",
"(",
"modified",
",",
"added",
",",
"removed",
")",
"types",
"=",
"{",
"MODIFICATION_TASKS",
"=>",
"modified",
",",
"ADDITION_TASKS",
"=>",
"added",
",",
"REMOVAL_TASKS",
"=>",
"removed",
"}",
"UI",
".",
"clearable",
"Guard",
".",
"state",
".",
"scope",
".",
"grouped_plugins",
".",
"each",
"do",
"|",
"_group",
",",
"plugins",
"|",
"_run_group_plugins",
"(",
"plugins",
")",
"do",
"|",
"plugin",
"|",
"UI",
".",
"clear",
"types",
".",
"each",
"do",
"|",
"tasks",
",",
"unmatched_paths",
"|",
"next",
"if",
"unmatched_paths",
".",
"empty?",
"match_result",
"=",
"Watcher",
".",
"match_files",
"(",
"plugin",
",",
"unmatched_paths",
")",
"next",
"if",
"match_result",
".",
"empty?",
"task",
"=",
"tasks",
".",
"detect",
"{",
"|",
"meth",
"|",
"plugin",
".",
"respond_to?",
"(",
"meth",
")",
"}",
"_supervise",
"(",
"plugin",
",",
"task",
",",
"match_result",
")",
"if",
"task",
"end",
"end",
"end",
"end"
] | Runs the appropriate tasks on all registered plugins
based on the passed changes.
@param [Array<String>] modified the modified paths.
@param [Array<String>] added the added paths.
@param [Array<String>] removed the removed paths. | [
"Runs",
"the",
"appropriate",
"tasks",
"on",
"all",
"registered",
"plugins",
"based",
"on",
"the",
"passed",
"changes",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/runner.rb#L44-L65 | train |
guard/guard | lib/guard/runner.rb | Guard.Runner._supervise | def _supervise(plugin, task, *args)
catch self.class.stopping_symbol_for(plugin) do
plugin.hook("#{ task }_begin", *args)
result = UI.options.with_progname(plugin.class.name) do
begin
plugin.send(task, *args)
rescue Interrupt
throw(:task_has_failed)
end
end
plugin.hook("#{ task }_end", result)
result
end
rescue ScriptError, StandardError, RuntimeError
UI.error("#{ plugin.class.name } failed to achieve its"\
" <#{ task }>, exception was:" \
"\n#{ $!.class }: #{ $!.message }" \
"\n#{ $!.backtrace.join("\n") }")
Guard.state.session.plugins.remove(plugin)
UI.info("\n#{ plugin.class.name } has just been fired")
$!
end | ruby | def _supervise(plugin, task, *args)
catch self.class.stopping_symbol_for(plugin) do
plugin.hook("#{ task }_begin", *args)
result = UI.options.with_progname(plugin.class.name) do
begin
plugin.send(task, *args)
rescue Interrupt
throw(:task_has_failed)
end
end
plugin.hook("#{ task }_end", result)
result
end
rescue ScriptError, StandardError, RuntimeError
UI.error("#{ plugin.class.name } failed to achieve its"\
" <#{ task }>, exception was:" \
"\n#{ $!.class }: #{ $!.message }" \
"\n#{ $!.backtrace.join("\n") }")
Guard.state.session.plugins.remove(plugin)
UI.info("\n#{ plugin.class.name } has just been fired")
$!
end | [
"def",
"_supervise",
"(",
"plugin",
",",
"task",
",",
"*",
"args",
")",
"catch",
"self",
".",
"class",
".",
"stopping_symbol_for",
"(",
"plugin",
")",
"do",
"plugin",
".",
"hook",
"(",
"\"#{ task }_begin\"",
",",
"args",
")",
"result",
"=",
"UI",
".",
"options",
".",
"with_progname",
"(",
"plugin",
".",
"class",
".",
"name",
")",
"do",
"begin",
"plugin",
".",
"send",
"(",
"task",
",",
"args",
")",
"rescue",
"Interrupt",
"throw",
"(",
":task_has_failed",
")",
"end",
"end",
"plugin",
".",
"hook",
"(",
"\"#{ task }_end\"",
",",
"result",
")",
"result",
"end",
"rescue",
"ScriptError",
",",
"StandardError",
",",
"RuntimeError",
"UI",
".",
"error",
"(",
"\"#{ plugin.class.name } failed to achieve its\"",
"\" <#{ task }>, exception was:\"",
"\"\\n#{ $!.class }: #{ $!.message }\"",
"\"\\n#{ $!.backtrace.join(\"\\n\") }\"",
")",
"Guard",
".",
"state",
".",
"session",
".",
"plugins",
".",
"remove",
"(",
"plugin",
")",
"UI",
".",
"info",
"(",
"\"\\n#{ plugin.class.name } has just been fired\"",
")",
"$!",
"end"
] | Run a Guard plugin task, but remove the Guard plugin when his work leads
to a system failure.
When the Group has `:halt_on_fail` disabled, we've to catch
`:task_has_failed` here in order to avoid an uncaught throw error.
@param [Guard::Plugin] plugin guard the Guard to execute
@param [Symbol] task the task to run
@param [Array] args the arguments for the task
@raise [:task_has_failed] when task has failed | [
"Run",
"a",
"Guard",
"plugin",
"task",
"but",
"remove",
"the",
"Guard",
"plugin",
"when",
"his",
"work",
"leads",
"to",
"a",
"system",
"failure",
"."
] | e2508cd83badf0d537dbaba35d307adc35d92e4f | https://github.com/guard/guard/blob/e2508cd83badf0d537dbaba35d307adc35d92e4f/lib/guard/runner.rb#L78-L99 | train |
httprb/http | lib/http/response.rb | HTTP.Response.content_length | def content_length
# http://greenbytes.de/tech/webdav/rfc7230.html#rfc.section.3.3.3
# Clause 3: "If a message is received with both a Transfer-Encoding
# and a Content-Length header field, the Transfer-Encoding overrides the Content-Length.
return nil if @headers.include?(Headers::TRANSFER_ENCODING)
value = @headers[Headers::CONTENT_LENGTH]
return nil unless value
begin
Integer(value)
rescue ArgumentError
nil
end
end | ruby | def content_length
# http://greenbytes.de/tech/webdav/rfc7230.html#rfc.section.3.3.3
# Clause 3: "If a message is received with both a Transfer-Encoding
# and a Content-Length header field, the Transfer-Encoding overrides the Content-Length.
return nil if @headers.include?(Headers::TRANSFER_ENCODING)
value = @headers[Headers::CONTENT_LENGTH]
return nil unless value
begin
Integer(value)
rescue ArgumentError
nil
end
end | [
"def",
"content_length",
"# http://greenbytes.de/tech/webdav/rfc7230.html#rfc.section.3.3.3",
"# Clause 3: \"If a message is received with both a Transfer-Encoding",
"# and a Content-Length header field, the Transfer-Encoding overrides the Content-Length.",
"return",
"nil",
"if",
"@headers",
".",
"include?",
"(",
"Headers",
"::",
"TRANSFER_ENCODING",
")",
"value",
"=",
"@headers",
"[",
"Headers",
"::",
"CONTENT_LENGTH",
"]",
"return",
"nil",
"unless",
"value",
"begin",
"Integer",
"(",
"value",
")",
"rescue",
"ArgumentError",
"nil",
"end",
"end"
] | Value of the Content-Length header.
@return [nil] if Content-Length was not given, or it's value was invalid
(not an integer, e.g. empty string or string with non-digits).
@return [Integer] otherwise | [
"Value",
"of",
"the",
"Content",
"-",
"Length",
"header",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/response.rb#L103-L117 | train |
httprb/http | lib/http/connection.rb | HTTP.Connection.readpartial | def readpartial(size = BUFFER_SIZE)
return unless @pending_response
chunk = @parser.read(size)
return chunk if chunk
finished = (read_more(size) == :eof) || @parser.finished?
chunk = @parser.read(size)
finish_response if finished
chunk.to_s
end | ruby | def readpartial(size = BUFFER_SIZE)
return unless @pending_response
chunk = @parser.read(size)
return chunk if chunk
finished = (read_more(size) == :eof) || @parser.finished?
chunk = @parser.read(size)
finish_response if finished
chunk.to_s
end | [
"def",
"readpartial",
"(",
"size",
"=",
"BUFFER_SIZE",
")",
"return",
"unless",
"@pending_response",
"chunk",
"=",
"@parser",
".",
"read",
"(",
"size",
")",
"return",
"chunk",
"if",
"chunk",
"finished",
"=",
"(",
"read_more",
"(",
"size",
")",
"==",
":eof",
")",
"||",
"@parser",
".",
"finished?",
"chunk",
"=",
"@parser",
".",
"read",
"(",
"size",
")",
"finish_response",
"if",
"finished",
"chunk",
".",
"to_s",
"end"
] | Read a chunk of the body
@return [String] data chunk
@return [nil] when no more data left | [
"Read",
"a",
"chunk",
"of",
"the",
"body"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/connection.rb#L86-L97 | train |
httprb/http | lib/http/connection.rb | HTTP.Connection.start_tls | def start_tls(req, options)
return unless req.uri.https? && !failed_proxy_connect?
ssl_context = options.ssl_context
unless ssl_context
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.set_params(options.ssl || {})
end
@socket.start_tls(req.uri.host, options.ssl_socket_class, ssl_context)
end | ruby | def start_tls(req, options)
return unless req.uri.https? && !failed_proxy_connect?
ssl_context = options.ssl_context
unless ssl_context
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.set_params(options.ssl || {})
end
@socket.start_tls(req.uri.host, options.ssl_socket_class, ssl_context)
end | [
"def",
"start_tls",
"(",
"req",
",",
"options",
")",
"return",
"unless",
"req",
".",
"uri",
".",
"https?",
"&&",
"!",
"failed_proxy_connect?",
"ssl_context",
"=",
"options",
".",
"ssl_context",
"unless",
"ssl_context",
"ssl_context",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"SSLContext",
".",
"new",
"ssl_context",
".",
"set_params",
"(",
"options",
".",
"ssl",
"||",
"{",
"}",
")",
"end",
"@socket",
".",
"start_tls",
"(",
"req",
".",
"uri",
".",
"host",
",",
"options",
".",
"ssl_socket_class",
",",
"ssl_context",
")",
"end"
] | Sets up SSL context and starts TLS if needed.
@param (see #initialize)
@return [void] | [
"Sets",
"up",
"SSL",
"context",
"and",
"starts",
"TLS",
"if",
"needed",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/connection.rb#L148-L159 | train |
httprb/http | lib/http/connection.rb | HTTP.Connection.send_proxy_connect_request | def send_proxy_connect_request(req)
return unless req.uri.https? && req.using_proxy?
@pending_request = true
req.connect_using_proxy @socket
@pending_request = false
@pending_response = true
read_headers!
@proxy_response_headers = @parser.headers
if @parser.status_code != 200
@failed_proxy_connect = true
return
end
@parser.reset
@pending_response = false
end | ruby | def send_proxy_connect_request(req)
return unless req.uri.https? && req.using_proxy?
@pending_request = true
req.connect_using_proxy @socket
@pending_request = false
@pending_response = true
read_headers!
@proxy_response_headers = @parser.headers
if @parser.status_code != 200
@failed_proxy_connect = true
return
end
@parser.reset
@pending_response = false
end | [
"def",
"send_proxy_connect_request",
"(",
"req",
")",
"return",
"unless",
"req",
".",
"uri",
".",
"https?",
"&&",
"req",
".",
"using_proxy?",
"@pending_request",
"=",
"true",
"req",
".",
"connect_using_proxy",
"@socket",
"@pending_request",
"=",
"false",
"@pending_response",
"=",
"true",
"read_headers!",
"@proxy_response_headers",
"=",
"@parser",
".",
"headers",
"if",
"@parser",
".",
"status_code",
"!=",
"200",
"@failed_proxy_connect",
"=",
"true",
"return",
"end",
"@parser",
".",
"reset",
"@pending_response",
"=",
"false",
"end"
] | Open tunnel through proxy | [
"Open",
"tunnel",
"through",
"proxy"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/connection.rb#L162-L182 | train |
httprb/http | lib/http/connection.rb | HTTP.Connection.set_keep_alive | def set_keep_alive
return @keep_alive = false unless @persistent
@keep_alive =
case @parser.http_version
when HTTP_1_0 # HTTP/1.0 requires opt in for Keep Alive
@parser.headers[Headers::CONNECTION] == KEEP_ALIVE
when HTTP_1_1 # HTTP/1.1 is opt-out
@parser.headers[Headers::CONNECTION] != CLOSE
else # Anything else we assume doesn't supportit
false
end
end | ruby | def set_keep_alive
return @keep_alive = false unless @persistent
@keep_alive =
case @parser.http_version
when HTTP_1_0 # HTTP/1.0 requires opt in for Keep Alive
@parser.headers[Headers::CONNECTION] == KEEP_ALIVE
when HTTP_1_1 # HTTP/1.1 is opt-out
@parser.headers[Headers::CONNECTION] != CLOSE
else # Anything else we assume doesn't supportit
false
end
end | [
"def",
"set_keep_alive",
"return",
"@keep_alive",
"=",
"false",
"unless",
"@persistent",
"@keep_alive",
"=",
"case",
"@parser",
".",
"http_version",
"when",
"HTTP_1_0",
"# HTTP/1.0 requires opt in for Keep Alive",
"@parser",
".",
"headers",
"[",
"Headers",
"::",
"CONNECTION",
"]",
"==",
"KEEP_ALIVE",
"when",
"HTTP_1_1",
"# HTTP/1.1 is opt-out",
"@parser",
".",
"headers",
"[",
"Headers",
"::",
"CONNECTION",
"]",
"!=",
"CLOSE",
"else",
"# Anything else we assume doesn't supportit",
"false",
"end",
"end"
] | Store whether the connection should be kept alive.
Once we reset the parser, we lose all of this state.
@return [void] | [
"Store",
"whether",
"the",
"connection",
"should",
"be",
"kept",
"alive",
".",
"Once",
"we",
"reset",
"the",
"parser",
"we",
"lose",
"all",
"of",
"this",
"state",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/connection.rb#L193-L205 | train |
httprb/http | lib/http/connection.rb | HTTP.Connection.read_more | def read_more(size)
return if @parser.finished?
value = @socket.readpartial(size, @buffer)
if value == :eof
@parser << ""
:eof
elsif value
@parser << value
end
rescue IOError, SocketError, SystemCallError => ex
raise ConnectionError, "error reading from socket: #{ex}", ex.backtrace
end | ruby | def read_more(size)
return if @parser.finished?
value = @socket.readpartial(size, @buffer)
if value == :eof
@parser << ""
:eof
elsif value
@parser << value
end
rescue IOError, SocketError, SystemCallError => ex
raise ConnectionError, "error reading from socket: #{ex}", ex.backtrace
end | [
"def",
"read_more",
"(",
"size",
")",
"return",
"if",
"@parser",
".",
"finished?",
"value",
"=",
"@socket",
".",
"readpartial",
"(",
"size",
",",
"@buffer",
")",
"if",
"value",
"==",
":eof",
"@parser",
"<<",
"\"\"",
":eof",
"elsif",
"value",
"@parser",
"<<",
"value",
"end",
"rescue",
"IOError",
",",
"SocketError",
",",
"SystemCallError",
"=>",
"ex",
"raise",
"ConnectionError",
",",
"\"error reading from socket: #{ex}\"",
",",
"ex",
".",
"backtrace",
"end"
] | Feeds some more data into parser
@return [void] | [
"Feeds",
"some",
"more",
"data",
"into",
"parser"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/connection.rb#L209-L221 | train |
httprb/http | lib/http/chainable.rb | HTTP.Chainable.via | def via(*proxy)
proxy_hash = {}
proxy_hash[:proxy_address] = proxy[0] if proxy[0].is_a?(String)
proxy_hash[:proxy_port] = proxy[1] if proxy[1].is_a?(Integer)
proxy_hash[:proxy_username] = proxy[2] if proxy[2].is_a?(String)
proxy_hash[:proxy_password] = proxy[3] if proxy[3].is_a?(String)
proxy_hash[:proxy_headers] = proxy[2] if proxy[2].is_a?(Hash)
proxy_hash[:proxy_headers] = proxy[4] if proxy[4].is_a?(Hash)
raise(RequestError, "invalid HTTP proxy: #{proxy_hash}") unless (2..5).cover?(proxy_hash.keys.size)
branch default_options.with_proxy(proxy_hash)
end | ruby | def via(*proxy)
proxy_hash = {}
proxy_hash[:proxy_address] = proxy[0] if proxy[0].is_a?(String)
proxy_hash[:proxy_port] = proxy[1] if proxy[1].is_a?(Integer)
proxy_hash[:proxy_username] = proxy[2] if proxy[2].is_a?(String)
proxy_hash[:proxy_password] = proxy[3] if proxy[3].is_a?(String)
proxy_hash[:proxy_headers] = proxy[2] if proxy[2].is_a?(Hash)
proxy_hash[:proxy_headers] = proxy[4] if proxy[4].is_a?(Hash)
raise(RequestError, "invalid HTTP proxy: #{proxy_hash}") unless (2..5).cover?(proxy_hash.keys.size)
branch default_options.with_proxy(proxy_hash)
end | [
"def",
"via",
"(",
"*",
"proxy",
")",
"proxy_hash",
"=",
"{",
"}",
"proxy_hash",
"[",
":proxy_address",
"]",
"=",
"proxy",
"[",
"0",
"]",
"if",
"proxy",
"[",
"0",
"]",
".",
"is_a?",
"(",
"String",
")",
"proxy_hash",
"[",
":proxy_port",
"]",
"=",
"proxy",
"[",
"1",
"]",
"if",
"proxy",
"[",
"1",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"proxy_hash",
"[",
":proxy_username",
"]",
"=",
"proxy",
"[",
"2",
"]",
"if",
"proxy",
"[",
"2",
"]",
".",
"is_a?",
"(",
"String",
")",
"proxy_hash",
"[",
":proxy_password",
"]",
"=",
"proxy",
"[",
"3",
"]",
"if",
"proxy",
"[",
"3",
"]",
".",
"is_a?",
"(",
"String",
")",
"proxy_hash",
"[",
":proxy_headers",
"]",
"=",
"proxy",
"[",
"2",
"]",
"if",
"proxy",
"[",
"2",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"proxy_hash",
"[",
":proxy_headers",
"]",
"=",
"proxy",
"[",
"4",
"]",
"if",
"proxy",
"[",
"4",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"(",
"RequestError",
",",
"\"invalid HTTP proxy: #{proxy_hash}\"",
")",
"unless",
"(",
"2",
"..",
"5",
")",
".",
"cover?",
"(",
"proxy_hash",
".",
"keys",
".",
"size",
")",
"branch",
"default_options",
".",
"with_proxy",
"(",
"proxy_hash",
")",
"end"
] | Make a request through an HTTP proxy
@param [Array] proxy
@raise [Request::Error] if HTTP proxy is invalid | [
"Make",
"a",
"request",
"through",
"an",
"HTTP",
"proxy"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/chainable.rb#L155-L167 | train |
httprb/http | lib/http/chainable.rb | HTTP.Chainable.basic_auth | def basic_auth(opts)
user = opts.fetch :user
pass = opts.fetch :pass
auth("Basic " + Base64.strict_encode64("#{user}:#{pass}"))
end | ruby | def basic_auth(opts)
user = opts.fetch :user
pass = opts.fetch :pass
auth("Basic " + Base64.strict_encode64("#{user}:#{pass}"))
end | [
"def",
"basic_auth",
"(",
"opts",
")",
"user",
"=",
"opts",
".",
"fetch",
":user",
"pass",
"=",
"opts",
".",
"fetch",
":pass",
"auth",
"(",
"\"Basic \"",
"+",
"Base64",
".",
"strict_encode64",
"(",
"\"#{user}:#{pass}\"",
")",
")",
"end"
] | Make a request with the given Basic authorization header
@see http://tools.ietf.org/html/rfc2617
@param [#fetch] opts
@option opts [#to_s] :user
@option opts [#to_s] :pass | [
"Make",
"a",
"request",
"with",
"the",
"given",
"Basic",
"authorization",
"header"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/chainable.rb#L211-L216 | train |
httprb/http | lib/http/client.rb | HTTP.Client.request | def request(verb, uri, opts = {}) # rubocop:disable Style/OptionHash
opts = @default_options.merge(opts)
req = build_request(verb, uri, opts)
res = perform(req, opts)
return res unless opts.follow
Redirector.new(opts.follow).perform(req, res) do |request|
perform(request, opts)
end
end | ruby | def request(verb, uri, opts = {}) # rubocop:disable Style/OptionHash
opts = @default_options.merge(opts)
req = build_request(verb, uri, opts)
res = perform(req, opts)
return res unless opts.follow
Redirector.new(opts.follow).perform(req, res) do |request|
perform(request, opts)
end
end | [
"def",
"request",
"(",
"verb",
",",
"uri",
",",
"opts",
"=",
"{",
"}",
")",
"# rubocop:disable Style/OptionHash",
"opts",
"=",
"@default_options",
".",
"merge",
"(",
"opts",
")",
"req",
"=",
"build_request",
"(",
"verb",
",",
"uri",
",",
"opts",
")",
"res",
"=",
"perform",
"(",
"req",
",",
"opts",
")",
"return",
"res",
"unless",
"opts",
".",
"follow",
"Redirector",
".",
"new",
"(",
"opts",
".",
"follow",
")",
".",
"perform",
"(",
"req",
",",
"res",
")",
"do",
"|",
"request",
"|",
"perform",
"(",
"request",
",",
"opts",
")",
"end",
"end"
] | Make an HTTP request | [
"Make",
"an",
"HTTP",
"request"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/client.rb#L28-L37 | train |
httprb/http | lib/http/client.rb | HTTP.Client.build_request | def build_request(verb, uri, opts = {}) # rubocop:disable Style/OptionHash
opts = @default_options.merge(opts)
uri = make_request_uri(uri, opts)
headers = make_request_headers(opts)
body = make_request_body(opts, headers)
req = HTTP::Request.new(
:verb => verb,
:uri => uri,
:uri_normalizer => opts.feature(:normalize_uri)&.normalizer,
:proxy => opts.proxy,
:headers => headers,
:body => body
)
opts.features.inject(req) do |request, (_name, feature)|
feature.wrap_request(request)
end
end | ruby | def build_request(verb, uri, opts = {}) # rubocop:disable Style/OptionHash
opts = @default_options.merge(opts)
uri = make_request_uri(uri, opts)
headers = make_request_headers(opts)
body = make_request_body(opts, headers)
req = HTTP::Request.new(
:verb => verb,
:uri => uri,
:uri_normalizer => opts.feature(:normalize_uri)&.normalizer,
:proxy => opts.proxy,
:headers => headers,
:body => body
)
opts.features.inject(req) do |request, (_name, feature)|
feature.wrap_request(request)
end
end | [
"def",
"build_request",
"(",
"verb",
",",
"uri",
",",
"opts",
"=",
"{",
"}",
")",
"# rubocop:disable Style/OptionHash",
"opts",
"=",
"@default_options",
".",
"merge",
"(",
"opts",
")",
"uri",
"=",
"make_request_uri",
"(",
"uri",
",",
"opts",
")",
"headers",
"=",
"make_request_headers",
"(",
"opts",
")",
"body",
"=",
"make_request_body",
"(",
"opts",
",",
"headers",
")",
"req",
"=",
"HTTP",
"::",
"Request",
".",
"new",
"(",
":verb",
"=>",
"verb",
",",
":uri",
"=>",
"uri",
",",
":uri_normalizer",
"=>",
"opts",
".",
"feature",
"(",
":normalize_uri",
")",
"&.",
"normalizer",
",",
":proxy",
"=>",
"opts",
".",
"proxy",
",",
":headers",
"=>",
"headers",
",",
":body",
"=>",
"body",
")",
"opts",
".",
"features",
".",
"inject",
"(",
"req",
")",
"do",
"|",
"request",
",",
"(",
"_name",
",",
"feature",
")",
"|",
"feature",
".",
"wrap_request",
"(",
"request",
")",
"end",
"end"
] | Prepare an HTTP request | [
"Prepare",
"an",
"HTTP",
"request"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/client.rb#L40-L58 | train |
httprb/http | lib/http/client.rb | HTTP.Client.verify_connection! | def verify_connection!(uri)
if default_options.persistent? && uri.origin != default_options.persistent
raise StateError, "Persistence is enabled for #{default_options.persistent}, but we got #{uri.origin}"
# We re-create the connection object because we want to let prior requests
# lazily load the body as long as possible, and this mimics prior functionality.
elsif @connection && ([email protected]_alive? || @connection.expired?)
close
# If we get into a bad state (eg, Timeout.timeout ensure being killed)
# close the connection to prevent potential for mixed responses.
elsif @state == :dirty
close
end
end | ruby | def verify_connection!(uri)
if default_options.persistent? && uri.origin != default_options.persistent
raise StateError, "Persistence is enabled for #{default_options.persistent}, but we got #{uri.origin}"
# We re-create the connection object because we want to let prior requests
# lazily load the body as long as possible, and this mimics prior functionality.
elsif @connection && ([email protected]_alive? || @connection.expired?)
close
# If we get into a bad state (eg, Timeout.timeout ensure being killed)
# close the connection to prevent potential for mixed responses.
elsif @state == :dirty
close
end
end | [
"def",
"verify_connection!",
"(",
"uri",
")",
"if",
"default_options",
".",
"persistent?",
"&&",
"uri",
".",
"origin",
"!=",
"default_options",
".",
"persistent",
"raise",
"StateError",
",",
"\"Persistence is enabled for #{default_options.persistent}, but we got #{uri.origin}\"",
"# We re-create the connection object because we want to let prior requests",
"# lazily load the body as long as possible, and this mimics prior functionality.",
"elsif",
"@connection",
"&&",
"(",
"!",
"@connection",
".",
"keep_alive?",
"||",
"@connection",
".",
"expired?",
")",
"close",
"# If we get into a bad state (eg, Timeout.timeout ensure being killed)",
"# close the connection to prevent potential for mixed responses.",
"elsif",
"@state",
"==",
":dirty",
"close",
"end",
"end"
] | Verify our request isn't going to be made against another URI | [
"Verify",
"our",
"request",
"isn",
"t",
"going",
"to",
"be",
"made",
"against",
"another",
"URI"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/client.rb#L110-L122 | train |
httprb/http | lib/http/client.rb | HTTP.Client.make_request_uri | def make_request_uri(uri, opts)
uri = uri.to_s
if default_options.persistent? && uri !~ HTTP_OR_HTTPS_RE
uri = "#{default_options.persistent}#{uri}"
end
uri = HTTP::URI.parse uri
if opts.params && !opts.params.empty?
uri.query_values = uri.query_values(Array).to_a.concat(opts.params.to_a)
end
# Some proxies (seen on WEBRick) fail if URL has
# empty path (e.g. `http://example.com`) while it's RFC-complaint:
# http://tools.ietf.org/html/rfc1738#section-3.1
uri.path = "/" if uri.path.empty?
uri
end | ruby | def make_request_uri(uri, opts)
uri = uri.to_s
if default_options.persistent? && uri !~ HTTP_OR_HTTPS_RE
uri = "#{default_options.persistent}#{uri}"
end
uri = HTTP::URI.parse uri
if opts.params && !opts.params.empty?
uri.query_values = uri.query_values(Array).to_a.concat(opts.params.to_a)
end
# Some proxies (seen on WEBRick) fail if URL has
# empty path (e.g. `http://example.com`) while it's RFC-complaint:
# http://tools.ietf.org/html/rfc1738#section-3.1
uri.path = "/" if uri.path.empty?
uri
end | [
"def",
"make_request_uri",
"(",
"uri",
",",
"opts",
")",
"uri",
"=",
"uri",
".",
"to_s",
"if",
"default_options",
".",
"persistent?",
"&&",
"uri",
"!~",
"HTTP_OR_HTTPS_RE",
"uri",
"=",
"\"#{default_options.persistent}#{uri}\"",
"end",
"uri",
"=",
"HTTP",
"::",
"URI",
".",
"parse",
"uri",
"if",
"opts",
".",
"params",
"&&",
"!",
"opts",
".",
"params",
".",
"empty?",
"uri",
".",
"query_values",
"=",
"uri",
".",
"query_values",
"(",
"Array",
")",
".",
"to_a",
".",
"concat",
"(",
"opts",
".",
"params",
".",
"to_a",
")",
"end",
"# Some proxies (seen on WEBRick) fail if URL has",
"# empty path (e.g. `http://example.com`) while it's RFC-complaint:",
"# http://tools.ietf.org/html/rfc1738#section-3.1",
"uri",
".",
"path",
"=",
"\"/\"",
"if",
"uri",
".",
"path",
".",
"empty?",
"uri",
"end"
] | Merges query params if needed
@param [#to_s] uri
@return [URI] | [
"Merges",
"query",
"params",
"if",
"needed"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/client.rb#L128-L147 | train |
httprb/http | lib/http/client.rb | HTTP.Client.make_request_body | def make_request_body(opts, headers)
case
when opts.body
opts.body
when opts.form
form = HTTP::FormData.create opts.form
headers[Headers::CONTENT_TYPE] ||= form.content_type
form
when opts.json
body = MimeType[:json].encode opts.json
headers[Headers::CONTENT_TYPE] ||= "application/json; charset=#{body.encoding.name}"
body
end
end | ruby | def make_request_body(opts, headers)
case
when opts.body
opts.body
when opts.form
form = HTTP::FormData.create opts.form
headers[Headers::CONTENT_TYPE] ||= form.content_type
form
when opts.json
body = MimeType[:json].encode opts.json
headers[Headers::CONTENT_TYPE] ||= "application/json; charset=#{body.encoding.name}"
body
end
end | [
"def",
"make_request_body",
"(",
"opts",
",",
"headers",
")",
"case",
"when",
"opts",
".",
"body",
"opts",
".",
"body",
"when",
"opts",
".",
"form",
"form",
"=",
"HTTP",
"::",
"FormData",
".",
"create",
"opts",
".",
"form",
"headers",
"[",
"Headers",
"::",
"CONTENT_TYPE",
"]",
"||=",
"form",
".",
"content_type",
"form",
"when",
"opts",
".",
"json",
"body",
"=",
"MimeType",
"[",
":json",
"]",
".",
"encode",
"opts",
".",
"json",
"headers",
"[",
"Headers",
"::",
"CONTENT_TYPE",
"]",
"||=",
"\"application/json; charset=#{body.encoding.name}\"",
"body",
"end",
"end"
] | Create the request body object to send | [
"Create",
"the",
"request",
"body",
"object",
"to",
"send"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/client.rb#L167-L180 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.delete | def delete(name)
name = normalize_header name.to_s
@pile.delete_if { |k, _| k == name }
end | ruby | def delete(name)
name = normalize_header name.to_s
@pile.delete_if { |k, _| k == name }
end | [
"def",
"delete",
"(",
"name",
")",
"name",
"=",
"normalize_header",
"name",
".",
"to_s",
"@pile",
".",
"delete_if",
"{",
"|",
"k",
",",
"_",
"|",
"k",
"==",
"name",
"}",
"end"
] | Removes header.
@param [#to_s] name header name
@return [void] | [
"Removes",
"header",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L41-L44 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.add | def add(name, value)
name = normalize_header name.to_s
Array(value).each { |v| @pile << [name, validate_value(v)] }
end | ruby | def add(name, value)
name = normalize_header name.to_s
Array(value).each { |v| @pile << [name, validate_value(v)] }
end | [
"def",
"add",
"(",
"name",
",",
"value",
")",
"name",
"=",
"normalize_header",
"name",
".",
"to_s",
"Array",
"(",
"value",
")",
".",
"each",
"{",
"|",
"v",
"|",
"@pile",
"<<",
"[",
"name",
",",
"validate_value",
"(",
"v",
")",
"]",
"}",
"end"
] | Appends header.
@param [#to_s] name header name
@param [Array<#to_s>, #to_s] value header value(s) to be appended
@return [void] | [
"Appends",
"header",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L51-L54 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.get | def get(name)
name = normalize_header name.to_s
@pile.select { |k, _| k == name }.map { |_, v| v }
end | ruby | def get(name)
name = normalize_header name.to_s
@pile.select { |k, _| k == name }.map { |_, v| v }
end | [
"def",
"get",
"(",
"name",
")",
"name",
"=",
"normalize_header",
"name",
".",
"to_s",
"@pile",
".",
"select",
"{",
"|",
"k",
",",
"_",
"|",
"k",
"==",
"name",
"}",
".",
"map",
"{",
"|",
"_",
",",
"v",
"|",
"v",
"}",
"end"
] | Returns list of header values if any.
@return [Array<String>] | [
"Returns",
"list",
"of",
"header",
"values",
"if",
"any",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L59-L62 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.include? | def include?(name)
name = normalize_header name.to_s
@pile.any? { |k, _| k == name }
end | ruby | def include?(name)
name = normalize_header name.to_s
@pile.any? { |k, _| k == name }
end | [
"def",
"include?",
"(",
"name",
")",
"name",
"=",
"normalize_header",
"name",
".",
"to_s",
"@pile",
".",
"any?",
"{",
"|",
"k",
",",
"_",
"|",
"k",
"==",
"name",
"}",
"end"
] | Tells whenever header with given `name` is set or not.
@return [Boolean] | [
"Tells",
"whenever",
"header",
"with",
"given",
"name",
"is",
"set",
"or",
"not",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L82-L85 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.merge! | def merge!(other)
self.class.coerce(other).to_h.each { |name, values| set name, values }
end | ruby | def merge!(other)
self.class.coerce(other).to_h.each { |name, values| set name, values }
end | [
"def",
"merge!",
"(",
"other",
")",
"self",
".",
"class",
".",
"coerce",
"(",
"other",
")",
".",
"to_h",
".",
"each",
"{",
"|",
"name",
",",
"values",
"|",
"set",
"name",
",",
"values",
"}",
"end"
] | Merges `other` headers into `self`.
@see #merge
@return [void] | [
"Merges",
"other",
"headers",
"into",
"self",
"."
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L160-L162 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.normalize_header | def normalize_header(name)
return name if name =~ CANONICAL_NAME_RE
normalized = name.split(/[\-_]/).each(&:capitalize!).join("-")
return normalized if normalized =~ COMPLIANT_NAME_RE
raise HeaderError, "Invalid HTTP header field name: #{name.inspect}"
end | ruby | def normalize_header(name)
return name if name =~ CANONICAL_NAME_RE
normalized = name.split(/[\-_]/).each(&:capitalize!).join("-")
return normalized if normalized =~ COMPLIANT_NAME_RE
raise HeaderError, "Invalid HTTP header field name: #{name.inspect}"
end | [
"def",
"normalize_header",
"(",
"name",
")",
"return",
"name",
"if",
"name",
"=~",
"CANONICAL_NAME_RE",
"normalized",
"=",
"name",
".",
"split",
"(",
"/",
"\\-",
"/",
")",
".",
"each",
"(",
":capitalize!",
")",
".",
"join",
"(",
"\"-\"",
")",
"return",
"normalized",
"if",
"normalized",
"=~",
"COMPLIANT_NAME_RE",
"raise",
"HeaderError",
",",
"\"Invalid HTTP header field name: #{name.inspect}\"",
"end"
] | Transforms `name` to canonical HTTP header capitalization
@param [String] name
@raise [HeaderError] if normalized name does not
match {HEADER_NAME_RE}
@return [String] canonical HTTP header name | [
"Transforms",
"name",
"to",
"canonical",
"HTTP",
"header",
"capitalization"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L203-L211 | train |
httprb/http | lib/http/headers.rb | HTTP.Headers.validate_value | def validate_value(value)
v = value.to_s
return v unless v.include?("\n")
raise HeaderError, "Invalid HTTP header field value: #{v.inspect}"
end | ruby | def validate_value(value)
v = value.to_s
return v unless v.include?("\n")
raise HeaderError, "Invalid HTTP header field value: #{v.inspect}"
end | [
"def",
"validate_value",
"(",
"value",
")",
"v",
"=",
"value",
".",
"to_s",
"return",
"v",
"unless",
"v",
".",
"include?",
"(",
"\"\\n\"",
")",
"raise",
"HeaderError",
",",
"\"Invalid HTTP header field value: #{v.inspect}\"",
"end"
] | Ensures there is no new line character in the header value
@param [String] value
@raise [HeaderError] if value includes new line character
@return [String] stringified header value | [
"Ensures",
"there",
"is",
"no",
"new",
"line",
"character",
"in",
"the",
"header",
"value"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/headers.rb#L218-L222 | train |
httprb/http | lib/http/redirector.rb | HTTP.Redirector.redirect_to | def redirect_to(uri)
raise StateError, "no Location header in redirect" unless uri
verb = @request.verb
code = @response.status.code
if UNSAFE_VERBS.include?(verb) && STRICT_SENSITIVE_CODES.include?(code)
raise StateError, "can't follow #{@response.status} redirect" if @strict
verb = :get
end
verb = :get if !SEE_OTHER_ALLOWED_VERBS.include?(verb) && 303 == code
@request.redirect(uri, verb)
end | ruby | def redirect_to(uri)
raise StateError, "no Location header in redirect" unless uri
verb = @request.verb
code = @response.status.code
if UNSAFE_VERBS.include?(verb) && STRICT_SENSITIVE_CODES.include?(code)
raise StateError, "can't follow #{@response.status} redirect" if @strict
verb = :get
end
verb = :get if !SEE_OTHER_ALLOWED_VERBS.include?(verb) && 303 == code
@request.redirect(uri, verb)
end | [
"def",
"redirect_to",
"(",
"uri",
")",
"raise",
"StateError",
",",
"\"no Location header in redirect\"",
"unless",
"uri",
"verb",
"=",
"@request",
".",
"verb",
"code",
"=",
"@response",
".",
"status",
".",
"code",
"if",
"UNSAFE_VERBS",
".",
"include?",
"(",
"verb",
")",
"&&",
"STRICT_SENSITIVE_CODES",
".",
"include?",
"(",
"code",
")",
"raise",
"StateError",
",",
"\"can't follow #{@response.status} redirect\"",
"if",
"@strict",
"verb",
"=",
":get",
"end",
"verb",
"=",
":get",
"if",
"!",
"SEE_OTHER_ALLOWED_VERBS",
".",
"include?",
"(",
"verb",
")",
"&&",
"303",
"==",
"code",
"@request",
".",
"redirect",
"(",
"uri",
",",
"verb",
")",
"end"
] | Redirect policy for follow
@return [Request] | [
"Redirect",
"policy",
"for",
"follow"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/redirector.rb#L84-L98 | train |
httprb/http | lib/http/request.rb | HTTP.Request.stream | def stream(socket)
include_proxy_headers if using_proxy? && [email protected]?
Request::Writer.new(socket, body, headers, headline).stream
end | ruby | def stream(socket)
include_proxy_headers if using_proxy? && [email protected]?
Request::Writer.new(socket, body, headers, headline).stream
end | [
"def",
"stream",
"(",
"socket",
")",
"include_proxy_headers",
"if",
"using_proxy?",
"&&",
"!",
"@uri",
".",
"https?",
"Request",
"::",
"Writer",
".",
"new",
"(",
"socket",
",",
"body",
",",
"headers",
",",
"headline",
")",
".",
"stream",
"end"
] | Stream the request to a socket | [
"Stream",
"the",
"request",
"to",
"a",
"socket"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/request.rb#L116-L119 | train |
httprb/http | lib/http/request.rb | HTTP.Request.proxy_connect_headers | def proxy_connect_headers
connect_headers = HTTP::Headers.coerce(
Headers::HOST => headers[Headers::HOST],
Headers::USER_AGENT => headers[Headers::USER_AGENT]
)
connect_headers[Headers::PROXY_AUTHORIZATION] = proxy_authorization_header if using_authenticated_proxy?
connect_headers.merge!(proxy[:proxy_headers]) if proxy.key?(:proxy_headers)
connect_headers
end | ruby | def proxy_connect_headers
connect_headers = HTTP::Headers.coerce(
Headers::HOST => headers[Headers::HOST],
Headers::USER_AGENT => headers[Headers::USER_AGENT]
)
connect_headers[Headers::PROXY_AUTHORIZATION] = proxy_authorization_header if using_authenticated_proxy?
connect_headers.merge!(proxy[:proxy_headers]) if proxy.key?(:proxy_headers)
connect_headers
end | [
"def",
"proxy_connect_headers",
"connect_headers",
"=",
"HTTP",
"::",
"Headers",
".",
"coerce",
"(",
"Headers",
"::",
"HOST",
"=>",
"headers",
"[",
"Headers",
"::",
"HOST",
"]",
",",
"Headers",
"::",
"USER_AGENT",
"=>",
"headers",
"[",
"Headers",
"::",
"USER_AGENT",
"]",
")",
"connect_headers",
"[",
"Headers",
"::",
"PROXY_AUTHORIZATION",
"]",
"=",
"proxy_authorization_header",
"if",
"using_authenticated_proxy?",
"connect_headers",
".",
"merge!",
"(",
"proxy",
"[",
":proxy_headers",
"]",
")",
"if",
"proxy",
".",
"key?",
"(",
":proxy_headers",
")",
"connect_headers",
"end"
] | Headers to send with proxy connect request | [
"Headers",
"to",
"send",
"with",
"proxy",
"connect",
"request"
] | f37a10ea4fab3ee411907ea2e4251ddf0ca33a93 | https://github.com/httprb/http/blob/f37a10ea4fab3ee411907ea2e4251ddf0ca33a93/lib/http/request.rb#L169-L178 | train |
roo-rb/roo | lib/roo/excelx.rb | Roo.Excelx.column | def column(column_number, sheet = nil)
if column_number.is_a?(::String)
column_number = ::Roo::Utils.letter_to_number(column_number)
end
sheet_for(sheet).column(column_number)
end | ruby | def column(column_number, sheet = nil)
if column_number.is_a?(::String)
column_number = ::Roo::Utils.letter_to_number(column_number)
end
sheet_for(sheet).column(column_number)
end | [
"def",
"column",
"(",
"column_number",
",",
"sheet",
"=",
"nil",
")",
"if",
"column_number",
".",
"is_a?",
"(",
"::",
"String",
")",
"column_number",
"=",
"::",
"Roo",
"::",
"Utils",
".",
"letter_to_number",
"(",
"column_number",
")",
"end",
"sheet_for",
"(",
"sheet",
")",
".",
"column",
"(",
"column_number",
")",
"end"
] | returns all values in this column as an array
column numbers are 1,2,3,... like in the spreadsheet | [
"returns",
"all",
"values",
"in",
"this",
"column",
"as",
"an",
"array",
"column",
"numbers",
"are",
"1",
"2",
"3",
"...",
"like",
"in",
"the",
"spreadsheet"
] | 4ec1104f0c3c2a29711c0c907371cd2be12bcc3c | https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/excelx.rb#L124-L129 | train |
roo-rb/roo | lib/roo/excelx.rb | Roo.Excelx.excelx_format | def excelx_format(row, col, sheet = nil)
key = normalize(row, col)
sheet_for(sheet).excelx_format(key)
end | ruby | def excelx_format(row, col, sheet = nil)
key = normalize(row, col)
sheet_for(sheet).excelx_format(key)
end | [
"def",
"excelx_format",
"(",
"row",
",",
"col",
",",
"sheet",
"=",
"nil",
")",
"key",
"=",
"normalize",
"(",
"row",
",",
"col",
")",
"sheet_for",
"(",
"sheet",
")",
".",
"excelx_format",
"(",
"key",
")",
"end"
] | returns the internal format of an excel cell | [
"returns",
"the",
"internal",
"format",
"of",
"an",
"excel",
"cell"
] | 4ec1104f0c3c2a29711c0c907371cd2be12bcc3c | https://github.com/roo-rb/roo/blob/4ec1104f0c3c2a29711c0c907371cd2be12bcc3c/lib/roo/excelx.rb#L226-L229 | train |
Subsets and Splits