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
mbj/unparser
lib/unparser/cli.rb
Unparser.CLI.exit_status
def exit_status effective_sources.each do |source| next if @ignore.include?(source) process_source(source) break if @fail_fast && !@success end @success ? EXIT_SUCCESS : EXIT_FAILURE end
ruby
def exit_status effective_sources.each do |source| next if @ignore.include?(source) process_source(source) break if @fail_fast && !@success end @success ? EXIT_SUCCESS : EXIT_FAILURE end
[ "def", "exit_status", "effective_sources", ".", "each", "do", "|", "source", "|", "next", "if", "@ignore", ".", "include?", "(", "source", ")", "process_source", "(", "source", ")", "break", "if", "@fail_fast", "&&", "!", "@success", "end", "@success", "?", "EXIT_SUCCESS", ":", "EXIT_FAILURE", "end" ]
Return exit status @return [Fixnum] @api private
[ "Return", "exit", "status" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/cli.rb#L96-L105
train
mbj/unparser
lib/unparser/cli.rb
Unparser.CLI.effective_sources
def effective_sources if @start_with reject = true @sources.reject do |source| if reject && source.eql?(@start_with) reject = false end reject end else @sources end end
ruby
def effective_sources if @start_with reject = true @sources.reject do |source| if reject && source.eql?(@start_with) reject = false end reject end else @sources end end
[ "def", "effective_sources", "if", "@start_with", "reject", "=", "true", "@sources", ".", "reject", "do", "|", "source", "|", "if", "reject", "&&", "source", ".", "eql?", "(", "@start_with", ")", "reject", "=", "false", "end", "reject", "end", "else", "@sources", "end", "end" ]
Return effective sources @return [Enumerable<CLI::Source>] @api private
[ "Return", "effective", "sources" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/cli.rb#L134-L147
train
mbj/unparser
lib/unparser/cli.rb
Unparser.CLI.sources
def sources(file_name) files = if File.directory?(file_name) Dir.glob(File.join(file_name, '**/*.rb')).sort elsif File.file?(file_name) [file_name] else Dir.glob(file_name).sort end files.map(&Source::File.method(:new)) end
ruby
def sources(file_name) files = if File.directory?(file_name) Dir.glob(File.join(file_name, '**/*.rb')).sort elsif File.file?(file_name) [file_name] else Dir.glob(file_name).sort end files.map(&Source::File.method(:new)) end
[ "def", "sources", "(", "file_name", ")", "files", "=", "if", "File", ".", "directory?", "(", "file_name", ")", "Dir", ".", "glob", "(", "File", ".", "join", "(", "file_name", ",", "'**/*.rb'", ")", ")", ".", "sort", "elsif", "File", ".", "file?", "(", "file_name", ")", "[", "file_name", "]", "else", "Dir", ".", "glob", "(", "file_name", ")", ".", "sort", "end", "files", ".", "map", "(", "Source", "::", "File", ".", "method", "(", ":new", ")", ")", "end" ]
Return sources for file name @param [String] file_name @return [Enumerable<CLI::Source>] @api private ignore :reek:UtilityFunction
[ "Return", "sources", "for", "file", "name" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/cli.rb#L158-L169
train
mbj/unparser
lib/unparser/dsl.rb
Unparser.DSL.define_child
def define_child(name, index) define_method(name) do children.at(index) end private name end
ruby
def define_child(name, index) define_method(name) do children.at(index) end private name end
[ "def", "define_child", "(", "name", ",", "index", ")", "define_method", "(", "name", ")", "do", "children", ".", "at", "(", "index", ")", "end", "private", "name", "end" ]
Define named child @param [Symbol] name @param [Fixnum] index @return [undefined] @api private
[ "Define", "named", "child" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/dsl.rb#L34-L39
train
mbj/unparser
lib/unparser/dsl.rb
Unparser.DSL.define_group
def define_group(name, range) define_method(name) do children[range] end private(name) memoize(name) end
ruby
def define_group(name, range) define_method(name) do children[range] end private(name) memoize(name) end
[ "def", "define_group", "(", "name", ",", "range", ")", "define_method", "(", "name", ")", "do", "children", "[", "range", "]", "end", "private", "(", "name", ")", "memoize", "(", "name", ")", "end" ]
Define a group of children @param [Symbol] name @param [Range] range @return [undefined] @pai private
[ "Define", "a", "group", "of", "children" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/dsl.rb#L50-L56
train
mbj/unparser
lib/unparser/dsl.rb
Unparser.DSL.children
def children(*names) define_remaining_children(names) names.each_with_index do |name, index| define_child(name, index) end end
ruby
def children(*names) define_remaining_children(names) names.each_with_index do |name, index| define_child(name, index) end end
[ "def", "children", "(", "*", "names", ")", "define_remaining_children", "(", "names", ")", "names", ".", "each_with_index", "do", "|", "name", ",", "index", "|", "define_child", "(", "name", ",", "index", ")", "end", "end" ]
Create name helpers @return [undefined] @api private
[ "Create", "name", "helpers" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/dsl.rb#L64-L70
train
mbj/unparser
lib/unparser/preprocessor.rb
Unparser.Preprocessor.visited_children
def visited_children children.map do |node| if node.is_a?(Parser::AST::Node) visit(node) else node end end end
ruby
def visited_children children.map do |node| if node.is_a?(Parser::AST::Node) visit(node) else node end end end
[ "def", "visited_children", "children", ".", "map", "do", "|", "node", "|", "if", "node", ".", "is_a?", "(", "Parser", "::", "AST", "::", "Node", ")", "visit", "(", "node", ")", "else", "node", "end", "end", "end" ]
Return visited children @return [Array<Parser::Ast::Node>] @api private
[ "Return", "visited", "children" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/preprocessor.rb#L79-L87
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.write_to_buffer
def write_to_buffer emit_comments_before if buffer.fresh_line? dispatch comments.consume(node) emit_eof_comments if parent.is_a?(Root) self end
ruby
def write_to_buffer emit_comments_before if buffer.fresh_line? dispatch comments.consume(node) emit_eof_comments if parent.is_a?(Root) self end
[ "def", "write_to_buffer", "emit_comments_before", "if", "buffer", ".", "fresh_line?", "dispatch", "comments", ".", "consume", "(", "node", ")", "emit_eof_comments", "if", "parent", ".", "is_a?", "(", "Root", ")", "self", "end" ]
Trigger write to buffer @return [self] @api private
[ "Trigger", "write", "to", "buffer" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L101-L107
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.visit
def visit(node) emitter = emitter(node) conditional_parentheses(!emitter.terminated?) do emitter.write_to_buffer end end
ruby
def visit(node) emitter = emitter(node) conditional_parentheses(!emitter.terminated?) do emitter.write_to_buffer end end
[ "def", "visit", "(", "node", ")", "emitter", "=", "emitter", "(", "node", ")", "conditional_parentheses", "(", "!", "emitter", ".", "terminated?", ")", "do", "emitter", ".", "write_to_buffer", "end", "end" ]
Visit ambiguous node @param [Parser::AST::Node] node @return [undefined] @api private
[ "Visit", "ambiguous", "node" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L199-L204
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.delimited
def delimited(nodes, &block) return if nodes.empty? block ||= method(:visit) head, *tail = nodes block.call(head) tail.each do |node| write(DEFAULT_DELIMITER) block.call(node) end end
ruby
def delimited(nodes, &block) return if nodes.empty? block ||= method(:visit) head, *tail = nodes block.call(head) tail.each do |node| write(DEFAULT_DELIMITER) block.call(node) end end
[ "def", "delimited", "(", "nodes", ",", "&", "block", ")", "return", "if", "nodes", ".", "empty?", "block", "||=", "method", "(", ":visit", ")", "head", ",", "*", "tail", "=", "nodes", "block", ".", "call", "(", "head", ")", "tail", ".", "each", "do", "|", "node", "|", "write", "(", "DEFAULT_DELIMITER", ")", "block", ".", "call", "(", "node", ")", "end", "end" ]
Emit delimited body @param [Enumerable<Parser::AST::Node>] nodes @param [String] delimiter @return [undefined] @api private
[ "Emit", "delimited", "body" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L271-L281
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_comments_before
def emit_comments_before(source_part = :expression) comments_before = comments.take_before(node, source_part) return if comments_before.empty? emit_comments(comments_before) buffer.nl end
ruby
def emit_comments_before(source_part = :expression) comments_before = comments.take_before(node, source_part) return if comments_before.empty? emit_comments(comments_before) buffer.nl end
[ "def", "emit_comments_before", "(", "source_part", "=", ":expression", ")", "comments_before", "=", "comments", ".", "take_before", "(", "node", ",", "source_part", ")", "return", "if", "comments_before", ".", "empty?", "emit_comments", "(", "comments_before", ")", "buffer", ".", "nl", "end" ]
Write comments that appeared before source_part in the source @param [Symbol] source_part @return [undefined] @api private
[ "Write", "comments", "that", "appeared", "before", "source_part", "in", "the", "source" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L312-L318
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_eof_comments
def emit_eof_comments emit_eol_comments comments_left = comments.take_all return if comments_left.empty? buffer.nl emit_comments(comments_left) end
ruby
def emit_eof_comments emit_eol_comments comments_left = comments.take_all return if comments_left.empty? buffer.nl emit_comments(comments_left) end
[ "def", "emit_eof_comments", "emit_eol_comments", "comments_left", "=", "comments", ".", "take_all", "return", "if", "comments_left", ".", "empty?", "buffer", ".", "nl", "emit_comments", "(", "comments_left", ")", "end" ]
Write end-of-file comments @return [undefined] @api private
[ "Write", "end", "-", "of", "-", "file", "comments" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L338-L345
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_comments
def emit_comments(comments) max = comments.size - 1 comments.each_with_index do |comment, index| if comment.type.equal?(:document) buffer.append_without_prefix(comment.text.chomp) else write(comment.text) end buffer.nl if index < max end end
ruby
def emit_comments(comments) max = comments.size - 1 comments.each_with_index do |comment, index| if comment.type.equal?(:document) buffer.append_without_prefix(comment.text.chomp) else write(comment.text) end buffer.nl if index < max end end
[ "def", "emit_comments", "(", "comments", ")", "max", "=", "comments", ".", "size", "-", "1", "comments", ".", "each_with_index", "do", "|", "comment", ",", "index", "|", "if", "comment", ".", "type", ".", "equal?", "(", ":document", ")", "buffer", ".", "append_without_prefix", "(", "comment", ".", "text", ".", "chomp", ")", "else", "write", "(", "comment", ".", "text", ")", "end", "buffer", ".", "nl", "if", "index", "<", "max", "end", "end" ]
Write each comment to a separate line @param [Array] comments @return [undefined] @api private
[ "Write", "each", "comment", "to", "a", "separate", "line" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L355-L365
train
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_body
def emit_body(body = body()) unless body buffer.indent nl buffer.unindent return end visit_indented(body) end
ruby
def emit_body(body = body()) unless body buffer.indent nl buffer.unindent return end visit_indented(body) end
[ "def", "emit_body", "(", "body", "=", "body", "(", ")", ")", "unless", "body", "buffer", ".", "indent", "nl", "buffer", ".", "unindent", "return", "end", "visit_indented", "(", "body", ")", "end" ]
Emit non nil body @param [Parser::AST::Node] node @return [undefined] @api private rubocop:disable MethodCallWithoutArgsParentheses
[ "Emit", "non", "nil", "body" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L442-L450
train
mbj/unparser
lib/unparser/comments.rb
Unparser.Comments.take_before
def take_before(node, source_part) range = source_range(node, source_part) if range take_while { |comment| comment.location.expression.end_pos <= range.begin_pos } else EMPTY_ARRAY end end
ruby
def take_before(node, source_part) range = source_range(node, source_part) if range take_while { |comment| comment.location.expression.end_pos <= range.begin_pos } else EMPTY_ARRAY end end
[ "def", "take_before", "(", "node", ",", "source_part", ")", "range", "=", "source_range", "(", "node", ",", "source_part", ")", "if", "range", "take_while", "{", "|", "comment", "|", "comment", ".", "location", ".", "expression", ".", "end_pos", "<=", "range", ".", "begin_pos", "}", "else", "EMPTY_ARRAY", "end", "end" ]
Take comments appear in the source before the specified part of the node @param [Parser::AST::Node] node @param [Symbol] source_part @return [Array] @api private
[ "Take", "comments", "appear", "in", "the", "source", "before", "the", "specified", "part", "of", "the", "node" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/comments.rb#L83-L90
train
mbj/unparser
lib/unparser/comments.rb
Unparser.Comments.unshift_documents
def unshift_documents(comments) doc_comments, other_comments = comments.partition(&:document?) doc_comments.reverse_each { |comment| @comments.unshift(comment) } other_comments end
ruby
def unshift_documents(comments) doc_comments, other_comments = comments.partition(&:document?) doc_comments.reverse_each { |comment| @comments.unshift(comment) } other_comments end
[ "def", "unshift_documents", "(", "comments", ")", "doc_comments", ",", "other_comments", "=", "comments", ".", "partition", "(", ":document?", ")", "doc_comments", ".", "reverse_each", "{", "|", "comment", "|", "@comments", ".", "unshift", "(", "comment", ")", "}", "other_comments", "end" ]
Unshift document comments and return the rest @param [Array] comments @return [Array] @api private
[ "Unshift", "document", "comments", "and", "return", "the", "rest" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/comments.rb#L149-L153
train
chef/appbundler
lib/appbundler/app.rb
Appbundler.App.copy_bundler_env
def copy_bundler_env gem_path = installed_spec.gem_dir # If we're already using that directory, don't copy (it won't work anyway) return if gem_path == File.dirname(gemfile_lock) FileUtils.install(gemfile_lock, gem_path, mode: 0644) if File.exist?(dot_bundle_dir) && File.directory?(dot_bundle_dir) FileUtils.cp_r(dot_bundle_dir, gem_path) FileUtils.chmod_R("ugo+rX", File.join(gem_path, ".bundle")) end end
ruby
def copy_bundler_env gem_path = installed_spec.gem_dir # If we're already using that directory, don't copy (it won't work anyway) return if gem_path == File.dirname(gemfile_lock) FileUtils.install(gemfile_lock, gem_path, mode: 0644) if File.exist?(dot_bundle_dir) && File.directory?(dot_bundle_dir) FileUtils.cp_r(dot_bundle_dir, gem_path) FileUtils.chmod_R("ugo+rX", File.join(gem_path, ".bundle")) end end
[ "def", "copy_bundler_env", "gem_path", "=", "installed_spec", ".", "gem_dir", "# If we're already using that directory, don't copy (it won't work anyway)", "return", "if", "gem_path", "==", "File", ".", "dirname", "(", "gemfile_lock", ")", "FileUtils", ".", "install", "(", "gemfile_lock", ",", "gem_path", ",", "mode", ":", "0644", ")", "if", "File", ".", "exist?", "(", "dot_bundle_dir", ")", "&&", "File", ".", "directory?", "(", "dot_bundle_dir", ")", "FileUtils", ".", "cp_r", "(", "dot_bundle_dir", ",", "gem_path", ")", "FileUtils", ".", "chmod_R", "(", "\"ugo+rX\"", ",", "File", ".", "join", "(", "gem_path", ",", "\".bundle\"", ")", ")", "end", "end" ]
Copy over any .bundler and Gemfile.lock files to the target gem directory. This will let us run tests from under that directory. This is only on the 2-arg implementations pathway. This is not used for the 3-arg version.
[ "Copy", "over", "any", ".", "bundler", "and", "Gemfile", ".", "lock", "files", "to", "the", "target", "gem", "directory", ".", "This", "will", "let", "us", "run", "tests", "from", "under", "that", "directory", "." ]
7f5782012cf8c3ef5d7590870e3f33a9537b99b2
https://github.com/chef/appbundler/blob/7f5782012cf8c3ef5d7590870e3f33a9537b99b2/lib/appbundler/app.rb#L126-L135
train
chef/appbundler
lib/appbundler/app.rb
Appbundler.App.write_merged_lockfiles
def write_merged_lockfiles(without: []) unless external_lockfile? copy_bundler_env return end # handle external lockfile Tempfile.open(".appbundler-gemfile", app_dir) do |t| t.puts "source 'https://rubygems.org'" locked_gems = {} gemfile_lock_specs.each do |s| # next if SHITLIST.include?(s.name) spec = safe_resolve_local_gem(s) next if spec.nil? case s.source when Bundler::Source::Path locked_gems[spec.name] = %Q{gem "#{spec.name}", path: "#{spec.gem_dir}"} when Bundler::Source::Rubygems # FIXME: should add the spec.version as a gem requirement below locked_gems[spec.name] = %Q{gem "#{spec.name}", "= #{spec.version}"} when Bundler::Source::Git raise "FIXME: appbundler needs a patch to support Git gems" else raise "appbundler doens't know this source type" end end seen_gems = {} t.puts "# GEMS FROM GEMFILE:" requested_dependencies(without).each do |dep| next if SHITLIST.include?(dep.name) if locked_gems[dep.name] t.puts locked_gems[dep.name] else string = %Q{gem "#{dep.name}", #{requirement_to_str(dep.requirement)}} string << %Q{, platform: #{dep.platforms}} unless dep.platforms.empty? t.puts string end seen_gems[dep.name] = true end t.puts "# GEMS FROM LOCKFILE: " locked_gems.each do |name, line| next if SHITLIST.include?(name) next if seen_gems[name] t.puts line end t.close puts IO.read(t.path) # debugging Dir.chdir(app_dir) do FileUtils.rm_f "#{app_dir}/Gemfile.lock" Bundler.with_clean_env do so = Mixlib::ShellOut.new("bundle lock", env: { "BUNDLE_GEMFILE" => t.path }) so.run_command so.error! end FileUtils.mv t.path, "#{app_dir}/Gemfile" end end "#{app_dir}/Gemfile" end
ruby
def write_merged_lockfiles(without: []) unless external_lockfile? copy_bundler_env return end # handle external lockfile Tempfile.open(".appbundler-gemfile", app_dir) do |t| t.puts "source 'https://rubygems.org'" locked_gems = {} gemfile_lock_specs.each do |s| # next if SHITLIST.include?(s.name) spec = safe_resolve_local_gem(s) next if spec.nil? case s.source when Bundler::Source::Path locked_gems[spec.name] = %Q{gem "#{spec.name}", path: "#{spec.gem_dir}"} when Bundler::Source::Rubygems # FIXME: should add the spec.version as a gem requirement below locked_gems[spec.name] = %Q{gem "#{spec.name}", "= #{spec.version}"} when Bundler::Source::Git raise "FIXME: appbundler needs a patch to support Git gems" else raise "appbundler doens't know this source type" end end seen_gems = {} t.puts "# GEMS FROM GEMFILE:" requested_dependencies(without).each do |dep| next if SHITLIST.include?(dep.name) if locked_gems[dep.name] t.puts locked_gems[dep.name] else string = %Q{gem "#{dep.name}", #{requirement_to_str(dep.requirement)}} string << %Q{, platform: #{dep.platforms}} unless dep.platforms.empty? t.puts string end seen_gems[dep.name] = true end t.puts "# GEMS FROM LOCKFILE: " locked_gems.each do |name, line| next if SHITLIST.include?(name) next if seen_gems[name] t.puts line end t.close puts IO.read(t.path) # debugging Dir.chdir(app_dir) do FileUtils.rm_f "#{app_dir}/Gemfile.lock" Bundler.with_clean_env do so = Mixlib::ShellOut.new("bundle lock", env: { "BUNDLE_GEMFILE" => t.path }) so.run_command so.error! end FileUtils.mv t.path, "#{app_dir}/Gemfile" end end "#{app_dir}/Gemfile" end
[ "def", "write_merged_lockfiles", "(", "without", ":", "[", "]", ")", "unless", "external_lockfile?", "copy_bundler_env", "return", "end", "# handle external lockfile", "Tempfile", ".", "open", "(", "\".appbundler-gemfile\"", ",", "app_dir", ")", "do", "|", "t", "|", "t", ".", "puts", "\"source 'https://rubygems.org'\"", "locked_gems", "=", "{", "}", "gemfile_lock_specs", ".", "each", "do", "|", "s", "|", "# next if SHITLIST.include?(s.name)", "spec", "=", "safe_resolve_local_gem", "(", "s", ")", "next", "if", "spec", ".", "nil?", "case", "s", ".", "source", "when", "Bundler", "::", "Source", "::", "Path", "locked_gems", "[", "spec", ".", "name", "]", "=", "%Q{gem \"#{spec.name}\", path: \"#{spec.gem_dir}\"}", "when", "Bundler", "::", "Source", "::", "Rubygems", "# FIXME: should add the spec.version as a gem requirement below", "locked_gems", "[", "spec", ".", "name", "]", "=", "%Q{gem \"#{spec.name}\", \"= #{spec.version}\"}", "when", "Bundler", "::", "Source", "::", "Git", "raise", "\"FIXME: appbundler needs a patch to support Git gems\"", "else", "raise", "\"appbundler doens't know this source type\"", "end", "end", "seen_gems", "=", "{", "}", "t", ".", "puts", "\"# GEMS FROM GEMFILE:\"", "requested_dependencies", "(", "without", ")", ".", "each", "do", "|", "dep", "|", "next", "if", "SHITLIST", ".", "include?", "(", "dep", ".", "name", ")", "if", "locked_gems", "[", "dep", ".", "name", "]", "t", ".", "puts", "locked_gems", "[", "dep", ".", "name", "]", "else", "string", "=", "%Q{gem \"#{dep.name}\", #{requirement_to_str(dep.requirement)}}", "string", "<<", "%Q{, platform: #{dep.platforms}}", "unless", "dep", ".", "platforms", ".", "empty?", "t", ".", "puts", "string", "end", "seen_gems", "[", "dep", ".", "name", "]", "=", "true", "end", "t", ".", "puts", "\"# GEMS FROM LOCKFILE: \"", "locked_gems", ".", "each", "do", "|", "name", ",", "line", "|", "next", "if", "SHITLIST", ".", "include?", "(", "name", ")", "next", "if", "seen_gems", "[", "name", "]", "t", ".", "puts", "line", "end", "t", ".", "close", "puts", "IO", ".", "read", "(", "t", ".", "path", ")", "# debugging", "Dir", ".", "chdir", "(", "app_dir", ")", "do", "FileUtils", ".", "rm_f", "\"#{app_dir}/Gemfile.lock\"", "Bundler", ".", "with_clean_env", "do", "so", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "\"bundle lock\"", ",", "env", ":", "{", "\"BUNDLE_GEMFILE\"", "=>", "t", ".", "path", "}", ")", "so", ".", "run_command", "so", ".", "error!", "end", "FileUtils", ".", "mv", "t", ".", "path", ",", "\"#{app_dir}/Gemfile\"", "end", "end", "\"#{app_dir}/Gemfile\"", "end" ]
This is the implementation of the 3-arg version of writing the merged lockfiles, when called with the 2-arg version it short-circuits, however, to the copy_bundler_env version above. This code does not affect the generated binstubs at all.
[ "This", "is", "the", "implementation", "of", "the", "3", "-", "arg", "version", "of", "writing", "the", "merged", "lockfiles", "when", "called", "with", "the", "2", "-", "arg", "version", "it", "short", "-", "circuits", "however", "to", "the", "copy_bundler_env", "version", "above", "." ]
7f5782012cf8c3ef5d7590870e3f33a9537b99b2
https://github.com/chef/appbundler/blob/7f5782012cf8c3ef5d7590870e3f33a9537b99b2/lib/appbundler/app.rb#L143-L210
train
tmm1/ripper-tags
lib/ripper-tags/vim_formatter.rb
RipperTags.VimFormatter.with_output
def with_output super do |out| out.puts header @queued_write = [] yield out @queued_write.sort.each do |line| out.puts(line) end end end
ruby
def with_output super do |out| out.puts header @queued_write = [] yield out @queued_write.sort.each do |line| out.puts(line) end end end
[ "def", "with_output", "super", "do", "|", "out", "|", "out", ".", "puts", "header", "@queued_write", "=", "[", "]", "yield", "out", "@queued_write", ".", "sort", ".", "each", "do", "|", "line", "|", "out", ".", "puts", "(", "line", ")", "end", "end", "end" ]
prepend header and sort lines before closing output
[ "prepend", "header", "and", "sort", "lines", "before", "closing", "output" ]
7f31ab7d9009ea2c566e81901cd344b04e6356e1
https://github.com/tmm1/ripper-tags/blob/7f31ab7d9009ea2c566e81901cd344b04e6356e1/lib/ripper-tags/vim_formatter.rb#L21-L30
train
tmm1/ripper-tags
lib/ripper-tags/parser.rb
RipperTags.Parser.on_command_call
def on_command_call(*args) if args.last && :args == args.last[0] args_add = args.pop call = on_call(*args) on_method_add_arg(call, args_add) else super end end
ruby
def on_command_call(*args) if args.last && :args == args.last[0] args_add = args.pop call = on_call(*args) on_method_add_arg(call, args_add) else super end end
[ "def", "on_command_call", "(", "*", "args", ")", "if", "args", ".", "last", "&&", ":args", "==", "args", ".", "last", "[", "0", "]", "args_add", "=", "args", ".", "pop", "call", "=", "on_call", "(", "args", ")", "on_method_add_arg", "(", "call", ",", "args_add", ")", "else", "super", "end", "end" ]
handle `Class.new arg` call without parens
[ "handle", "Class", ".", "new", "arg", "call", "without", "parens" ]
7f31ab7d9009ea2c566e81901cd344b04e6356e1
https://github.com/tmm1/ripper-tags/blob/7f31ab7d9009ea2c566e81901cd344b04e6356e1/lib/ripper-tags/parser.rb#L245-L253
train
tmm1/ripper-tags
lib/ripper-tags/parser.rb
RipperTags.Visitor.on_assign
def on_assign(name, rhs, line, *junk) return unless name =~ /^[A-Z]/ && junk.empty? if rhs && :call == rhs[0] && rhs[1] && "#{rhs[1][0]}.#{rhs[2]}" =~ /^(Class|Module|Struct)\.new$/ kind = $1 == 'Module' ? :module : :class superclass = $1 == 'Class' ? rhs[3] : nil superclass.flatten! if superclass return on_module_or_class(kind, [name, line], superclass, rhs[4]) end namespace = @namespace if name.include?('::') parts = name.split('::') name = parts.pop namespace = namespace + parts end process(rhs) emit_tag :constant, line, :name => name, :full_name => (namespace + [name]).join('::'), :class => namespace.join('::') end
ruby
def on_assign(name, rhs, line, *junk) return unless name =~ /^[A-Z]/ && junk.empty? if rhs && :call == rhs[0] && rhs[1] && "#{rhs[1][0]}.#{rhs[2]}" =~ /^(Class|Module|Struct)\.new$/ kind = $1 == 'Module' ? :module : :class superclass = $1 == 'Class' ? rhs[3] : nil superclass.flatten! if superclass return on_module_or_class(kind, [name, line], superclass, rhs[4]) end namespace = @namespace if name.include?('::') parts = name.split('::') name = parts.pop namespace = namespace + parts end process(rhs) emit_tag :constant, line, :name => name, :full_name => (namespace + [name]).join('::'), :class => namespace.join('::') end
[ "def", "on_assign", "(", "name", ",", "rhs", ",", "line", ",", "*", "junk", ")", "return", "unless", "name", "=~", "/", "/", "&&", "junk", ".", "empty?", "if", "rhs", "&&", ":call", "==", "rhs", "[", "0", "]", "&&", "rhs", "[", "1", "]", "&&", "\"#{rhs[1][0]}.#{rhs[2]}\"", "=~", "/", "\\.", "/", "kind", "=", "$1", "==", "'Module'", "?", ":module", ":", ":class", "superclass", "=", "$1", "==", "'Class'", "?", "rhs", "[", "3", "]", ":", "nil", "superclass", ".", "flatten!", "if", "superclass", "return", "on_module_or_class", "(", "kind", ",", "[", "name", ",", "line", "]", ",", "superclass", ",", "rhs", "[", "4", "]", ")", "end", "namespace", "=", "@namespace", "if", "name", ".", "include?", "(", "'::'", ")", "parts", "=", "name", ".", "split", "(", "'::'", ")", "name", "=", "parts", ".", "pop", "namespace", "=", "namespace", "+", "parts", "end", "process", "(", "rhs", ")", "emit_tag", ":constant", ",", "line", ",", ":name", "=>", "name", ",", ":full_name", "=>", "(", "namespace", "+", "[", "name", "]", ")", ".", "join", "(", "'::'", ")", ",", ":class", "=>", "namespace", ".", "join", "(", "'::'", ")", "end" ]
Ripper trips up on keyword arguments in pre-2.1 Ruby and supplies extra arguments that we just ignore here
[ "Ripper", "trips", "up", "on", "keyword", "arguments", "in", "pre", "-", "2", ".", "1", "Ruby", "and", "supplies", "extra", "arguments", "that", "we", "just", "ignore", "here" ]
7f31ab7d9009ea2c566e81901cd344b04e6356e1
https://github.com/tmm1/ripper-tags/blob/7f31ab7d9009ea2c566e81901cd344b04e6356e1/lib/ripper-tags/parser.rb#L423-L446
train
prograils/lit
lib/lit/i18n_backend.rb
Lit.I18nBackend.store_translations
def store_translations(locale, data, options = {}) super ActiveRecord::Base.transaction do store_item(locale, data) end if store_items? && valid_locale?(locale) end
ruby
def store_translations(locale, data, options = {}) super ActiveRecord::Base.transaction do store_item(locale, data) end if store_items? && valid_locale?(locale) end
[ "def", "store_translations", "(", "locale", ",", "data", ",", "options", "=", "{", "}", ")", "super", "ActiveRecord", "::", "Base", ".", "transaction", "do", "store_item", "(", "locale", ",", "data", ")", "end", "if", "store_items?", "&&", "valid_locale?", "(", "locale", ")", "end" ]
Stores the given translations. @param [String] locale the locale (ie "en") to store translations for @param [Hash] data nested key-value pairs to be added as blurbs
[ "Stores", "the", "given", "translations", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/i18n_backend.rb#L48-L53
train
prograils/lit
lib/lit/cache.rb
Lit.Cache.fallback_localization
def fallback_localization(locale, key_without_locale) value = nil return nil unless fallbacks = ::Rails.application.config.i18n.fallbacks keys = fallbacks == true ? @locale_cache.keys : fallbacks keys.map(&:to_s).each do |lc| if lc != locale.locale && value.nil? nk = "#{lc}.#{key_without_locale}" v = localizations[nk] value = v if v.present? && value.nil? end end value end
ruby
def fallback_localization(locale, key_without_locale) value = nil return nil unless fallbacks = ::Rails.application.config.i18n.fallbacks keys = fallbacks == true ? @locale_cache.keys : fallbacks keys.map(&:to_s).each do |lc| if lc != locale.locale && value.nil? nk = "#{lc}.#{key_without_locale}" v = localizations[nk] value = v if v.present? && value.nil? end end value end
[ "def", "fallback_localization", "(", "locale", ",", "key_without_locale", ")", "value", "=", "nil", "return", "nil", "unless", "fallbacks", "=", "::", "Rails", ".", "application", ".", "config", ".", "i18n", ".", "fallbacks", "keys", "=", "fallbacks", "==", "true", "?", "@locale_cache", ".", "keys", ":", "fallbacks", "keys", ".", "map", "(", ":to_s", ")", ".", "each", "do", "|", "lc", "|", "if", "lc", "!=", "locale", ".", "locale", "&&", "value", ".", "nil?", "nk", "=", "\"#{lc}.#{key_without_locale}\"", "v", "=", "localizations", "[", "nk", "]", "value", "=", "v", "if", "v", ".", "present?", "&&", "value", ".", "nil?", "end", "end", "value", "end" ]
fallback to translation in different locale
[ "fallback", "to", "translation", "in", "different", "locale" ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cache.rb#L204-L216
train
prograils/lit
lib/lit/cache.rb
Lit.Cache.fallback_to_default
def fallback_to_default(localization_key, localization) localization_key.localizations.where.not(default_value: nil). \ where.not(id: localization.id).first&.default_value end
ruby
def fallback_to_default(localization_key, localization) localization_key.localizations.where.not(default_value: nil). \ where.not(id: localization.id).first&.default_value end
[ "def", "fallback_to_default", "(", "localization_key", ",", "localization", ")", "localization_key", ".", "localizations", ".", "where", ".", "not", "(", "default_value", ":", "nil", ")", ".", "where", ".", "not", "(", "id", ":", "localization", ".", "id", ")", ".", "first", "&.", "default_value", "end" ]
tries to get `default_value` from localization_key - checks other localizations
[ "tries", "to", "get", "default_value", "from", "localization_key", "-", "checks", "other", "localizations" ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cache.rb#L220-L223
train
prograils/lit
lib/lit/cloud_translation.rb
Lit.CloudTranslation.translate
def translate(text:, from: nil, to:, **opts) provider.translate(text: text, from: from, to: to, **opts) end
ruby
def translate(text:, from: nil, to:, **opts) provider.translate(text: text, from: from, to: to, **opts) end
[ "def", "translate", "(", "text", ":", ",", "from", ":", "nil", ",", "to", ":", ",", "**", "opts", ")", "provider", ".", "translate", "(", "text", ":", "text", ",", "from", ":", "from", ",", "to", ":", "to", ",", "**", "opts", ")", "end" ]
Uses the active translation provider to translate a text or array of texts. @param [String, Array] text The text (or array of texts) to translate @param [Symbol, String] from The language to translate from. If not given, auto-detection will be attempted. @param [Symbol, String] to The language to translate to. @param [Hash] opts Additional, provider-specific optional parameters.
[ "Uses", "the", "active", "translation", "provider", "to", "translate", "a", "text", "or", "array", "of", "texts", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cloud_translation.rb#L29-L31
train
prograils/lit
lib/lit/cloud_translation.rb
Lit.CloudTranslation.configure
def configure(&block) unless provider raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' \ '.provider = PROVIDER_KLASS` before calling #configure.' end provider.tap do |p| p.configure(&block) end end
ruby
def configure(&block) unless provider raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' \ '.provider = PROVIDER_KLASS` before calling #configure.' end provider.tap do |p| p.configure(&block) end end
[ "def", "configure", "(", "&", "block", ")", "unless", "provider", "raise", "'Translation provider not selected yet. Use `Lit::CloudTranslation'", "'.provider = PROVIDER_KLASS` before calling #configure.'", "end", "provider", ".", "tap", "do", "|", "p", "|", "p", ".", "configure", "(", "block", ")", "end", "end" ]
Optional if provider-speciffic environment variables are set correctly. Configures the cloud translation provider with specific settings, overriding those from environment if needed. @example Lit::CloudTranslation.configure do |config| # For Yandex, this overrides the YANDEX_TRANSLATE_API_KEY env config.api_key = 'my_awesome_api_key' end
[ "Optional", "if", "provider", "-", "speciffic", "environment", "variables", "are", "set", "correctly", ".", "Configures", "the", "cloud", "translation", "provider", "with", "specific", "settings", "overriding", "those", "from", "environment", "if", "needed", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cloud_translation.rb#L42-L50
train
prograils/lit
lib/lit/import.rb
Lit.Import.upsert
def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength I18n.with_locale(locale) do # when an array has to be inserted with a default value, it needs to # be done like: # I18n.t('foo', default: [['bar', 'baz']]) # because without the double array, array items are treated as fallback keys # - then, the last array element is the final fallback; so in this case we # don't specify fallback keys and only specify the final fallback, which # is the array val = value.is_a?(Array) ? [value] : value I18n.t(key, default: val) unless @raw # this indicates that this translation already exists existing_translation = Lit::Localization.joins(:locale, :localization_key) .find_by('localization_key = ? and locale = ?', key, locale) if existing_translation existing_translation.update(translated_value: value, is_changed: true) lkey = existing_translation.localization_key lkey.update(is_deleted: false) if lkey.is_deleted end end end end
ruby
def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength I18n.with_locale(locale) do # when an array has to be inserted with a default value, it needs to # be done like: # I18n.t('foo', default: [['bar', 'baz']]) # because without the double array, array items are treated as fallback keys # - then, the last array element is the final fallback; so in this case we # don't specify fallback keys and only specify the final fallback, which # is the array val = value.is_a?(Array) ? [value] : value I18n.t(key, default: val) unless @raw # this indicates that this translation already exists existing_translation = Lit::Localization.joins(:locale, :localization_key) .find_by('localization_key = ? and locale = ?', key, locale) if existing_translation existing_translation.update(translated_value: value, is_changed: true) lkey = existing_translation.localization_key lkey.update(is_deleted: false) if lkey.is_deleted end end end end
[ "def", "upsert", "(", "locale", ",", "key", ",", "value", ")", "# rubocop:disable Metrics/MethodLength", "I18n", ".", "with_locale", "(", "locale", ")", "do", "# when an array has to be inserted with a default value, it needs to", "# be done like:", "# I18n.t('foo', default: [['bar', 'baz']])", "# because without the double array, array items are treated as fallback keys", "# - then, the last array element is the final fallback; so in this case we", "# don't specify fallback keys and only specify the final fallback, which", "# is the array", "val", "=", "value", ".", "is_a?", "(", "Array", ")", "?", "[", "value", "]", ":", "value", "I18n", ".", "t", "(", "key", ",", "default", ":", "val", ")", "unless", "@raw", "# this indicates that this translation already exists", "existing_translation", "=", "Lit", "::", "Localization", ".", "joins", "(", ":locale", ",", ":localization_key", ")", ".", "find_by", "(", "'localization_key = ? and locale = ?'", ",", "key", ",", "locale", ")", "if", "existing_translation", "existing_translation", ".", "update", "(", "translated_value", ":", "value", ",", "is_changed", ":", "true", ")", "lkey", "=", "existing_translation", ".", "localization_key", "lkey", ".", "update", "(", "is_deleted", ":", "false", ")", "if", "lkey", ".", "is_deleted", "end", "end", "end", "end" ]
This is mean to insert a value for a key in a given locale using some kind of strategy which depends on the service's options. For instance, when @raw option is true (it's the default), if a key already exists, it overrides the default_value of the existing localization key; otherwise, with @raw set to false, it keeps the default as it is and, no matter if a translated value is there, translated_value is overridden with the imported one and is_changed is set to true.
[ "This", "is", "mean", "to", "insert", "a", "value", "for", "a", "key", "in", "a", "given", "locale", "using", "some", "kind", "of", "strategy", "which", "depends", "on", "the", "service", "s", "options", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/import.rb#L128-L152
train
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.transliterate!
def transliterate!(*kinds) kinds.compact! kinds = [:latin] if kinds.empty? kinds.each do |kind| transliterator = Transliterator.get(kind).instance @wrapped_string = transliterator.transliterate(@wrapped_string) end @wrapped_string end
ruby
def transliterate!(*kinds) kinds.compact! kinds = [:latin] if kinds.empty? kinds.each do |kind| transliterator = Transliterator.get(kind).instance @wrapped_string = transliterator.transliterate(@wrapped_string) end @wrapped_string end
[ "def", "transliterate!", "(", "*", "kinds", ")", "kinds", ".", "compact!", "kinds", "=", "[", ":latin", "]", "if", "kinds", ".", "empty?", "kinds", ".", "each", "do", "|", "kind", "|", "transliterator", "=", "Transliterator", ".", "get", "(", "kind", ")", ".", "instance", "@wrapped_string", "=", "transliterator", ".", "transliterate", "(", "@wrapped_string", ")", "end", "@wrapped_string", "end" ]
Approximate an ASCII string. This works only for Western strings using characters that are Roman-alphabet characters + diacritics. Non-letter characters are left unmodified. string = Identifier.new "Łódź string.transliterate # => "Lodz, Poland" string = Identifier.new "日本" string.transliterate # => "日本" You can pass any key(s) from +Characters.approximations+ as arguments. This allows for contextual approximations. Various languages are supported, you can see which ones by looking at the source of {Babosa::Transliterator::Base}. string = Identifier.new "Jürgen Müller" string.transliterate # => "Jurgen Muller" string.transliterate :german # => "Juergen Mueller" string = Identifier.new "¡Feliz año!" string.transliterate # => "¡Feliz ano!" string.transliterate :spanish # => "¡Feliz anio!" The approximations are an array, which you can modify if you choose: # Make Spanish use "nh" rather than "nn" Babosa::Transliterator::Spanish::APPROXIMATIONS["ñ"] = "nh" Notice that this method does not simply convert to ASCII; if you want to remove non-ASCII characters such as "¡" and "¿", use {#to_ascii!}: string.transliterate!(:spanish) # => "¡Feliz anio!" string.transliterate! # => "¡Feliz anio!" @param *args <Symbol> @return String
[ "Approximate", "an", "ASCII", "string", ".", "This", "works", "only", "for", "Western", "strings", "using", "characters", "that", "are", "Roman", "-", "alphabet", "characters", "+", "diacritics", ".", "Non", "-", "letter", "characters", "are", "left", "unmodified", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L118-L126
train
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.to_ruby_method!
def to_ruby_method!(allow_bangs = true) leader, trailer = @wrapped_string.strip.scan(/\A(.+)(.)\z/).flatten leader = leader.to_s trailer = trailer.to_s if allow_bangs trailer.downcase! trailer.gsub!(/[^a-z0-9!=\\?]/, '') else trailer.downcase! trailer.gsub!(/[^a-z0-9]/, '') end id = leader.to_identifier id.transliterate! id.to_ascii! id.clean! id.word_chars! id.clean! @wrapped_string = id.to_s + trailer if @wrapped_string == "" raise Error, "Input generates impossible Ruby method name" end with_separators!("_") end
ruby
def to_ruby_method!(allow_bangs = true) leader, trailer = @wrapped_string.strip.scan(/\A(.+)(.)\z/).flatten leader = leader.to_s trailer = trailer.to_s if allow_bangs trailer.downcase! trailer.gsub!(/[^a-z0-9!=\\?]/, '') else trailer.downcase! trailer.gsub!(/[^a-z0-9]/, '') end id = leader.to_identifier id.transliterate! id.to_ascii! id.clean! id.word_chars! id.clean! @wrapped_string = id.to_s + trailer if @wrapped_string == "" raise Error, "Input generates impossible Ruby method name" end with_separators!("_") end
[ "def", "to_ruby_method!", "(", "allow_bangs", "=", "true", ")", "leader", ",", "trailer", "=", "@wrapped_string", ".", "strip", ".", "scan", "(", "/", "\\A", "\\z", "/", ")", ".", "flatten", "leader", "=", "leader", ".", "to_s", "trailer", "=", "trailer", ".", "to_s", "if", "allow_bangs", "trailer", ".", "downcase!", "trailer", ".", "gsub!", "(", "/", "\\\\", "/", ",", "''", ")", "else", "trailer", ".", "downcase!", "trailer", ".", "gsub!", "(", "/", "/", ",", "''", ")", "end", "id", "=", "leader", ".", "to_identifier", "id", ".", "transliterate!", "id", ".", "to_ascii!", "id", ".", "clean!", "id", ".", "word_chars!", "id", ".", "clean!", "@wrapped_string", "=", "id", ".", "to_s", "+", "trailer", "if", "@wrapped_string", "==", "\"\"", "raise", "Error", ",", "\"Input generates impossible Ruby method name\"", "end", "with_separators!", "(", "\"_\"", ")", "end" ]
Normalize a string so that it can safely be used as a Ruby method name.
[ "Normalize", "a", "string", "so", "that", "it", "can", "safely", "be", "used", "as", "a", "Ruby", "method", "name", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L167-L189
train
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.truncate_bytes!
def truncate_bytes!(max) return @wrapped_string if @wrapped_string.bytesize <= max curr = 0 new = [] unpack("U*").each do |char| break if curr > max char = [char].pack("U") curr += char.bytesize if curr <= max new << char end end @wrapped_string = new.join end
ruby
def truncate_bytes!(max) return @wrapped_string if @wrapped_string.bytesize <= max curr = 0 new = [] unpack("U*").each do |char| break if curr > max char = [char].pack("U") curr += char.bytesize if curr <= max new << char end end @wrapped_string = new.join end
[ "def", "truncate_bytes!", "(", "max", ")", "return", "@wrapped_string", "if", "@wrapped_string", ".", "bytesize", "<=", "max", "curr", "=", "0", "new", "=", "[", "]", "unpack", "(", "\"U*\"", ")", ".", "each", "do", "|", "char", "|", "break", "if", "curr", ">", "max", "char", "=", "[", "char", "]", ".", "pack", "(", "\"U\"", ")", "curr", "+=", "char", ".", "bytesize", "if", "curr", "<=", "max", "new", "<<", "char", "end", "end", "@wrapped_string", "=", "new", ".", "join", "end" ]
Truncate the string to +max+ bytes. This can be useful for ensuring that a UTF-8 string will always fit into a database column with a certain max byte length. The resulting string may be less than +max+ if the string must be truncated at a multibyte character boundary. @example "üéøá".to_identifier.truncate_bytes(3) #=> "ü" @return String
[ "Truncate", "the", "string", "to", "+", "max", "+", "bytes", ".", "This", "can", "be", "useful", "for", "ensuring", "that", "a", "UTF", "-", "8", "string", "will", "always", "fit", "into", "a", "database", "column", "with", "a", "certain", "max", "byte", "length", ".", "The", "resulting", "string", "may", "be", "less", "than", "+", "max", "+", "if", "the", "string", "must", "be", "truncated", "at", "a", "multibyte", "character", "boundary", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L212-L225
train
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.send_to_new_instance
def send_to_new_instance(*args) id = Identifier.allocate id.instance_variable_set :@wrapped_string, to_s id.send(*args) id end
ruby
def send_to_new_instance(*args) id = Identifier.allocate id.instance_variable_set :@wrapped_string, to_s id.send(*args) id end
[ "def", "send_to_new_instance", "(", "*", "args", ")", "id", "=", "Identifier", ".", "allocate", "id", ".", "instance_variable_set", ":@wrapped_string", ",", "to_s", "id", ".", "send", "(", "args", ")", "id", "end" ]
Used as the basis of the bangless methods.
[ "Used", "as", "the", "basis", "of", "the", "bangless", "methods", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L286-L291
train
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.nyan_cat
def nyan_cat if self.failed_or_pending? && self.finished? ascii_cat('x')[@color_index%2].join("\n") #'~|_(x.x)' elsif self.failed_or_pending? ascii_cat('o')[@color_index%2].join("\n") #'~|_(o.o)' elsif self.finished? ascii_cat('-')[@color_index%2].join("\n") # '~|_(-.-)' else ascii_cat('^')[@color_index%2].join("\n") # '~|_(^.^)' end end
ruby
def nyan_cat if self.failed_or_pending? && self.finished? ascii_cat('x')[@color_index%2].join("\n") #'~|_(x.x)' elsif self.failed_or_pending? ascii_cat('o')[@color_index%2].join("\n") #'~|_(o.o)' elsif self.finished? ascii_cat('-')[@color_index%2].join("\n") # '~|_(-.-)' else ascii_cat('^')[@color_index%2].join("\n") # '~|_(^.^)' end end
[ "def", "nyan_cat", "if", "self", ".", "failed_or_pending?", "&&", "self", ".", "finished?", "ascii_cat", "(", "'x'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "#'~|_(x.x)'", "elsif", "self", ".", "failed_or_pending?", "ascii_cat", "(", "'o'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "#'~|_(o.o)'", "elsif", "self", ".", "finished?", "ascii_cat", "(", "'-'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "# '~|_(-.-)'", "else", "ascii_cat", "(", "'^'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "# '~|_(^.^)'", "end", "end" ]
Determine which Ascii Nyan Cat to display. If tests are complete, Nyan Cat goes to sleep. If there are failing or pending examples, Nyan Cat is concerned. @return [String] Nyan Cat
[ "Determine", "which", "Ascii", "Nyan", "Cat", "to", "display", ".", "If", "tests", "are", "complete", "Nyan", "Cat", "goes", "to", "sleep", ".", "If", "there", "are", "failing", "or", "pending", "examples", "Nyan", "Cat", "is", "concerned", "." ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L48-L58
train
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.terminal_width
def terminal_width if defined? JRUBY_VERSION default_width = 80 else default_width = `stty size`.split.map { |x| x.to_i }.reverse.first - 1 end @terminal_width ||= default_width end
ruby
def terminal_width if defined? JRUBY_VERSION default_width = 80 else default_width = `stty size`.split.map { |x| x.to_i }.reverse.first - 1 end @terminal_width ||= default_width end
[ "def", "terminal_width", "if", "defined?", "JRUBY_VERSION", "default_width", "=", "80", "else", "default_width", "=", "`", "`", ".", "split", ".", "map", "{", "|", "x", "|", "x", ".", "to_i", "}", ".", "reverse", ".", "first", "-", "1", "end", "@terminal_width", "||=", "default_width", "end" ]
A Unix trick using stty to get the console columns @return [Fixnum]
[ "A", "Unix", "trick", "using", "stty", "to", "get", "the", "console", "columns" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L103-L110
train
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.scoreboard
def scoreboard @pending_examples ||= [] @failed_examples ||= [] padding = @example_count.to_s.length [ @current.to_s.rjust(padding), success_color((@current - @pending_examples.size - @failed_examples.size).to_s.rjust(padding)), pending_color(@pending_examples.size.to_s.rjust(padding)), failure_color(@failed_examples.size.to_s.rjust(padding)) ] end
ruby
def scoreboard @pending_examples ||= [] @failed_examples ||= [] padding = @example_count.to_s.length [ @current.to_s.rjust(padding), success_color((@current - @pending_examples.size - @failed_examples.size).to_s.rjust(padding)), pending_color(@pending_examples.size.to_s.rjust(padding)), failure_color(@failed_examples.size.to_s.rjust(padding)) ] end
[ "def", "scoreboard", "@pending_examples", "||=", "[", "]", "@failed_examples", "||=", "[", "]", "padding", "=", "@example_count", ".", "to_s", ".", "length", "[", "@current", ".", "to_s", ".", "rjust", "(", "padding", ")", ",", "success_color", "(", "(", "@current", "-", "@pending_examples", ".", "size", "-", "@failed_examples", ".", "size", ")", ".", "to_s", ".", "rjust", "(", "padding", ")", ")", ",", "pending_color", "(", "@pending_examples", ".", "size", ".", "to_s", ".", "rjust", "(", "padding", ")", ")", ",", "failure_color", "(", "@failed_examples", ".", "size", ".", "to_s", ".", "rjust", "(", "padding", ")", ")", "]", "end" ]
Creates a data store of pass, failed, and pending example results We have to pad the results here because sprintf can't properly pad color @return [Array]
[ "Creates", "a", "data", "store", "of", "pass", "failed", "and", "pending", "example", "results", "We", "have", "to", "pad", "the", "results", "here", "because", "sprintf", "can", "t", "properly", "pad", "color" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L116-L124
train
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.nyan_trail
def nyan_trail marks = @example_results.each_with_index.map{ |mark, i| highlight(mark) * example_width(i) } marks.shift(current_width - terminal_width) if current_width >= terminal_width nyan_cat.split("\n").each_with_index.map do |line, index| format("%s#{line}", marks.join) end.join("\n") end
ruby
def nyan_trail marks = @example_results.each_with_index.map{ |mark, i| highlight(mark) * example_width(i) } marks.shift(current_width - terminal_width) if current_width >= terminal_width nyan_cat.split("\n").each_with_index.map do |line, index| format("%s#{line}", marks.join) end.join("\n") end
[ "def", "nyan_trail", "marks", "=", "@example_results", ".", "each_with_index", ".", "map", "{", "|", "mark", ",", "i", "|", "highlight", "(", "mark", ")", "*", "example_width", "(", "i", ")", "}", "marks", ".", "shift", "(", "current_width", "-", "terminal_width", ")", "if", "current_width", ">=", "terminal_width", "nyan_cat", ".", "split", "(", "\"\\n\"", ")", ".", "each_with_index", ".", "map", "do", "|", "line", ",", "index", "|", "format", "(", "\"%s#{line}\"", ",", "marks", ".", "join", ")", "end", ".", "join", "(", "\"\\n\"", ")", "end" ]
Creates a rainbow trail @return [String] the sprintf format of the Nyan cat
[ "Creates", "a", "rainbow", "trail" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L129-L135
train
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.colors
def colors @colors ||= (0...(6 * 7)).map do |n| pi_3 = Math::PI / 3 n *= 1.0 / 6 r = (3 * Math.sin(n ) + 3).to_i g = (3 * Math.sin(n + 2 * pi_3) + 3).to_i b = (3 * Math.sin(n + 4 * pi_3) + 3).to_i 36 * r + 6 * g + b + 16 end end
ruby
def colors @colors ||= (0...(6 * 7)).map do |n| pi_3 = Math::PI / 3 n *= 1.0 / 6 r = (3 * Math.sin(n ) + 3).to_i g = (3 * Math.sin(n + 2 * pi_3) + 3).to_i b = (3 * Math.sin(n + 4 * pi_3) + 3).to_i 36 * r + 6 * g + b + 16 end end
[ "def", "colors", "@colors", "||=", "(", "0", "...", "(", "6", "*", "7", ")", ")", ".", "map", "do", "|", "n", "|", "pi_3", "=", "Math", "::", "PI", "/", "3", "n", "*=", "1.0", "/", "6", "r", "=", "(", "3", "*", "Math", ".", "sin", "(", "n", ")", "+", "3", ")", ".", "to_i", "g", "=", "(", "3", "*", "Math", ".", "sin", "(", "n", "+", "2", "*", "pi_3", ")", "+", "3", ")", ".", "to_i", "b", "=", "(", "3", "*", "Math", ".", "sin", "(", "n", "+", "4", "*", "pi_3", ")", "+", "3", ")", ".", "to_i", "36", "*", "r", "+", "6", "*", "g", "+", "b", "+", "16", "end", "end" ]
Calculates the colors of the rainbow @return [Array]
[ "Calculates", "the", "colors", "of", "the", "rainbow" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L172-L181
train
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.highlight
def highlight(mark = PASS) case mark when PASS; rainbowify PASS_ARY[@color_index%2] when FAIL; "\e[31m#{mark}\e[0m" when ERROR; "\e[33m#{mark}\e[0m" when PENDING; "\e[33m#{mark}\e[0m" else mark end end
ruby
def highlight(mark = PASS) case mark when PASS; rainbowify PASS_ARY[@color_index%2] when FAIL; "\e[31m#{mark}\e[0m" when ERROR; "\e[33m#{mark}\e[0m" when PENDING; "\e[33m#{mark}\e[0m" else mark end end
[ "def", "highlight", "(", "mark", "=", "PASS", ")", "case", "mark", "when", "PASS", ";", "rainbowify", "PASS_ARY", "[", "@color_index", "%", "2", "]", "when", "FAIL", ";", "\"\\e[31m#{mark}\\e[0m\"", "when", "ERROR", ";", "\"\\e[33m#{mark}\\e[0m\"", "when", "PENDING", ";", "\"\\e[33m#{mark}\\e[0m\"", "else", "mark", "end", "end" ]
Determines how to color the example. If pass, it is rainbowified, otherwise we assign red if failed or yellow if an error occurred. @return [String]
[ "Determines", "how", "to", "color", "the", "example", ".", "If", "pass", "it", "is", "rainbowified", "otherwise", "we", "assign", "red", "if", "failed", "or", "yellow", "if", "an", "error", "occurred", "." ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L187-L195
train
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.set_fonts
def set_fonts(font) font_name = Pathname.new(font).basename @pdf.font_families.update( "#{font_name}" => { normal: font, italic: font, bold: font, bold_italic: font } ) @pdf.font(font_name) end
ruby
def set_fonts(font) font_name = Pathname.new(font).basename @pdf.font_families.update( "#{font_name}" => { normal: font, italic: font, bold: font, bold_italic: font } ) @pdf.font(font_name) end
[ "def", "set_fonts", "(", "font", ")", "font_name", "=", "Pathname", ".", "new", "(", "font", ")", ".", "basename", "@pdf", ".", "font_families", ".", "update", "(", "\"#{font_name}\"", "=>", "{", "normal", ":", "font", ",", "italic", ":", "font", ",", "bold", ":", "font", ",", "bold_italic", ":", "font", "}", ")", "@pdf", ".", "font", "(", "font_name", ")", "end" ]
Add font family in Prawn for a given +font+ file
[ "Add", "font", "family", "in", "Prawn", "for", "a", "given", "+", "font", "+", "file" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L120-L131
train
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.build_pdf
def build_pdf @push_down = 0 @push_items_table = 0 @pdf.fill_color '000000' build_header build_provider_box build_purchaser_box build_payment_method_box build_info_box build_items build_total build_stamp build_logo build_note build_footer end
ruby
def build_pdf @push_down = 0 @push_items_table = 0 @pdf.fill_color '000000' build_header build_provider_box build_purchaser_box build_payment_method_box build_info_box build_items build_total build_stamp build_logo build_note build_footer end
[ "def", "build_pdf", "@push_down", "=", "0", "@push_items_table", "=", "0", "@pdf", ".", "fill_color", "'000000'", "build_header", "build_provider_box", "build_purchaser_box", "build_payment_method_box", "build_info_box", "build_items", "build_total", "build_stamp", "build_logo", "build_note", "build_footer", "end" ]
Build the PDF version of the document (@pdf)
[ "Build", "the", "PDF", "version", "of", "the", "document", "(" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L134-L149
train
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.determine_items_structure
def determine_items_structure items_params = {} @document.items.each do |item| items_params[:names] = true unless item.name.empty? items_params[:variables] = true unless item.variable.empty? items_params[:quantities] = true unless item.quantity.empty? items_params[:units] = true unless item.unit.empty? items_params[:prices] = true unless item.price.empty? items_params[:taxes] = true unless item.tax.empty? items_params[:taxes2] = true unless item.tax2.empty? items_params[:taxes3] = true unless item.tax3.empty? items_params[:amounts] = true unless item.amount.empty? end items_params end
ruby
def determine_items_structure items_params = {} @document.items.each do |item| items_params[:names] = true unless item.name.empty? items_params[:variables] = true unless item.variable.empty? items_params[:quantities] = true unless item.quantity.empty? items_params[:units] = true unless item.unit.empty? items_params[:prices] = true unless item.price.empty? items_params[:taxes] = true unless item.tax.empty? items_params[:taxes2] = true unless item.tax2.empty? items_params[:taxes3] = true unless item.tax3.empty? items_params[:amounts] = true unless item.amount.empty? end items_params end
[ "def", "determine_items_structure", "items_params", "=", "{", "}", "@document", ".", "items", ".", "each", "do", "|", "item", "|", "items_params", "[", ":names", "]", "=", "true", "unless", "item", ".", "name", ".", "empty?", "items_params", "[", ":variables", "]", "=", "true", "unless", "item", ".", "variable", ".", "empty?", "items_params", "[", ":quantities", "]", "=", "true", "unless", "item", ".", "quantity", ".", "empty?", "items_params", "[", ":units", "]", "=", "true", "unless", "item", ".", "unit", ".", "empty?", "items_params", "[", ":prices", "]", "=", "true", "unless", "item", ".", "price", ".", "empty?", "items_params", "[", ":taxes", "]", "=", "true", "unless", "item", ".", "tax", ".", "empty?", "items_params", "[", ":taxes2", "]", "=", "true", "unless", "item", ".", "tax2", ".", "empty?", "items_params", "[", ":taxes3", "]", "=", "true", "unless", "item", ".", "tax3", ".", "empty?", "items_params", "[", ":amounts", "]", "=", "true", "unless", "item", ".", "amount", ".", "empty?", "end", "items_params", "end" ]
Determine sections of the items table to show based on provided data
[ "Determine", "sections", "of", "the", "items", "table", "to", "show", "based", "on", "provided", "data" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L647-L661
train
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.build_items_data
def build_items_data(items_params) @document.items.map do |item| line = [] line << item.name if items_params[:names] line << item.variable if items_params[:variables] line << item.quantity if items_params[:quantities] line << item.unit if items_params[:units] line << item.price if items_params[:prices] line << item.tax if items_params[:taxes] line << item.tax2 if items_params[:taxes2] line << item.tax3 if items_params[:taxes3] line << item.amount if items_params[:amounts] line end end
ruby
def build_items_data(items_params) @document.items.map do |item| line = [] line << item.name if items_params[:names] line << item.variable if items_params[:variables] line << item.quantity if items_params[:quantities] line << item.unit if items_params[:units] line << item.price if items_params[:prices] line << item.tax if items_params[:taxes] line << item.tax2 if items_params[:taxes2] line << item.tax3 if items_params[:taxes3] line << item.amount if items_params[:amounts] line end end
[ "def", "build_items_data", "(", "items_params", ")", "@document", ".", "items", ".", "map", "do", "|", "item", "|", "line", "=", "[", "]", "line", "<<", "item", ".", "name", "if", "items_params", "[", ":names", "]", "line", "<<", "item", ".", "variable", "if", "items_params", "[", ":variables", "]", "line", "<<", "item", ".", "quantity", "if", "items_params", "[", ":quantities", "]", "line", "<<", "item", ".", "unit", "if", "items_params", "[", ":units", "]", "line", "<<", "item", ".", "price", "if", "items_params", "[", ":prices", "]", "line", "<<", "item", ".", "tax", "if", "items_params", "[", ":taxes", "]", "line", "<<", "item", ".", "tax2", "if", "items_params", "[", ":taxes2", "]", "line", "<<", "item", ".", "tax3", "if", "items_params", "[", ":taxes3", "]", "line", "<<", "item", ".", "amount", "if", "items_params", "[", ":amounts", "]", "line", "end", "end" ]
Include only items params with provided data
[ "Include", "only", "items", "params", "with", "provided", "data" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L664-L678
train
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.build_items_header
def build_items_header(items_params) headers = [] headers << { text: label_with_sublabel(:item) } if items_params[:names] headers << { text: label_with_sublabel(:variable) } if items_params[:variables] headers << { text: label_with_sublabel(:quantity) } if items_params[:quantities] headers << { text: label_with_sublabel(:unit) } if items_params[:units] headers << { text: label_with_sublabel(:price_per_item) } if items_params[:prices] headers << { text: label_with_sublabel(:tax) } if items_params[:taxes] headers << { text: label_with_sublabel(:tax2) } if items_params[:taxes2] headers << { text: label_with_sublabel(:tax3) } if items_params[:taxes3] headers << { text: label_with_sublabel(:amount) } if items_params[:amounts] headers end
ruby
def build_items_header(items_params) headers = [] headers << { text: label_with_sublabel(:item) } if items_params[:names] headers << { text: label_with_sublabel(:variable) } if items_params[:variables] headers << { text: label_with_sublabel(:quantity) } if items_params[:quantities] headers << { text: label_with_sublabel(:unit) } if items_params[:units] headers << { text: label_with_sublabel(:price_per_item) } if items_params[:prices] headers << { text: label_with_sublabel(:tax) } if items_params[:taxes] headers << { text: label_with_sublabel(:tax2) } if items_params[:taxes2] headers << { text: label_with_sublabel(:tax3) } if items_params[:taxes3] headers << { text: label_with_sublabel(:amount) } if items_params[:amounts] headers end
[ "def", "build_items_header", "(", "items_params", ")", "headers", "=", "[", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":item", ")", "}", "if", "items_params", "[", ":names", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":variable", ")", "}", "if", "items_params", "[", ":variables", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":quantity", ")", "}", "if", "items_params", "[", ":quantities", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":unit", ")", "}", "if", "items_params", "[", ":units", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":price_per_item", ")", "}", "if", "items_params", "[", ":prices", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":tax", ")", "}", "if", "items_params", "[", ":taxes", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":tax2", ")", "}", "if", "items_params", "[", ":taxes2", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":tax3", ")", "}", "if", "items_params", "[", ":taxes3", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":amount", ")", "}", "if", "items_params", "[", ":amounts", "]", "headers", "end" ]
Include only relevant headers
[ "Include", "only", "relevant", "headers" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L681-L693
train
mdsol/mauth-client-ruby
lib/mauth/proxy.rb
MAuth.Proxy.call
def call(request_env) request = ::Rack::Request.new(request_env) request_method = request_env['REQUEST_METHOD'].downcase.to_sym request_env['rack.input'].rewind request_body = request_env['rack.input'].read request_env['rack.input'].rewind request_headers = {} request_env.each do |k, v| if k.start_with?('HTTP_') && k != 'HTTP_HOST' name = k.sub(/\AHTTP_/, '') request_headers[name] = v end end request_headers.merge!(@persistent_headers) if @browser_proxy target_uri = request_env["REQUEST_URI"] connection = @target_uris.any? { |u| target_uri.start_with? u } ? @signer_connection : @unsigned_connection response = connection.run_request(request_method, target_uri, request_body, request_headers) else response = @connection.run_request(request_method, request.fullpath, request_body, request_headers) end response_headers = response.headers.reject do |name, _value| %w(Content-Length Transfer-Encoding).map(&:downcase).include?(name.downcase) end [response.status, response_headers, [response.body || '']] end
ruby
def call(request_env) request = ::Rack::Request.new(request_env) request_method = request_env['REQUEST_METHOD'].downcase.to_sym request_env['rack.input'].rewind request_body = request_env['rack.input'].read request_env['rack.input'].rewind request_headers = {} request_env.each do |k, v| if k.start_with?('HTTP_') && k != 'HTTP_HOST' name = k.sub(/\AHTTP_/, '') request_headers[name] = v end end request_headers.merge!(@persistent_headers) if @browser_proxy target_uri = request_env["REQUEST_URI"] connection = @target_uris.any? { |u| target_uri.start_with? u } ? @signer_connection : @unsigned_connection response = connection.run_request(request_method, target_uri, request_body, request_headers) else response = @connection.run_request(request_method, request.fullpath, request_body, request_headers) end response_headers = response.headers.reject do |name, _value| %w(Content-Length Transfer-Encoding).map(&:downcase).include?(name.downcase) end [response.status, response_headers, [response.body || '']] end
[ "def", "call", "(", "request_env", ")", "request", "=", "::", "Rack", "::", "Request", ".", "new", "(", "request_env", ")", "request_method", "=", "request_env", "[", "'REQUEST_METHOD'", "]", ".", "downcase", ".", "to_sym", "request_env", "[", "'rack.input'", "]", ".", "rewind", "request_body", "=", "request_env", "[", "'rack.input'", "]", ".", "read", "request_env", "[", "'rack.input'", "]", ".", "rewind", "request_headers", "=", "{", "}", "request_env", ".", "each", "do", "|", "k", ",", "v", "|", "if", "k", ".", "start_with?", "(", "'HTTP_'", ")", "&&", "k", "!=", "'HTTP_HOST'", "name", "=", "k", ".", "sub", "(", "/", "\\A", "/", ",", "''", ")", "request_headers", "[", "name", "]", "=", "v", "end", "end", "request_headers", ".", "merge!", "(", "@persistent_headers", ")", "if", "@browser_proxy", "target_uri", "=", "request_env", "[", "\"REQUEST_URI\"", "]", "connection", "=", "@target_uris", ".", "any?", "{", "|", "u", "|", "target_uri", ".", "start_with?", "u", "}", "?", "@signer_connection", ":", "@unsigned_connection", "response", "=", "connection", ".", "run_request", "(", "request_method", ",", "target_uri", ",", "request_body", ",", "request_headers", ")", "else", "response", "=", "@connection", ".", "run_request", "(", "request_method", ",", "request", ".", "fullpath", ",", "request_body", ",", "request_headers", ")", "end", "response_headers", "=", "response", ".", "headers", ".", "reject", "do", "|", "name", ",", "_value", "|", "%w(", "Content-Length", "Transfer-Encoding", ")", ".", "map", "(", ":downcase", ")", ".", "include?", "(", "name", ".", "downcase", ")", "end", "[", "response", ".", "status", ",", "response_headers", ",", "[", "response", ".", "body", "||", "''", "]", "]", "end" ]
target_uri is the base relative to which requests are made. options: - :authenticate_responses - boolean, default true. whether responses will be authenticated. if this is true and an inauthentic response is encountered, then MAuth::InauthenticError will be raised. - :mauth_config - configuration passed to MAuth::Client.new (see its doc). default is MAuth::Client.default_config
[ "target_uri", "is", "the", "base", "relative", "to", "which", "requests", "are", "made", "." ]
cbe24f762d1c4469df01c56f80ce3b9022983b12
https://github.com/mdsol/mauth-client-ruby/blob/cbe24f762d1c4469df01c56f80ce3b9022983b12/lib/mauth/proxy.rb#L50-L75
train
mdsol/mauth-client-ruby
lib/mauth/client.rb
MAuth.Client.symbolize_keys
def symbolize_keys(hash) hash.keys.each do |key| hash[(key.to_sym rescue key) || key] = hash.delete(key) end hash end
ruby
def symbolize_keys(hash) hash.keys.each do |key| hash[(key.to_sym rescue key) || key] = hash.delete(key) end hash end
[ "def", "symbolize_keys", "(", "hash", ")", "hash", ".", "keys", ".", "each", "do", "|", "key", "|", "hash", "[", "(", "key", ".", "to_sym", "rescue", "key", ")", "||", "key", "]", "=", "hash", ".", "delete", "(", "key", ")", "end", "hash", "end" ]
Changes all keys in the top level of the hash to symbols. Does not affect nested hashes inside this one.
[ "Changes", "all", "keys", "in", "the", "top", "level", "of", "the", "hash", "to", "symbols", ".", "Does", "not", "affect", "nested", "hashes", "inside", "this", "one", "." ]
cbe24f762d1c4469df01c56f80ce3b9022983b12
https://github.com/mdsol/mauth-client-ruby/blob/cbe24f762d1c4469df01c56f80ce3b9022983b12/lib/mauth/client.rb#L247-L252
train
deliveroo/determinator
lib/determinator/control.rb
Determinator.Control.for_actor
def for_actor(id: nil, guid: nil, default_properties: {}) ActorControl.new(self, id: id, guid: guid, default_properties: default_properties) end
ruby
def for_actor(id: nil, guid: nil, default_properties: {}) ActorControl.new(self, id: id, guid: guid, default_properties: default_properties) end
[ "def", "for_actor", "(", "id", ":", "nil", ",", "guid", ":", "nil", ",", "default_properties", ":", "{", "}", ")", "ActorControl", ".", "new", "(", "self", ",", "id", ":", "id", ",", "guid", ":", "guid", ",", "default_properties", ":", "default_properties", ")", "end" ]
Creates a new determinator instance which assumes the actor id, guid and properties given are always specified. This is useful for within a before filter in a webserver, for example, so that the determinator instance made available has the logged-in user's credentials prefilled. @param :id [#to_s] The ID of the actor being specified @param :guid [#to_s] The Anonymous ID of the actor being specified @param :default_properties [Hash<Symbol,String>] The default properties for the determinator being created @return [ActorControl] A helper object removing the need to know id and guid everywhere
[ "Creates", "a", "new", "determinator", "instance", "which", "assumes", "the", "actor", "id", "guid", "and", "properties", "given", "are", "always", "specified", ".", "This", "is", "useful", "for", "within", "a", "before", "filter", "in", "a", "webserver", "for", "example", "so", "that", "the", "determinator", "instance", "made", "available", "has", "the", "logged", "-", "in", "user", "s", "credentials", "prefilled", "." ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/control.rb#L20-L22
train
deliveroo/determinator
lib/determinator/control.rb
Determinator.Control.feature_flag_on?
def feature_flag_on?(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.feature_flag? end end
ruby
def feature_flag_on?(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.feature_flag? end end
[ "def", "feature_flag_on?", "(", "name", ",", "id", ":", "nil", ",", "guid", ":", "nil", ",", "properties", ":", "{", "}", ")", "determinate_and_notice", "(", "name", ",", "id", ":", "id", ",", "guid", ":", "guid", ",", "properties", ":", "properties", ")", "do", "|", "feature", "|", "feature", ".", "feature_flag?", "end", "end" ]
Determines whether a specific feature is on or off for the given actor @param name [#to_s] The name of the feature flag being checked @param :id [#to_s] The id of the actor being determinated for @param :guid [#to_s] The Anonymous id of the actor being determinated for @param :properties [Hash<Symbol,String>] The properties of this actor which will be used for including this actor or not @raise [ArgumentError] When the arguments given to this method aren't ever going to produce a useful response @return [true,false] Whether the feature is on (true) or off (false) for this actor
[ "Determines", "whether", "a", "specific", "feature", "is", "on", "or", "off", "for", "the", "given", "actor" ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/control.rb#L32-L36
train
deliveroo/determinator
lib/determinator/control.rb
Determinator.Control.which_variant
def which_variant(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.experiment? end end
ruby
def which_variant(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.experiment? end end
[ "def", "which_variant", "(", "name", ",", "id", ":", "nil", ",", "guid", ":", "nil", ",", "properties", ":", "{", "}", ")", "determinate_and_notice", "(", "name", ",", "id", ":", "id", ",", "guid", ":", "guid", ",", "properties", ":", "properties", ")", "do", "|", "feature", "|", "feature", ".", "experiment?", "end", "end" ]
Determines what an actor should see for a specific experiment @param name [#to_s] The name of the experiment being checked @param :id [#to_s] The id of the actor being determinated for @param :guid [#to_s] The Anonymous id of the actor being determinated for @param :properties [Hash<Symbol,String>] The properties of this actor which will be used for including this actor or not @raise [ArgumentError] When the arguments given to this method aren't ever going to produce a useful response @return [false,String] Returns false, if the actor is not in this experiment, or otherwise the variant name.
[ "Determines", "what", "an", "actor", "should", "see", "for", "a", "specific", "experiment" ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/control.rb#L46-L50
train
deliveroo/determinator
lib/determinator/feature.rb
Determinator.Feature.parse_outcome
def parse_outcome(outcome, allow_exclusion:) valid_outcomes = experiment? ? variants.keys : [true] valid_outcomes << false if allow_exclusion valid_outcomes.include?(outcome) ? outcome : nil end
ruby
def parse_outcome(outcome, allow_exclusion:) valid_outcomes = experiment? ? variants.keys : [true] valid_outcomes << false if allow_exclusion valid_outcomes.include?(outcome) ? outcome : nil end
[ "def", "parse_outcome", "(", "outcome", ",", "allow_exclusion", ":", ")", "valid_outcomes", "=", "experiment?", "?", "variants", ".", "keys", ":", "[", "true", "]", "valid_outcomes", "<<", "false", "if", "allow_exclusion", "valid_outcomes", ".", "include?", "(", "outcome", ")", "?", "outcome", ":", "nil", "end" ]
Validates the given outcome for this feature.
[ "Validates", "the", "given", "outcome", "for", "this", "feature", "." ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/feature.rb#L50-L54
train
deliveroo/roo_on_rails
spec/support/sub_process.rb
ROR.SubProcess.stop
def stop return self if @pid.nil? _log "stopping (##{@pid})" Process.kill('INT', @pid) Timeout::timeout(10) do sleep(10e-3) until Process.wait(@pid, Process::WNOHANG) @status = $? end @pid = nil self end
ruby
def stop return self if @pid.nil? _log "stopping (##{@pid})" Process.kill('INT', @pid) Timeout::timeout(10) do sleep(10e-3) until Process.wait(@pid, Process::WNOHANG) @status = $? end @pid = nil self end
[ "def", "stop", "return", "self", "if", "@pid", ".", "nil?", "_log", "\"stopping (##{@pid})\"", "Process", ".", "kill", "(", "'INT'", ",", "@pid", ")", "Timeout", "::", "timeout", "(", "10", ")", "do", "sleep", "(", "10e-3", ")", "until", "Process", ".", "wait", "(", "@pid", ",", "Process", "::", "WNOHANG", ")", "@status", "=", "$?", "end", "@pid", "=", "nil", "self", "end" ]
politely ask the process to stop, and wait for it to exit
[ "politely", "ask", "the", "process", "to", "stop", "and", "wait", "for", "it", "to", "exit" ]
29d664e3718278068bae08f5da9e51c88152059c
https://github.com/deliveroo/roo_on_rails/blob/29d664e3718278068bae08f5da9e51c88152059c/spec/support/sub_process.rb#L56-L68
train
deliveroo/roo_on_rails
spec/support/sub_process.rb
ROR.SubProcess.wait_log
def wait_log(regexp) cursor = 0 Timeout::timeout(10) do loop do line = @loglines[cursor] sleep(10e-3) if line.nil? break if line && line =~ regexp cursor += 1 unless line.nil? end end self end
ruby
def wait_log(regexp) cursor = 0 Timeout::timeout(10) do loop do line = @loglines[cursor] sleep(10e-3) if line.nil? break if line && line =~ regexp cursor += 1 unless line.nil? end end self end
[ "def", "wait_log", "(", "regexp", ")", "cursor", "=", "0", "Timeout", "::", "timeout", "(", "10", ")", "do", "loop", "do", "line", "=", "@loglines", "[", "cursor", "]", "sleep", "(", "10e-3", ")", "if", "line", ".", "nil?", "break", "if", "line", "&&", "line", "=~", "regexp", "cursor", "+=", "1", "unless", "line", ".", "nil?", "end", "end", "self", "end" ]
wait until a log line is seen that matches `regexp`, up to a timeout
[ "wait", "until", "a", "log", "line", "is", "seen", "that", "matches", "regexp", "up", "to", "a", "timeout" ]
29d664e3718278068bae08f5da9e51c88152059c
https://github.com/deliveroo/roo_on_rails/blob/29d664e3718278068bae08f5da9e51c88152059c/spec/support/sub_process.rb#L103-L114
train
ledermann/unread
lib/unread/garbage_collector.rb
Unread.GarbageCollector.readers_to_cleanup
def readers_to_cleanup(reader_class) reader_class. reader_scope. joins(:read_marks). where(ReadMark.table_name => { readable_type: readable_class.name }). group("#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}"). having("COUNT(#{ReadMark.quoted_table_name}.id) > 1"). select("#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}") end
ruby
def readers_to_cleanup(reader_class) reader_class. reader_scope. joins(:read_marks). where(ReadMark.table_name => { readable_type: readable_class.name }). group("#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}"). having("COUNT(#{ReadMark.quoted_table_name}.id) > 1"). select("#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}") end
[ "def", "readers_to_cleanup", "(", "reader_class", ")", "reader_class", ".", "reader_scope", ".", "joins", "(", ":read_marks", ")", ".", "where", "(", "ReadMark", ".", "table_name", "=>", "{", "readable_type", ":", "readable_class", ".", "name", "}", ")", ".", "group", "(", "\"#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}\"", ")", ".", "having", "(", "\"COUNT(#{ReadMark.quoted_table_name}.id) > 1\"", ")", ".", "select", "(", "\"#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}\"", ")", "end" ]
Not for every reader a cleanup is needed. Look for those readers with at least one single read mark
[ "Not", "for", "every", "reader", "a", "cleanup", "is", "needed", ".", "Look", "for", "those", "readers", "with", "at", "least", "one", "single", "read", "mark" ]
e765c8878f6c780dc1189ec11070b308428a78d9
https://github.com/ledermann/unread/blob/e765c8878f6c780dc1189ec11070b308428a78d9/lib/unread/garbage_collector.rb#L28-L36
train
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.truncate
def truncate(string, options = {}) length = options[:length] || 30 if string.length > length string[0..length - 3] + "..." else string end end
ruby
def truncate(string, options = {}) length = options[:length] || 30 if string.length > length string[0..length - 3] + "..." else string end end
[ "def", "truncate", "(", "string", ",", "options", "=", "{", "}", ")", "length", "=", "options", "[", ":length", "]", "||", "30", "if", "string", ".", "length", ">", "length", "string", "[", "0", "..", "length", "-", "3", "]", "+", "\"...\"", "else", "string", "end", "end" ]
Truncate the given string to a certain number of characters. @param [String] string the string to truncate @param [Hash] options the list of options (such as +length+)
[ "Truncate", "the", "given", "string", "to", "a", "certain", "number", "of", "characters", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L70-L78
train
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.rename_keys
def rename_keys(options, map = {}) Hash[options.map { |k, v| [map[k] || k, v] }] end
ruby
def rename_keys(options, map = {}) Hash[options.map { |k, v| [map[k] || k, v] }] end
[ "def", "rename_keys", "(", "options", ",", "map", "=", "{", "}", ")", "Hash", "[", "options", ".", "map", "{", "|", "k", ",", "v", "|", "[", "map", "[", "k", "]", "||", "k", ",", "v", "]", "}", "]", "end" ]
Rename a list of keys to the given map. @example Rename the given keys rename_keys(hash, foo: :bar, zip: :zap) @param [Hash] options the options to map @param [Hash] map the map of keys to map @return [Hash]
[ "Rename", "a", "list", "of", "keys", "to", "the", "given", "map", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L93-L95
train
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.slice
def slice(options, *keys) keys.inject({}) do |hash, key| hash[key] = options[key] if options[key] hash end end
ruby
def slice(options, *keys) keys.inject({}) do |hash, key| hash[key] = options[key] if options[key] hash end end
[ "def", "slice", "(", "options", ",", "*", "keys", ")", "keys", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "options", "[", "key", "]", "if", "options", "[", "key", "]", "hash", "end", "end" ]
Slice the given list of options with the given keys. @param [Hash] options the list of options to slice @param [Array<Object>] keys the keys to slice @return [Hash] the sliced hash
[ "Slice", "the", "given", "list", "of", "options", "with", "the", "given", "keys", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L108-L113
train
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.xml_to_hash
def xml_to_hash(element, child_with_children = "", unique_children = true) properties = {} element.each_element_with_text do |e| if e.name.eql?(child_with_children) if unique_children e.each_element_with_text do |t| properties[t.name] = to_type(t.text) end else children = [] e.each_element_with_text do |t| properties[t.name] = children.push(to_type(t.text)) end end else properties[e.name] = to_type(e.text) end end properties end
ruby
def xml_to_hash(element, child_with_children = "", unique_children = true) properties = {} element.each_element_with_text do |e| if e.name.eql?(child_with_children) if unique_children e.each_element_with_text do |t| properties[t.name] = to_type(t.text) end else children = [] e.each_element_with_text do |t| properties[t.name] = children.push(to_type(t.text)) end end else properties[e.name] = to_type(e.text) end end properties end
[ "def", "xml_to_hash", "(", "element", ",", "child_with_children", "=", "\"\"", ",", "unique_children", "=", "true", ")", "properties", "=", "{", "}", "element", ".", "each_element_with_text", "do", "|", "e", "|", "if", "e", ".", "name", ".", "eql?", "(", "child_with_children", ")", "if", "unique_children", "e", ".", "each_element_with_text", "do", "|", "t", "|", "properties", "[", "t", ".", "name", "]", "=", "to_type", "(", "t", ".", "text", ")", "end", "else", "children", "=", "[", "]", "e", ".", "each_element_with_text", "do", "|", "t", "|", "properties", "[", "t", ".", "name", "]", "=", "children", ".", "push", "(", "to_type", "(", "t", ".", "text", ")", ")", "end", "end", "else", "properties", "[", "e", ".", "name", "]", "=", "to_type", "(", "e", ".", "text", ")", "end", "end", "properties", "end" ]
Flatten an xml element with at most one child node with children into a hash. @param [REXML] element xml element
[ "Flatten", "an", "xml", "element", "with", "at", "most", "one", "child", "node", "with", "children", "into", "a", "hash", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L122-L141
train
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.properties
def properties(props = nil) if props.nil? || props.empty? get_properties else set_properties(props) get_properties(true) end end
ruby
def properties(props = nil) if props.nil? || props.empty? get_properties else set_properties(props) get_properties(true) end end
[ "def", "properties", "(", "props", "=", "nil", ")", "if", "props", ".", "nil?", "||", "props", ".", "empty?", "get_properties", "else", "set_properties", "(", "props", ")", "get_properties", "(", "true", ")", "end", "end" ]
Set properties for this object. If no properties are given it lists the properties for this object. @example List all properties for an artifact artifact.properties #=> { 'licenses'=>['Apache-2.0'] } @example Set new properties for an artifact artifact.properties(maintainer: 'SuperStartup01') #=> { 'licenses'=>['Apache-2.0'], 'maintainer'=>'SuperStartup01' } @param [Hash<String, Object>] props (default: +nil+) A hash of properties and corresponding values to set for the artifact @return [Hash<String, Object>] the list of properties
[ "Set", "properties", "for", "this", "object", ".", "If", "no", "properties", "are", "given", "it", "lists", "the", "properties", "for", "this", "object", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L447-L454
train
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.download
def download(target = Dir.mktmpdir, options = {}) target = File.expand_path(target) # Make the directory if it doesn't yet exist FileUtils.mkdir_p(target) unless File.exist?(target) # Use the server artifact's filename if one wasn't given filename = options[:filename] || File.basename(download_uri) # Construct the full path for the file destination = File.join(target, filename) File.open(destination, "wb") do |file| client.get(download_uri) do |chunk| file.write chunk end end destination end
ruby
def download(target = Dir.mktmpdir, options = {}) target = File.expand_path(target) # Make the directory if it doesn't yet exist FileUtils.mkdir_p(target) unless File.exist?(target) # Use the server artifact's filename if one wasn't given filename = options[:filename] || File.basename(download_uri) # Construct the full path for the file destination = File.join(target, filename) File.open(destination, "wb") do |file| client.get(download_uri) do |chunk| file.write chunk end end destination end
[ "def", "download", "(", "target", "=", "Dir", ".", "mktmpdir", ",", "options", "=", "{", "}", ")", "target", "=", "File", ".", "expand_path", "(", "target", ")", "# Make the directory if it doesn't yet exist", "FileUtils", ".", "mkdir_p", "(", "target", ")", "unless", "File", ".", "exist?", "(", "target", ")", "# Use the server artifact's filename if one wasn't given", "filename", "=", "options", "[", ":filename", "]", "||", "File", ".", "basename", "(", "download_uri", ")", "# Construct the full path for the file", "destination", "=", "File", ".", "join", "(", "target", ",", "filename", ")", "File", ".", "open", "(", "destination", ",", "\"wb\"", ")", "do", "|", "file", "|", "client", ".", "get", "(", "download_uri", ")", "do", "|", "chunk", "|", "file", ".", "write", "chunk", "end", "end", "destination", "end" ]
Download the artifact onto the local disk. @example Download an artifact artifact.download #=> /tmp/cache/000adad0-bac/artifact.deb @example Download a remote artifact into a specific target artifact.download('~/Desktop') #=> ~/Desktop/artifact.deb @param [String] target the target directory where the artifact should be downloaded to (defaults to a temporary directory). **It is the user's responsibility to cleanup the temporary directory when finished!** @param [Hash] options @option options [String] filename the name of the file when downloaded to disk (defaults to the basename of the file on the server) @return [String] the path where the file was downloaded on disk
[ "Download", "the", "artifact", "onto", "the", "local", "disk", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L492-L511
train
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.upload
def upload(repo, remote_path, properties = {}, headers = {}) file = File.new(File.expand_path(local_path)) matrix = to_matrix_properties(properties) endpoint = File.join("#{url_safe(repo)}#{matrix}", remote_path) # Include checksums in headers if given. headers["X-Checksum-Md5"] = md5 if md5 headers["X-Checksum-Sha1"] = sha1 if sha1 response = client.put(endpoint, file, headers) return unless response.is_a?(Hash) self.class.from_hash(response) end
ruby
def upload(repo, remote_path, properties = {}, headers = {}) file = File.new(File.expand_path(local_path)) matrix = to_matrix_properties(properties) endpoint = File.join("#{url_safe(repo)}#{matrix}", remote_path) # Include checksums in headers if given. headers["X-Checksum-Md5"] = md5 if md5 headers["X-Checksum-Sha1"] = sha1 if sha1 response = client.put(endpoint, file, headers) return unless response.is_a?(Hash) self.class.from_hash(response) end
[ "def", "upload", "(", "repo", ",", "remote_path", ",", "properties", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "file", "=", "File", ".", "new", "(", "File", ".", "expand_path", "(", "local_path", ")", ")", "matrix", "=", "to_matrix_properties", "(", "properties", ")", "endpoint", "=", "File", ".", "join", "(", "\"#{url_safe(repo)}#{matrix}\"", ",", "remote_path", ")", "# Include checksums in headers if given.", "headers", "[", "\"X-Checksum-Md5\"", "]", "=", "md5", "if", "md5", "headers", "[", "\"X-Checksum-Sha1\"", "]", "=", "sha1", "if", "sha1", "response", "=", "client", ".", "put", "(", "endpoint", ",", "file", ",", "headers", ")", "return", "unless", "response", ".", "is_a?", "(", "Hash", ")", "self", ".", "class", ".", "from_hash", "(", "response", ")", "end" ]
Upload an artifact into the repository. If the first parameter is a File object, that file descriptor is passed to the uploader. If the first parameter is a string, it is assumed to be the path to a local file on disk. This method will automatically construct the File object from the given path. @see bit.ly/1dhJRMO Artifactory Matrix Properties @example Upload an artifact from a File instance artifact = Artifact.new(local_path: '/local/path/to/file.deb') artifact.upload('libs-release-local', '/remote/path') @example Upload an artifact with matrix properties artifact = Artifact.new(local_path: '/local/path/to/file.deb') artifact.upload('libs-release-local', '/remote/path', { status: 'DEV', rating: 5, branch: 'master' }) @param [String] repo the key of the repository to which to upload the file @param [String] remote_path the path where this resource will live in the remote artifactory repository, relative to the repository key @param [Hash] headers the list of headers to send with the request @param [Hash] properties a list of matrix properties @return [Resource::Artifact]
[ "Upload", "an", "artifact", "into", "the", "repository", ".", "If", "the", "first", "parameter", "is", "a", "File", "object", "that", "file", "descriptor", "is", "passed", "to", "the", "uploader", ".", "If", "the", "first", "parameter", "is", "a", "string", "it", "is", "assumed", "to", "be", "the", "path", "to", "a", "local", "file", "on", "disk", ".", "This", "method", "will", "automatically", "construct", "the", "File", "object", "from", "the", "given", "path", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L546-L559
train
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.get_properties
def get_properties(refresh_cache = false) if refresh_cache || @properties.nil? @properties = client.get(File.join("/api/storage", relative_path), properties: nil)["properties"] end @properties end
ruby
def get_properties(refresh_cache = false) if refresh_cache || @properties.nil? @properties = client.get(File.join("/api/storage", relative_path), properties: nil)["properties"] end @properties end
[ "def", "get_properties", "(", "refresh_cache", "=", "false", ")", "if", "refresh_cache", "||", "@properties", ".", "nil?", "@properties", "=", "client", ".", "get", "(", "File", ".", "join", "(", "\"/api/storage\"", ",", "relative_path", ")", ",", "properties", ":", "nil", ")", "[", "\"properties\"", "]", "end", "@properties", "end" ]
Helper method for reading artifact properties @example List all properties for an artifact artifact.get_properties #=> { 'artifactory.licenses'=>['Apache-2.0'] } @param [TrueClass, FalseClass] refresh_cache (default: +false+) wether or not to use the locally cached value if it exists and is not nil @return [Hash<String, Object>] the list of properties
[ "Helper", "method", "for", "reading", "artifact", "properties" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L647-L653
train
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.set_properties
def set_properties(properties) matrix = to_matrix_properties(properties) endpoint = File.join("/api/storage", relative_path) + "?properties=#{matrix}" client.put(endpoint, nil) end
ruby
def set_properties(properties) matrix = to_matrix_properties(properties) endpoint = File.join("/api/storage", relative_path) + "?properties=#{matrix}" client.put(endpoint, nil) end
[ "def", "set_properties", "(", "properties", ")", "matrix", "=", "to_matrix_properties", "(", "properties", ")", "endpoint", "=", "File", ".", "join", "(", "\"/api/storage\"", ",", "relative_path", ")", "+", "\"?properties=#{matrix}\"", "client", ".", "put", "(", "endpoint", ",", "nil", ")", "end" ]
Helper method for setting artifact properties @example Set properties for an artifact artifact.set_properties({ prop1: 'value1', 'prop2' => 'value2' }) @param [Hash<String, Object>] properties A hash of properties and corresponding values to set for the artifact @return [Hash] the parsed JSON response from the server
[ "Helper", "method", "for", "setting", "artifact", "properties" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L667-L672
train
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.copy_or_move
def copy_or_move(action, destination, options = {}) params = {}.tap do |param| param[:to] = destination param[:failFast] = 1 if options[:fail_fast] param[:suppressLayouts] = 1 if options[:suppress_layouts] param[:dry] = 1 if options[:dry_run] end endpoint = File.join("/api", action.to_s, relative_path) + "?#{to_query_string_parameters(params)}" client.post(endpoint, {}) end
ruby
def copy_or_move(action, destination, options = {}) params = {}.tap do |param| param[:to] = destination param[:failFast] = 1 if options[:fail_fast] param[:suppressLayouts] = 1 if options[:suppress_layouts] param[:dry] = 1 if options[:dry_run] end endpoint = File.join("/api", action.to_s, relative_path) + "?#{to_query_string_parameters(params)}" client.post(endpoint, {}) end
[ "def", "copy_or_move", "(", "action", ",", "destination", ",", "options", "=", "{", "}", ")", "params", "=", "{", "}", ".", "tap", "do", "|", "param", "|", "param", "[", ":to", "]", "=", "destination", "param", "[", ":failFast", "]", "=", "1", "if", "options", "[", ":fail_fast", "]", "param", "[", ":suppressLayouts", "]", "=", "1", "if", "options", "[", ":suppress_layouts", "]", "param", "[", ":dry", "]", "=", "1", "if", "options", "[", ":dry_run", "]", "end", "endpoint", "=", "File", ".", "join", "(", "\"/api\"", ",", "action", ".", "to_s", ",", "relative_path", ")", "+", "\"?#{to_query_string_parameters(params)}\"", "client", ".", "post", "(", "endpoint", ",", "{", "}", ")", "end" ]
Copy or move current artifact to a new destination. @example Move the current artifact to +ext-releases-local+ artifact.move(to: '/ext-releaes-local/org/acme') @example Copy the current artifact to +ext-releases-local+ artifact.move(to: '/ext-releaes-local/org/acme') @param [Symbol] action the action (+:move+ or +:copy+) @param [String] destination the server-side destination to move or copy the artifact @param [Hash] options the list of options to pass @option options [Boolean] :fail_fast (default: +false+) fail on the first failure @option options [Boolean] :suppress_layouts (default: +false+) suppress cross-layout module path translation during copying or moving @option options [Boolean] :dry_run (default: +false+) pretend to do the copy or move @return [Hash] the parsed JSON response from the server
[ "Copy", "or", "move", "current", "artifact", "to", "a", "new", "destination", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L712-L723
train
chef/artifactory-client
lib/artifactory/resources/base.rb
Artifactory.Resource::Base.to_hash
def to_hash attributes.inject({}) do |hash, (key, value)| unless Resource::Base.has_attribute?(key) hash[Util.camelize(key, true)] = send(key.to_sym) end hash end end
ruby
def to_hash attributes.inject({}) do |hash, (key, value)| unless Resource::Base.has_attribute?(key) hash[Util.camelize(key, true)] = send(key.to_sym) end hash end end
[ "def", "to_hash", "attributes", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "(", "key", ",", "value", ")", "|", "unless", "Resource", "::", "Base", ".", "has_attribute?", "(", "key", ")", "hash", "[", "Util", ".", "camelize", "(", "key", ",", "true", ")", "]", "=", "send", "(", "key", ".", "to_sym", ")", "end", "hash", "end", "end" ]
The hash representation @example An example hash response { 'key' => 'local-repo1', 'includesPattern' => '**/*' } @return [Hash]
[ "The", "hash", "representation" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/base.rb#L306-L314
train
chef/artifactory-client
lib/artifactory/resources/base.rb
Artifactory.Resource::Base.to_matrix_properties
def to_matrix_properties(hash = {}) properties = hash.map do |k, v| key = CGI.escape(k.to_s) value = CGI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else ";#{properties.join(';')}" end end
ruby
def to_matrix_properties(hash = {}) properties = hash.map do |k, v| key = CGI.escape(k.to_s) value = CGI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else ";#{properties.join(';')}" end end
[ "def", "to_matrix_properties", "(", "hash", "=", "{", "}", ")", "properties", "=", "hash", ".", "map", "do", "|", "k", ",", "v", "|", "key", "=", "CGI", ".", "escape", "(", "k", ".", "to_s", ")", "value", "=", "CGI", ".", "escape", "(", "v", ".", "to_s", ")", "\"#{key}=#{value}\"", "end", "if", "properties", ".", "empty?", "nil", "else", "\";#{properties.join(';')}\"", "end", "end" ]
Create CGI-escaped string from matrix properties @see http://bit.ly/1qeVYQl
[ "Create", "CGI", "-", "escaped", "string", "from", "matrix", "properties" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/base.rb#L332-L345
train
chef/artifactory-client
lib/artifactory/resources/base.rb
Artifactory.Resource::Base.to_query_string_parameters
def to_query_string_parameters(hash = {}) properties = hash.map do |k, v| key = URI.escape(k.to_s) value = URI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else properties.join("&") end end
ruby
def to_query_string_parameters(hash = {}) properties = hash.map do |k, v| key = URI.escape(k.to_s) value = URI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else properties.join("&") end end
[ "def", "to_query_string_parameters", "(", "hash", "=", "{", "}", ")", "properties", "=", "hash", ".", "map", "do", "|", "k", ",", "v", "|", "key", "=", "URI", ".", "escape", "(", "k", ".", "to_s", ")", "value", "=", "URI", ".", "escape", "(", "v", ".", "to_s", ")", "\"#{key}=#{value}\"", "end", "if", "properties", ".", "empty?", "nil", "else", "properties", ".", "join", "(", "\"&\"", ")", "end", "end" ]
Create URI-escaped querystring parameters @see http://bit.ly/1qeVYQl
[ "Create", "URI", "-", "escaped", "querystring", "parameters" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/base.rb#L352-L365
train
chef/artifactory-client
lib/artifactory/resources/build.rb
Artifactory.Resource::Build.promote
def promote(target_repo, options = {}) request_body = {}.tap do |body| body[:status] = options[:status] || "promoted" body[:comment] = options[:comment] || "" body[:ciUser] = options[:user] || Artifactory.username body[:dryRun] = options[:dry_run] || false body[:targetRepo] = target_repo body[:copy] = options[:copy] || false body[:artifacts] = true # always move/copy the build's artifacts body[:dependencies] = options[:dependencies] || false body[:scopes] = options[:scopes] || [] body[:properties] = options[:properties] || {} body[:failFast] = options[:fail_fast] || true end endpoint = "/api/build/promote/#{url_safe(name)}/#{url_safe(number)}" client.post(endpoint, JSON.fast_generate(request_body), "Content-Type" => "application/json" ) end
ruby
def promote(target_repo, options = {}) request_body = {}.tap do |body| body[:status] = options[:status] || "promoted" body[:comment] = options[:comment] || "" body[:ciUser] = options[:user] || Artifactory.username body[:dryRun] = options[:dry_run] || false body[:targetRepo] = target_repo body[:copy] = options[:copy] || false body[:artifacts] = true # always move/copy the build's artifacts body[:dependencies] = options[:dependencies] || false body[:scopes] = options[:scopes] || [] body[:properties] = options[:properties] || {} body[:failFast] = options[:fail_fast] || true end endpoint = "/api/build/promote/#{url_safe(name)}/#{url_safe(number)}" client.post(endpoint, JSON.fast_generate(request_body), "Content-Type" => "application/json" ) end
[ "def", "promote", "(", "target_repo", ",", "options", "=", "{", "}", ")", "request_body", "=", "{", "}", ".", "tap", "do", "|", "body", "|", "body", "[", ":status", "]", "=", "options", "[", ":status", "]", "||", "\"promoted\"", "body", "[", ":comment", "]", "=", "options", "[", ":comment", "]", "||", "\"\"", "body", "[", ":ciUser", "]", "=", "options", "[", ":user", "]", "||", "Artifactory", ".", "username", "body", "[", ":dryRun", "]", "=", "options", "[", ":dry_run", "]", "||", "false", "body", "[", ":targetRepo", "]", "=", "target_repo", "body", "[", ":copy", "]", "=", "options", "[", ":copy", "]", "||", "false", "body", "[", ":artifacts", "]", "=", "true", "# always move/copy the build's artifacts", "body", "[", ":dependencies", "]", "=", "options", "[", ":dependencies", "]", "||", "false", "body", "[", ":scopes", "]", "=", "options", "[", ":scopes", "]", "||", "[", "]", "body", "[", ":properties", "]", "=", "options", "[", ":properties", "]", "||", "{", "}", "body", "[", ":failFast", "]", "=", "options", "[", ":fail_fast", "]", "||", "true", "end", "endpoint", "=", "\"/api/build/promote/#{url_safe(name)}/#{url_safe(number)}\"", "client", ".", "post", "(", "endpoint", ",", "JSON", ".", "fast_generate", "(", "request_body", ")", ",", "\"Content-Type\"", "=>", "\"application/json\"", ")", "end" ]
Move a build's artifacts to a new repository optionally moving or copying the build's dependencies to the target repository and setting properties on promoted artifacts. @example promote the build to 'omnibus-stable-local' build.promote('omnibus-stable-local') @example promote a build attaching some new properites build.promote('omnibus-stable-local' properties: { 'promoted_by' => 'hipchat:[email protected]' } ) @param [String] target_repo repository to move or copy the build's artifacts and/or dependencies @param [Hash] options the list of options to pass @option options [String] :status (default: 'promoted') new build status (any string) @option options [String] :comment (default: '') an optional comment describing the reason for promotion @option options [String] :user (default: +Artifactory.username+) the user that invoked promotion @option options [Boolean] :dry_run (default: +false+) pretend to do the promotion @option options [Boolean] :copy (default: +false+) whether to copy instead of move @option options [Boolean] :dependencies (default: +false+) whether to move/copy the build's dependencies @option options [Array] :scopes (default: []) an array of dependency scopes to include when "dependencies" is true @option options [Hash<String, Array<String>>] :properties (default: []) a list of properties to attach to the build's artifacts @option options [Boolean] :fail_fast (default: +true+) fail and abort the operation upon receiving an error @return [Hash] the parsed JSON response from the server
[ "Move", "a", "build", "s", "artifacts", "to", "a", "new", "repository", "optionally", "moving", "or", "copying", "the", "build", "s", "dependencies", "to", "the", "target", "repository", "and", "setting", "properties", "on", "promoted", "artifacts", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build.rb#L175-L194
train
chef/artifactory-client
lib/artifactory/resources/build.rb
Artifactory.Resource::Build.save
def save raise Error::InvalidBuildType.new(type) unless BUILD_TYPES.include?(type) file = Tempfile.new("build.json") file.write(to_json) file.rewind client.put("/api/build", file, "Content-Type" => "application/json" ) true ensure if file file.close file.unlink end end
ruby
def save raise Error::InvalidBuildType.new(type) unless BUILD_TYPES.include?(type) file = Tempfile.new("build.json") file.write(to_json) file.rewind client.put("/api/build", file, "Content-Type" => "application/json" ) true ensure if file file.close file.unlink end end
[ "def", "save", "raise", "Error", "::", "InvalidBuildType", ".", "new", "(", "type", ")", "unless", "BUILD_TYPES", ".", "include?", "(", "type", ")", "file", "=", "Tempfile", ".", "new", "(", "\"build.json\"", ")", "file", ".", "write", "(", "to_json", ")", "file", ".", "rewind", "client", ".", "put", "(", "\"/api/build\"", ",", "file", ",", "\"Content-Type\"", "=>", "\"application/json\"", ")", "true", "ensure", "if", "file", "file", ".", "close", "file", ".", "unlink", "end", "end" ]
Creates data about a build. @return [Boolean]
[ "Creates", "data", "about", "a", "build", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build.rb#L201-L217
train
chef/artifactory-client
lib/artifactory/resources/build_component.rb
Artifactory.Resource::BuildComponent.builds
def builds @builds ||= Collection::Build.new(self, name: name) do Resource::Build.all(name) end end
ruby
def builds @builds ||= Collection::Build.new(self, name: name) do Resource::Build.all(name) end end
[ "def", "builds", "@builds", "||=", "Collection", "::", "Build", ".", "new", "(", "self", ",", "name", ":", "name", ")", "do", "Resource", "::", "Build", ".", "all", "(", "name", ")", "end", "end" ]
The list of build data for this component. @example Get the list of artifacts for a repository component = BuildComponent.new(name: 'wicket') component.builds #=> [#<Resource::Build>, ...] @return [Collection::Build] the list of builds
[ "The", "list", "of", "build", "data", "for", "this", "component", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build_component.rb#L98-L102
train
chef/artifactory-client
lib/artifactory/resources/build_component.rb
Artifactory.Resource::BuildComponent.delete
def delete(options = {}) params = {}.tap do |param| param[:buildNumbers] = options[:build_numbers].join(",") if options[:build_numbers] param[:artifacts] = 1 if options[:artifacts] param[:deleteAll] = 1 if options[:delete_all] end endpoint = api_path + "?#{to_query_string_parameters(params)}" client.delete(endpoint, {}) true rescue Error::HTTPError => e false end
ruby
def delete(options = {}) params = {}.tap do |param| param[:buildNumbers] = options[:build_numbers].join(",") if options[:build_numbers] param[:artifacts] = 1 if options[:artifacts] param[:deleteAll] = 1 if options[:delete_all] end endpoint = api_path + "?#{to_query_string_parameters(params)}" client.delete(endpoint, {}) true rescue Error::HTTPError => e false end
[ "def", "delete", "(", "options", "=", "{", "}", ")", "params", "=", "{", "}", ".", "tap", "do", "|", "param", "|", "param", "[", ":buildNumbers", "]", "=", "options", "[", ":build_numbers", "]", ".", "join", "(", "\",\"", ")", "if", "options", "[", ":build_numbers", "]", "param", "[", ":artifacts", "]", "=", "1", "if", "options", "[", ":artifacts", "]", "param", "[", ":deleteAll", "]", "=", "1", "if", "options", "[", ":delete_all", "]", "end", "endpoint", "=", "api_path", "+", "\"?#{to_query_string_parameters(params)}\"", "client", ".", "delete", "(", "endpoint", ",", "{", "}", ")", "true", "rescue", "Error", "::", "HTTPError", "=>", "e", "false", "end" ]
Remove this component's build data stored in Artifactory @option options [Array<String>] :build_numbers (default: nil) an array of build numbers that should be deleted; if not given all builds (for this component) are deleted @option options [Boolean] :artifacts (default: +false+) if true the component's artifacts are also removed @option options [Boolean] :delete_all (default: +false+) if true the entire component is removed @return [Boolean] true if the object was deleted successfully, false otherwise
[ "Remove", "this", "component", "s", "build", "data", "stored", "in", "Artifactory" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build_component.rb#L118-L130
train
chef/artifactory-client
lib/artifactory/resources/build_component.rb
Artifactory.Resource::BuildComponent.rename
def rename(new_name, options = {}) endpoint = "/api/build/rename/#{url_safe(name)}" + "?to=#{new_name}" client.post(endpoint, {}) true rescue Error::HTTPError => e false end
ruby
def rename(new_name, options = {}) endpoint = "/api/build/rename/#{url_safe(name)}" + "?to=#{new_name}" client.post(endpoint, {}) true rescue Error::HTTPError => e false end
[ "def", "rename", "(", "new_name", ",", "options", "=", "{", "}", ")", "endpoint", "=", "\"/api/build/rename/#{url_safe(name)}\"", "+", "\"?to=#{new_name}\"", "client", ".", "post", "(", "endpoint", ",", "{", "}", ")", "true", "rescue", "Error", "::", "HTTPError", "=>", "e", "false", "end" ]
Rename a build component. @param [String] new_name new name for the component @return [Boolean] true if the object was renamed successfully, false otherwise
[ "Rename", "a", "build", "component", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build_component.rb#L141-L147
train
chef/artifactory-client
lib/artifactory/resources/repository.rb
Artifactory.Resource::Repository.upload
def upload(local_path, remote_path, properties = {}, headers = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload(key, remote_path, properties, headers) end
ruby
def upload(local_path, remote_path, properties = {}, headers = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload(key, remote_path, properties, headers) end
[ "def", "upload", "(", "local_path", ",", "remote_path", ",", "properties", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "artifact", "=", "Resource", "::", "Artifact", ".", "new", "(", "local_path", ":", "local_path", ")", "artifact", ".", "upload", "(", "key", ",", "remote_path", ",", "properties", ",", "headers", ")", "end" ]
Upload to a given repository @see Artifact#upload Upload syntax examples @return [Resource::Artifact]
[ "Upload", "to", "a", "given", "repository" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/repository.rb#L114-L117
train
chef/artifactory-client
lib/artifactory/resources/repository.rb
Artifactory.Resource::Repository.upload_from_archive
def upload_from_archive(local_path, remote_path, properties = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload_from_archive(key, remote_path, properties) end
ruby
def upload_from_archive(local_path, remote_path, properties = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload_from_archive(key, remote_path, properties) end
[ "def", "upload_from_archive", "(", "local_path", ",", "remote_path", ",", "properties", "=", "{", "}", ")", "artifact", "=", "Resource", "::", "Artifact", ".", "new", "(", "local_path", ":", "local_path", ")", "artifact", ".", "upload_from_archive", "(", "key", ",", "remote_path", ",", "properties", ")", "end" ]
Upload an artifact with the given archive. Consult the artifactory documentation for the format of the archive to upload. @see Artifact#upload_from_archive More syntax examples
[ "Upload", "an", "artifact", "with", "the", "given", "archive", ".", "Consult", "the", "artifactory", "documentation", "for", "the", "format", "of", "the", "archive", "to", "upload", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/repository.rb#L137-L140
train
chef/artifactory-client
lib/artifactory/resources/repository.rb
Artifactory.Resource::Repository.artifacts
def artifacts @artifacts ||= Collection::Artifact.new(self, repos: key) do Resource::Artifact.search(name: ".*", repos: key) end end
ruby
def artifacts @artifacts ||= Collection::Artifact.new(self, repos: key) do Resource::Artifact.search(name: ".*", repos: key) end end
[ "def", "artifacts", "@artifacts", "||=", "Collection", "::", "Artifact", ".", "new", "(", "self", ",", "repos", ":", "key", ")", "do", "Resource", "::", "Artifact", ".", "search", "(", "name", ":", "\".*\"", ",", "repos", ":", "key", ")", "end", "end" ]
The list of artifacts in this repository on the remote artifactory server. @see Artifact.search Search syntax examples @example Get the list of artifacts for a repository repo = Repository.new('libs-release-local') repo.artifacts #=> [#<Resource::Artifacts>, ...] @return [Collection::Artifact] the list of artifacts
[ "The", "list", "of", "artifacts", "in", "this", "repository", "on", "the", "remote", "artifactory", "server", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/repository.rb#L155-L159
train
stripe/subprocess
lib/subprocess.rb
Subprocess.Process.drain_fd
def drain_fd(fd, buf=nil) loop do tmp = fd.read_nonblock(4096) buf << tmp unless buf.nil? end rescue EOFError, Errno::EPIPE fd.close true rescue Errno::EINTR rescue Errno::EWOULDBLOCK, Errno::EAGAIN false end
ruby
def drain_fd(fd, buf=nil) loop do tmp = fd.read_nonblock(4096) buf << tmp unless buf.nil? end rescue EOFError, Errno::EPIPE fd.close true rescue Errno::EINTR rescue Errno::EWOULDBLOCK, Errno::EAGAIN false end
[ "def", "drain_fd", "(", "fd", ",", "buf", "=", "nil", ")", "loop", "do", "tmp", "=", "fd", ".", "read_nonblock", "(", "4096", ")", "buf", "<<", "tmp", "unless", "buf", ".", "nil?", "end", "rescue", "EOFError", ",", "Errno", "::", "EPIPE", "fd", ".", "close", "true", "rescue", "Errno", "::", "EINTR", "rescue", "Errno", "::", "EWOULDBLOCK", ",", "Errno", "::", "EAGAIN", "false", "end" ]
Do nonblocking reads from `fd`, appending all data read into `buf`. @param [IO] fd The file to read from. @param [String] buf A buffer to append the read data to. @return [true, false] Whether `fd` was closed due to an exceptional condition (`EOFError` or `EPIPE`).
[ "Do", "nonblocking", "reads", "from", "fd", "appending", "all", "data", "read", "into", "buf", "." ]
5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a
https://github.com/stripe/subprocess/blob/5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a/lib/subprocess.rb#L371-L382
train
stripe/subprocess
lib/subprocess.rb
Subprocess.Process.select_until
def select_until(read_array, write_array, err_array, timeout_at) if !timeout_at return IO.select(read_array, write_array, err_array) end remaining = (timeout_at - Time.now) return nil if remaining <= 0 IO.select(read_array, write_array, err_array, remaining) end
ruby
def select_until(read_array, write_array, err_array, timeout_at) if !timeout_at return IO.select(read_array, write_array, err_array) end remaining = (timeout_at - Time.now) return nil if remaining <= 0 IO.select(read_array, write_array, err_array, remaining) end
[ "def", "select_until", "(", "read_array", ",", "write_array", ",", "err_array", ",", "timeout_at", ")", "if", "!", "timeout_at", "return", "IO", ".", "select", "(", "read_array", ",", "write_array", ",", "err_array", ")", "end", "remaining", "=", "(", "timeout_at", "-", "Time", ".", "now", ")", "return", "nil", "if", "remaining", "<=", "0", "IO", ".", "select", "(", "read_array", ",", "write_array", ",", "err_array", ",", "remaining", ")", "end" ]
Call IO.select timing out at Time `timeout_at`. If `timeout_at` is nil, never times out.
[ "Call", "IO", ".", "select", "timing", "out", "at", "Time", "timeout_at", ".", "If", "timeout_at", "is", "nil", "never", "times", "out", "." ]
5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a
https://github.com/stripe/subprocess/blob/5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a/lib/subprocess.rb#L551-L560
train
Pathgather/predictor
lib/predictor/input_matrix.rb
Predictor.InputMatrix.remove_from_set
def remove_from_set(set, item) Predictor.redis.multi do |redis| redis.srem(redis_key(:items, set), item) redis.srem(redis_key(:sets, item), set) end end
ruby
def remove_from_set(set, item) Predictor.redis.multi do |redis| redis.srem(redis_key(:items, set), item) redis.srem(redis_key(:sets, item), set) end end
[ "def", "remove_from_set", "(", "set", ",", "item", ")", "Predictor", ".", "redis", ".", "multi", "do", "|", "redis", "|", "redis", ".", "srem", "(", "redis_key", "(", ":items", ",", "set", ")", ",", "item", ")", "redis", ".", "srem", "(", "redis_key", "(", ":sets", ",", "item", ")", ",", "set", ")", "end", "end" ]
Delete a specific relationship
[ "Delete", "a", "specific", "relationship" ]
09b7a98293ca976fed643d6b72498defe89b2779
https://github.com/Pathgather/predictor/blob/09b7a98293ca976fed643d6b72498defe89b2779/lib/predictor/input_matrix.rb#L43-L48
train
Pathgather/predictor
lib/predictor/input_matrix.rb
Predictor.InputMatrix.delete_item
def delete_item(item) Predictor.redis.watch(redis_key(:sets, item)) do sets = Predictor.redis.smembers(redis_key(:sets, item)) Predictor.redis.multi do |multi| sets.each do |set| multi.srem(redis_key(:items, set), item) end multi.del redis_key(:sets, item) end end end
ruby
def delete_item(item) Predictor.redis.watch(redis_key(:sets, item)) do sets = Predictor.redis.smembers(redis_key(:sets, item)) Predictor.redis.multi do |multi| sets.each do |set| multi.srem(redis_key(:items, set), item) end multi.del redis_key(:sets, item) end end end
[ "def", "delete_item", "(", "item", ")", "Predictor", ".", "redis", ".", "watch", "(", "redis_key", "(", ":sets", ",", "item", ")", ")", "do", "sets", "=", "Predictor", ".", "redis", ".", "smembers", "(", "redis_key", "(", ":sets", ",", "item", ")", ")", "Predictor", ".", "redis", ".", "multi", "do", "|", "multi", "|", "sets", ".", "each", "do", "|", "set", "|", "multi", ".", "srem", "(", "redis_key", "(", ":items", ",", "set", ")", ",", "item", ")", "end", "multi", ".", "del", "redis_key", "(", ":sets", ",", "item", ")", "end", "end", "end" ]
delete item from the matrix
[ "delete", "item", "from", "the", "matrix" ]
09b7a98293ca976fed643d6b72498defe89b2779
https://github.com/Pathgather/predictor/blob/09b7a98293ca976fed643d6b72498defe89b2779/lib/predictor/input_matrix.rb#L73-L84
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.acquire_token_for_client
def acquire_token_for_client(resource, client_cred) fail_if_arguments_nil(resource, client_cred) token_request_for(client_cred).get_for_client(resource) end
ruby
def acquire_token_for_client(resource, client_cred) fail_if_arguments_nil(resource, client_cred) token_request_for(client_cred).get_for_client(resource) end
[ "def", "acquire_token_for_client", "(", "resource", ",", "client_cred", ")", "fail_if_arguments_nil", "(", "resource", ",", "client_cred", ")", "token_request_for", "(", "client_cred", ")", ".", "get_for_client", "(", "resource", ")", "end" ]
Gets an access token with only the clients credentials and no user information. @param String resource The resource being requested. @param ClientCredential|ClientAssertion|ClientAssertionCertificate An object that validates the client application by adding #request_params to the OAuth request. @return TokenResponse
[ "Gets", "an", "access", "token", "with", "only", "the", "clients", "credentials", "and", "no", "user", "information", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L76-L79
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.acquire_token_with_authorization_code
def acquire_token_with_authorization_code( auth_code, redirect_uri, client_cred, resource = nil) fail_if_arguments_nil(auth_code, redirect_uri, client_cred) token_request_for(client_cred) .get_with_authorization_code(auth_code, redirect_uri, resource) end
ruby
def acquire_token_with_authorization_code( auth_code, redirect_uri, client_cred, resource = nil) fail_if_arguments_nil(auth_code, redirect_uri, client_cred) token_request_for(client_cred) .get_with_authorization_code(auth_code, redirect_uri, resource) end
[ "def", "acquire_token_with_authorization_code", "(", "auth_code", ",", "redirect_uri", ",", "client_cred", ",", "resource", "=", "nil", ")", "fail_if_arguments_nil", "(", "auth_code", ",", "redirect_uri", ",", "client_cred", ")", "token_request_for", "(", "client_cred", ")", ".", "get_with_authorization_code", "(", "auth_code", ",", "redirect_uri", ",", "resource", ")", "end" ]
Gets an access token with a previously acquire authorization code. @param String auth_code The authorization code that was issued by the authorization server. @param URI redirect_uri The URI that was passed to the authorization server with the request for the authorization code. @param ClientCredential|ClientAssertion|ClientAssertionCertificate An object that validates the client application by adding #request_params to the OAuth request. @optional String resource The resource being requested. @return TokenResponse
[ "Gets", "an", "access", "token", "with", "a", "previously", "acquire", "authorization", "code", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L95-L100
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.acquire_token_with_refresh_token
def acquire_token_with_refresh_token( refresh_token, client_cred, resource = nil) fail_if_arguments_nil(refresh_token, client_cred) token_request_for(client_cred) .get_with_refresh_token(refresh_token, resource) end
ruby
def acquire_token_with_refresh_token( refresh_token, client_cred, resource = nil) fail_if_arguments_nil(refresh_token, client_cred) token_request_for(client_cred) .get_with_refresh_token(refresh_token, resource) end
[ "def", "acquire_token_with_refresh_token", "(", "refresh_token", ",", "client_cred", ",", "resource", "=", "nil", ")", "fail_if_arguments_nil", "(", "refresh_token", ",", "client_cred", ")", "token_request_for", "(", "client_cred", ")", ".", "get_with_refresh_token", "(", "refresh_token", ",", "resource", ")", "end" ]
Gets an access token using a previously acquire refresh token. @param String refresh_token The previously acquired refresh token. @param String|ClientCredential|ClientAssertion|ClientAssertionCertificate The client application can be validated in four different manners, depending on the OAuth flow. This object must support #request_params. @optional String resource The resource being requested. @return TokenResponse
[ "Gets", "an", "access", "token", "using", "a", "previously", "acquire", "refresh", "token", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L113-L118
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.authorization_request_url
def authorization_request_url( resource, client_id, redirect_uri, extra_query_params = {}) @authority.authorize_endpoint( extra_query_params.reverse_merge( client_id: client_id, response_mode: FORM_POST, redirect_uri: redirect_uri, resource: resource, response_type: CODE)) end
ruby
def authorization_request_url( resource, client_id, redirect_uri, extra_query_params = {}) @authority.authorize_endpoint( extra_query_params.reverse_merge( client_id: client_id, response_mode: FORM_POST, redirect_uri: redirect_uri, resource: resource, response_type: CODE)) end
[ "def", "authorization_request_url", "(", "resource", ",", "client_id", ",", "redirect_uri", ",", "extra_query_params", "=", "{", "}", ")", "@authority", ".", "authorize_endpoint", "(", "extra_query_params", ".", "reverse_merge", "(", "client_id", ":", "client_id", ",", "response_mode", ":", "FORM_POST", ",", "redirect_uri", ":", "redirect_uri", ",", "resource", ":", "resource", ",", "response_type", ":", "CODE", ")", ")", "end" ]
Constructs a URL for an authorization endpoint using query parameters. @param String resource The intended recipient of the requested token. @param String client_id The identifier of the calling client application. @param URI redirect_uri The URI that the the authorization code should be sent back to. @optional Hash extra_query_params Any remaining query parameters to add to the URI. @return URI
[ "Constructs", "a", "URL", "for", "an", "authorization", "endpoint", "using", "query", "parameters", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L165-L174
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/client_assertion_certificate.rb
ADAL.ClientAssertionCertificate.request_params
def request_params jwt_assertion = SelfSignedJwtFactory .new(@client_id, @authority.token_endpoint) .create_and_sign_jwt(@certificate, @private_key) ClientAssertion.new(client_id, jwt_assertion).request_params end
ruby
def request_params jwt_assertion = SelfSignedJwtFactory .new(@client_id, @authority.token_endpoint) .create_and_sign_jwt(@certificate, @private_key) ClientAssertion.new(client_id, jwt_assertion).request_params end
[ "def", "request_params", "jwt_assertion", "=", "SelfSignedJwtFactory", ".", "new", "(", "@client_id", ",", "@authority", ".", "token_endpoint", ")", ".", "create_and_sign_jwt", "(", "@certificate", ",", "@private_key", ")", "ClientAssertion", ".", "new", "(", "client_id", ",", "jwt_assertion", ")", ".", "request_params", "end" ]
Creates a new ClientAssertionCertificate. @param Authority authority The authority object that will recognize this certificate. @param [String] client_id The client id of the calling application. @param [OpenSSL::PKCS12] pkcs12_file The PKCS12 file containing the certificate and private key. The relevant parameters from this credential for OAuth.
[ "Creates", "a", "new", "ClientAssertionCertificate", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/client_assertion_certificate.rb#L59-L64
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/user_credential.rb
ADAL.UserCredential.request_params
def request_params case account_type when AccountType::MANAGED managed_request_params when AccountType::FEDERATED federated_request_params else fail UnsupportedAccountTypeError, account_type end end
ruby
def request_params case account_type when AccountType::MANAGED managed_request_params when AccountType::FEDERATED federated_request_params else fail UnsupportedAccountTypeError, account_type end end
[ "def", "request_params", "case", "account_type", "when", "AccountType", "::", "MANAGED", "managed_request_params", "when", "AccountType", "::", "FEDERATED", "federated_request_params", "else", "fail", "UnsupportedAccountTypeError", ",", "account_type", "end", "end" ]
The OAuth parameters that respresent this UserCredential. @return Hash
[ "The", "OAuth", "parameters", "that", "respresent", "this", "UserCredential", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/user_credential.rb#L83-L92
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/wstrust_request.rb
ADAL.WSTrustRequest.execute
def execute(username, password) logger.verbose("Making a WSTrust request with action #{@action}.") request = Net::HTTP::Get.new(@endpoint.path) add_headers(request) request.body = rst(username, password) response = http(@endpoint).request(request) if response.code == '200' WSTrustResponse.parse(response.body) else fail WSTrustResponse::WSTrustError, "Failed request: code #{response.code}." end end
ruby
def execute(username, password) logger.verbose("Making a WSTrust request with action #{@action}.") request = Net::HTTP::Get.new(@endpoint.path) add_headers(request) request.body = rst(username, password) response = http(@endpoint).request(request) if response.code == '200' WSTrustResponse.parse(response.body) else fail WSTrustResponse::WSTrustError, "Failed request: code #{response.code}." end end
[ "def", "execute", "(", "username", ",", "password", ")", "logger", ".", "verbose", "(", "\"Making a WSTrust request with action #{@action}.\"", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@endpoint", ".", "path", ")", "add_headers", "(", "request", ")", "request", ".", "body", "=", "rst", "(", "username", ",", "password", ")", "response", "=", "http", "(", "@endpoint", ")", ".", "request", "(", "request", ")", "if", "response", ".", "code", "==", "'200'", "WSTrustResponse", ".", "parse", "(", "response", ".", "body", ")", "else", "fail", "WSTrustResponse", "::", "WSTrustError", ",", "\"Failed request: code #{response.code}.\"", "end", "end" ]
Constructs a new WSTrustRequest. @param String|URI endpoint @param String action @param String applies_to Performs a WS-Trust RequestSecurityToken request with a username and password to obtain a federated token. @param String username @param String password @return WSTrustResponse
[ "Constructs", "a", "new", "WSTrustRequest", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/wstrust_request.rb#L69-L80
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/mex_request.rb
ADAL.MexRequest.execute
def execute request = Net::HTTP::Get.new(@endpoint.path) request.add_field('Content-Type', 'application/soap+xml') MexResponse.parse(http(@endpoint).request(request).body) end
ruby
def execute request = Net::HTTP::Get.new(@endpoint.path) request.add_field('Content-Type', 'application/soap+xml') MexResponse.parse(http(@endpoint).request(request).body) end
[ "def", "execute", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@endpoint", ".", "path", ")", "request", ".", "add_field", "(", "'Content-Type'", ",", "'application/soap+xml'", ")", "MexResponse", ".", "parse", "(", "http", "(", "@endpoint", ")", ".", "request", "(", "request", ")", ".", "body", ")", "end" ]
Constructs a MexRequest object for a specific URL endpoint. @param String|URI endpoint The Metadata Exchange endpoint. @return MexResponse
[ "Constructs", "a", "MexRequest", "object", "for", "a", "specific", "URL", "endpoint", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/mex_request.rb#L46-L50
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authority.rb
ADAL.Authority.authorize_endpoint
def authorize_endpoint(params = nil) params = params.select { |_, v| !v.nil? } if params.respond_to? :select if params.nil? || params.empty? URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH) else URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH, query: URI.encode_www_form(params)) end end
ruby
def authorize_endpoint(params = nil) params = params.select { |_, v| !v.nil? } if params.respond_to? :select if params.nil? || params.empty? URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH) else URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH, query: URI.encode_www_form(params)) end end
[ "def", "authorize_endpoint", "(", "params", "=", "nil", ")", "params", "=", "params", ".", "select", "{", "|", "_", ",", "v", "|", "!", "v", ".", "nil?", "}", "if", "params", ".", "respond_to?", ":select", "if", "params", ".", "nil?", "||", "params", ".", "empty?", "URI", "::", "HTTPS", ".", "build", "(", "host", ":", "@host", ",", "path", ":", "'/'", "+", "@tenant", "+", "AUTHORIZE_PATH", ")", "else", "URI", "::", "HTTPS", ".", "build", "(", "host", ":", "@host", ",", "path", ":", "'/'", "+", "@tenant", "+", "AUTHORIZE_PATH", ",", "query", ":", "URI", ".", "encode_www_form", "(", "params", ")", ")", "end", "end" ]
URI that can be used to acquire authorization codes. @optional Hash params Query parameters that will added to the endpoint. @return [URI]
[ "URI", "that", "can", "be", "used", "to", "acquire", "authorization", "codes", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authority.rb#L79-L88
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authority.rb
ADAL.Authority.discovery_uri
def discovery_uri(host = WORLD_WIDE_AUTHORITY) URI(DISCOVERY_TEMPLATE.expand(host: host, endpoint: authorize_endpoint)) end
ruby
def discovery_uri(host = WORLD_WIDE_AUTHORITY) URI(DISCOVERY_TEMPLATE.expand(host: host, endpoint: authorize_endpoint)) end
[ "def", "discovery_uri", "(", "host", "=", "WORLD_WIDE_AUTHORITY", ")", "URI", "(", "DISCOVERY_TEMPLATE", ".", "expand", "(", "host", ":", "host", ",", "endpoint", ":", "authorize_endpoint", ")", ")", "end" ]
Creates an instance discovery endpoint url for authority that this object represents. @return [URI]
[ "Creates", "an", "instance", "discovery", "endpoint", "url", "for", "authority", "that", "this", "object", "represents", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authority.rb#L122-L124
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authority.rb
ADAL.Authority.validated_dynamically?
def validated_dynamically? logger.verbose("Attempting instance discovery at: #{discovery_uri}.") http_response = Net::HTTP.get(discovery_uri) if http_response.nil? logger.error('Dynamic validation received no response from endpoint.') return false end parse_dynamic_validation(JSON.parse(http_response)) end
ruby
def validated_dynamically? logger.verbose("Attempting instance discovery at: #{discovery_uri}.") http_response = Net::HTTP.get(discovery_uri) if http_response.nil? logger.error('Dynamic validation received no response from endpoint.') return false end parse_dynamic_validation(JSON.parse(http_response)) end
[ "def", "validated_dynamically?", "logger", ".", "verbose", "(", "\"Attempting instance discovery at: #{discovery_uri}.\"", ")", "http_response", "=", "Net", "::", "HTTP", ".", "get", "(", "discovery_uri", ")", "if", "http_response", ".", "nil?", "logger", ".", "error", "(", "'Dynamic validation received no response from endpoint.'", ")", "return", "false", "end", "parse_dynamic_validation", "(", "JSON", ".", "parse", "(", "http_response", ")", ")", "end" ]
Performs instance discovery via a network call to well known authorities. @return [String] The tenant discovery endpoint, if found. Otherwise nil.
[ "Performs", "instance", "discovery", "via", "a", "network", "call", "to", "well", "known", "authorities", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authority.rb#L131-L139
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/wstrust_response.rb
ADAL.WSTrustResponse.grant_type
def grant_type case @token_type when TokenType::V1 TokenRequest::GrantType::SAML1 when TokenType::V2 TokenRequest::GrantType::SAML2 end end
ruby
def grant_type case @token_type when TokenType::V1 TokenRequest::GrantType::SAML1 when TokenType::V2 TokenRequest::GrantType::SAML2 end end
[ "def", "grant_type", "case", "@token_type", "when", "TokenType", "::", "V1", "TokenRequest", "::", "GrantType", "::", "SAML1", "when", "TokenType", "::", "V2", "TokenRequest", "::", "GrantType", "::", "SAML2", "end", "end" ]
Constructs a WSTrustResponse. @param String token The content of the returned token. @param WSTrustResponse::TokenType token_type The type of the token contained within the WS-Trust response. Gets the OAuth grant type for the SAML token type of the response. @return TokenRequest::GrantType
[ "Constructs", "a", "WSTrustResponse", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/wstrust_response.rb#L159-L166
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/self_signed_jwt_factory.rb
ADAL.SelfSignedJwtFactory.create_and_sign_jwt
def create_and_sign_jwt(certificate, private_key) JWT.encode(payload, private_key, RS256, header(certificate)) end
ruby
def create_and_sign_jwt(certificate, private_key) JWT.encode(payload, private_key, RS256, header(certificate)) end
[ "def", "create_and_sign_jwt", "(", "certificate", ",", "private_key", ")", "JWT", ".", "encode", "(", "payload", ",", "private_key", ",", "RS256", ",", "header", "(", "certificate", ")", ")", "end" ]
Constructs a new SelfSignedJwtFactory. @param String client_id The client id of the calling application. @param String token_endpoint The token endpoint that will accept the certificate. Creates a JWT from a client certificate and signs it with a private key. @param OpenSSL::X509::Certificate certificate The certifcate object to be converted to a JWT and signed for use in an authentication flow. @param OpenSSL::PKey::RSA private_key The private key used to sign the certificate. @return String
[ "Constructs", "a", "new", "SelfSignedJwtFactory", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/self_signed_jwt_factory.rb#L57-L59
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/self_signed_jwt_factory.rb
ADAL.SelfSignedJwtFactory.header
def header(certificate) x5t = thumbprint(certificate) logger.verbose("Creating self signed JWT header with thumbprint: #{x5t}.") { TYPE => TYPE_JWT, ALGORITHM => RS256, THUMBPRINT => x5t } end
ruby
def header(certificate) x5t = thumbprint(certificate) logger.verbose("Creating self signed JWT header with thumbprint: #{x5t}.") { TYPE => TYPE_JWT, ALGORITHM => RS256, THUMBPRINT => x5t } end
[ "def", "header", "(", "certificate", ")", "x5t", "=", "thumbprint", "(", "certificate", ")", "logger", ".", "verbose", "(", "\"Creating self signed JWT header with thumbprint: #{x5t}.\"", ")", "{", "TYPE", "=>", "TYPE_JWT", ",", "ALGORITHM", "=>", "RS256", ",", "THUMBPRINT", "=>", "x5t", "}", "end" ]
The JWT header for a certificate to be encoded.
[ "The", "JWT", "header", "for", "a", "certificate", "to", "be", "encoded", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/self_signed_jwt_factory.rb#L64-L70
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/self_signed_jwt_factory.rb
ADAL.SelfSignedJwtFactory.payload
def payload now = Time.now - 1 expires = now + 60 * SELF_SIGNED_JWT_LIFETIME logger.verbose("Creating self signed JWT payload. Expires: #{expires}. " \ "NotBefore: #{now}.") { AUDIENCE => @token_endpoint, ISSUER => @client_id, SUBJECT => @client_id, NOT_BEFORE => now.to_i, EXPIRES_ON => expires.to_i, JWT_ID => SecureRandom.uuid } end
ruby
def payload now = Time.now - 1 expires = now + 60 * SELF_SIGNED_JWT_LIFETIME logger.verbose("Creating self signed JWT payload. Expires: #{expires}. " \ "NotBefore: #{now}.") { AUDIENCE => @token_endpoint, ISSUER => @client_id, SUBJECT => @client_id, NOT_BEFORE => now.to_i, EXPIRES_ON => expires.to_i, JWT_ID => SecureRandom.uuid } end
[ "def", "payload", "now", "=", "Time", ".", "now", "-", "1", "expires", "=", "now", "+", "60", "*", "SELF_SIGNED_JWT_LIFETIME", "logger", ".", "verbose", "(", "\"Creating self signed JWT payload. Expires: #{expires}. \"", "\"NotBefore: #{now}.\"", ")", "{", "AUDIENCE", "=>", "@token_endpoint", ",", "ISSUER", "=>", "@client_id", ",", "SUBJECT", "=>", "@client_id", ",", "NOT_BEFORE", "=>", "now", ".", "to_i", ",", "EXPIRES_ON", "=>", "expires", ".", "to_i", ",", "JWT_ID", "=>", "SecureRandom", ".", "uuid", "}", "end" ]
The JWT payload.
[ "The", "JWT", "payload", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/self_signed_jwt_factory.rb#L73-L84
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_for_client
def get_for_client(resource) logger.verbose("TokenRequest getting token for client for #{resource}.") request(GRANT_TYPE => GrantType::CLIENT_CREDENTIALS, RESOURCE => resource) end
ruby
def get_for_client(resource) logger.verbose("TokenRequest getting token for client for #{resource}.") request(GRANT_TYPE => GrantType::CLIENT_CREDENTIALS, RESOURCE => resource) end
[ "def", "get_for_client", "(", "resource", ")", "logger", ".", "verbose", "(", "\"TokenRequest getting token for client for #{resource}.\"", ")", "request", "(", "GRANT_TYPE", "=>", "GrantType", "::", "CLIENT_CREDENTIALS", ",", "RESOURCE", "=>", "resource", ")", "end" ]
Gets a token based solely on the clients credentials that were used to initialize the token request. @param String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "solely", "on", "the", "clients", "credentials", "that", "were", "used", "to", "initialize", "the", "token", "request", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L82-L86
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_with_authorization_code
def get_with_authorization_code(auth_code, redirect_uri, resource = nil) logger.verbose('TokenRequest getting token with authorization code ' \ "#{auth_code}, redirect_uri #{redirect_uri} and " \ "resource #{resource}.") request(CODE => auth_code, GRANT_TYPE => GrantType::AUTHORIZATION_CODE, REDIRECT_URI => URI.parse(redirect_uri.to_s), RESOURCE => resource) end
ruby
def get_with_authorization_code(auth_code, redirect_uri, resource = nil) logger.verbose('TokenRequest getting token with authorization code ' \ "#{auth_code}, redirect_uri #{redirect_uri} and " \ "resource #{resource}.") request(CODE => auth_code, GRANT_TYPE => GrantType::AUTHORIZATION_CODE, REDIRECT_URI => URI.parse(redirect_uri.to_s), RESOURCE => resource) end
[ "def", "get_with_authorization_code", "(", "auth_code", ",", "redirect_uri", ",", "resource", "=", "nil", ")", "logger", ".", "verbose", "(", "'TokenRequest getting token with authorization code '", "\"#{auth_code}, redirect_uri #{redirect_uri} and \"", "\"resource #{resource}.\"", ")", "request", "(", "CODE", "=>", "auth_code", ",", "GRANT_TYPE", "=>", "GrantType", "::", "AUTHORIZATION_CODE", ",", "REDIRECT_URI", "=>", "URI", ".", "parse", "(", "redirect_uri", ".", "to_s", ")", ",", "RESOURCE", "=>", "resource", ")", "end" ]
Gets a token based on a previously acquired authentication code. @param String auth_code An authentication code that was previously acquired from an authentication endpoint. @param String redirect_uri The redirect uri that was passed to the authentication endpoint when the auth code was acquired. @optional String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "on", "a", "previously", "acquired", "authentication", "code", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L100-L108
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_with_refresh_token
def get_with_refresh_token(refresh_token, resource = nil) logger.verbose('TokenRequest getting token with refresh token digest ' \ "#{Digest::SHA256.hexdigest refresh_token} and resource " \ "#{resource}.") request_no_cache(GRANT_TYPE => GrantType::REFRESH_TOKEN, REFRESH_TOKEN => refresh_token, RESOURCE => resource) end
ruby
def get_with_refresh_token(refresh_token, resource = nil) logger.verbose('TokenRequest getting token with refresh token digest ' \ "#{Digest::SHA256.hexdigest refresh_token} and resource " \ "#{resource}.") request_no_cache(GRANT_TYPE => GrantType::REFRESH_TOKEN, REFRESH_TOKEN => refresh_token, RESOURCE => resource) end
[ "def", "get_with_refresh_token", "(", "refresh_token", ",", "resource", "=", "nil", ")", "logger", ".", "verbose", "(", "'TokenRequest getting token with refresh token digest '", "\"#{Digest::SHA256.hexdigest refresh_token} and resource \"", "\"#{resource}.\"", ")", "request_no_cache", "(", "GRANT_TYPE", "=>", "GrantType", "::", "REFRESH_TOKEN", ",", "REFRESH_TOKEN", "=>", "refresh_token", ",", "RESOURCE", "=>", "resource", ")", "end" ]
Gets a token based on a previously acquired refresh token. @param String refresh_token The refresh token that was previously acquired from a token response. @optional String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "on", "a", "previously", "acquired", "refresh", "token", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L118-L125
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_with_user_credential
def get_with_user_credential(user_cred, resource = nil) logger.verbose('TokenRequest getting token with user credential ' \ "#{user_cred} and resource #{resource}.") oauth = if user_cred.is_a? UserIdentifier lambda do fail UserCredentialError, 'UserIdentifier can only be used once there is a ' \ 'matching token in the cache.' end end || -> {} request(user_cred.request_params.merge(RESOURCE => resource), &oauth) end
ruby
def get_with_user_credential(user_cred, resource = nil) logger.verbose('TokenRequest getting token with user credential ' \ "#{user_cred} and resource #{resource}.") oauth = if user_cred.is_a? UserIdentifier lambda do fail UserCredentialError, 'UserIdentifier can only be used once there is a ' \ 'matching token in the cache.' end end || -> {} request(user_cred.request_params.merge(RESOURCE => resource), &oauth) end
[ "def", "get_with_user_credential", "(", "user_cred", ",", "resource", "=", "nil", ")", "logger", ".", "verbose", "(", "'TokenRequest getting token with user credential '", "\"#{user_cred} and resource #{resource}.\"", ")", "oauth", "=", "if", "user_cred", ".", "is_a?", "UserIdentifier", "lambda", "do", "fail", "UserCredentialError", ",", "'UserIdentifier can only be used once there is a '", "'matching token in the cache.'", "end", "end", "||", "->", "{", "}", "request", "(", "user_cred", ".", "request_params", ".", "merge", "(", "RESOURCE", "=>", "resource", ")", ",", "oauth", ")", "end" ]
Gets a token based on possessing the users credentials. @param UserCredential|UserIdentifier user_cred Something that can be used to verify the user. Typically a username and password. If it is a UserIdentifier, only the cache will be checked. If a matching token is not there, it will fail. @optional String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "on", "possessing", "the", "users", "credentials", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L137-L148
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.request
def request(params, &block) cached_token = check_cache(request_params(params)) return cached_token if cached_token cache_response(request_no_cache(request_params(params), &block)) end
ruby
def request(params, &block) cached_token = check_cache(request_params(params)) return cached_token if cached_token cache_response(request_no_cache(request_params(params), &block)) end
[ "def", "request", "(", "params", ",", "&", "block", ")", "cached_token", "=", "check_cache", "(", "request_params", "(", "params", ")", ")", "return", "cached_token", "if", "cached_token", "cache_response", "(", "request_no_cache", "(", "request_params", "(", "params", ")", ",", "block", ")", ")", "end" ]
Attempts to fulfill a token request, first via the token cache and then through OAuth. @param Hash params Any additional request parameters that should be used. @return TokenResponse
[ "Attempts", "to", "fulfill", "a", "token", "request", "first", "via", "the", "token", "cache", "and", "then", "through", "OAuth", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L168-L172
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.add
def add(token_response) return unless token_response.instance_of? SuccessResponse logger.verbose('Adding successful TokenResponse to cache.') entry = CachedTokenResponse.new(@client, @authority, token_response) update_refresh_tokens(entry) if entry.mrrt? @token_cache.add(entry) end
ruby
def add(token_response) return unless token_response.instance_of? SuccessResponse logger.verbose('Adding successful TokenResponse to cache.') entry = CachedTokenResponse.new(@client, @authority, token_response) update_refresh_tokens(entry) if entry.mrrt? @token_cache.add(entry) end
[ "def", "add", "(", "token_response", ")", "return", "unless", "token_response", ".", "instance_of?", "SuccessResponse", "logger", ".", "verbose", "(", "'Adding successful TokenResponse to cache.'", ")", "entry", "=", "CachedTokenResponse", ".", "new", "(", "@client", ",", "@authority", ",", "token_response", ")", "update_refresh_tokens", "(", "entry", ")", "if", "entry", ".", "mrrt?", "@token_cache", ".", "add", "(", "entry", ")", "end" ]
Constructs a CacheDriver to interact with a token cache. @param String authority The URL of the authority endpoint. @param ClientAssertion|ClientCredential|etc client The credentials representing the calling application. We need this instead of just the client id so that the tokens can be refreshed if necessary. @param TokenCache token_cache The cache implementation to store tokens. @optional Fixnum expiration_buffer_sec The number of seconds to use as a leeway when dealing with cache expiry. Checks if a TokenResponse is successful and if so adds it to the token cache for future retrieval. @param SuccessResponse token_response The successful token response to be cached. If it is not successful, it fails silently.
[ "Constructs", "a", "CacheDriver", "to", "interact", "with", "a", "token", "cache", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L69-L75
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.find
def find(query = {}) query = query.map { |k, v| [FIELDS[k], v] if FIELDS[k] }.compact.to_h resource = query.delete(RESOURCE) matches = validate( find_all_cached_entries( query.reverse_merge( authority: @authority, client_id: @client.client_id)) ) resource_specific(matches, resource) || refresh_mrrt(matches, resource) end
ruby
def find(query = {}) query = query.map { |k, v| [FIELDS[k], v] if FIELDS[k] }.compact.to_h resource = query.delete(RESOURCE) matches = validate( find_all_cached_entries( query.reverse_merge( authority: @authority, client_id: @client.client_id)) ) resource_specific(matches, resource) || refresh_mrrt(matches, resource) end
[ "def", "find", "(", "query", "=", "{", "}", ")", "query", "=", "query", ".", "map", "{", "|", "k", ",", "v", "|", "[", "FIELDS", "[", "k", "]", ",", "v", "]", "if", "FIELDS", "[", "k", "]", "}", ".", "compact", ".", "to_h", "resource", "=", "query", ".", "delete", "(", "RESOURCE", ")", "matches", "=", "validate", "(", "find_all_cached_entries", "(", "query", ".", "reverse_merge", "(", "authority", ":", "@authority", ",", "client_id", ":", "@client", ".", "client_id", ")", ")", ")", "resource_specific", "(", "matches", ",", "resource", ")", "||", "refresh_mrrt", "(", "matches", ",", "resource", ")", "end" ]
Searches the cache for a token matching a specific query of fields. @param Hash query The fields to match against. @return TokenResponse
[ "Searches", "the", "cache", "for", "a", "token", "matching", "a", "specific", "query", "of", "fields", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L83-L92
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.find_all_cached_entries
def find_all_cached_entries(query) logger.verbose("Searching cache for tokens by keys: #{query.keys}.") @token_cache.find do |entry| query.map do |k, v| (entry.respond_to? k.to_sym) && (v == entry.send(k.to_sym)) end.reduce(:&) end end
ruby
def find_all_cached_entries(query) logger.verbose("Searching cache for tokens by keys: #{query.keys}.") @token_cache.find do |entry| query.map do |k, v| (entry.respond_to? k.to_sym) && (v == entry.send(k.to_sym)) end.reduce(:&) end end
[ "def", "find_all_cached_entries", "(", "query", ")", "logger", ".", "verbose", "(", "\"Searching cache for tokens by keys: #{query.keys}.\"", ")", "@token_cache", ".", "find", "do", "|", "entry", "|", "query", ".", "map", "do", "|", "k", ",", "v", "|", "(", "entry", ".", "respond_to?", "k", ".", "to_sym", ")", "&&", "(", "v", "==", "entry", ".", "send", "(", "k", ".", "to_sym", ")", ")", "end", ".", "reduce", "(", ":&", ")", "end", "end" ]
All cache entries that match a query. This matches keys in values against a hash to method calls on an object. @param Hash query The fields to be matched and the values to match them to. @return Array<CachedTokenResponse>
[ "All", "cache", "entries", "that", "match", "a", "query", ".", "This", "matches", "keys", "in", "values", "against", "a", "hash", "to", "method", "calls", "on", "an", "object", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L103-L110
train
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.refresh_mrrt
def refresh_mrrt(responses, resource) logger.verbose("Attempting to obtain access token for #{resource} by " \ "refreshing 1 of #{responses.count(&:mrrt?)} matching " \ 'MRRTs.') responses.each do |response| if response.mrrt? refresh_response = response.refresh(resource) return refresh_response if add(refresh_response) end end nil end
ruby
def refresh_mrrt(responses, resource) logger.verbose("Attempting to obtain access token for #{resource} by " \ "refreshing 1 of #{responses.count(&:mrrt?)} matching " \ 'MRRTs.') responses.each do |response| if response.mrrt? refresh_response = response.refresh(resource) return refresh_response if add(refresh_response) end end nil end
[ "def", "refresh_mrrt", "(", "responses", ",", "resource", ")", "logger", ".", "verbose", "(", "\"Attempting to obtain access token for #{resource} by \"", "\"refreshing 1 of #{responses.count(&:mrrt?)} matching \"", "'MRRTs.'", ")", "responses", ".", "each", "do", "|", "response", "|", "if", "response", ".", "mrrt?", "refresh_response", "=", "response", ".", "refresh", "(", "resource", ")", "return", "refresh_response", "if", "add", "(", "refresh_response", ")", "end", "end", "nil", "end" ]
Attempts to obtain an access token for a resource with refresh tokens from a list of MRRTs. @param Array[CachedTokenResponse] @return SuccessResponse|nil
[ "Attempts", "to", "obtain", "an", "access", "token", "for", "a", "resource", "with", "refresh", "tokens", "from", "a", "list", "of", "MRRTs", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L118-L129
train