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
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.commit_data
def commit_data(sha) sha = sha.to_s cdata = command_lines('cat-file', ['commit', sha]) process_commit_data(cdata, sha, 0) end
ruby
def commit_data(sha) sha = sha.to_s cdata = command_lines('cat-file', ['commit', sha]) process_commit_data(cdata, sha, 0) end
[ "def", "commit_data", "(", "sha", ")", "sha", "=", "sha", ".", "to_s", "cdata", "=", "command_lines", "(", "'cat-file'", ",", "[", "'commit'", ",", "sha", "]", ")", "process_commit_data", "(", "cdata", ",", "sha", ",", "0", ")", "end" ]
returns useful array of raw commit object data
[ "returns", "useful", "array", "of", "raw", "commit", "object", "data" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L175-L179
train
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.read_tree
def read_tree(treeish, opts = {}) arr_opts = [] arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix] arr_opts += [treeish] command('read-tree', arr_opts) end
ruby
def read_tree(treeish, opts = {}) arr_opts = [] arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix] arr_opts += [treeish] command('read-tree', arr_opts) end
[ "def", "read_tree", "(", "treeish", ",", "opts", "=", "{", "}", ")", "arr_opts", "=", "[", "]", "arr_opts", "<<", "\"--prefix=#{opts[:prefix]}\"", "if", "opts", "[", ":prefix", "]", "arr_opts", "+=", "[", "treeish", "]", "command", "(", "'read-tree'", ",", "arr_opts", ")", "end" ]
reads a tree into the current index file
[ "reads", "a", "tree", "into", "the", "current", "index", "file" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L808-L813
train
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.archive
def archive(sha, file = nil, opts = {}) opts[:format] ||= 'zip' if opts[:format] == 'tgz' opts[:format] = 'tar' opts[:add_gzip] = true end if !file tempfile = Tempfile.new('archive') file = tempfile.path # delete it now, before we write to it, so that Ruby doesn't delete it # when it finalizes the Tempfile. tempfile.close! end arr_opts = [] arr_opts << "--format=#{opts[:format]}" if opts[:format] arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix] arr_opts << "--remote=#{opts[:remote]}" if opts[:remote] arr_opts << sha arr_opts << '--' << opts[:path] if opts[:path] command('archive', arr_opts, true, (opts[:add_gzip] ? '| gzip' : '') + " > #{escape file}") return file end
ruby
def archive(sha, file = nil, opts = {}) opts[:format] ||= 'zip' if opts[:format] == 'tgz' opts[:format] = 'tar' opts[:add_gzip] = true end if !file tempfile = Tempfile.new('archive') file = tempfile.path # delete it now, before we write to it, so that Ruby doesn't delete it # when it finalizes the Tempfile. tempfile.close! end arr_opts = [] arr_opts << "--format=#{opts[:format]}" if opts[:format] arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix] arr_opts << "--remote=#{opts[:remote]}" if opts[:remote] arr_opts << sha arr_opts << '--' << opts[:path] if opts[:path] command('archive', arr_opts, true, (opts[:add_gzip] ? '| gzip' : '') + " > #{escape file}") return file end
[ "def", "archive", "(", "sha", ",", "file", "=", "nil", ",", "opts", "=", "{", "}", ")", "opts", "[", ":format", "]", "||=", "'zip'", "if", "opts", "[", ":format", "]", "==", "'tgz'", "opts", "[", ":format", "]", "=", "'tar'", "opts", "[", ":add_gzip", "]", "=", "true", "end", "if", "!", "file", "tempfile", "=", "Tempfile", ".", "new", "(", "'archive'", ")", "file", "=", "tempfile", ".", "path", "# delete it now, before we write to it, so that Ruby doesn't delete it", "# when it finalizes the Tempfile.", "tempfile", ".", "close!", "end", "arr_opts", "=", "[", "]", "arr_opts", "<<", "\"--format=#{opts[:format]}\"", "if", "opts", "[", ":format", "]", "arr_opts", "<<", "\"--prefix=#{opts[:prefix]}\"", "if", "opts", "[", ":prefix", "]", "arr_opts", "<<", "\"--remote=#{opts[:remote]}\"", "if", "opts", "[", ":remote", "]", "arr_opts", "<<", "sha", "arr_opts", "<<", "'--'", "<<", "opts", "[", ":path", "]", "if", "opts", "[", ":path", "]", "command", "(", "'archive'", ",", "arr_opts", ",", "true", ",", "(", "opts", "[", ":add_gzip", "]", "?", "'| gzip'", ":", "''", ")", "+", "\" > #{escape file}\"", ")", "return", "file", "end" ]
creates an archive file options :format (zip, tar) :prefix :remote :path
[ "creates", "an", "archive", "file" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L853-L877
train
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.current_command_version
def current_command_version output = command('version', [], false) version = output[/\d+\.\d+(\.\d+)+/] version.split('.').collect {|i| i.to_i} end
ruby
def current_command_version output = command('version', [], false) version = output[/\d+\.\d+(\.\d+)+/] version.split('.').collect {|i| i.to_i} end
[ "def", "current_command_version", "output", "=", "command", "(", "'version'", ",", "[", "]", ",", "false", ")", "version", "=", "output", "[", "/", "\\d", "\\.", "\\d", "\\.", "\\d", "/", "]", "version", ".", "split", "(", "'.'", ")", ".", "collect", "{", "|", "i", "|", "i", ".", "to_i", "}", "end" ]
returns the current version of git, as an Array of Fixnums.
[ "returns", "the", "current", "version", "of", "git", "as", "an", "Array", "of", "Fixnums", "." ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L880-L884
train
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.log_common_options
def log_common_options(opts) arr_opts = [] arr_opts << "-#{opts[:count]}" if opts[:count] arr_opts << "--no-color" arr_opts << "--since=#{opts[:since]}" if opts[:since].is_a? String arr_opts << "--until=#{opts[:until]}" if opts[:until].is_a? String arr_opts << "--grep=#{opts[:grep]}" if opts[:grep].is_a? String arr_opts << "--author=#{opts[:author]}" if opts[:author].is_a? String arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2) arr_opts end
ruby
def log_common_options(opts) arr_opts = [] arr_opts << "-#{opts[:count]}" if opts[:count] arr_opts << "--no-color" arr_opts << "--since=#{opts[:since]}" if opts[:since].is_a? String arr_opts << "--until=#{opts[:until]}" if opts[:until].is_a? String arr_opts << "--grep=#{opts[:grep]}" if opts[:grep].is_a? String arr_opts << "--author=#{opts[:author]}" if opts[:author].is_a? String arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2) arr_opts end
[ "def", "log_common_options", "(", "opts", ")", "arr_opts", "=", "[", "]", "arr_opts", "<<", "\"-#{opts[:count]}\"", "if", "opts", "[", ":count", "]", "arr_opts", "<<", "\"--no-color\"", "arr_opts", "<<", "\"--since=#{opts[:since]}\"", "if", "opts", "[", ":since", "]", ".", "is_a?", "String", "arr_opts", "<<", "\"--until=#{opts[:until]}\"", "if", "opts", "[", ":until", "]", ".", "is_a?", "String", "arr_opts", "<<", "\"--grep=#{opts[:grep]}\"", "if", "opts", "[", ":grep", "]", ".", "is_a?", "String", "arr_opts", "<<", "\"--author=#{opts[:author]}\"", "if", "opts", "[", ":author", "]", ".", "is_a?", "String", "arr_opts", "<<", "\"#{opts[:between][0].to_s}..#{opts[:between][1].to_s}\"", "if", "(", "opts", "[", ":between", "]", "&&", "opts", "[", ":between", "]", ".", "size", "==", "2", ")", "arr_opts", "end" ]
Returns an array holding the common options for the log commands @param [Hash] opts the given options @return [Array] the set of common options that the log command will use
[ "Returns", "an", "array", "holding", "the", "common", "options", "for", "the", "log", "commands" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L1016-L1028
train
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.log_path_options
def log_path_options(opts) arr_opts = [] arr_opts << opts[:object] if opts[:object].is_a? String arr_opts << '--' << opts[:path_limiter] if opts[:path_limiter] arr_opts end
ruby
def log_path_options(opts) arr_opts = [] arr_opts << opts[:object] if opts[:object].is_a? String arr_opts << '--' << opts[:path_limiter] if opts[:path_limiter] arr_opts end
[ "def", "log_path_options", "(", "opts", ")", "arr_opts", "=", "[", "]", "arr_opts", "<<", "opts", "[", ":object", "]", "if", "opts", "[", ":object", "]", ".", "is_a?", "String", "arr_opts", "<<", "'--'", "<<", "opts", "[", ":path_limiter", "]", "if", "opts", "[", ":path_limiter", "]", "arr_opts", "end" ]
Retrurns an array holding path options for the log commands @param [Hash] opts the given options @return [Array] the set of path options that the log command will use
[ "Retrurns", "an", "array", "holding", "path", "options", "for", "the", "log", "commands" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L1034-L1040
train
ruby-git/ruby-git
lib/git/base.rb
Git.Base.is_local_branch?
def is_local_branch?(branch) branch_names = self.branches.local.map {|b| b.name} branch_names.include?(branch) end
ruby
def is_local_branch?(branch) branch_names = self.branches.local.map {|b| b.name} branch_names.include?(branch) end
[ "def", "is_local_branch?", "(", "branch", ")", "branch_names", "=", "self", ".", "branches", ".", "local", ".", "map", "{", "|", "b", "|", "b", ".", "name", "}", "branch_names", ".", "include?", "(", "branch", ")", "end" ]
returns +true+ if the branch exists locally
[ "returns", "+", "true", "+", "if", "the", "branch", "exists", "locally" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/base.rb#L163-L166
train
ruby-git/ruby-git
lib/git/base.rb
Git.Base.is_remote_branch?
def is_remote_branch?(branch) branch_names = self.branches.remote.map {|b| b.name} branch_names.include?(branch) end
ruby
def is_remote_branch?(branch) branch_names = self.branches.remote.map {|b| b.name} branch_names.include?(branch) end
[ "def", "is_remote_branch?", "(", "branch", ")", "branch_names", "=", "self", ".", "branches", ".", "remote", ".", "map", "{", "|", "b", "|", "b", ".", "name", "}", "branch_names", ".", "include?", "(", "branch", ")", "end" ]
returns +true+ if the branch exists remotely
[ "returns", "+", "true", "+", "if", "the", "branch", "exists", "remotely" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/base.rb#L169-L172
train
ruby-git/ruby-git
lib/git/base.rb
Git.Base.is_branch?
def is_branch?(branch) branch_names = self.branches.map {|b| b.name} branch_names.include?(branch) end
ruby
def is_branch?(branch) branch_names = self.branches.map {|b| b.name} branch_names.include?(branch) end
[ "def", "is_branch?", "(", "branch", ")", "branch_names", "=", "self", ".", "branches", ".", "map", "{", "|", "b", "|", "b", ".", "name", "}", "branch_names", ".", "include?", "(", "branch", ")", "end" ]
returns +true+ if the branch exists
[ "returns", "+", "true", "+", "if", "the", "branch", "exists" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/base.rb#L175-L178
train
ruby-git/ruby-git
lib/git/base.rb
Git.Base.commit_all
def commit_all(message, opts = {}) opts = {:add_all => true}.merge(opts) self.lib.commit(message, opts) end
ruby
def commit_all(message, opts = {}) opts = {:add_all => true}.merge(opts) self.lib.commit(message, opts) end
[ "def", "commit_all", "(", "message", ",", "opts", "=", "{", "}", ")", "opts", "=", "{", ":add_all", "=>", "true", "}", ".", "merge", "(", "opts", ")", "self", ".", "lib", ".", "commit", "(", "message", ",", "opts", ")", "end" ]
commits all pending changes in the index file to the git repository, but automatically adds all modified files without having to explicitly calling @git.add() on them.
[ "commits", "all", "pending", "changes", "in", "the", "index", "file", "to", "the", "git", "repository", "but", "automatically", "adds", "all", "modified", "files", "without", "having", "to", "explicitly", "calling" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/base.rb#L299-L302
train
ruby-git/ruby-git
lib/git/base.rb
Git.Base.with_index
def with_index(new_index) # :yields: new_index old_index = @index set_index(new_index, false) return_value = yield @index set_index(old_index) return_value end
ruby
def with_index(new_index) # :yields: new_index old_index = @index set_index(new_index, false) return_value = yield @index set_index(old_index) return_value end
[ "def", "with_index", "(", "new_index", ")", "# :yields: new_index", "old_index", "=", "@index", "set_index", "(", "new_index", ",", "false", ")", "return_value", "=", "yield", "@index", "set_index", "(", "old_index", ")", "return_value", "end" ]
LOWER LEVEL INDEX OPERATIONS
[ "LOWER", "LEVEL", "INDEX", "OPERATIONS" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/base.rb#L456-L462
train
pythonicrubyist/creek
lib/creek/sheet.rb
Creek.Creek::Sheet.rows_generator
def rows_generator include_meta_data=false, use_simple_rows_format=false path = if @sheetfile.start_with? "/xl/" or @sheetfile.start_with? "xl/" then @sheetfile else "xl/#{@sheetfile}" end if @book.files.file.exist?(path) # SAX parsing, Each element in the stream comes through as two events: # one to open the element and one to close it. opener = Nokogiri::XML::Reader::TYPE_ELEMENT closer = Nokogiri::XML::Reader::TYPE_END_ELEMENT Enumerator.new do |y| row, cells, cell = nil, {}, nil cell_type = nil cell_style_idx = nil @book.files.file.open(path) do |xml| Nokogiri::XML::Reader.from_io(xml).each do |node| if (node.name.eql? 'row') and (node.node_type.eql? opener) row = node.attributes row['cells'] = Hash.new cells = Hash.new y << (include_meta_data ? row : cells) if node.self_closing? elsif (node.name.eql? 'row') and (node.node_type.eql? closer) processed_cells = fill_in_empty_cells(cells, row['r'], cell, use_simple_rows_format) if @images_present processed_cells.each do |cell_name, cell_value| next unless cell_value.nil? processed_cells[cell_name] = images_at(cell_name) end end row['cells'] = processed_cells y << (include_meta_data ? row : processed_cells) elsif (node.name.eql? 'c') and (node.node_type.eql? opener) cell_type = node.attributes['t'] cell_style_idx = node.attributes['s'] cell = node.attributes['r'] elsif (['v', 't'].include? node.name) and (node.node_type.eql? opener) unless cell.nil? node.read cells[(use_simple_rows_format ? cell.tr("0-9", "") : cell)] = convert(node.value, cell_type, cell_style_idx) end end end end end end end
ruby
def rows_generator include_meta_data=false, use_simple_rows_format=false path = if @sheetfile.start_with? "/xl/" or @sheetfile.start_with? "xl/" then @sheetfile else "xl/#{@sheetfile}" end if @book.files.file.exist?(path) # SAX parsing, Each element in the stream comes through as two events: # one to open the element and one to close it. opener = Nokogiri::XML::Reader::TYPE_ELEMENT closer = Nokogiri::XML::Reader::TYPE_END_ELEMENT Enumerator.new do |y| row, cells, cell = nil, {}, nil cell_type = nil cell_style_idx = nil @book.files.file.open(path) do |xml| Nokogiri::XML::Reader.from_io(xml).each do |node| if (node.name.eql? 'row') and (node.node_type.eql? opener) row = node.attributes row['cells'] = Hash.new cells = Hash.new y << (include_meta_data ? row : cells) if node.self_closing? elsif (node.name.eql? 'row') and (node.node_type.eql? closer) processed_cells = fill_in_empty_cells(cells, row['r'], cell, use_simple_rows_format) if @images_present processed_cells.each do |cell_name, cell_value| next unless cell_value.nil? processed_cells[cell_name] = images_at(cell_name) end end row['cells'] = processed_cells y << (include_meta_data ? row : processed_cells) elsif (node.name.eql? 'c') and (node.node_type.eql? opener) cell_type = node.attributes['t'] cell_style_idx = node.attributes['s'] cell = node.attributes['r'] elsif (['v', 't'].include? node.name) and (node.node_type.eql? opener) unless cell.nil? node.read cells[(use_simple_rows_format ? cell.tr("0-9", "") : cell)] = convert(node.value, cell_type, cell_style_idx) end end end end end end end
[ "def", "rows_generator", "include_meta_data", "=", "false", ",", "use_simple_rows_format", "=", "false", "path", "=", "if", "@sheetfile", ".", "start_with?", "\"/xl/\"", "or", "@sheetfile", ".", "start_with?", "\"xl/\"", "then", "@sheetfile", "else", "\"xl/#{@sheetfile}\"", "end", "if", "@book", ".", "files", ".", "file", ".", "exist?", "(", "path", ")", "# SAX parsing, Each element in the stream comes through as two events:", "# one to open the element and one to close it.", "opener", "=", "Nokogiri", "::", "XML", "::", "Reader", "::", "TYPE_ELEMENT", "closer", "=", "Nokogiri", "::", "XML", "::", "Reader", "::", "TYPE_END_ELEMENT", "Enumerator", ".", "new", "do", "|", "y", "|", "row", ",", "cells", ",", "cell", "=", "nil", ",", "{", "}", ",", "nil", "cell_type", "=", "nil", "cell_style_idx", "=", "nil", "@book", ".", "files", ".", "file", ".", "open", "(", "path", ")", "do", "|", "xml", "|", "Nokogiri", "::", "XML", "::", "Reader", ".", "from_io", "(", "xml", ")", ".", "each", "do", "|", "node", "|", "if", "(", "node", ".", "name", ".", "eql?", "'row'", ")", "and", "(", "node", ".", "node_type", ".", "eql?", "opener", ")", "row", "=", "node", ".", "attributes", "row", "[", "'cells'", "]", "=", "Hash", ".", "new", "cells", "=", "Hash", ".", "new", "y", "<<", "(", "include_meta_data", "?", "row", ":", "cells", ")", "if", "node", ".", "self_closing?", "elsif", "(", "node", ".", "name", ".", "eql?", "'row'", ")", "and", "(", "node", ".", "node_type", ".", "eql?", "closer", ")", "processed_cells", "=", "fill_in_empty_cells", "(", "cells", ",", "row", "[", "'r'", "]", ",", "cell", ",", "use_simple_rows_format", ")", "if", "@images_present", "processed_cells", ".", "each", "do", "|", "cell_name", ",", "cell_value", "|", "next", "unless", "cell_value", ".", "nil?", "processed_cells", "[", "cell_name", "]", "=", "images_at", "(", "cell_name", ")", "end", "end", "row", "[", "'cells'", "]", "=", "processed_cells", "y", "<<", "(", "include_meta_data", "?", "row", ":", "processed_cells", ")", "elsif", "(", "node", ".", "name", ".", "eql?", "'c'", ")", "and", "(", "node", ".", "node_type", ".", "eql?", "opener", ")", "cell_type", "=", "node", ".", "attributes", "[", "'t'", "]", "cell_style_idx", "=", "node", ".", "attributes", "[", "'s'", "]", "cell", "=", "node", ".", "attributes", "[", "'r'", "]", "elsif", "(", "[", "'v'", ",", "'t'", "]", ".", "include?", "node", ".", "name", ")", "and", "(", "node", ".", "node_type", ".", "eql?", "opener", ")", "unless", "cell", ".", "nil?", "node", ".", "read", "cells", "[", "(", "use_simple_rows_format", "?", "cell", ".", "tr", "(", "\"0-9\"", ",", "\"\"", ")", ":", "cell", ")", "]", "=", "convert", "(", "node", ".", "value", ",", "cell_type", ",", "cell_style_idx", ")", "end", "end", "end", "end", "end", "end", "end" ]
Returns a hash per row that includes the cell ids and values. Empty cells will be also included in the hash with a nil value.
[ "Returns", "a", "hash", "per", "row", "that", "includes", "the", "cell", "ids", "and", "values", ".", "Empty", "cells", "will", "be", "also", "included", "in", "the", "hash", "with", "a", "nil", "value", "." ]
1a5c99032ee736e8f24ebd524adffba068d236b4
https://github.com/pythonicrubyist/creek/blob/1a5c99032ee736e8f24ebd524adffba068d236b4/lib/creek/sheet.rb#L83-L127
train
pythonicrubyist/creek
lib/creek/sheet.rb
Creek.Creek::Sheet.fill_in_empty_cells
def fill_in_empty_cells(cells, row_number, last_col, use_simple_rows_format) new_cells = Hash.new unless cells.empty? last_col = last_col.gsub(row_number, '') ("A"..last_col).to_a.each do |column| id = use_simple_rows_format ? "#{column}" : "#{column}#{row_number}" new_cells[id] = cells[id] end end new_cells end
ruby
def fill_in_empty_cells(cells, row_number, last_col, use_simple_rows_format) new_cells = Hash.new unless cells.empty? last_col = last_col.gsub(row_number, '') ("A"..last_col).to_a.each do |column| id = use_simple_rows_format ? "#{column}" : "#{column}#{row_number}" new_cells[id] = cells[id] end end new_cells end
[ "def", "fill_in_empty_cells", "(", "cells", ",", "row_number", ",", "last_col", ",", "use_simple_rows_format", ")", "new_cells", "=", "Hash", ".", "new", "unless", "cells", ".", "empty?", "last_col", "=", "last_col", ".", "gsub", "(", "row_number", ",", "''", ")", "(", "\"A\"", "..", "last_col", ")", ".", "to_a", ".", "each", "do", "|", "column", "|", "id", "=", "use_simple_rows_format", "?", "\"#{column}\"", ":", "\"#{column}#{row_number}\"", "new_cells", "[", "id", "]", "=", "cells", "[", "id", "]", "end", "end", "new_cells", "end" ]
The unzipped XML file does not contain any node for empty cells. Empty cells are being padded in using this function
[ "The", "unzipped", "XML", "file", "does", "not", "contain", "any", "node", "for", "empty", "cells", ".", "Empty", "cells", "are", "being", "padded", "in", "using", "this", "function" ]
1a5c99032ee736e8f24ebd524adffba068d236b4
https://github.com/pythonicrubyist/creek/blob/1a5c99032ee736e8f24ebd524adffba068d236b4/lib/creek/sheet.rb#L144-L157
train
pythonicrubyist/creek
lib/creek/sheet.rb
Creek.Creek::Sheet.extract_drawing_filepath
def extract_drawing_filepath # Read drawing relationship ID from the sheet. sheet_filepath = "xl/#{@sheetfile}" drawing = parse_xml(sheet_filepath).css('drawing').first return if drawing.nil? drawing_rid = drawing.attributes['id'].value # Read sheet rels to find drawing file's location. sheet_rels_filepath = expand_to_rels_path(sheet_filepath) parse_xml(sheet_rels_filepath).css("Relationship[@Id='#{drawing_rid}']").first.attributes['Target'].value end
ruby
def extract_drawing_filepath # Read drawing relationship ID from the sheet. sheet_filepath = "xl/#{@sheetfile}" drawing = parse_xml(sheet_filepath).css('drawing').first return if drawing.nil? drawing_rid = drawing.attributes['id'].value # Read sheet rels to find drawing file's location. sheet_rels_filepath = expand_to_rels_path(sheet_filepath) parse_xml(sheet_rels_filepath).css("Relationship[@Id='#{drawing_rid}']").first.attributes['Target'].value end
[ "def", "extract_drawing_filepath", "# Read drawing relationship ID from the sheet.", "sheet_filepath", "=", "\"xl/#{@sheetfile}\"", "drawing", "=", "parse_xml", "(", "sheet_filepath", ")", ".", "css", "(", "'drawing'", ")", ".", "first", "return", "if", "drawing", ".", "nil?", "drawing_rid", "=", "drawing", ".", "attributes", "[", "'id'", "]", ".", "value", "# Read sheet rels to find drawing file's location.", "sheet_rels_filepath", "=", "expand_to_rels_path", "(", "sheet_filepath", ")", "parse_xml", "(", "sheet_rels_filepath", ")", ".", "css", "(", "\"Relationship[@Id='#{drawing_rid}']\"", ")", ".", "first", ".", "attributes", "[", "'Target'", "]", ".", "value", "end" ]
Find drawing filepath for the current sheet. Sheet xml contains drawing relationship ID. Sheet relationships xml contains drawing file's location.
[ "Find", "drawing", "filepath", "for", "the", "current", "sheet", ".", "Sheet", "xml", "contains", "drawing", "relationship", "ID", ".", "Sheet", "relationships", "xml", "contains", "drawing", "file", "s", "location", "." ]
1a5c99032ee736e8f24ebd524adffba068d236b4
https://github.com/pythonicrubyist/creek/blob/1a5c99032ee736e8f24ebd524adffba068d236b4/lib/creek/sheet.rb#L163-L174
train
rollbar/rollbar-gem
lib/rollbar/notifier.rb
Rollbar.Notifier.log
def log(level, *args) return 'disabled' unless enabled? message, exception, extra, context = extract_arguments(args) use_exception_level_filters = use_exception_level_filters?(extra) return 'ignored' if ignored?(exception, use_exception_level_filters) begin status = call_before_process(:level => level, :exception => exception, :message => message, :extra => extra) return 'ignored' if status == 'ignored' rescue Rollbar::Ignore return 'ignored' end level = lookup_exception_level(level, exception, use_exception_level_filters) begin report(level, message, exception, extra, context) rescue StandardError, SystemStackError => e report_internal_error(e) 'error' end end
ruby
def log(level, *args) return 'disabled' unless enabled? message, exception, extra, context = extract_arguments(args) use_exception_level_filters = use_exception_level_filters?(extra) return 'ignored' if ignored?(exception, use_exception_level_filters) begin status = call_before_process(:level => level, :exception => exception, :message => message, :extra => extra) return 'ignored' if status == 'ignored' rescue Rollbar::Ignore return 'ignored' end level = lookup_exception_level(level, exception, use_exception_level_filters) begin report(level, message, exception, extra, context) rescue StandardError, SystemStackError => e report_internal_error(e) 'error' end end
[ "def", "log", "(", "level", ",", "*", "args", ")", "return", "'disabled'", "unless", "enabled?", "message", ",", "exception", ",", "extra", ",", "context", "=", "extract_arguments", "(", "args", ")", "use_exception_level_filters", "=", "use_exception_level_filters?", "(", "extra", ")", "return", "'ignored'", "if", "ignored?", "(", "exception", ",", "use_exception_level_filters", ")", "begin", "status", "=", "call_before_process", "(", ":level", "=>", "level", ",", ":exception", "=>", "exception", ",", ":message", "=>", "message", ",", ":extra", "=>", "extra", ")", "return", "'ignored'", "if", "status", "==", "'ignored'", "rescue", "Rollbar", "::", "Ignore", "return", "'ignored'", "end", "level", "=", "lookup_exception_level", "(", "level", ",", "exception", ",", "use_exception_level_filters", ")", "begin", "report", "(", "level", ",", "message", ",", "exception", ",", "extra", ",", "context", ")", "rescue", "StandardError", ",", "SystemStackError", "=>", "e", "report_internal_error", "(", "e", ")", "'error'", "end", "end" ]
Sends a report to Rollbar. Accepts any number of arguments. The last String argument will become the message or description of the report. The last Exception argument will become the associated exception for the report. The last hash argument will be used as the extra data for the report. If the extra hash contains a symbol key :custom_data_method_context the value of the key will be used as the context for configuration.custom_data_method and will be removed from the extra hash. @example begin foo = bar rescue => e Rollbar.log(e) end @example Rollbar.log('This is a simple log message') @example Rollbar.log(e, 'This is a description of the exception')
[ "Sends", "a", "report", "to", "Rollbar", "." ]
83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6
https://github.com/rollbar/rollbar-gem/blob/83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6/lib/rollbar/notifier.rb#L129-L157
train
rollbar/rollbar-gem
lib/rollbar/notifier.rb
Rollbar.Notifier.process_from_async_handler
def process_from_async_handler(payload) payload = Rollbar::JSON.load(payload) if payload.is_a?(String) item = Item.build_with(payload, :notifier => self, :configuration => configuration, :logger => logger) Rollbar.silenced do begin process_item(item) rescue StandardError => e report_internal_error(e) raise end end end
ruby
def process_from_async_handler(payload) payload = Rollbar::JSON.load(payload) if payload.is_a?(String) item = Item.build_with(payload, :notifier => self, :configuration => configuration, :logger => logger) Rollbar.silenced do begin process_item(item) rescue StandardError => e report_internal_error(e) raise end end end
[ "def", "process_from_async_handler", "(", "payload", ")", "payload", "=", "Rollbar", "::", "JSON", ".", "load", "(", "payload", ")", "if", "payload", ".", "is_a?", "(", "String", ")", "item", "=", "Item", ".", "build_with", "(", "payload", ",", ":notifier", "=>", "self", ",", ":configuration", "=>", "configuration", ",", ":logger", "=>", "logger", ")", "Rollbar", ".", "silenced", "do", "begin", "process_item", "(", "item", ")", "rescue", "StandardError", "=>", "e", "report_internal_error", "(", "e", ")", "raise", "end", "end", "end" ]
We will reraise exceptions in this method so async queues can retry the job or, in general, handle an error report some way. At same time that exception is silenced so we don't generate infinite reports. This example is what we want to avoid: 1. New exception in a the project is raised 2. That report enqueued to Sidekiq queue. 3. The Sidekiq job tries to send the report to our API 4. The report fails, for example cause a network failure, and a exception is raised 5. We report an internal error for that exception 6. We reraise the exception so Sidekiq job fails and Sidekiq can retry the job reporting the original exception 7. Because the job failed and Sidekiq can be managed by rollbar we'll report a new exception. 8. Go to point 2. We'll then push to Sidekiq queue indefinitely until the network failure is fixed. Using Rollbar.silenced we avoid the above behavior but Sidekiq will have a chance to retry the original job.
[ "We", "will", "reraise", "exceptions", "in", "this", "method", "so", "async", "queues", "can", "retry", "the", "job", "or", "in", "general", "handle", "an", "error", "report", "some", "way", "." ]
83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6
https://github.com/rollbar/rollbar-gem/blob/83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6/lib/rollbar/notifier.rb#L234-L251
train
rollbar/rollbar-gem
lib/rollbar/notifier.rb
Rollbar.Notifier.report_internal_error
def report_internal_error(exception) log_error '[Rollbar] Reporting internal error encountered while sending data to Rollbar.' configuration.execute_hook(:on_report_internal_error, exception) begin item = build_item('error', nil, exception, { :internal => true }, nil) rescue StandardError => e send_failsafe('build_item in exception_data', e) log_error "[Rollbar] Exception: #{exception}" return end begin process_item(item) rescue StandardError => e send_failsafe('error in process_item', e) log_error "[Rollbar] Item: #{item}" return end begin log_instance_link(item['data']) rescue StandardError => e send_failsafe('error logging instance link', e) log_error "[Rollbar] Item: #{item}" return end end
ruby
def report_internal_error(exception) log_error '[Rollbar] Reporting internal error encountered while sending data to Rollbar.' configuration.execute_hook(:on_report_internal_error, exception) begin item = build_item('error', nil, exception, { :internal => true }, nil) rescue StandardError => e send_failsafe('build_item in exception_data', e) log_error "[Rollbar] Exception: #{exception}" return end begin process_item(item) rescue StandardError => e send_failsafe('error in process_item', e) log_error "[Rollbar] Item: #{item}" return end begin log_instance_link(item['data']) rescue StandardError => e send_failsafe('error logging instance link', e) log_error "[Rollbar] Item: #{item}" return end end
[ "def", "report_internal_error", "(", "exception", ")", "log_error", "'[Rollbar] Reporting internal error encountered while sending data to Rollbar.'", "configuration", ".", "execute_hook", "(", ":on_report_internal_error", ",", "exception", ")", "begin", "item", "=", "build_item", "(", "'error'", ",", "nil", ",", "exception", ",", "{", ":internal", "=>", "true", "}", ",", "nil", ")", "rescue", "StandardError", "=>", "e", "send_failsafe", "(", "'build_item in exception_data'", ",", "e", ")", "log_error", "\"[Rollbar] Exception: #{exception}\"", "return", "end", "begin", "process_item", "(", "item", ")", "rescue", "StandardError", "=>", "e", "send_failsafe", "(", "'error in process_item'", ",", "e", ")", "log_error", "\"[Rollbar] Item: #{item}\"", "return", "end", "begin", "log_instance_link", "(", "item", "[", "'data'", "]", ")", "rescue", "StandardError", "=>", "e", "send_failsafe", "(", "'error logging instance link'", ",", "e", ")", "log_error", "\"[Rollbar] Item: #{item}\"", "return", "end", "end" ]
Reports an internal error in the Rollbar library. This will be reported within the configured Rollbar project. We'll first attempt to provide a report including the exception traceback. If that fails, we'll fall back to a more static failsafe response.
[ "Reports", "an", "internal", "error", "in", "the", "Rollbar", "library", ".", "This", "will", "be", "reported", "within", "the", "configured", "Rollbar", "project", ".", "We", "ll", "first", "attempt", "to", "provide", "a", "report", "including", "the", "exception", "traceback", ".", "If", "that", "fails", "we", "ll", "fall", "back", "to", "a", "more", "static", "failsafe", "response", "." ]
83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6
https://github.com/rollbar/rollbar-gem/blob/83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6/lib/rollbar/notifier.rb#L444-L472
train
rollbar/rollbar-gem
lib/rollbar/notifier.rb
Rollbar.Notifier.build_item
def build_item(level, message, exception, extra, context) options = { :level => level, :message => message, :exception => exception, :extra => extra, :configuration => configuration, :logger => logger, :scope => scope_object, :notifier => self, :context => context } item = Item.new(options) item.build item end
ruby
def build_item(level, message, exception, extra, context) options = { :level => level, :message => message, :exception => exception, :extra => extra, :configuration => configuration, :logger => logger, :scope => scope_object, :notifier => self, :context => context } item = Item.new(options) item.build item end
[ "def", "build_item", "(", "level", ",", "message", ",", "exception", ",", "extra", ",", "context", ")", "options", "=", "{", ":level", "=>", "level", ",", ":message", "=>", "message", ",", ":exception", "=>", "exception", ",", ":extra", "=>", "extra", ",", ":configuration", "=>", "configuration", ",", ":logger", "=>", "logger", ",", ":scope", "=>", "scope_object", ",", ":notifier", "=>", "self", ",", ":context", "=>", "context", "}", "item", "=", "Item", ".", "new", "(", "options", ")", "item", ".", "build", "item", "end" ]
Payload building functions
[ "Payload", "building", "functions" ]
83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6
https://github.com/rollbar/rollbar-gem/blob/83ef1acca2b0b1d1b74ff8ef29435ca82e8ca1d6/lib/rollbar/notifier.rb#L476-L493
train
plum-umd/rdl
lib/rdl/typecheck.rb
RDL::Typecheck.Env.bind
def bind(var, typ, force: false) raise RuntimeError, "Can't update variable with fixed type" if !force && @env[var] && @env[var][:fixed] result = Env.new result.env = @env.merge(var => {type: typ, fixed: false}) return result end
ruby
def bind(var, typ, force: false) raise RuntimeError, "Can't update variable with fixed type" if !force && @env[var] && @env[var][:fixed] result = Env.new result.env = @env.merge(var => {type: typ, fixed: false}) return result end
[ "def", "bind", "(", "var", ",", "typ", ",", "force", ":", "false", ")", "raise", "RuntimeError", ",", "\"Can't update variable with fixed type\"", "if", "!", "force", "&&", "@env", "[", "var", "]", "&&", "@env", "[", "var", "]", "[", ":fixed", "]", "result", "=", "Env", ".", "new", "result", ".", "env", "=", "@env", ".", "merge", "(", "var", "=>", "{", "type", ":", "typ", ",", "fixed", ":", "false", "}", ")", "return", "result", "end" ]
force should only be used with care! currently only used when type is being refined to a subtype in a lexical scope
[ "force", "should", "only", "be", "used", "with", "care!", "currently", "only", "used", "when", "type", "is", "being", "refined", "to", "a", "subtype", "in", "a", "lexical", "scope" ]
c00134413f7a600fd395e7e7cd8b01f57f850830
https://github.com/plum-umd/rdl/blob/c00134413f7a600fd395e7e7cd8b01f57f850830/lib/rdl/typecheck.rb#L69-L74
train
plum-umd/rdl
lib/rdl/typecheck.rb
RDL::Typecheck.Env.merge
def merge(other) result = Env.new result.env = @env.merge(other.env) return result end
ruby
def merge(other) result = Env.new result.env = @env.merge(other.env) return result end
[ "def", "merge", "(", "other", ")", "result", "=", "Env", ".", "new", "result", ".", "env", "=", "@env", ".", "merge", "(", "other", ".", "env", ")", "return", "result", "end" ]
merges bindings in self with bindings in other, preferring bindings in other if there is a common key
[ "merges", "bindings", "in", "self", "with", "bindings", "in", "other", "preferring", "bindings", "in", "other", "if", "there", "is", "a", "common", "key" ]
c00134413f7a600fd395e7e7cd8b01f57f850830
https://github.com/plum-umd/rdl/blob/c00134413f7a600fd395e7e7cd8b01f57f850830/lib/rdl/typecheck.rb#L97-L101
train
plum-umd/rdl
lib/rdl/types/method.rb
RDL::Type.MethodType.match
def match(other) other = other.type if other.instance_of? AnnotatedArgType return true if other.instance_of? WildQuery return false unless other.instance_of? MethodType return false unless @ret.match(other.ret) if @block == nil return false unless other.block == nil else return false if other.block == nil return false unless @block.match(other.block) end # Check arg matches; logic is similar to pre_cond states = [[0,0]] # [position in self, position in other] until states.empty? s_arg, o_arg = states.pop return true if s_arg == @args.size && o_arg == other.args.size # everything matches next if s_arg >= @args.size # match not possible, not enough args in self if @args[s_arg].instance_of? DotsQuery then if o_arg == other.args.size # no args left in other, skip ... states << [s_arg+1, o_arg] else states << [s_arg+1, o_arg+1] # match, no more matches to ... states << [s_arg, o_arg+1] # match, more matches to ... coming end else next if o_arg == other.args.size # match not possible, not enough args in other s_arg_t = @args[s_arg] s_arg_t = s_arg_t.type if s_arg_t.instance_of? AnnotatedArgType o_arg_t = other.args[o_arg] o_arg_t = o_arg_t.type if o_arg_t.instance_of? AnnotatedArgType next unless s_arg_t.match(o_arg_t) states << [s_arg+1, o_arg+1] end end return false end
ruby
def match(other) other = other.type if other.instance_of? AnnotatedArgType return true if other.instance_of? WildQuery return false unless other.instance_of? MethodType return false unless @ret.match(other.ret) if @block == nil return false unless other.block == nil else return false if other.block == nil return false unless @block.match(other.block) end # Check arg matches; logic is similar to pre_cond states = [[0,0]] # [position in self, position in other] until states.empty? s_arg, o_arg = states.pop return true if s_arg == @args.size && o_arg == other.args.size # everything matches next if s_arg >= @args.size # match not possible, not enough args in self if @args[s_arg].instance_of? DotsQuery then if o_arg == other.args.size # no args left in other, skip ... states << [s_arg+1, o_arg] else states << [s_arg+1, o_arg+1] # match, no more matches to ... states << [s_arg, o_arg+1] # match, more matches to ... coming end else next if o_arg == other.args.size # match not possible, not enough args in other s_arg_t = @args[s_arg] s_arg_t = s_arg_t.type if s_arg_t.instance_of? AnnotatedArgType o_arg_t = other.args[o_arg] o_arg_t = o_arg_t.type if o_arg_t.instance_of? AnnotatedArgType next unless s_arg_t.match(o_arg_t) states << [s_arg+1, o_arg+1] end end return false end
[ "def", "match", "(", "other", ")", "other", "=", "other", ".", "type", "if", "other", ".", "instance_of?", "AnnotatedArgType", "return", "true", "if", "other", ".", "instance_of?", "WildQuery", "return", "false", "unless", "other", ".", "instance_of?", "MethodType", "return", "false", "unless", "@ret", ".", "match", "(", "other", ".", "ret", ")", "if", "@block", "==", "nil", "return", "false", "unless", "other", ".", "block", "==", "nil", "else", "return", "false", "if", "other", ".", "block", "==", "nil", "return", "false", "unless", "@block", ".", "match", "(", "other", ".", "block", ")", "end", "# Check arg matches; logic is similar to pre_cond", "states", "=", "[", "[", "0", ",", "0", "]", "]", "# [position in self, position in other]", "until", "states", ".", "empty?", "s_arg", ",", "o_arg", "=", "states", ".", "pop", "return", "true", "if", "s_arg", "==", "@args", ".", "size", "&&", "o_arg", "==", "other", ".", "args", ".", "size", "# everything matches", "next", "if", "s_arg", ">=", "@args", ".", "size", "# match not possible, not enough args in self", "if", "@args", "[", "s_arg", "]", ".", "instance_of?", "DotsQuery", "then", "if", "o_arg", "==", "other", ".", "args", ".", "size", "# no args left in other, skip ...", "states", "<<", "[", "s_arg", "+", "1", ",", "o_arg", "]", "else", "states", "<<", "[", "s_arg", "+", "1", ",", "o_arg", "+", "1", "]", "# match, no more matches to ...", "states", "<<", "[", "s_arg", ",", "o_arg", "+", "1", "]", "# match, more matches to ... coming", "end", "else", "next", "if", "o_arg", "==", "other", ".", "args", ".", "size", "# match not possible, not enough args in other", "s_arg_t", "=", "@args", "[", "s_arg", "]", "s_arg_t", "=", "s_arg_t", ".", "type", "if", "s_arg_t", ".", "instance_of?", "AnnotatedArgType", "o_arg_t", "=", "other", ".", "args", "[", "o_arg", "]", "o_arg_t", "=", "o_arg_t", ".", "type", "if", "o_arg_t", ".", "instance_of?", "AnnotatedArgType", "next", "unless", "s_arg_t", ".", "match", "(", "o_arg_t", ")", "states", "<<", "[", "s_arg", "+", "1", ",", "o_arg", "+", "1", "]", "end", "end", "return", "false", "end" ]
other may not be a query
[ "other", "may", "not", "be", "a", "query" ]
c00134413f7a600fd395e7e7cd8b01f57f850830
https://github.com/plum-umd/rdl/blob/c00134413f7a600fd395e7e7cd8b01f57f850830/lib/rdl/types/method.rb#L308-L344
train
spohlenz/tinymce-rails
lib/tinymce/rails/helper.rb
TinyMCE::Rails.Helper.tinymce
def tinymce(config=:default, options={}) javascript_tag(nonce: true) do unless @_tinymce_configurations_added concat tinymce_configurations_javascript concat "\n" @_tinymce_configurations_added = true end concat tinymce_javascript(config, options) end end
ruby
def tinymce(config=:default, options={}) javascript_tag(nonce: true) do unless @_tinymce_configurations_added concat tinymce_configurations_javascript concat "\n" @_tinymce_configurations_added = true end concat tinymce_javascript(config, options) end end
[ "def", "tinymce", "(", "config", "=", ":default", ",", "options", "=", "{", "}", ")", "javascript_tag", "(", "nonce", ":", "true", ")", "do", "unless", "@_tinymce_configurations_added", "concat", "tinymce_configurations_javascript", "concat", "\"\\n\"", "@_tinymce_configurations_added", "=", "true", "end", "concat", "tinymce_javascript", "(", "config", ",", "options", ")", "end", "end" ]
Initializes TinyMCE on the current page based on the global configuration. Custom options can be set via the options hash, which will be passed to the TinyMCE init function. By default, all textareas with a class of "tinymce" will have the TinyMCE editor applied. The current locale will also be used as the language when TinyMCE language files are available, falling back to English if not available. The :editor_selector and :language options can be used to override these defaults. @example <%= tinymce(selector: "editorClass", theme: "inlite") %>
[ "Initializes", "TinyMCE", "on", "the", "current", "page", "based", "on", "the", "global", "configuration", "." ]
6f94b295f030939c8b3c7739f13812e42e6d920a
https://github.com/spohlenz/tinymce-rails/blob/6f94b295f030939c8b3c7739f13812e42e6d920a/lib/tinymce/rails/helper.rb#L18-L28
train
spohlenz/tinymce-rails
lib/tinymce/rails/helper.rb
TinyMCE::Rails.Helper.tinymce_javascript
def tinymce_javascript(config=:default, options={}) options, config = config, :default if config.is_a?(Hash) options = Configuration.new(options) "TinyMCERails.initialize('#{config}', #{options.to_javascript});".html_safe end
ruby
def tinymce_javascript(config=:default, options={}) options, config = config, :default if config.is_a?(Hash) options = Configuration.new(options) "TinyMCERails.initialize('#{config}', #{options.to_javascript});".html_safe end
[ "def", "tinymce_javascript", "(", "config", "=", ":default", ",", "options", "=", "{", "}", ")", "options", ",", "config", "=", "config", ",", ":default", "if", "config", ".", "is_a?", "(", "Hash", ")", "options", "=", "Configuration", ".", "new", "(", "options", ")", "\"TinyMCERails.initialize('#{config}', #{options.to_javascript});\"", ".", "html_safe", "end" ]
Returns the JavaScript code required to initialize TinyMCE.
[ "Returns", "the", "JavaScript", "code", "required", "to", "initialize", "TinyMCE", "." ]
6f94b295f030939c8b3c7739f13812e42e6d920a
https://github.com/spohlenz/tinymce-rails/blob/6f94b295f030939c8b3c7739f13812e42e6d920a/lib/tinymce/rails/helper.rb#L31-L36
train
spohlenz/tinymce-rails
lib/tinymce/rails/helper.rb
TinyMCE::Rails.Helper.tinymce_configurations_javascript
def tinymce_configurations_javascript(options={}) javascript = [] TinyMCE::Rails.each_configuration do |name, config| config = config.merge(options) if options.present? javascript << "TinyMCERails.configuration.#{name} = #{config.to_javascript};".html_safe end safe_join(javascript, "\n") end
ruby
def tinymce_configurations_javascript(options={}) javascript = [] TinyMCE::Rails.each_configuration do |name, config| config = config.merge(options) if options.present? javascript << "TinyMCERails.configuration.#{name} = #{config.to_javascript};".html_safe end safe_join(javascript, "\n") end
[ "def", "tinymce_configurations_javascript", "(", "options", "=", "{", "}", ")", "javascript", "=", "[", "]", "TinyMCE", "::", "Rails", ".", "each_configuration", "do", "|", "name", ",", "config", "|", "config", "=", "config", ".", "merge", "(", "options", ")", "if", "options", ".", "present?", "javascript", "<<", "\"TinyMCERails.configuration.#{name} = #{config.to_javascript};\"", ".", "html_safe", "end", "safe_join", "(", "javascript", ",", "\"\\n\"", ")", "end" ]
Returns the JavaScript code for initializing each configuration defined within tinymce.yml.
[ "Returns", "the", "JavaScript", "code", "for", "initializing", "each", "configuration", "defined", "within", "tinymce", ".", "yml", "." ]
6f94b295f030939c8b3c7739f13812e42e6d920a
https://github.com/spohlenz/tinymce-rails/blob/6f94b295f030939c8b3c7739f13812e42e6d920a/lib/tinymce/rails/helper.rb#L39-L48
train
devise-security/devise-security
lib/devise-security/routes.rb
ActionDispatch::Routing.Mapper.devise_verification_code
def devise_verification_code(mapping, controllers) resource :paranoid_verification_code, only: [:show, :update], path: mapping.path_names[:verification_code], controller: controllers[:paranoid_verification_code] end
ruby
def devise_verification_code(mapping, controllers) resource :paranoid_verification_code, only: [:show, :update], path: mapping.path_names[:verification_code], controller: controllers[:paranoid_verification_code] end
[ "def", "devise_verification_code", "(", "mapping", ",", "controllers", ")", "resource", ":paranoid_verification_code", ",", "only", ":", "[", ":show", ",", ":update", "]", ",", "path", ":", "mapping", ".", "path_names", "[", ":verification_code", "]", ",", "controller", ":", "controllers", "[", ":paranoid_verification_code", "]", "end" ]
route for handle paranoid verification
[ "route", "for", "handle", "paranoid", "verification" ]
d0b44a7bb249f6763641f45d34dd52e7fda3fca2
https://github.com/devise-security/devise-security/blob/d0b44a7bb249f6763641f45d34dd52e7fda3fca2/lib/devise-security/routes.rb#L14-L16
train
devise-security/devise-security
lib/devise-security/models/password_expirable.rb
Devise::Models.PasswordExpirable.password_too_old?
def password_too_old? return false if new_record? return false unless password_expiration_enabled? return false if expire_password_on_demand? password_changed_at < expire_password_after.seconds.ago end
ruby
def password_too_old? return false if new_record? return false unless password_expiration_enabled? return false if expire_password_on_demand? password_changed_at < expire_password_after.seconds.ago end
[ "def", "password_too_old?", "return", "false", "if", "new_record?", "return", "false", "unless", "password_expiration_enabled?", "return", "false", "if", "expire_password_on_demand?", "password_changed_at", "<", "expire_password_after", ".", "seconds", ".", "ago", "end" ]
Is this password older than the configured expiration timeout? @return [Boolean]
[ "Is", "this", "password", "older", "than", "the", "configured", "expiration", "timeout?" ]
d0b44a7bb249f6763641f45d34dd52e7fda3fca2
https://github.com/devise-security/devise-security/blob/d0b44a7bb249f6763641f45d34dd52e7fda3fca2/lib/devise-security/models/password_expirable.rb#L81-L87
train
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
MetaTags.ViewHelper.title
def title(title = nil, headline = '') set_meta_tags(title: title) unless title.nil? headline.presence || meta_tags[:title] end
ruby
def title(title = nil, headline = '') set_meta_tags(title: title) unless title.nil? headline.presence || meta_tags[:title] end
[ "def", "title", "(", "title", "=", "nil", ",", "headline", "=", "''", ")", "set_meta_tags", "(", "title", ":", "title", ")", "unless", "title", ".", "nil?", "headline", ".", "presence", "||", "meta_tags", "[", ":title", "]", "end" ]
Set the page title and return it back. This method is best suited for use in helpers. It sets the page title and returns it (or +headline+ if specified). @param [nil, String, Array] title page title. When passed as an +Array+, parts will be joined using configured separator value (see {#display_meta_tags}). When nil, current title will be returned. @param [String] headline the value to return from method. Useful for using this method in views to set both page title and the content of heading tag. @return [String] returns +title+ value or +headline+ if passed. @example Set HTML title to "Please login", return "Please login" title 'Login Page' @example Set HTML title to "Login Page", return "Please login" title 'Login Page', 'Please login' @example Set title as array of strings title title: ['part1', 'part2'] # => "part1 | part2" @example Get current title title @see #display_meta_tags
[ "Set", "the", "page", "title", "and", "return", "it", "back", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/view_helper.rb#L58-L61
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.update
def update(object = {}) meta_tags = object.respond_to?(:to_meta_tags) ? object.to_meta_tags : object @meta_tags.deep_merge! normalize_open_graph(meta_tags) end
ruby
def update(object = {}) meta_tags = object.respond_to?(:to_meta_tags) ? object.to_meta_tags : object @meta_tags.deep_merge! normalize_open_graph(meta_tags) end
[ "def", "update", "(", "object", "=", "{", "}", ")", "meta_tags", "=", "object", ".", "respond_to?", "(", ":to_meta_tags", ")", "?", "object", ".", "to_meta_tags", ":", "object", "@meta_tags", ".", "deep_merge!", "normalize_open_graph", "(", "meta_tags", ")", "end" ]
Recursively merges a Hash of meta tag attributes into current list. @param [Hash, #to_meta_tags] object Hash of meta tags (or object responding to #to_meta_tags and returning a hash) to merge into the current list. @return [Hash] result of the merge.
[ "Recursively", "merges", "a", "Hash", "of", "meta", "tag", "attributes", "into", "current", "list", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L40-L43
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.extract_full_title
def extract_full_title site_title = extract(:site) || '' title = extract_title || [] separator = extract_separator reverse = extract(:reverse) == true TextNormalizer.normalize_title(site_title, title, separator, reverse) end
ruby
def extract_full_title site_title = extract(:site) || '' title = extract_title || [] separator = extract_separator reverse = extract(:reverse) == true TextNormalizer.normalize_title(site_title, title, separator, reverse) end
[ "def", "extract_full_title", "site_title", "=", "extract", "(", ":site", ")", "||", "''", "title", "=", "extract_title", "||", "[", "]", "separator", "=", "extract_separator", "reverse", "=", "extract", "(", ":reverse", ")", "==", "true", "TextNormalizer", ".", "normalize_title", "(", "site_title", ",", "title", ",", "separator", ",", "reverse", ")", "end" ]
Extracts full page title and deletes all related meta tags. @return [String] page title.
[ "Extracts", "full", "page", "title", "and", "deletes", "all", "related", "meta", "tags", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L100-L107
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.extract_title
def extract_title title = extract(:title).presence return unless title title = Array(title) return title.map(&:downcase) if extract(:lowercase) == true title end
ruby
def extract_title title = extract(:title).presence return unless title title = Array(title) return title.map(&:downcase) if extract(:lowercase) == true title end
[ "def", "extract_title", "title", "=", "extract", "(", ":title", ")", ".", "presence", "return", "unless", "title", "title", "=", "Array", "(", "title", ")", "return", "title", ".", "map", "(", ":downcase", ")", "if", "extract", "(", ":lowercase", ")", "==", "true", "title", "end" ]
Extracts page title as an array of segments without site title and separators. @return [Array<String>] segments of page title.
[ "Extracts", "page", "title", "as", "an", "array", "of", "segments", "without", "site", "title", "and", "separators", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L113-L121
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.extract_separator
def extract_separator if meta_tags[:separator] == false # Special case: if separator is hidden, do not display suffix/prefix prefix = separator = suffix = '' else prefix = extract_separator_section(:prefix, ' ') separator = extract_separator_section(:separator, '|') suffix = extract_separator_section(:suffix, ' ') end delete(:separator, :prefix, :suffix) TextNormalizer.safe_join([prefix, separator, suffix], '') end
ruby
def extract_separator if meta_tags[:separator] == false # Special case: if separator is hidden, do not display suffix/prefix prefix = separator = suffix = '' else prefix = extract_separator_section(:prefix, ' ') separator = extract_separator_section(:separator, '|') suffix = extract_separator_section(:suffix, ' ') end delete(:separator, :prefix, :suffix) TextNormalizer.safe_join([prefix, separator, suffix], '') end
[ "def", "extract_separator", "if", "meta_tags", "[", ":separator", "]", "==", "false", "# Special case: if separator is hidden, do not display suffix/prefix", "prefix", "=", "separator", "=", "suffix", "=", "''", "else", "prefix", "=", "extract_separator_section", "(", ":prefix", ",", "' '", ")", "separator", "=", "extract_separator_section", "(", ":separator", ",", "'|'", ")", "suffix", "=", "extract_separator_section", "(", ":suffix", ",", "' '", ")", "end", "delete", "(", ":separator", ",", ":prefix", ",", ":suffix", ")", "TextNormalizer", ".", "safe_join", "(", "[", "prefix", ",", "separator", ",", "suffix", "]", ",", "''", ")", "end" ]
Extracts title separator as a string. @return [String] page title separator.
[ "Extracts", "title", "separator", "as", "a", "string", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L127-L139
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.extract_noindex
def extract_noindex noindex_name, noindex_value = extract_noindex_attribute(:noindex) index_name, index_value = extract_noindex_attribute(:index) nofollow_name, nofollow_value = extract_noindex_attribute(:nofollow) follow_name, follow_value = extract_noindex_attribute(:follow) noindex_attributes = if noindex_name == follow_name && (noindex_value || follow_value) # noindex has higher priority than index and follow has higher priority than nofollow [ [noindex_name, noindex_value || index_value], [follow_name, follow_value || nofollow_value], ] else [ [index_name, index_value], [follow_name, follow_value], [noindex_name, noindex_value], [nofollow_name, nofollow_value], ] end append_noarchive_attribute group_attributes_by_key noindex_attributes end
ruby
def extract_noindex noindex_name, noindex_value = extract_noindex_attribute(:noindex) index_name, index_value = extract_noindex_attribute(:index) nofollow_name, nofollow_value = extract_noindex_attribute(:nofollow) follow_name, follow_value = extract_noindex_attribute(:follow) noindex_attributes = if noindex_name == follow_name && (noindex_value || follow_value) # noindex has higher priority than index and follow has higher priority than nofollow [ [noindex_name, noindex_value || index_value], [follow_name, follow_value || nofollow_value], ] else [ [index_name, index_value], [follow_name, follow_value], [noindex_name, noindex_value], [nofollow_name, nofollow_value], ] end append_noarchive_attribute group_attributes_by_key noindex_attributes end
[ "def", "extract_noindex", "noindex_name", ",", "noindex_value", "=", "extract_noindex_attribute", "(", ":noindex", ")", "index_name", ",", "index_value", "=", "extract_noindex_attribute", "(", ":index", ")", "nofollow_name", ",", "nofollow_value", "=", "extract_noindex_attribute", "(", ":nofollow", ")", "follow_name", ",", "follow_value", "=", "extract_noindex_attribute", "(", ":follow", ")", "noindex_attributes", "=", "if", "noindex_name", "==", "follow_name", "&&", "(", "noindex_value", "||", "follow_value", ")", "# noindex has higher priority than index and follow has higher priority than nofollow", "[", "[", "noindex_name", ",", "noindex_value", "||", "index_value", "]", ",", "[", "follow_name", ",", "follow_value", "||", "nofollow_value", "]", ",", "]", "else", "[", "[", "index_name", ",", "index_value", "]", ",", "[", "follow_name", ",", "follow_value", "]", ",", "[", "noindex_name", ",", "noindex_value", "]", ",", "[", "nofollow_name", ",", "nofollow_value", "]", ",", "]", "end", "append_noarchive_attribute", "group_attributes_by_key", "noindex_attributes", "end" ]
Extracts noindex settings as a Hash mapping noindex tag name to value. @return [Hash<String,String>] noindex attributes.
[ "Extracts", "noindex", "settings", "as", "a", "Hash", "mapping", "noindex", "tag", "name", "to", "value", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L145-L167
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.extract_noindex_attribute
def extract_noindex_attribute(name) noindex = extract(name) noindex_name = noindex.kind_of?(String) ? noindex : 'robots' noindex_value = noindex ? name.to_s : nil [ noindex_name, noindex_value ] end
ruby
def extract_noindex_attribute(name) noindex = extract(name) noindex_name = noindex.kind_of?(String) ? noindex : 'robots' noindex_value = noindex ? name.to_s : nil [ noindex_name, noindex_value ] end
[ "def", "extract_noindex_attribute", "(", "name", ")", "noindex", "=", "extract", "(", "name", ")", "noindex_name", "=", "noindex", ".", "kind_of?", "(", "String", ")", "?", "noindex", ":", "'robots'", "noindex_value", "=", "noindex", "?", "name", ".", "to_s", ":", "nil", "[", "noindex_name", ",", "noindex_value", "]", "end" ]
Extracts noindex attribute name and value without deleting it from meta tags list. @param [String, Symbol] name noindex attribute name. @return [Array<String>] pair of noindex attribute name and value.
[ "Extracts", "noindex", "attribute", "name", "and", "value", "without", "deleting", "it", "from", "meta", "tags", "list", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L198-L204
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.append_noarchive_attribute
def append_noarchive_attribute(noindex) noarchive_name, noarchive_value = extract_noindex_attribute :noarchive if noarchive_value if noindex[noarchive_name].blank? noindex[noarchive_name] = noarchive_value else noindex[noarchive_name] += ", #{noarchive_value}" end end noindex end
ruby
def append_noarchive_attribute(noindex) noarchive_name, noarchive_value = extract_noindex_attribute :noarchive if noarchive_value if noindex[noarchive_name].blank? noindex[noarchive_name] = noarchive_value else noindex[noarchive_name] += ", #{noarchive_value}" end end noindex end
[ "def", "append_noarchive_attribute", "(", "noindex", ")", "noarchive_name", ",", "noarchive_value", "=", "extract_noindex_attribute", ":noarchive", "if", "noarchive_value", "if", "noindex", "[", "noarchive_name", "]", ".", "blank?", "noindex", "[", "noarchive_name", "]", "=", "noarchive_value", "else", "noindex", "[", "noarchive_name", "]", "+=", "\", #{noarchive_value}\"", "end", "end", "noindex", "end" ]
Append noarchive attribute if it present. @param [Hash<String, String>] noindex noindex attributes. @return [Hash<String, String>] modified noindex attributes.
[ "Append", "noarchive", "attribute", "if", "it", "present", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L211-L221
train
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
MetaTags.MetaTagsCollection.group_attributes_by_key
def group_attributes_by_key(attributes) Hash[attributes.group_by(&:first).map { |k, v| [k, v.map(&:last).tap(&:compact!).join(', ')] }] end
ruby
def group_attributes_by_key(attributes) Hash[attributes.group_by(&:first).map { |k, v| [k, v.map(&:last).tap(&:compact!).join(', ')] }] end
[ "def", "group_attributes_by_key", "(", "attributes", ")", "Hash", "[", "attributes", ".", "group_by", "(", ":first", ")", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "v", ".", "map", "(", ":last", ")", ".", "tap", "(", ":compact!", ")", ".", "join", "(", "', '", ")", "]", "}", "]", "end" ]
Convert array of arrays to hashes and concatenate values @param [Array<Array>] attributes list of noindex keys and values @return [Hash<String, String>] hash of grouped noindex keys and values
[ "Convert", "array", "of", "arrays", "to", "hashes", "and", "concatenate", "values" ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/meta_tags_collection.rb#L228-L230
train
kpumuk/meta-tags
lib/meta_tags/tag.rb
MetaTags.Tag.render
def render(view) view.tag(name, prepare_attributes(attributes), MetaTags.config.open_meta_tags?) end
ruby
def render(view) view.tag(name, prepare_attributes(attributes), MetaTags.config.open_meta_tags?) end
[ "def", "render", "(", "view", ")", "view", ".", "tag", "(", "name", ",", "prepare_attributes", "(", "attributes", ")", ",", "MetaTags", ".", "config", ".", "open_meta_tags?", ")", "end" ]
Initializes a new instance of Tag class. @param [String, Symbol] name HTML tag name @param [Hash] attributes list of HTML tag attributes Render tag into a Rails view. @param [ActionView::Base] view instance of a Rails view. @return [String] HTML string for the tag.
[ "Initializes", "a", "new", "instance", "of", "Tag", "class", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/tag.rb#L23-L25
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.normalize_description
def normalize_description(description) # description could be another object not a string, but since it probably # serves the same purpose we could just as it to convert itself to str # and continue from there description = cleanup_string(description) return '' if description.blank? truncate(description, MetaTags.config.description_limit) end
ruby
def normalize_description(description) # description could be another object not a string, but since it probably # serves the same purpose we could just as it to convert itself to str # and continue from there description = cleanup_string(description) return '' if description.blank? truncate(description, MetaTags.config.description_limit) end
[ "def", "normalize_description", "(", "description", ")", "# description could be another object not a string, but since it probably", "# serves the same purpose we could just as it to convert itself to str", "# and continue from there", "description", "=", "cleanup_string", "(", "description", ")", "return", "''", "if", "description", ".", "blank?", "truncate", "(", "description", ",", "MetaTags", ".", "config", ".", "description_limit", ")", "end" ]
Normalize description value. @param [String] description description string. @return [String] text with tags removed, squashed spaces, truncated to 200 characters.
[ "Normalize", "description", "value", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L42-L50
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.normalize_keywords
def normalize_keywords(keywords) keywords = cleanup_strings(keywords) return '' if keywords.blank? keywords.each(&:downcase!) if MetaTags.config.keywords_lowercase separator = cleanup_string MetaTags.config.keywords_separator, strip: false keywords = truncate_array(keywords, MetaTags.config.keywords_limit, separator) safe_join(keywords, separator) end
ruby
def normalize_keywords(keywords) keywords = cleanup_strings(keywords) return '' if keywords.blank? keywords.each(&:downcase!) if MetaTags.config.keywords_lowercase separator = cleanup_string MetaTags.config.keywords_separator, strip: false keywords = truncate_array(keywords, MetaTags.config.keywords_limit, separator) safe_join(keywords, separator) end
[ "def", "normalize_keywords", "(", "keywords", ")", "keywords", "=", "cleanup_strings", "(", "keywords", ")", "return", "''", "if", "keywords", ".", "blank?", "keywords", ".", "each", "(", ":downcase!", ")", "if", "MetaTags", ".", "config", ".", "keywords_lowercase", "separator", "=", "cleanup_string", "MetaTags", ".", "config", ".", "keywords_separator", ",", "strip", ":", "false", "keywords", "=", "truncate_array", "(", "keywords", ",", "MetaTags", ".", "config", ".", "keywords_limit", ",", "separator", ")", "safe_join", "(", "keywords", ",", "separator", ")", "end" ]
Normalize keywords value. @param [String, Array<String>] keywords list of keywords as a string or Array. @return [String] list of keywords joined with comma, with tags removed.
[ "Normalize", "keywords", "value", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L57-L66
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.strip_tags
def strip_tags(string) if defined?(Loofah) # Instead of strip_tags we will use Loofah to strip tags from now on Loofah.fragment(string).text(encode_special_chars: false) else helpers.strip_tags(string) end end
ruby
def strip_tags(string) if defined?(Loofah) # Instead of strip_tags we will use Loofah to strip tags from now on Loofah.fragment(string).text(encode_special_chars: false) else helpers.strip_tags(string) end end
[ "def", "strip_tags", "(", "string", ")", "if", "defined?", "(", "Loofah", ")", "# Instead of strip_tags we will use Loofah to strip tags from now on", "Loofah", ".", "fragment", "(", "string", ")", ".", "text", "(", "encode_special_chars", ":", "false", ")", "else", "helpers", ".", "strip_tags", "(", "string", ")", "end", "end" ]
Strips all HTML tags from the +html+, including comments. @param [String] string HTML string. @return [String] html_safe string with no HTML tags.
[ "Strips", "all", "HTML", "tags", "from", "the", "+", "html", "+", "including", "comments", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L81-L88
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.cleanup_string
def cleanup_string(string, strip: true) return '' if string.nil? raise ArgumentError, 'Expected a string or an object that implements #to_str' unless string.respond_to?(:to_str) strip_tags(string.to_str).tap do |s| s.gsub!(/\s+/, ' ') s.strip! if strip end end
ruby
def cleanup_string(string, strip: true) return '' if string.nil? raise ArgumentError, 'Expected a string or an object that implements #to_str' unless string.respond_to?(:to_str) strip_tags(string.to_str).tap do |s| s.gsub!(/\s+/, ' ') s.strip! if strip end end
[ "def", "cleanup_string", "(", "string", ",", "strip", ":", "true", ")", "return", "''", "if", "string", ".", "nil?", "raise", "ArgumentError", ",", "'Expected a string or an object that implements #to_str'", "unless", "string", ".", "respond_to?", "(", ":to_str", ")", "strip_tags", "(", "string", ".", "to_str", ")", ".", "tap", "do", "|", "s", "|", "s", ".", "gsub!", "(", "/", "\\s", "/", ",", "' '", ")", "s", ".", "strip!", "if", "strip", "end", "end" ]
Removes HTML tags and squashes down all the spaces. @param [String] string input string. @return [String] input string with no HTML tags and consequent white space characters squashed into a single space.
[ "Removes", "HTML", "tags", "and", "squashes", "down", "all", "the", "spaces", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L109-L117
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.cleanup_strings
def cleanup_strings(strings, strip: true) strings = Array(strings).flatten.map! { |s| cleanup_string(s, strip: strip) } strings.reject!(&:blank?) strings end
ruby
def cleanup_strings(strings, strip: true) strings = Array(strings).flatten.map! { |s| cleanup_string(s, strip: strip) } strings.reject!(&:blank?) strings end
[ "def", "cleanup_strings", "(", "strings", ",", "strip", ":", "true", ")", "strings", "=", "Array", "(", "strings", ")", ".", "flatten", ".", "map!", "{", "|", "s", "|", "cleanup_string", "(", "s", ",", "strip", ":", "strip", ")", "}", "strings", ".", "reject!", "(", ":blank?", ")", "strings", "end" ]
Cleans multiple strings up. @param [Array<String>] strings input strings. @return [Array<String>] clean strings. @see cleanup_string
[ "Cleans", "multiple", "strings", "up", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L125-L129
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.truncate
def truncate(string, limit = nil, natural_separator = ' ') return string if limit.to_i == 0 # rubocop:disable Lint/NumberConversion helpers.truncate( string, length: limit, separator: natural_separator, omission: '', escape: true, ) end
ruby
def truncate(string, limit = nil, natural_separator = ' ') return string if limit.to_i == 0 # rubocop:disable Lint/NumberConversion helpers.truncate( string, length: limit, separator: natural_separator, omission: '', escape: true, ) end
[ "def", "truncate", "(", "string", ",", "limit", "=", "nil", ",", "natural_separator", "=", "' '", ")", "return", "string", "if", "limit", ".", "to_i", "==", "0", "# rubocop:disable Lint/NumberConversion", "helpers", ".", "truncate", "(", "string", ",", "length", ":", "limit", ",", "separator", ":", "natural_separator", ",", "omission", ":", "''", ",", "escape", ":", "true", ",", ")", "end" ]
Truncates a string to a specific limit. Return string without truncation when limit 0 or nil @param [String] string input strings. @param [Integer,nil] limit characters number to truncate to. @param [String] natural_separator natural separator to truncate at. @return [String] truncated string.
[ "Truncates", "a", "string", "to", "a", "specific", "limit", ".", "Return", "string", "without", "truncation", "when", "limit", "0", "or", "nil" ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L138-L148
train
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
MetaTags.TextNormalizer.truncate_array
def truncate_array(string_array, limit = nil, separator = '', natural_separator = ' ') return string_array if limit.nil? || limit <= 0 length = 0 result = [] string_array.each do |string| limit_left = calculate_limit_left(limit, length, result, separator) if string.length > limit_left result << truncate(string, limit_left, natural_separator) break end length += (result.any? ? separator.length : 0) + string.length result << string # No more strings will fit break if length + separator.length >= limit end result end
ruby
def truncate_array(string_array, limit = nil, separator = '', natural_separator = ' ') return string_array if limit.nil? || limit <= 0 length = 0 result = [] string_array.each do |string| limit_left = calculate_limit_left(limit, length, result, separator) if string.length > limit_left result << truncate(string, limit_left, natural_separator) break end length += (result.any? ? separator.length : 0) + string.length result << string # No more strings will fit break if length + separator.length >= limit end result end
[ "def", "truncate_array", "(", "string_array", ",", "limit", "=", "nil", ",", "separator", "=", "''", ",", "natural_separator", "=", "' '", ")", "return", "string_array", "if", "limit", ".", "nil?", "||", "limit", "<=", "0", "length", "=", "0", "result", "=", "[", "]", "string_array", ".", "each", "do", "|", "string", "|", "limit_left", "=", "calculate_limit_left", "(", "limit", ",", "length", ",", "result", ",", "separator", ")", "if", "string", ".", "length", ">", "limit_left", "result", "<<", "truncate", "(", "string", ",", "limit_left", ",", "natural_separator", ")", "break", "end", "length", "+=", "(", "result", ".", "any?", "?", "separator", ".", "length", ":", "0", ")", "+", "string", ".", "length", "result", "<<", "string", "# No more strings will fit", "break", "if", "length", "+", "separator", ".", "length", ">=", "limit", "end", "result", "end" ]
Truncates a string to a specific limit. @param [Array<String>] string_array input strings. @param [Integer,nil] limit characters number to truncate to. @param [String] separator separator that will be used to join array later. @param [String] natural_separator natural separator to truncate at. @return [String] truncated string.
[ "Truncates", "a", "string", "to", "a", "specific", "limit", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/text_normalizer.rb#L158-L180
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render
def render(view) tags = [] render_charset(tags) render_title(tags) render_icon(tags) render_with_normalization(tags, :description) render_with_normalization(tags, :keywords) render_refresh(tags) render_noindex(tags) render_alternate(tags) render_open_search(tags) render_links(tags) render_hashes(tags) render_custom(tags) tags.tap(&:compact!).map! { |tag| tag.render(view) } view.safe_join tags, MetaTags.config.minify_output ? "" : "\n" end
ruby
def render(view) tags = [] render_charset(tags) render_title(tags) render_icon(tags) render_with_normalization(tags, :description) render_with_normalization(tags, :keywords) render_refresh(tags) render_noindex(tags) render_alternate(tags) render_open_search(tags) render_links(tags) render_hashes(tags) render_custom(tags) tags.tap(&:compact!).map! { |tag| tag.render(view) } view.safe_join tags, MetaTags.config.minify_output ? "" : "\n" end
[ "def", "render", "(", "view", ")", "tags", "=", "[", "]", "render_charset", "(", "tags", ")", "render_title", "(", "tags", ")", "render_icon", "(", "tags", ")", "render_with_normalization", "(", "tags", ",", ":description", ")", "render_with_normalization", "(", "tags", ",", ":keywords", ")", "render_refresh", "(", "tags", ")", "render_noindex", "(", "tags", ")", "render_alternate", "(", "tags", ")", "render_open_search", "(", "tags", ")", "render_links", "(", "tags", ")", "render_hashes", "(", "tags", ")", "render_custom", "(", "tags", ")", "tags", ".", "tap", "(", ":compact!", ")", ".", "map!", "{", "|", "tag", "|", "tag", ".", "render", "(", "view", ")", "}", "view", ".", "safe_join", "tags", ",", "MetaTags", ".", "config", ".", "minify_output", "?", "\"\"", ":", "\"\\n\"", "end" ]
Initialized a new instance of Renderer. @param [MetaTagsCollection] meta_tags meta tags object to render. Renders meta tags on the page. @param [ActionView::Base] view Rails view object.
[ "Initialized", "a", "new", "instance", "of", "Renderer", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L20-L39
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_charset
def render_charset(tags) charset = meta_tags.extract(:charset) tags << Tag.new(:meta, charset: charset) if charset.present? end
ruby
def render_charset(tags) charset = meta_tags.extract(:charset) tags << Tag.new(:meta, charset: charset) if charset.present? end
[ "def", "render_charset", "(", "tags", ")", "charset", "=", "meta_tags", ".", "extract", "(", ":charset", ")", "tags", "<<", "Tag", ".", "new", "(", ":meta", ",", "charset", ":", "charset", ")", "if", "charset", ".", "present?", "end" ]
Renders charset tag. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "charset", "tag", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L47-L50
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_title
def render_title(tags) normalized_meta_tags[:title] = meta_tags.page_title normalized_meta_tags[:site] = meta_tags[:site] title = meta_tags.extract_full_title normalized_meta_tags[:full_title] = title tags << ContentTag.new(:title, content: title) if title.present? end
ruby
def render_title(tags) normalized_meta_tags[:title] = meta_tags.page_title normalized_meta_tags[:site] = meta_tags[:site] title = meta_tags.extract_full_title normalized_meta_tags[:full_title] = title tags << ContentTag.new(:title, content: title) if title.present? end
[ "def", "render_title", "(", "tags", ")", "normalized_meta_tags", "[", ":title", "]", "=", "meta_tags", ".", "page_title", "normalized_meta_tags", "[", ":site", "]", "=", "meta_tags", "[", ":site", "]", "title", "=", "meta_tags", ".", "extract_full_title", "normalized_meta_tags", "[", ":full_title", "]", "=", "title", "tags", "<<", "ContentTag", ".", "new", "(", ":title", ",", "content", ":", "title", ")", "if", "title", ".", "present?", "end" ]
Renders title tag. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "title", "tag", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L56-L62
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_noindex
def render_noindex(tags) meta_tags.extract_noindex.each do |name, content| tags << Tag.new(:meta, name: name, content: content) if content.present? end end
ruby
def render_noindex(tags) meta_tags.extract_noindex.each do |name, content| tags << Tag.new(:meta, name: name, content: content) if content.present? end end
[ "def", "render_noindex", "(", "tags", ")", "meta_tags", ".", "extract_noindex", ".", "each", "do", "|", "name", ",", "content", "|", "tags", "<<", "Tag", ".", "new", "(", ":meta", ",", "name", ":", "name", ",", "content", ":", "content", ")", "if", "content", ".", "present?", "end", "end" ]
Renders noindex and nofollow meta tags. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "noindex", "and", "nofollow", "meta", "tags", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L99-L103
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_refresh
def render_refresh(tags) refresh = meta_tags.extract(:refresh) tags << Tag.new(:meta, 'http-equiv' => 'refresh', content: refresh.to_s) if refresh.present? end
ruby
def render_refresh(tags) refresh = meta_tags.extract(:refresh) tags << Tag.new(:meta, 'http-equiv' => 'refresh', content: refresh.to_s) if refresh.present? end
[ "def", "render_refresh", "(", "tags", ")", "refresh", "=", "meta_tags", ".", "extract", "(", ":refresh", ")", "tags", "<<", "Tag", ".", "new", "(", ":meta", ",", "'http-equiv'", "=>", "'refresh'", ",", "content", ":", "refresh", ".", "to_s", ")", "if", "refresh", ".", "present?", "end" ]
Renders refresh meta tag. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "refresh", "meta", "tag", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L109-L112
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_alternate
def render_alternate(tags) alternate = meta_tags.extract(:alternate) return unless alternate if alternate.kind_of?(Hash) alternate.each do |hreflang, href| tags << Tag.new(:link, rel: 'alternate', href: href, hreflang: hreflang) if href.present? end elsif alternate.kind_of?(Array) alternate.each do |link_params| tags << Tag.new(:link, { rel: 'alternate' }.with_indifferent_access.merge(link_params)) end end end
ruby
def render_alternate(tags) alternate = meta_tags.extract(:alternate) return unless alternate if alternate.kind_of?(Hash) alternate.each do |hreflang, href| tags << Tag.new(:link, rel: 'alternate', href: href, hreflang: hreflang) if href.present? end elsif alternate.kind_of?(Array) alternate.each do |link_params| tags << Tag.new(:link, { rel: 'alternate' }.with_indifferent_access.merge(link_params)) end end end
[ "def", "render_alternate", "(", "tags", ")", "alternate", "=", "meta_tags", ".", "extract", "(", ":alternate", ")", "return", "unless", "alternate", "if", "alternate", ".", "kind_of?", "(", "Hash", ")", "alternate", ".", "each", "do", "|", "hreflang", ",", "href", "|", "tags", "<<", "Tag", ".", "new", "(", ":link", ",", "rel", ":", "'alternate'", ",", "href", ":", "href", ",", "hreflang", ":", "hreflang", ")", "if", "href", ".", "present?", "end", "elsif", "alternate", ".", "kind_of?", "(", "Array", ")", "alternate", ".", "each", "do", "|", "link_params", "|", "tags", "<<", "Tag", ".", "new", "(", ":link", ",", "{", "rel", ":", "'alternate'", "}", ".", "with_indifferent_access", ".", "merge", "(", "link_params", ")", ")", "end", "end", "end" ]
Renders alternate link tags. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "alternate", "link", "tags", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L118-L131
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_open_search
def render_open_search(tags) open_search = meta_tags.extract(:open_search) return unless open_search href = open_search[:href] title = open_search[:title] type = "application/opensearchdescription+xml" tags << Tag.new(:link, rel: 'search', type: type, href: href, title: title) if href.present? end
ruby
def render_open_search(tags) open_search = meta_tags.extract(:open_search) return unless open_search href = open_search[:href] title = open_search[:title] type = "application/opensearchdescription+xml" tags << Tag.new(:link, rel: 'search', type: type, href: href, title: title) if href.present? end
[ "def", "render_open_search", "(", "tags", ")", "open_search", "=", "meta_tags", ".", "extract", "(", ":open_search", ")", "return", "unless", "open_search", "href", "=", "open_search", "[", ":href", "]", "title", "=", "open_search", "[", ":title", "]", "type", "=", "\"application/opensearchdescription+xml\"", "tags", "<<", "Tag", ".", "new", "(", ":link", ",", "rel", ":", "'search'", ",", "type", ":", "type", ",", "href", ":", "href", ",", "title", ":", "title", ")", "if", "href", ".", "present?", "end" ]
Renders open_search link tag. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "open_search", "link", "tag", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L137-L146
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_links
def render_links(tags) [ :amphtml, :canonical, :prev, :next, :image_src ].each do |tag_name| href = meta_tags.extract(tag_name) if href.present? @normalized_meta_tags[tag_name] = href tags << Tag.new(:link, rel: tag_name, href: href) end end end
ruby
def render_links(tags) [ :amphtml, :canonical, :prev, :next, :image_src ].each do |tag_name| href = meta_tags.extract(tag_name) if href.present? @normalized_meta_tags[tag_name] = href tags << Tag.new(:link, rel: tag_name, href: href) end end end
[ "def", "render_links", "(", "tags", ")", "[", ":amphtml", ",", ":canonical", ",", ":prev", ",", ":next", ",", ":image_src", "]", ".", "each", "do", "|", "tag_name", "|", "href", "=", "meta_tags", ".", "extract", "(", "tag_name", ")", "if", "href", ".", "present?", "@normalized_meta_tags", "[", "tag_name", "]", "=", "href", "tags", "<<", "Tag", ".", "new", "(", ":link", ",", "rel", ":", "tag_name", ",", "href", ":", "href", ")", "end", "end", "end" ]
Renders links. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "links", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L152-L160
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_hashes
def render_hashes(tags, **opts) meta_tags.meta_tags.each_key do |property| render_hash(tags, property, **opts) end end
ruby
def render_hashes(tags, **opts) meta_tags.meta_tags.each_key do |property| render_hash(tags, property, **opts) end end
[ "def", "render_hashes", "(", "tags", ",", "**", "opts", ")", "meta_tags", ".", "meta_tags", ".", "each_key", "do", "|", "property", "|", "render_hash", "(", "tags", ",", "property", ",", "**", "opts", ")", "end", "end" ]
Renders complex hash objects. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "complex", "hash", "objects", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L166-L170
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_hash
def render_hash(tags, key, **opts) data = meta_tags.meta_tags[key] return unless data.kind_of?(Hash) process_hash(tags, key, data, **opts) meta_tags.extract(key) end
ruby
def render_hash(tags, key, **opts) data = meta_tags.meta_tags[key] return unless data.kind_of?(Hash) process_hash(tags, key, data, **opts) meta_tags.extract(key) end
[ "def", "render_hash", "(", "tags", ",", "key", ",", "**", "opts", ")", "data", "=", "meta_tags", ".", "meta_tags", "[", "key", "]", "return", "unless", "data", ".", "kind_of?", "(", "Hash", ")", "process_hash", "(", "tags", ",", "key", ",", "data", ",", "**", "opts", ")", "meta_tags", ".", "extract", "(", "key", ")", "end" ]
Renders a complex hash object by key. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "a", "complex", "hash", "object", "by", "key", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L176-L182
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.render_custom
def render_custom(tags) meta_tags.meta_tags.each do |name, data| Array(data).each do |val| tags << Tag.new(:meta, configured_name_key(name) => name, content: val) end meta_tags.extract(name) end end
ruby
def render_custom(tags) meta_tags.meta_tags.each do |name, data| Array(data).each do |val| tags << Tag.new(:meta, configured_name_key(name) => name, content: val) end meta_tags.extract(name) end end
[ "def", "render_custom", "(", "tags", ")", "meta_tags", ".", "meta_tags", ".", "each", "do", "|", "name", ",", "data", "|", "Array", "(", "data", ")", ".", "each", "do", "|", "val", "|", "tags", "<<", "Tag", ".", "new", "(", ":meta", ",", "configured_name_key", "(", "name", ")", "=>", "name", ",", "content", ":", "val", ")", "end", "meta_tags", ".", "extract", "(", "name", ")", "end", "end" ]
Renders custom meta tags. @param [Array<Tag>] tags a buffer object to store tag in.
[ "Renders", "custom", "meta", "tags", "." ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L188-L195
train
kpumuk/meta-tags
lib/meta_tags/renderer.rb
MetaTags.Renderer.process_tree
def process_tree(tags, property, content, **opts) method = case content when Hash :process_hash when Array :process_array else :render_tag end __send__(method, tags, property, content, **opts) end
ruby
def process_tree(tags, property, content, **opts) method = case content when Hash :process_hash when Array :process_array else :render_tag end __send__(method, tags, property, content, **opts) end
[ "def", "process_tree", "(", "tags", ",", "property", ",", "content", ",", "**", "opts", ")", "method", "=", "case", "content", "when", "Hash", ":process_hash", "when", "Array", ":process_array", "else", ":render_tag", "end", "__send__", "(", "method", ",", "tags", ",", "property", ",", "content", ",", "**", "opts", ")", "end" ]
Recursive method to process all the hashes and arrays on meta tags @param [Array<Tag>] tags a buffer object to store tag in. @param [String, Symbol] property a Hash or a String to render as meta tag. @param [Hash, Array, String, Symbol] content text content or a symbol reference to top-level meta tag.
[ "Recursive", "method", "to", "process", "all", "the", "hashes", "and", "arrays", "on", "meta", "tags" ]
03585f95edf96cd17024c5c155ce46ec8bc47232
https://github.com/kpumuk/meta-tags/blob/03585f95edf96cd17024c5c155ce46ec8bc47232/lib/meta_tags/renderer.rb#L204-L214
train
ankane/ahoy_email
lib/ahoy_email/processor.rb
AhoyEmail.Processor.trackable?
def trackable?(uri) uri && uri.absolute? && %w(http https).include?(uri.scheme) end
ruby
def trackable?(uri) uri && uri.absolute? && %w(http https).include?(uri.scheme) end
[ "def", "trackable?", "(", "uri", ")", "uri", "&&", "uri", ".", "absolute?", "&&", "%w(", "http", "https", ")", ".", "include?", "(", "uri", ".", "scheme", ")", "end" ]
Filter trackable URIs, i.e. absolute one with http
[ "Filter", "trackable", "URIs", "i", ".", "e", ".", "absolute", "one", "with", "http" ]
6f2777080365f4f515f7ad9c74f5dbbd348ce948
https://github.com/ankane/ahoy_email/blob/6f2777080365f4f515f7ad9c74f5dbbd348ce948/lib/ahoy_email/processor.rb#L141-L143
train
geokit/geokit-rails
lib/geokit-rails/ip_geocode_lookup.rb
Geokit.IpGeocodeLookup.retrieve_location_from_cookie_or_service
def retrieve_location_from_cookie_or_service return GeoLoc.new(YAML.load(cookies[:geo_location])) if cookies[:geo_location] location = Geocoders::MultiGeocoder.geocode(get_ip_address) return location.success ? location : nil end
ruby
def retrieve_location_from_cookie_or_service return GeoLoc.new(YAML.load(cookies[:geo_location])) if cookies[:geo_location] location = Geocoders::MultiGeocoder.geocode(get_ip_address) return location.success ? location : nil end
[ "def", "retrieve_location_from_cookie_or_service", "return", "GeoLoc", ".", "new", "(", "YAML", ".", "load", "(", "cookies", "[", ":geo_location", "]", ")", ")", "if", "cookies", "[", ":geo_location", "]", "location", "=", "Geocoders", "::", "MultiGeocoder", ".", "geocode", "(", "get_ip_address", ")", "return", "location", ".", "success", "?", "location", ":", "nil", "end" ]
Uses the stored location value from the cookie if it exists. If no cookie exists, calls out to the web service to get the location.
[ "Uses", "the", "stored", "location", "value", "from", "the", "cookie", "if", "it", "exists", ".", "If", "no", "cookie", "exists", "calls", "out", "to", "the", "web", "service", "to", "get", "the", "location", "." ]
cc5fd43ab4e69878fb31ebd1fc22918e2952b560
https://github.com/geokit/geokit-rails/blob/cc5fd43ab4e69878fb31ebd1fc22918e2952b560/lib/geokit-rails/ip_geocode_lookup.rb#L36-L40
train
ruby-protobuf/protobuf
lib/protobuf/message.rb
Protobuf.Message.to_json_hash
def to_json_hash result = {} @values.each_key do |field_name| value = self[field_name] field = self.class.get_field(field_name, true) # NB: to_json_hash_value should come before json_encode so as to handle # repeated fields without extra logic. hashed_value = if value.respond_to?(:to_json_hash_value) value.to_json_hash_value elsif field.respond_to?(:json_encode) field.json_encode(value) else value end result[field.name] = hashed_value end result end
ruby
def to_json_hash result = {} @values.each_key do |field_name| value = self[field_name] field = self.class.get_field(field_name, true) # NB: to_json_hash_value should come before json_encode so as to handle # repeated fields without extra logic. hashed_value = if value.respond_to?(:to_json_hash_value) value.to_json_hash_value elsif field.respond_to?(:json_encode) field.json_encode(value) else value end result[field.name] = hashed_value end result end
[ "def", "to_json_hash", "result", "=", "{", "}", "@values", ".", "each_key", "do", "|", "field_name", "|", "value", "=", "self", "[", "field_name", "]", "field", "=", "self", ".", "class", ".", "get_field", "(", "field_name", ",", "true", ")", "# NB: to_json_hash_value should come before json_encode so as to handle", "# repeated fields without extra logic.", "hashed_value", "=", "if", "value", ".", "respond_to?", "(", ":to_json_hash_value", ")", "value", ".", "to_json_hash_value", "elsif", "field", ".", "respond_to?", "(", ":json_encode", ")", "field", ".", "json_encode", "(", "value", ")", "else", "value", "end", "result", "[", "field", ".", "name", "]", "=", "hashed_value", "end", "result", "end" ]
Return a hash-representation of the given fields for this message type that is safe to convert to JSON.
[ "Return", "a", "hash", "-", "representation", "of", "the", "given", "fields", "for", "this", "message", "type", "that", "is", "safe", "to", "convert", "to", "JSON", "." ]
a2e0cbb783d49d37648c07d795dc4f7eb8d14eb1
https://github.com/ruby-protobuf/protobuf/blob/a2e0cbb783d49d37648c07d795dc4f7eb8d14eb1/lib/protobuf/message.rb#L142-L163
train
chloerei/alipay
lib/alipay/client.rb
Alipay.Client.page_execute_url
def page_execute_url(params) params = prepare_params(params) uri = URI(@url) uri.query = URI.encode_www_form(params) uri.to_s end
ruby
def page_execute_url(params) params = prepare_params(params) uri = URI(@url) uri.query = URI.encode_www_form(params) uri.to_s end
[ "def", "page_execute_url", "(", "params", ")", "params", "=", "prepare_params", "(", "params", ")", "uri", "=", "URI", "(", "@url", ")", "uri", ".", "query", "=", "URI", ".", "encode_www_form", "(", "params", ")", "uri", ".", "to_s", "end" ]
Generate a url that use to redirect user to Alipay payment page. Example: alipay_client.page_execute_url( method: 'alipay.trade.page.pay', biz_content: { out_trade_no: '20160401000000', product_code: 'FAST_INSTANT_TRADE_PAY', total_amount: '0.01', subject: 'test' }.to_json(ascii_only: true), timestamp: '2016-04-01 00:00:00' ) # => 'https://openapi.alipaydev.com/gateway.do?app_id=2016...'
[ "Generate", "a", "url", "that", "use", "to", "redirect", "user", "to", "Alipay", "payment", "page", "." ]
a525989b659da970e08bc8fcd1b004453bfed89f
https://github.com/chloerei/alipay/blob/a525989b659da970e08bc8fcd1b004453bfed89f/lib/alipay/client.rb#L78-L84
train
chloerei/alipay
lib/alipay/client.rb
Alipay.Client.page_execute_form
def page_execute_form(params) params = prepare_params(params) html = %Q(<form id='alipaysubmit' name='alipaysubmit' action='#{@url}' method='POST'>) params.each do |key, value| html << %Q(<input type='hidden' name='#{key}' value='#{value.gsub("'", "&apos;")}'/>) end html << "<input type='submit' value='ok' style='display:none'></form>" html << "<script>document.forms['alipaysubmit'].submit();</script>" html end
ruby
def page_execute_form(params) params = prepare_params(params) html = %Q(<form id='alipaysubmit' name='alipaysubmit' action='#{@url}' method='POST'>) params.each do |key, value| html << %Q(<input type='hidden' name='#{key}' value='#{value.gsub("'", "&apos;")}'/>) end html << "<input type='submit' value='ok' style='display:none'></form>" html << "<script>document.forms['alipaysubmit'].submit();</script>" html end
[ "def", "page_execute_form", "(", "params", ")", "params", "=", "prepare_params", "(", "params", ")", "html", "=", "%Q(<form id='alipaysubmit' name='alipaysubmit' action='#{@url}' method='POST'>)", "params", ".", "each", "do", "|", "key", ",", "value", "|", "html", "<<", "%Q(<input type='hidden' name='#{key}' value='#{value.gsub(\"'\", \"&apos;\")}'/>)", "end", "html", "<<", "\"<input type='submit' value='ok' style='display:none'></form>\"", "html", "<<", "\"<script>document.forms['alipaysubmit'].submit();</script>\"", "html", "end" ]
Generate a form string that use to render in view and auto POST to Alipay server. Example: alipay_client.page_execute_form( method: 'alipay.trade.page.pay', biz_content: { out_trade_no: '20160401000000', product_code: 'FAST_INSTANT_TRADE_PAY', total_amount: '0.01', subject: 'test' }.to_json(ascii_only: true), timestamp: '2016-04-01 00:00:00' ) # => '<form id='alipaysubmit' name='alipaysubmit' action=...'
[ "Generate", "a", "form", "string", "that", "use", "to", "render", "in", "view", "and", "auto", "POST", "to", "Alipay", "server", "." ]
a525989b659da970e08bc8fcd1b004453bfed89f
https://github.com/chloerei/alipay/blob/a525989b659da970e08bc8fcd1b004453bfed89f/lib/alipay/client.rb#L102-L112
train
chloerei/alipay
lib/alipay/client.rb
Alipay.Client.execute
def execute(params) params = prepare_params(params) Net::HTTP.post_form(URI(@url), params).body end
ruby
def execute(params) params = prepare_params(params) Net::HTTP.post_form(URI(@url), params).body end
[ "def", "execute", "(", "params", ")", "params", "=", "prepare_params", "(", "params", ")", "Net", "::", "HTTP", ".", "post_form", "(", "URI", "(", "@url", ")", ",", "params", ")", ".", "body", "end" ]
Immediately make a API request to Alipay and return response body. Example: alipay_client.execute( method: 'alipay.data.dataservice.bill.downloadurl.query', biz_content: { bill_type: 'trade', bill_date: '2016-04-01' }.to_json(ascii_only: true) ) # => '{ "alipay_data_dataservice_bill_downloadurl_query_response":{...'
[ "Immediately", "make", "a", "API", "request", "to", "Alipay", "and", "return", "response", "body", "." ]
a525989b659da970e08bc8fcd1b004453bfed89f
https://github.com/chloerei/alipay/blob/a525989b659da970e08bc8fcd1b004453bfed89f/lib/alipay/client.rb#L126-L130
train
chloerei/alipay
lib/alipay/client.rb
Alipay.Client.sign
def sign(params) string = params_to_string(params) case @sign_type when 'RSA' ::Alipay::Sign::RSA.sign(@app_private_key, string) when 'RSA2' ::Alipay::Sign::RSA2.sign(@app_private_key, string) else raise "Unsupported sign_type: #{@sign_type}" end end
ruby
def sign(params) string = params_to_string(params) case @sign_type when 'RSA' ::Alipay::Sign::RSA.sign(@app_private_key, string) when 'RSA2' ::Alipay::Sign::RSA2.sign(@app_private_key, string) else raise "Unsupported sign_type: #{@sign_type}" end end
[ "def", "sign", "(", "params", ")", "string", "=", "params_to_string", "(", "params", ")", "case", "@sign_type", "when", "'RSA'", "::", "Alipay", "::", "Sign", "::", "RSA", ".", "sign", "(", "@app_private_key", ",", "string", ")", "when", "'RSA2'", "::", "Alipay", "::", "Sign", "::", "RSA2", ".", "sign", "(", "@app_private_key", ",", "string", ")", "else", "raise", "\"Unsupported sign_type: #{@sign_type}\"", "end", "end" ]
Generate sign for params.
[ "Generate", "sign", "for", "params", "." ]
a525989b659da970e08bc8fcd1b004453bfed89f
https://github.com/chloerei/alipay/blob/a525989b659da970e08bc8fcd1b004453bfed89f/lib/alipay/client.rb#L133-L144
train
chloerei/alipay
lib/alipay/client.rb
Alipay.Client.verify?
def verify?(params) params = Utils.stringify_keys(params) return false if params['sign_type'] != @sign_type sign = params.delete('sign') # sign_type does not use in notify sign params.delete('sign_type') string = params_to_string(params) case @sign_type when 'RSA' ::Alipay::Sign::RSA.verify?(@alipay_public_key, string, sign) when 'RSA2' ::Alipay::Sign::RSA2.verify?(@alipay_public_key, string, sign) else raise "Unsupported sign_type: #{@sign_type}" end end
ruby
def verify?(params) params = Utils.stringify_keys(params) return false if params['sign_type'] != @sign_type sign = params.delete('sign') # sign_type does not use in notify sign params.delete('sign_type') string = params_to_string(params) case @sign_type when 'RSA' ::Alipay::Sign::RSA.verify?(@alipay_public_key, string, sign) when 'RSA2' ::Alipay::Sign::RSA2.verify?(@alipay_public_key, string, sign) else raise "Unsupported sign_type: #{@sign_type}" end end
[ "def", "verify?", "(", "params", ")", "params", "=", "Utils", ".", "stringify_keys", "(", "params", ")", "return", "false", "if", "params", "[", "'sign_type'", "]", "!=", "@sign_type", "sign", "=", "params", ".", "delete", "(", "'sign'", ")", "# sign_type does not use in notify sign", "params", ".", "delete", "(", "'sign_type'", ")", "string", "=", "params_to_string", "(", "params", ")", "case", "@sign_type", "when", "'RSA'", "::", "Alipay", "::", "Sign", "::", "RSA", ".", "verify?", "(", "@alipay_public_key", ",", "string", ",", "sign", ")", "when", "'RSA2'", "::", "Alipay", "::", "Sign", "::", "RSA2", ".", "verify?", "(", "@alipay_public_key", ",", "string", ",", "sign", ")", "else", "raise", "\"Unsupported sign_type: #{@sign_type}\"", "end", "end" ]
Verify Alipay notification. Example: params = { out_trade_no: '20160401000000', trade_status: 'TRADE_SUCCESS' sign_type: 'RSA2', sign: '...' } alipay_client.verify?(params) # => true / false
[ "Verify", "Alipay", "notification", "." ]
a525989b659da970e08bc8fcd1b004453bfed89f
https://github.com/chloerei/alipay/blob/a525989b659da970e08bc8fcd1b004453bfed89f/lib/alipay/client.rb#L158-L174
train
binarylogic/authlogic
lib/authlogic/config.rb
Authlogic.Config.rw_config
def rw_config(key, value, default_value = nil) if value.nil? acts_as_authentic_config.include?(key) ? acts_as_authentic_config[key] : default_value else self.acts_as_authentic_config = acts_as_authentic_config.merge(key => value) value end end
ruby
def rw_config(key, value, default_value = nil) if value.nil? acts_as_authentic_config.include?(key) ? acts_as_authentic_config[key] : default_value else self.acts_as_authentic_config = acts_as_authentic_config.merge(key => value) value end end
[ "def", "rw_config", "(", "key", ",", "value", ",", "default_value", "=", "nil", ")", "if", "value", ".", "nil?", "acts_as_authentic_config", ".", "include?", "(", "key", ")", "?", "acts_as_authentic_config", "[", "key", "]", ":", "default_value", "else", "self", ".", "acts_as_authentic_config", "=", "acts_as_authentic_config", ".", "merge", "(", "key", "=>", "value", ")", "value", "end", "end" ]
This is a one-liner method to write a config setting, read the config setting, and also set a default value for the setting.
[ "This", "is", "a", "one", "-", "liner", "method", "to", "write", "a", "config", "setting", "read", "the", "config", "setting", "and", "also", "set", "a", "default", "value", "for", "the", "setting", "." ]
ac2bb32a918f69d4f5ea28a174d0a2715f37a9ea
https://github.com/binarylogic/authlogic/blob/ac2bb32a918f69d4f5ea28a174d0a2715f37a9ea/lib/authlogic/config.rb#L34-L41
train
cypriss/mutations
lib/mutations/model_filter.rb
Mutations.ModelFilter.initialize_constants!
def initialize_constants! @initialize_constants ||= begin class_const = options[:class] || @name.to_s.camelize class_const = class_const.constantize if class_const.is_a?(String) options[:class] = class_const if options[:builder] options[:builder] = options[:builder].constantize if options[:builder].is_a?(String) end true end unless Mutations.cache_constants? options[:class] = options[:class].to_s.constantize if options[:class] options[:builder] = options[:builder].to_s.constantize if options[:builder] end end
ruby
def initialize_constants! @initialize_constants ||= begin class_const = options[:class] || @name.to_s.camelize class_const = class_const.constantize if class_const.is_a?(String) options[:class] = class_const if options[:builder] options[:builder] = options[:builder].constantize if options[:builder].is_a?(String) end true end unless Mutations.cache_constants? options[:class] = options[:class].to_s.constantize if options[:class] options[:builder] = options[:builder].to_s.constantize if options[:builder] end end
[ "def", "initialize_constants!", "@initialize_constants", "||=", "begin", "class_const", "=", "options", "[", ":class", "]", "||", "@name", ".", "to_s", ".", "camelize", "class_const", "=", "class_const", ".", "constantize", "if", "class_const", ".", "is_a?", "(", "String", ")", "options", "[", ":class", "]", "=", "class_const", "if", "options", "[", ":builder", "]", "options", "[", ":builder", "]", "=", "options", "[", ":builder", "]", ".", "constantize", "if", "options", "[", ":builder", "]", ".", "is_a?", "(", "String", ")", "end", "true", "end", "unless", "Mutations", ".", "cache_constants?", "options", "[", ":class", "]", "=", "options", "[", ":class", "]", ".", "to_s", ".", "constantize", "if", "options", "[", ":class", "]", "options", "[", ":builder", "]", "=", "options", "[", ":builder", "]", ".", "to_s", ".", "constantize", "if", "options", "[", ":builder", "]", "end", "end" ]
Initialize the model class and builder
[ "Initialize", "the", "model", "class", "and", "builder" ]
c9948325648d0ea85420963829d1a4d6b4f17bd9
https://github.com/cypriss/mutations/blob/c9948325648d0ea85420963829d1a4d6b4f17bd9/lib/mutations/model_filter.rb#L16-L33
train
mongodb/mongo-ruby-driver
lib/mongo/client.rb
Mongo.Client.cluster_options
def cluster_options # We share clusters when a new client with different CRUD_OPTIONS # is requested; therefore, cluster should not be getting any of these # options upon instantiation options.reject do |key, value| CRUD_OPTIONS.include?(key.to_sym) end.merge( server_selection_semaphore: @server_selection_semaphore, # but need to put the database back in for auth... database: options[:database], # Put these options in for legacy compatibility, but note that # their values on the client and the cluster do not have to match - # applications should read these values from client, not from cluster max_read_retries: options[:max_read_retries], read_retry_interval: options[:read_retry_interval], ) end
ruby
def cluster_options # We share clusters when a new client with different CRUD_OPTIONS # is requested; therefore, cluster should not be getting any of these # options upon instantiation options.reject do |key, value| CRUD_OPTIONS.include?(key.to_sym) end.merge( server_selection_semaphore: @server_selection_semaphore, # but need to put the database back in for auth... database: options[:database], # Put these options in for legacy compatibility, but note that # their values on the client and the cluster do not have to match - # applications should read these values from client, not from cluster max_read_retries: options[:max_read_retries], read_retry_interval: options[:read_retry_interval], ) end
[ "def", "cluster_options", "# We share clusters when a new client with different CRUD_OPTIONS", "# is requested; therefore, cluster should not be getting any of these", "# options upon instantiation", "options", ".", "reject", "do", "|", "key", ",", "value", "|", "CRUD_OPTIONS", ".", "include?", "(", "key", ".", "to_sym", ")", "end", ".", "merge", "(", "server_selection_semaphore", ":", "@server_selection_semaphore", ",", "# but need to put the database back in for auth...", "database", ":", "options", "[", ":database", "]", ",", "# Put these options in for legacy compatibility, but note that", "# their values on the client and the cluster do not have to match -", "# applications should read these values from client, not from cluster", "max_read_retries", ":", "options", "[", ":max_read_retries", "]", ",", "read_retry_interval", ":", "options", "[", ":read_retry_interval", "]", ",", ")", "end" ]
Get the hash value of the client. @example Get the client hash value. client.hash @return [ Integer ] The client hash value. @since 2.0.0 Instantiate a new driver client. @example Instantiate a single server or mongos client. Mongo::Client.new(['127.0.0.1:27017']) @example Instantiate a client for a replica set. Mongo::Client.new(['127.0.0.1:27017', '127.0.0.1:27021']) @example Directly connect to a mongod in a replica set Mongo::Client.new(['127.0.0.1:27017'], :connect => :direct) # without `:connect => :direct`, Mongo::Client will discover and # connect to the replica set if given the address of a server in # a replica set @param [ Array<String> | String ] addresses_or_uri The array of server addresses in the form of host:port or a MongoDB URI connection string. @param [ Hash ] options The options to be used by the client. @option options [ String, Symbol ] :app_name Application name that is printed to the mongod logs upon establishing a connection in server versions >= 3.4. @option options [ Symbol ] :auth_mech The authentication mechanism to use. One of :mongodb_cr, :mongodb_x509, :plain, :scram, :scram256 @option options [ Hash ] :auth_mech_properties @option options [ String ] :auth_source The source to authenticate from. @option options [ Array<String> ] :compressors A list of potential compressors to use, in order of preference. The driver chooses the first compressor that is also supported by the server. Currently the driver only supports 'zlib'. @option options [ Symbol ] :connect The connection method to use. This forces the cluster to behave in the specified way instead of auto-discovering. One of :direct, :replica_set, :sharded @option options [ Float ] :connect_timeout The timeout, in seconds, to attempt a connection. @option options [ String ] :database The database to connect to. @option options [ Float ] :heartbeat_frequency The number of seconds for the server monitor to refresh it's description via ismaster. @option options [ Object ] :id_generator A custom object to generate ids for documents. Must respond to #generate. @option options [ Integer ] :local_threshold The local threshold boundary in seconds for selecting a near server for an operation. @option options [ Logger ] :logger A custom logger if desired. @option options [ Integer ] :max_idle_time The maximum seconds a socket can remain idle since it has been checked in to the pool. @option options [ Integer ] :max_pool_size The maximum size of the connection pool. @option options [ Integer ] :max_read_retries The maximum number of read retries when legacy read retries are in use. @option options [ Integer ] :max_write_retries The maximum number of write retries when legacy write retries are in use. @option options [ Integer ] :min_pool_size The minimum size of the connection pool. @option options [ true, false ] :monitoring If false is given, the client is initialized without global SDAM event subscribers and will not publish SDAM events. Command monitoring and legacy events will still be published, and the driver will still perform SDAM and monitor its cluster in order to perform server selection. Built-in driver logging of SDAM events will be disabled because it is implemented through SDAM event subscription. Client#subscribe will succeed for all event types, but subscribers to SDAM events will not be invoked. Values other than false result in default behavior which is to perform normal SDAM event publication. @option options [ true, false ] :monitoring_io For internal driver use only. Set to false to prevent SDAM-related I/O from being done by this client or servers under it. Note: setting this option to false will make the client non-functional. It is intended for use in tests which manually invoke SDAM state transitions. @option options [ String ] :password The user's password. @option options [ String ] :platform Platform information to include in the metadata printed to the mongod logs upon establishing a connection in server versions >= 3.4. @option options [ Hash ] :read The read preference options. The hash may have the following items: - *:mode* -- read preference specified as a symbol; valid values are *:primary*, *:primary_preferred*, *:secondary*, *:secondary_preferred* and *:nearest*. - *:tag_sets* -- an array of hashes. - *:local_threshold*. @option options [ Hash ] :read_concern The read concern option. @option options [ Float ] :read_retry_interval The interval, in seconds, in which reads on a mongos are retried. @option options [ Symbol ] :replica_set The name of the replica set to connect to. Servers not in this replica set will be ignored. @option options [ true | false ] :retry_reads If true, modern retryable reads are enabled (which is the default). If false, modern retryable reads are disabled and legacy retryable reads are enabled. @option options [ true | false ] :retry_writes Retry writes once when connected to a replica set or sharded cluster versions 3.6 and up. (Default is true.) @option options [ true | false ] :scan Whether to scan all seeds in constructor. The default in driver version 2.x is to do so; driver version 3.x will not scan seeds in constructor. Opt in to the new behavior by setting this option to false. *Note:* setting this option to nil enables scanning seeds in constructor in driver version 2.x. Driver version 3.x will recognize this option but will ignore it and will never scan seeds in the constructor. @option options [ Proc ] :sdam_proc A Proc to invoke with the client as the argument prior to performing server discovery and monitoring. Use this to set up SDAM event listeners to receive events dispatched during client construction. Note: the client is not fully constructed when sdam_proc is invoked, in particular the cluster is nil at this time. sdam_proc should limit itself to calling #subscribe and #unsubscribe methods on the client only. @option options [ Integer ] :server_selection_timeout The timeout in seconds for selecting a server for an operation. @option options [ Float ] :socket_timeout The timeout, in seconds, to execute operations on a socket. @option options [ true, false ] :ssl Whether to use SSL. @option options [ String ] :ssl_ca_cert The file containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify. @option options [ Array<OpenSSL::X509::Certificate> ] :ssl_ca_cert_object An array of OpenSSL::X509::Certificate representing the certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify. @option options [ String ] :ssl_ca_cert_string A string containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify. @option options [ String ] :ssl_cert The certificate file used to identify the connection against MongoDB. This option, if present, takes precedence over the values of :ssl_cert_string and :ssl_cert_object @option options [ OpenSSL::X509::Certificate ] :ssl_cert_object The OpenSSL::X509::Certificate used to identify the connection against MongoDB @option options [ String ] :ssl_cert_string A string containing the PEM-encoded certificate used to identify the connection against MongoDB. This option, if present, takes precedence over the value of :ssl_cert_object @option options [ String ] :ssl_key The private keyfile used to identify the connection against MongoDB. Note that even if the key is stored in the same file as the certificate, both need to be explicitly specified. This option, if present, takes precedence over the values of :ssl_key_string and :ssl_key_object @option options [ OpenSSL::PKey ] :ssl_key_object The private key used to identify the connection against MongoDB @option options [ String ] :ssl_key_pass_phrase A passphrase for the private key. @option options [ String ] :ssl_key_string A string containing the PEM-encoded private key used to identify the connection against MongoDB. This parameter, if present, takes precedence over the value of option :ssl_key_object @option options [ true, false ] :ssl_verify Whether to perform peer certificate validation and hostname verification. Note that the decision of whether to validate certificates will be overridden if :ssl_verify_certificate is set, and the decision of whether to validate hostnames will be overridden if :ssl_verify_hostname is set. @option options [ true, false ] :ssl_verify_certificate Whether to perform peer certificate validation. This setting overrides :ssl_verify with respect to whether certificate validation is performed. @option options [ true, false ] :ssl_verify_hostname Whether to perform peer hostname validation. This setting overrides :ssl_verify with respect to whether hostname validation is performed. @option options [ true, false ] :truncate_logs Whether to truncate the logs at the default 250 characters. @option options [ String ] :user The user name. @option options [ Float ] :wait_queue_timeout The time to wait, in seconds, in the connection pool for a connection to be checked in. @option options [ Hash ] :write The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean. @option options [ Integer ] :zlib_compression_level The Zlib compression level to use, if using compression. See Ruby's Zlib module for valid levels. @since 2.0.0 @api private
[ "Get", "the", "hash", "value", "of", "the", "client", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/client.rb#L367-L384
train
mongodb/mongo-ruby-driver
lib/mongo/client.rb
Mongo.Client.with
def with(new_options = Options::Redacted.new) clone.tap do |client| opts = validate_options!(new_options) client.options.update(opts) Database.create(client) # We can't use the same cluster if some options that would affect it # have changed. if cluster_modifying?(opts) Cluster.create(client) end end end
ruby
def with(new_options = Options::Redacted.new) clone.tap do |client| opts = validate_options!(new_options) client.options.update(opts) Database.create(client) # We can't use the same cluster if some options that would affect it # have changed. if cluster_modifying?(opts) Cluster.create(client) end end end
[ "def", "with", "(", "new_options", "=", "Options", "::", "Redacted", ".", "new", ")", "clone", ".", "tap", "do", "|", "client", "|", "opts", "=", "validate_options!", "(", "new_options", ")", "client", ".", "options", ".", "update", "(", "opts", ")", "Database", ".", "create", "(", "client", ")", "# We can't use the same cluster if some options that would affect it", "# have changed.", "if", "cluster_modifying?", "(", "opts", ")", "Cluster", ".", "create", "(", "client", ")", "end", "end", "end" ]
Creates a new client with the passed options merged over the existing options of this client. Useful for one-offs to change specific options without altering the original client. @note Depending on options given, the returned client may share the cluster with the original client or be created with a new cluster. If a new cluster is created, the monitoring event subscribers on the new client are set to the default event subscriber set and none of the subscribers on the original client are copied over. @example Get a client with changed options. client.with(:read => { :mode => :primary_preferred }) @param [ Hash ] new_options The new options to use. @return [ Mongo::Client ] A new client instance. @since 2.0.0
[ "Creates", "a", "new", "client", "with", "the", "passed", "options", "merged", "over", "the", "existing", "options", "of", "this", "client", ".", "Useful", "for", "one", "-", "offs", "to", "change", "specific", "options", "without", "altering", "the", "original", "client", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/client.rb#L512-L523
train
mongodb/mongo-ruby-driver
lib/mongo/client.rb
Mongo.Client.reconnect
def reconnect addresses = cluster.addresses.map(&:to_s) @cluster.disconnect! rescue nil @cluster = Cluster.new(addresses, monitoring, cluster_options) true end
ruby
def reconnect addresses = cluster.addresses.map(&:to_s) @cluster.disconnect! rescue nil @cluster = Cluster.new(addresses, monitoring, cluster_options) true end
[ "def", "reconnect", "addresses", "=", "cluster", ".", "addresses", ".", "map", "(", ":to_s", ")", "@cluster", ".", "disconnect!", "rescue", "nil", "@cluster", "=", "Cluster", ".", "new", "(", "addresses", ",", "monitoring", ",", "cluster_options", ")", "true", "end" ]
Reconnect the client. @example Reconnect the client. client.reconnect @return [ true ] Always true. @since 2.1.0
[ "Reconnect", "the", "client", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/client.rb#L575-L582
train
mongodb/mongo-ruby-driver
lib/mongo/client.rb
Mongo.Client.database_names
def database_names(filter = {}, opts = {}) list_databases(filter, true, opts).collect{ |info| info[Database::NAME] } end
ruby
def database_names(filter = {}, opts = {}) list_databases(filter, true, opts).collect{ |info| info[Database::NAME] } end
[ "def", "database_names", "(", "filter", "=", "{", "}", ",", "opts", "=", "{", "}", ")", "list_databases", "(", "filter", ",", "true", ",", "opts", ")", ".", "collect", "{", "|", "info", "|", "info", "[", "Database", "::", "NAME", "]", "}", "end" ]
Get the names of all databases. @example Get the database names. client.database_names @param [ Hash ] filter The filter criteria for getting a list of databases. @param [ Hash ] opts The command options. @return [ Array<String> ] The names of the databases. @since 2.0.5
[ "Get", "the", "names", "of", "all", "databases", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/client.rb#L595-L597
train
mongodb/mongo-ruby-driver
lib/mongo/client.rb
Mongo.Client.list_databases
def list_databases(filter = {}, name_only = false, opts = {}) cmd = { listDatabases: 1 } cmd[:nameOnly] = !!name_only cmd[:filter] = filter unless filter.empty? use(Database::ADMIN).command(cmd, opts).first[Database::DATABASES] end
ruby
def list_databases(filter = {}, name_only = false, opts = {}) cmd = { listDatabases: 1 } cmd[:nameOnly] = !!name_only cmd[:filter] = filter unless filter.empty? use(Database::ADMIN).command(cmd, opts).first[Database::DATABASES] end
[ "def", "list_databases", "(", "filter", "=", "{", "}", ",", "name_only", "=", "false", ",", "opts", "=", "{", "}", ")", "cmd", "=", "{", "listDatabases", ":", "1", "}", "cmd", "[", ":nameOnly", "]", "=", "!", "!", "name_only", "cmd", "[", ":filter", "]", "=", "filter", "unless", "filter", ".", "empty?", "use", "(", "Database", "::", "ADMIN", ")", ".", "command", "(", "cmd", ",", "opts", ")", ".", "first", "[", "Database", "::", "DATABASES", "]", "end" ]
Get info for each database. @example Get the info for each database. client.list_databases @param [ Hash ] filter The filter criteria for getting a list of databases. @param [ true, false ] name_only Whether to only return each database name without full metadata. @param [ Hash ] opts The command options. @return [ Array<Hash> ] The info for each database. @since 2.0.5
[ "Get", "info", "for", "each", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/client.rb#L611-L616
train
mongodb/mongo-ruby-driver
lib/mongo/client.rb
Mongo.Client.start_session
def start_session(options = {}) cluster.send(:get_session, self, options.merge(implicit: false)) || (raise Error::InvalidSession.new(Session::SESSIONS_NOT_SUPPORTED)) end
ruby
def start_session(options = {}) cluster.send(:get_session, self, options.merge(implicit: false)) || (raise Error::InvalidSession.new(Session::SESSIONS_NOT_SUPPORTED)) end
[ "def", "start_session", "(", "options", "=", "{", "}", ")", "cluster", ".", "send", "(", ":get_session", ",", "self", ",", "options", ".", "merge", "(", "implicit", ":", "false", ")", ")", "||", "(", "raise", "Error", "::", "InvalidSession", ".", "new", "(", "Session", "::", "SESSIONS_NOT_SUPPORTED", ")", ")", "end" ]
Start a session. If the deployment does not support sessions, raises Mongo::Error::InvalidSession. This exception can also be raised when the driver is not connected to a data-bearing server, for example during failover. @example Start a session. client.start_session(causal_consistency: true) @param [ Hash ] options The session options. Accepts the options that Session#initialize accepts. @note A Session cannot be used by multiple threads at once; session objects are not thread-safe. @return [ Session ] The session. @since 2.5.0
[ "Start", "a", "session", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/client.rb#L654-L657
train
mongodb/mongo-ruby-driver
lib/mongo/dbref.rb
Mongo.DBRef.as_json
def as_json(*args) document = { COLLECTION => collection, ID => id } document.merge!(DATABASE => database) if database document end
ruby
def as_json(*args) document = { COLLECTION => collection, ID => id } document.merge!(DATABASE => database) if database document end
[ "def", "as_json", "(", "*", "args", ")", "document", "=", "{", "COLLECTION", "=>", "collection", ",", "ID", "=>", "id", "}", "document", ".", "merge!", "(", "DATABASE", "=>", "database", ")", "if", "database", "document", "end" ]
Get the DBRef as a JSON document @example Get the DBRef as a JSON hash. dbref.as_json @return [ Hash ] The max key as a JSON hash. @since 2.1.0
[ "Get", "the", "DBRef", "as", "a", "JSON", "document" ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/dbref.rb#L55-L59
train
mongodb/mongo-ruby-driver
lib/mongo/dbref.rb
Mongo.DBRef.to_bson
def to_bson(buffer = BSON::ByteBuffer.new, validating_keys = BSON::Config.validating_keys?) as_json.to_bson(buffer) end
ruby
def to_bson(buffer = BSON::ByteBuffer.new, validating_keys = BSON::Config.validating_keys?) as_json.to_bson(buffer) end
[ "def", "to_bson", "(", "buffer", "=", "BSON", "::", "ByteBuffer", ".", "new", ",", "validating_keys", "=", "BSON", "::", "Config", ".", "validating_keys?", ")", "as_json", ".", "to_bson", "(", "buffer", ")", "end" ]
Instantiate a new DBRef. @example Create the DBRef. Mongo::DBRef.new('users', id, 'database') @param [ String ] collection The collection name. @param [ BSON::ObjectId ] id The object id. @param [ String ] database The database name. @since 2.1.0 Converts the DBRef to raw BSON. @example Convert the DBRef to raw BSON. dbref.to_bson @param [ BSON::ByteBuffer ] buffer The encoded BSON buffer to append to. @param [ true, false ] validating_keys Whether keys should be validated when serializing. @return [ String ] The raw BSON. @since 2.1.0
[ "Instantiate", "a", "new", "DBRef", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/dbref.rb#L88-L90
train
mongodb/mongo-ruby-driver
lib/mongo/cluster.rb
Mongo.Cluster.disconnect!
def disconnect!(wait=false) unless @connecting || @connected return true end @periodic_executor.stop! @servers.each do |server| if server.connected? server.disconnect!(wait) publish_sdam_event( Monitoring::SERVER_CLOSED, Monitoring::Event::ServerClosed.new(server.address, topology) ) end end publish_sdam_event( Monitoring::TOPOLOGY_CLOSED, Monitoring::Event::TopologyClosed.new(topology) ) @connecting = @connected = false true end
ruby
def disconnect!(wait=false) unless @connecting || @connected return true end @periodic_executor.stop! @servers.each do |server| if server.connected? server.disconnect!(wait) publish_sdam_event( Monitoring::SERVER_CLOSED, Monitoring::Event::ServerClosed.new(server.address, topology) ) end end publish_sdam_event( Monitoring::TOPOLOGY_CLOSED, Monitoring::Event::TopologyClosed.new(topology) ) @connecting = @connected = false true end
[ "def", "disconnect!", "(", "wait", "=", "false", ")", "unless", "@connecting", "||", "@connected", "return", "true", "end", "@periodic_executor", ".", "stop!", "@servers", ".", "each", "do", "|", "server", "|", "if", "server", ".", "connected?", "server", ".", "disconnect!", "(", "wait", ")", "publish_sdam_event", "(", "Monitoring", "::", "SERVER_CLOSED", ",", "Monitoring", "::", "Event", "::", "ServerClosed", ".", "new", "(", "server", ".", "address", ",", "topology", ")", ")", "end", "end", "publish_sdam_event", "(", "Monitoring", "::", "TOPOLOGY_CLOSED", ",", "Monitoring", "::", "Event", "::", "TopologyClosed", ".", "new", "(", "topology", ")", ")", "@connecting", "=", "@connected", "=", "false", "true", "end" ]
Disconnect all servers. @note Applications should call Client#close to disconnect from the cluster rather than calling this method. This method is for internal driver use only. @example Disconnect the cluster's servers. cluster.disconnect! @param [ Boolean ] wait Whether to wait for background threads to finish running. @return [ true ] Always true. @since 2.1.0
[ "Disconnect", "all", "servers", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cluster.rb#L392-L412
train
mongodb/mongo-ruby-driver
lib/mongo/cluster.rb
Mongo.Cluster.reconnect!
def reconnect! @connecting = true scan! servers.each do |server| server.reconnect! end @periodic_executor.restart! @connecting = false @connected = true end
ruby
def reconnect! @connecting = true scan! servers.each do |server| server.reconnect! end @periodic_executor.restart! @connecting = false @connected = true end
[ "def", "reconnect!", "@connecting", "=", "true", "scan!", "servers", ".", "each", "do", "|", "server", "|", "server", ".", "reconnect!", "end", "@periodic_executor", ".", "restart!", "@connecting", "=", "false", "@connected", "=", "true", "end" ]
Reconnect all servers. @example Reconnect the cluster's servers. cluster.reconnect! @return [ true ] Always true. @since 2.1.0 @deprecated Use Client#reconnect to reconnect to the cluster instead of calling this method. This method does not send SDAM events.
[ "Reconnect", "all", "servers", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cluster.rb#L424-L433
train
mongodb/mongo-ruby-driver
lib/mongo/cluster.rb
Mongo.Cluster.scan!
def scan!(sync=true) if sync servers_list.each do |server| server.scan! end else servers_list.each do |server| server.monitor.scan_semaphore.signal end end true end
ruby
def scan!(sync=true) if sync servers_list.each do |server| server.scan! end else servers_list.each do |server| server.monitor.scan_semaphore.signal end end true end
[ "def", "scan!", "(", "sync", "=", "true", ")", "if", "sync", "servers_list", ".", "each", "do", "|", "server", "|", "server", ".", "scan!", "end", "else", "servers_list", ".", "each", "do", "|", "server", "|", "server", ".", "monitor", ".", "scan_semaphore", ".", "signal", "end", "end", "true", "end" ]
Force a scan of all known servers in the cluster. If the sync parameter is true which is the default, the scan is performed synchronously in the thread which called this method. Each server in the cluster is checked sequentially. If there are many servers in the cluster or they are slow to respond, this can be a long running operation. If the sync parameter is false, this method instructs all server monitor threads to perform an immediate scan and returns without waiting for scan results. @note In both synchronous and asynchronous scans, each monitor thread maintains a minimum interval between scans, meaning calling this method may not initiate a scan on a particular server the very next instant. @example Force a full cluster scan. cluster.scan! @return [ true ] Always true. @since 2.0.0
[ "Force", "a", "scan", "of", "all", "known", "servers", "in", "the", "cluster", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cluster.rb#L458-L469
train
mongodb/mongo-ruby-driver
lib/mongo/cluster.rb
Mongo.Cluster.update_cluster_time
def update_cluster_time(result) if cluster_time_doc = result.cluster_time @cluster_time_lock.synchronize do if @cluster_time.nil? @cluster_time = cluster_time_doc elsif cluster_time_doc[CLUSTER_TIME] > @cluster_time[CLUSTER_TIME] @cluster_time = cluster_time_doc end end end end
ruby
def update_cluster_time(result) if cluster_time_doc = result.cluster_time @cluster_time_lock.synchronize do if @cluster_time.nil? @cluster_time = cluster_time_doc elsif cluster_time_doc[CLUSTER_TIME] > @cluster_time[CLUSTER_TIME] @cluster_time = cluster_time_doc end end end end
[ "def", "update_cluster_time", "(", "result", ")", "if", "cluster_time_doc", "=", "result", ".", "cluster_time", "@cluster_time_lock", ".", "synchronize", "do", "if", "@cluster_time", ".", "nil?", "@cluster_time", "=", "cluster_time_doc", "elsif", "cluster_time_doc", "[", "CLUSTER_TIME", "]", ">", "@cluster_time", "[", "CLUSTER_TIME", "]", "@cluster_time", "=", "cluster_time_doc", "end", "end", "end", "end" ]
Update the max cluster time seen in a response. @example Update the cluster time. cluster.update_cluster_time(result) @param [ Operation::Result ] result The operation result containing the cluster time. @return [ Object ] The cluster time. @since 2.5.0
[ "Update", "the", "max", "cluster", "time", "seen", "in", "a", "response", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cluster.rb#L559-L569
train
mongodb/mongo-ruby-driver
lib/mongo/cluster.rb
Mongo.Cluster.add
def add(host, add_options=nil) address = Address.new(host, options) if !addresses.include?(address) server = Server.new(address, self, @monitoring, event_listeners, options.merge( monitor: false)) @update_lock.synchronize { @servers.push(server) } if add_options.nil? || add_options[:monitor] != false server.start_monitoring end server end end
ruby
def add(host, add_options=nil) address = Address.new(host, options) if !addresses.include?(address) server = Server.new(address, self, @monitoring, event_listeners, options.merge( monitor: false)) @update_lock.synchronize { @servers.push(server) } if add_options.nil? || add_options[:monitor] != false server.start_monitoring end server end end
[ "def", "add", "(", "host", ",", "add_options", "=", "nil", ")", "address", "=", "Address", ".", "new", "(", "host", ",", "options", ")", "if", "!", "addresses", ".", "include?", "(", "address", ")", "server", "=", "Server", ".", "new", "(", "address", ",", "self", ",", "@monitoring", ",", "event_listeners", ",", "options", ".", "merge", "(", "monitor", ":", "false", ")", ")", "@update_lock", ".", "synchronize", "{", "@servers", ".", "push", "(", "server", ")", "}", "if", "add_options", ".", "nil?", "||", "add_options", "[", ":monitor", "]", "!=", "false", "server", ".", "start_monitoring", "end", "server", "end", "end" ]
Add a server to the cluster with the provided address. Useful in auto-discovery of new servers when an existing server executes an ismaster and potentially non-configured servers were included. @example Add the server for the address to the cluster. cluster.add('127.0.0.1:27018') @param [ String ] host The address of the server to add. @option options [ Boolean ] :monitor For internal driver use only: whether to monitor the newly added server. @return [ Server ] The newly added server, if not present already. @since 2.0.0
[ "Add", "a", "server", "to", "the", "cluster", "with", "the", "provided", "address", ".", "Useful", "in", "auto", "-", "discovery", "of", "new", "servers", "when", "an", "existing", "server", "executes", "an", "ismaster", "and", "potentially", "non", "-", "configured", "servers", "were", "included", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cluster.rb#L586-L597
train
mongodb/mongo-ruby-driver
lib/mongo/cluster.rb
Mongo.Cluster.remove
def remove(host) address = Address.new(host) removed_servers = @servers.select { |s| s.address == address } @update_lock.synchronize { @servers = @servers - removed_servers } removed_servers.each do |server| if server.connected? server.disconnect! publish_sdam_event( Monitoring::SERVER_CLOSED, Monitoring::Event::ServerClosed.new(address, topology) ) end end removed_servers.any? end
ruby
def remove(host) address = Address.new(host) removed_servers = @servers.select { |s| s.address == address } @update_lock.synchronize { @servers = @servers - removed_servers } removed_servers.each do |server| if server.connected? server.disconnect! publish_sdam_event( Monitoring::SERVER_CLOSED, Monitoring::Event::ServerClosed.new(address, topology) ) end end removed_servers.any? end
[ "def", "remove", "(", "host", ")", "address", "=", "Address", ".", "new", "(", "host", ")", "removed_servers", "=", "@servers", ".", "select", "{", "|", "s", "|", "s", ".", "address", "==", "address", "}", "@update_lock", ".", "synchronize", "{", "@servers", "=", "@servers", "-", "removed_servers", "}", "removed_servers", ".", "each", "do", "|", "server", "|", "if", "server", ".", "connected?", "server", ".", "disconnect!", "publish_sdam_event", "(", "Monitoring", "::", "SERVER_CLOSED", ",", "Monitoring", "::", "Event", "::", "ServerClosed", ".", "new", "(", "address", ",", "topology", ")", ")", "end", "end", "removed_servers", ".", "any?", "end" ]
Remove the server from the cluster for the provided address, if it exists. @example Remove the server from the cluster. server.remove('127.0.0.1:27017') @param [ String ] host The host/port or socket address. @return [ true|false ] Whether any servers were removed. @since 2.0.0, return value added in 2.7.0
[ "Remove", "the", "server", "from", "the", "cluster", "for", "the", "provided", "address", "if", "it", "exists", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cluster.rb#L610-L624
train
mongodb/mongo-ruby-driver
lib/mongo/address.rb
Mongo.Address.socket
def socket(socket_timeout, ssl_options = {}, options = {}) create_resolver(ssl_options).socket(socket_timeout, ssl_options, options) end
ruby
def socket(socket_timeout, ssl_options = {}, options = {}) create_resolver(ssl_options).socket(socket_timeout, ssl_options, options) end
[ "def", "socket", "(", "socket_timeout", ",", "ssl_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "create_resolver", "(", "ssl_options", ")", ".", "socket", "(", "socket_timeout", ",", "ssl_options", ",", "options", ")", "end" ]
Get a socket for the provided address, given the options. The address the socket connects to is determined by the algorithm described in the #intialize_resolver! documentation. Each time this method is called, #initialize_resolver! will be called, meaning that a new hostname lookup will occur. This is done so that any changes to which addresses the hostname resolves to will be picked up even if a socket has been connected to it before. @example Get a socket. address.socket(5, :ssl => true) @param [ Float ] socket_timeout The socket timeout. @param [ Hash ] ssl_options SSL options. @param [ Hash ] options The options. @option options [ Float ] :connect_timeout Connect timeout. @return [ Mongo::Socket::SSL, Mongo::Socket::TCP, Mongo::Socket::Unix ] The socket. @since 2.0.0
[ "Get", "a", "socket", "for", "the", "provided", "address", "given", "the", "options", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/address.rb#L157-L159
train
mongodb/mongo-ruby-driver
lib/mongo/bulk_write.rb
Mongo.BulkWrite.execute
def execute operation_id = Monitoring.next_operation_id result_combiner = ResultCombiner.new operations = op_combiner.combine client.send(:with_session, @options) do |session| operations.each do |operation| if single_statement?(operation) write_with_retry(session, write_concern) do |server, txn_num| execute_operation( operation.keys.first, operation.values.flatten, server, operation_id, result_combiner, session, txn_num) end else legacy_write_with_retry do |server| execute_operation( operation.keys.first, operation.values.flatten, server, operation_id, result_combiner, session) end end end end result_combiner.result end
ruby
def execute operation_id = Monitoring.next_operation_id result_combiner = ResultCombiner.new operations = op_combiner.combine client.send(:with_session, @options) do |session| operations.each do |operation| if single_statement?(operation) write_with_retry(session, write_concern) do |server, txn_num| execute_operation( operation.keys.first, operation.values.flatten, server, operation_id, result_combiner, session, txn_num) end else legacy_write_with_retry do |server| execute_operation( operation.keys.first, operation.values.flatten, server, operation_id, result_combiner, session) end end end end result_combiner.result end
[ "def", "execute", "operation_id", "=", "Monitoring", ".", "next_operation_id", "result_combiner", "=", "ResultCombiner", ".", "new", "operations", "=", "op_combiner", ".", "combine", "client", ".", "send", "(", ":with_session", ",", "@options", ")", "do", "|", "session", "|", "operations", ".", "each", "do", "|", "operation", "|", "if", "single_statement?", "(", "operation", ")", "write_with_retry", "(", "session", ",", "write_concern", ")", "do", "|", "server", ",", "txn_num", "|", "execute_operation", "(", "operation", ".", "keys", ".", "first", ",", "operation", ".", "values", ".", "flatten", ",", "server", ",", "operation_id", ",", "result_combiner", ",", "session", ",", "txn_num", ")", "end", "else", "legacy_write_with_retry", "do", "|", "server", "|", "execute_operation", "(", "operation", ".", "keys", ".", "first", ",", "operation", ".", "values", ".", "flatten", ",", "server", ",", "operation_id", ",", "result_combiner", ",", "session", ")", "end", "end", "end", "end", "result_combiner", ".", "result", "end" ]
Execute the bulk write operation. @example Execute the bulk write. bulk_write.execute @return [ Mongo::BulkWrite::Result ] The result. @since 2.1.0
[ "Execute", "the", "bulk", "write", "operation", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/bulk_write.rb#L53-L85
train
mongodb/mongo-ruby-driver
spec/support/server_discovery_and_monitoring.rb
Mongo.SDAM.find_server
def find_server(client, address_str) client.cluster.servers_list.detect{ |s| s.address.to_s == address_str } end
ruby
def find_server(client, address_str) client.cluster.servers_list.detect{ |s| s.address.to_s == address_str } end
[ "def", "find_server", "(", "client", ",", "address_str", ")", "client", ".", "cluster", ".", "servers_list", ".", "detect", "{", "|", "s", "|", "s", ".", "address", ".", "to_s", "==", "address_str", "}", "end" ]
Convenience helper to find a server by it's URI. @since 2.0.0
[ "Convenience", "helper", "to", "find", "a", "server", "by", "it", "s", "URI", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/spec/support/server_discovery_and_monitoring.rb#L47-L49
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.apply_transform
def apply_transform(key, value, type) if type if respond_to?("convert_#{type}", true) send("convert_#{type}", key, value) else send(type, value) end else value end end
ruby
def apply_transform(key, value, type) if type if respond_to?("convert_#{type}", true) send("convert_#{type}", key, value) else send(type, value) end else value end end
[ "def", "apply_transform", "(", "key", ",", "value", ",", "type", ")", "if", "type", "if", "respond_to?", "(", "\"convert_#{type}\"", ",", "true", ")", "send", "(", "\"convert_#{type}\"", ",", "key", ",", "value", ")", "else", "send", "(", "type", ",", "value", ")", "end", "else", "value", "end", "end" ]
Applies URI value transformation by either using the default cast or a transformation appropriate for the given type. @param key [String] URI option name. @param value [String] The value to be transformed. @param type [Symbol] The transform method.
[ "Applies", "URI", "value", "transformation", "by", "either", "using", "the", "default", "cast", "or", "a", "transformation", "appropriate", "for", "the", "given", "type", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L539-L549
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.merge_uri_option
def merge_uri_option(target, value, name) if target.key?(name) if REPEATABLE_OPTIONS.include?(name) target[name] += value else log_warn("Repeated option key: #{name}.") end else target.merge!(name => value) end end
ruby
def merge_uri_option(target, value, name) if target.key?(name) if REPEATABLE_OPTIONS.include?(name) target[name] += value else log_warn("Repeated option key: #{name}.") end else target.merge!(name => value) end end
[ "def", "merge_uri_option", "(", "target", ",", "value", ",", "name", ")", "if", "target", ".", "key?", "(", "name", ")", "if", "REPEATABLE_OPTIONS", ".", "include?", "(", "name", ")", "target", "[", "name", "]", "+=", "value", "else", "log_warn", "(", "\"Repeated option key: #{name}.\"", ")", "end", "else", "target", ".", "merge!", "(", "name", "=>", "value", ")", "end", "end" ]
Merges a new option into the target. If the option exists at the target destination the merge will be an addition. Specifically required to append an additional tag set to the array of tag sets without overwriting the original. @param target [Hash] The destination. @param value [Object] The value to be merged. @param name [Symbol] The name of the option.
[ "Merges", "a", "new", "option", "into", "the", "target", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L576-L586
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.add_uri_option
def add_uri_option(key, strategy, value, uri_options) target = select_target(uri_options, strategy[:group]) value = apply_transform(key, value, strategy[:type]) merge_uri_option(target, value, strategy[:name]) end
ruby
def add_uri_option(key, strategy, value, uri_options) target = select_target(uri_options, strategy[:group]) value = apply_transform(key, value, strategy[:type]) merge_uri_option(target, value, strategy[:name]) end
[ "def", "add_uri_option", "(", "key", ",", "strategy", ",", "value", ",", "uri_options", ")", "target", "=", "select_target", "(", "uri_options", ",", "strategy", "[", ":group", "]", ")", "value", "=", "apply_transform", "(", "key", ",", "value", ",", "strategy", "[", ":type", "]", ")", "merge_uri_option", "(", "target", ",", "value", ",", "strategy", "[", ":name", "]", ")", "end" ]
Adds an option to the uri options hash via the supplied strategy. Acquires a target for the option based on group. Transforms the value. Merges the option into the target. @param key [String] URI option name. @param strategy [Symbol] The strategy for this option. @param value [String] The value of the option. @param uri_options [Hash] The base option target.
[ "Adds", "an", "option", "to", "the", "uri", "options", "hash", "via", "the", "supplied", "strategy", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L598-L602
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.auth_mech_props
def auth_mech_props(value) properties = hash_extractor('authMechanismProperties', value) if properties[:canonicalize_host_name] properties.merge!(canonicalize_host_name: %w(true TRUE).include?(properties[:canonicalize_host_name])) end properties end
ruby
def auth_mech_props(value) properties = hash_extractor('authMechanismProperties', value) if properties[:canonicalize_host_name] properties.merge!(canonicalize_host_name: %w(true TRUE).include?(properties[:canonicalize_host_name])) end properties end
[ "def", "auth_mech_props", "(", "value", ")", "properties", "=", "hash_extractor", "(", "'authMechanismProperties'", ",", "value", ")", "if", "properties", "[", ":canonicalize_host_name", "]", "properties", ".", "merge!", "(", "canonicalize_host_name", ":", "%w(", "true", "TRUE", ")", ".", "include?", "(", "properties", "[", ":canonicalize_host_name", "]", ")", ")", "end", "properties", "end" ]
Auth mechanism properties extractor. @param value [ String ] The auth mechanism properties string. @return [ Hash ] The auth mechanism properties hash.
[ "Auth", "mechanism", "properties", "extractor", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L666-L673
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.zlib_compression_level
def zlib_compression_level(value) if /\A-?\d+\z/ =~ value i = value.to_i if i >= -1 && i <= 9 return i end end log_warn("#{value} is not a valid zlibCompressionLevel") nil end
ruby
def zlib_compression_level(value) if /\A-?\d+\z/ =~ value i = value.to_i if i >= -1 && i <= 9 return i end end log_warn("#{value} is not a valid zlibCompressionLevel") nil end
[ "def", "zlib_compression_level", "(", "value", ")", "if", "/", "\\A", "\\d", "\\z", "/", "=~", "value", "i", "=", "value", ".", "to_i", "if", "i", ">=", "-", "1", "&&", "i", "<=", "9", "return", "i", "end", "end", "log_warn", "(", "\"#{value} is not a valid zlibCompressionLevel\"", ")", "nil", "end" ]
Parses the zlib compression level. @param value [ String ] The zlib compression level string. @return [ Integer | nil ] The compression level value if it is between -1 and 9 (inclusive), otherwise nil (and a warning will be logged).
[ "Parses", "the", "zlib", "compression", "level", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L681-L692
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.inverse_bool
def inverse_bool(name, value) b = convert_bool(name, value) if b.nil? nil else !b end end
ruby
def inverse_bool(name, value) b = convert_bool(name, value) if b.nil? nil else !b end end
[ "def", "inverse_bool", "(", "name", ",", "value", ")", "b", "=", "convert_bool", "(", "name", ",", "value", ")", "if", "b", ".", "nil?", "nil", "else", "!", "b", "end", "end" ]
Parses a boolean value and returns its inverse. @param value [ String ] The URI option value. @return [ true | false | nil ] The inverse of the boolean value parsed out, otherwise nil (and a warning will be logged).
[ "Parses", "a", "boolean", "value", "and", "returns", "its", "inverse", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L872-L880
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.max_staleness
def max_staleness(value) if /\A\d+\z/ =~ value int = value.to_i if int >= 0 && int < 90 log_warn("max staleness must be either 0 or greater than 90: #{value}") end return int end log_warn("Invalid max staleness value: #{value}") nil end
ruby
def max_staleness(value) if /\A\d+\z/ =~ value int = value.to_i if int >= 0 && int < 90 log_warn("max staleness must be either 0 or greater than 90: #{value}") end return int end log_warn("Invalid max staleness value: #{value}") nil end
[ "def", "max_staleness", "(", "value", ")", "if", "/", "\\A", "\\d", "\\z", "/", "=~", "value", "int", "=", "value", ".", "to_i", "if", "int", ">=", "0", "&&", "int", "<", "90", "log_warn", "(", "\"max staleness must be either 0 or greater than 90: #{value}\"", ")", "end", "return", "int", "end", "log_warn", "(", "\"Invalid max staleness value: #{value}\"", ")", "nil", "end" ]
Parses the max staleness value, which must be either "0" or an integer greater or equal to 90. @param value [ String ] The max staleness string. @return [ Integer | nil ] The max staleness integer parsed out if it is valid, otherwise nil (and a warning will be logged).
[ "Parses", "the", "max", "staleness", "value", "which", "must", "be", "either", "0", "or", "an", "integer", "greater", "or", "equal", "to", "90", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L888-L901
train
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.hash_extractor
def hash_extractor(name, value) value.split(',').reduce({}) do |set, tag| k, v = tag.split(':') if v.nil? log_warn("Invalid hash value for #{name}: #{value}") return nil end set.merge(decode(k).downcase.to_sym => decode(v)) end end
ruby
def hash_extractor(name, value) value.split(',').reduce({}) do |set, tag| k, v = tag.split(':') if v.nil? log_warn("Invalid hash value for #{name}: #{value}") return nil end set.merge(decode(k).downcase.to_sym => decode(v)) end end
[ "def", "hash_extractor", "(", "name", ",", "value", ")", "value", ".", "split", "(", "','", ")", ".", "reduce", "(", "{", "}", ")", "do", "|", "set", ",", "tag", "|", "k", ",", "v", "=", "tag", ".", "split", "(", "':'", ")", "if", "v", ".", "nil?", "log_warn", "(", "\"Invalid hash value for #{name}: #{value}\"", ")", "return", "nil", "end", "set", ".", "merge", "(", "decode", "(", "k", ")", ".", "downcase", ".", "to_sym", "=>", "decode", "(", "v", ")", ")", "end", "end" ]
Extract values from the string and put them into a nested hash. @param value [ String ] The string to build a hash from. @return [ Hash ] The hash built from the string.
[ "Extract", "values", "from", "the", "string", "and", "put", "them", "into", "a", "nested", "hash", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L1016-L1026
train
mongodb/mongo-ruby-driver
lib/mongo/cursor.rb
Mongo.Cursor.each
def each process(@initial_result).each { |doc| yield doc } while more? return kill_cursors if exhausted? get_more.each { |doc| yield doc } end end
ruby
def each process(@initial_result).each { |doc| yield doc } while more? return kill_cursors if exhausted? get_more.each { |doc| yield doc } end end
[ "def", "each", "process", "(", "@initial_result", ")", ".", "each", "{", "|", "doc", "|", "yield", "doc", "}", "while", "more?", "return", "kill_cursors", "if", "exhausted?", "get_more", ".", "each", "{", "|", "doc", "|", "yield", "doc", "}", "end", "end" ]
Iterate through documents returned from the query. @example Iterate over the documents in the cursor. cursor.each do |doc| ... end @return [ Enumerator ] The enumerator. @since 2.0.0
[ "Iterate", "through", "documents", "returned", "from", "the", "query", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/cursor.rb#L127-L133
train
mongodb/mongo-ruby-driver
lib/mongo/server.rb
Mongo.Server.disconnect!
def disconnect!(wait=false) begin # For backwards compatibility we disconnect/clear the pool rather # than close it here. pool.disconnect! rescue Error::PoolClosedError # If the pool was already closed, we don't need to do anything here. end monitor.stop!(wait) @connected = false true end
ruby
def disconnect!(wait=false) begin # For backwards compatibility we disconnect/clear the pool rather # than close it here. pool.disconnect! rescue Error::PoolClosedError # If the pool was already closed, we don't need to do anything here. end monitor.stop!(wait) @connected = false true end
[ "def", "disconnect!", "(", "wait", "=", "false", ")", "begin", "# For backwards compatibility we disconnect/clear the pool rather", "# than close it here.", "pool", ".", "disconnect!", "rescue", "Error", "::", "PoolClosedError", "# If the pool was already closed, we don't need to do anything here.", "end", "monitor", ".", "stop!", "(", "wait", ")", "@connected", "=", "false", "true", "end" ]
Disconnect the server from the connection. @example Disconnect the server. server.disconnect! @param [ Boolean ] wait Whether to wait for background threads to finish running. @return [ true ] Always true with no exception. @since 2.0.0
[ "Disconnect", "the", "server", "from", "the", "connection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server.rb#L183-L194
train
mongodb/mongo-ruby-driver
lib/mongo/server.rb
Mongo.Server.start_monitoring
def start_monitoring publish_sdam_event( Monitoring::SERVER_OPENING, Monitoring::Event::ServerOpening.new(address, cluster.topology) ) if options[:monitoring_io] != false monitor.run! ObjectSpace.define_finalizer(self, self.class.finalize(monitor)) end end
ruby
def start_monitoring publish_sdam_event( Monitoring::SERVER_OPENING, Monitoring::Event::ServerOpening.new(address, cluster.topology) ) if options[:monitoring_io] != false monitor.run! ObjectSpace.define_finalizer(self, self.class.finalize(monitor)) end end
[ "def", "start_monitoring", "publish_sdam_event", "(", "Monitoring", "::", "SERVER_OPENING", ",", "Monitoring", "::", "Event", "::", "ServerOpening", ".", "new", "(", "address", ",", "cluster", ".", "topology", ")", ")", "if", "options", "[", ":monitoring_io", "]", "!=", "false", "monitor", ".", "run!", "ObjectSpace", ".", "define_finalizer", "(", "self", ",", "self", ".", "class", ".", "finalize", "(", "monitor", ")", ")", "end", "end" ]
Start monitoring the server. Used internally by the driver to add a server to a cluster while delaying monitoring until the server is in the cluster. @api private
[ "Start", "monitoring", "the", "server", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server.rb#L225-L234
train
mongodb/mongo-ruby-driver
lib/mongo/server.rb
Mongo.Server.matches_tag_set?
def matches_tag_set?(tag_set) tag_set.keys.all? do |k| tags[k] && tags[k] == tag_set[k] end end
ruby
def matches_tag_set?(tag_set) tag_set.keys.all? do |k| tags[k] && tags[k] == tag_set[k] end end
[ "def", "matches_tag_set?", "(", "tag_set", ")", "tag_set", ".", "keys", ".", "all?", "do", "|", "k", "|", "tags", "[", "k", "]", "&&", "tags", "[", "k", "]", "==", "tag_set", "[", "k", "]", "end", "end" ]
Determine if the provided tags are a subset of the server's tags. @example Are the provided tags a subset of the server's tags. server.matches_tag_set?({ 'rack' => 'a', 'dc' => 'nyc' }) @param [ Hash ] tag_set The tag set to compare to the server's tags. @return [ true, false ] If the provided tags are a subset of the server's tags. @since 2.0.0
[ "Determine", "if", "the", "provided", "tags", "are", "a", "subset", "of", "the", "server", "s", "tags", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server.rb#L308-L312
train
mongodb/mongo-ruby-driver
lib/mongo/server.rb
Mongo.Server.handle_auth_failure!
def handle_auth_failure! yield rescue Mongo::Error::SocketTimeoutError # possibly cluster is slow, do not give up on it raise rescue Mongo::Error::SocketError # non-timeout network error unknown! pool.disconnect! raise rescue Auth::Unauthorized # auth error, keep server description and topology as they are pool.disconnect! raise end
ruby
def handle_auth_failure! yield rescue Mongo::Error::SocketTimeoutError # possibly cluster is slow, do not give up on it raise rescue Mongo::Error::SocketError # non-timeout network error unknown! pool.disconnect! raise rescue Auth::Unauthorized # auth error, keep server description and topology as they are pool.disconnect! raise end
[ "def", "handle_auth_failure!", "yield", "rescue", "Mongo", "::", "Error", "::", "SocketTimeoutError", "# possibly cluster is slow, do not give up on it", "raise", "rescue", "Mongo", "::", "Error", "::", "SocketError", "# non-timeout network error", "unknown!", "pool", ".", "disconnect!", "raise", "rescue", "Auth", "::", "Unauthorized", "# auth error, keep server description and topology as they are", "pool", ".", "disconnect!", "raise", "end" ]
Handle authentication failure. @example Handle possible authentication failure. server.handle_auth_failure! do Auth.get(user).login(self) end @raise [ Auth::Unauthorized ] If the authentication failed. @return [ Object ] The result of the block execution. @since 2.3.0
[ "Handle", "authentication", "failure", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server.rb#L367-L381
train
mongodb/mongo-ruby-driver
profile/benchmarking/helper.rb
Mongo.Benchmarking.load_file
def load_file(file_name) File.open(file_name, "r") do |f| f.each_line.collect do |line| parse_json(line) end end end
ruby
def load_file(file_name) File.open(file_name, "r") do |f| f.each_line.collect do |line| parse_json(line) end end end
[ "def", "load_file", "(", "file_name", ")", "File", ".", "open", "(", "file_name", ",", "\"r\"", ")", "do", "|", "f", "|", "f", ".", "each_line", ".", "collect", "do", "|", "line", "|", "parse_json", "(", "line", ")", "end", "end", "end" ]
Load a json file and represent each document as a Hash. @example Load a file. Benchmarking.load_file(file_name) @param [ String ] The file name. @return [ Array ] A list of extended-json documents. @since 2.2.3
[ "Load", "a", "json", "file", "and", "represent", "each", "document", "as", "a", "Hash", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/profile/benchmarking/helper.rb#L18-L24
train
mongodb/mongo-ruby-driver
lib/mongo/auth.rb
Mongo.Auth.get
def get(user) mechanism = user.mechanism raise InvalidMechanism.new(mechanism) if !SOURCES.has_key?(mechanism) SOURCES[mechanism].new(user) end
ruby
def get(user) mechanism = user.mechanism raise InvalidMechanism.new(mechanism) if !SOURCES.has_key?(mechanism) SOURCES[mechanism].new(user) end
[ "def", "get", "(", "user", ")", "mechanism", "=", "user", ".", "mechanism", "raise", "InvalidMechanism", ".", "new", "(", "mechanism", ")", "if", "!", "SOURCES", ".", "has_key?", "(", "mechanism", ")", "SOURCES", "[", "mechanism", "]", ".", "new", "(", "user", ")", "end" ]
Get the authorization strategy for the provided auth mechanism. @example Get the strategy. Auth.get(user) @param [ Auth::User ] user The user object. @return [ CR, X509, LDAP, Kerberos ] The auth strategy. @since 2.0.0
[ "Get", "the", "authorization", "strategy", "for", "the", "provided", "auth", "mechanism", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/auth.rb#L67-L71
train
mongodb/mongo-ruby-driver
lib/mongo/monitoring.rb
Mongo.Monitoring.started
def started(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.started(event) } end
ruby
def started(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.started(event) } end
[ "def", "started", "(", "topic", ",", "event", ")", "subscribers_for", "(", "topic", ")", ".", "each", "{", "|", "subscriber", "|", "subscriber", ".", "started", "(", "event", ")", "}", "end" ]
Publish a started event. @example Publish a started event. monitoring.started(COMMAND, event) @param [ String ] topic The event topic. @param [ Event ] event The event to publish. @since 2.1.0
[ "Publish", "a", "started", "event", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/monitoring.rb#L252-L254
train
mongodb/mongo-ruby-driver
lib/mongo/monitoring.rb
Mongo.Monitoring.succeeded
def succeeded(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.succeeded(event) } end
ruby
def succeeded(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.succeeded(event) } end
[ "def", "succeeded", "(", "topic", ",", "event", ")", "subscribers_for", "(", "topic", ")", ".", "each", "{", "|", "subscriber", "|", "subscriber", ".", "succeeded", "(", "event", ")", "}", "end" ]
Publish a succeeded event. @example Publish a succeeded event. monitoring.succeeded(COMMAND, event) @param [ String ] topic The event topic. @param [ Event ] event The event to publish. @since 2.1.0
[ "Publish", "a", "succeeded", "event", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/monitoring.rb#L265-L267
train
mongodb/mongo-ruby-driver
lib/mongo/monitoring.rb
Mongo.Monitoring.failed
def failed(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.failed(event) } end
ruby
def failed(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.failed(event) } end
[ "def", "failed", "(", "topic", ",", "event", ")", "subscribers_for", "(", "topic", ")", ".", "each", "{", "|", "subscriber", "|", "subscriber", ".", "failed", "(", "event", ")", "}", "end" ]
Publish a failed event. @example Publish a failed event. monitoring.failed(COMMAND, event) @param [ String ] topic The event topic. @param [ Event ] event The event to publish. @since 2.1.0
[ "Publish", "a", "failed", "event", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/monitoring.rb#L278-L280
train