id
int32
0
24.9k
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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
13,100
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
13,101
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
13,102
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
13,103
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
13,104
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
13,105
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
13,106
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
13,107
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
13,108
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
13,109
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
13,110
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
13,111
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
13,112
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
13,113
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
13,114
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
13,115
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
13,116
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
13,117
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
13,118
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
13,119
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
13,120
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
13,121
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
13,122
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
13,123
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
13,124
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
13,125
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
13,126
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
13,127
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
13,128
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
13,129
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
13,130
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
13,131
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
13,132
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
13,133
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
13,134
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
13,135
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
13,136
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
13,137
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
13,138
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
13,139
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
13,140
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
13,141
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
13,142
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
13,143
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
13,144
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
13,145
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
13,146
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
13,147
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
13,148
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
13,149
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
13,150
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
13,151
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
13,152
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
13,153
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
13,154
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
13,155
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
13,156
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
13,157
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
13,158
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
13,159
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
13,160
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
13,161
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
13,162
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
13,163
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
13,164
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
13,165
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
13,166
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
13,167
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
13,168
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
13,169
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
13,170
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
13,171
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
13,172
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
13,173
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
13,174
mongodb/mongo-ruby-driver
lib/mongo/write_concern.rb
Mongo.WriteConcern.get
def get(options) return options if options.is_a?(Unacknowledged) || options.is_a?(Acknowledged) if options validate!(options) if unacknowledged?(options) Unacknowledged.new(options) else Acknowledged.new(options) end end end
ruby
def get(options) return options if options.is_a?(Unacknowledged) || options.is_a?(Acknowledged) if options validate!(options) if unacknowledged?(options) Unacknowledged.new(options) else Acknowledged.new(options) end end end
[ "def", "get", "(", "options", ")", "return", "options", "if", "options", ".", "is_a?", "(", "Unacknowledged", ")", "||", "options", ".", "is_a?", "(", "Acknowledged", ")", "if", "options", "validate!", "(", "options", ")", "if", "unacknowledged?", "(", "options", ")", "Unacknowledged", ".", "new", "(", "options", ")", "else", "Acknowledged", ".", "new", "(", "options", ")", "end", "end", "end" ]
Create a write concern object for the provided options. @example Get a write concern. Mongo::WriteConcern.get(:w => 1) @param [ Hash ] options The options to instantiate with. @option options :w [ Integer, String ] The number of servers or the custom mode to acknowledge. @option options :j [ true, false ] Whether to acknowledge a write to the journal. @option options :fsync [ true, false ] Should the write be synced to disc. @option options :wtimeout [ Integer ] The number of milliseconds to wait for acknowledgement before raising an error. @return [ Unacknowledged, Acknowledged ] The appropriate concern. @raise [ Error::InvalidWriteConcern ] If the options are invalid. @since 2.0.0
[ "Create", "a", "write", "concern", "object", "for", "the", "provided", "options", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/write_concern.rb#L78-L88
13,175
mongodb/mongo-ruby-driver
lib/mongo/database.rb
Mongo.Database.command
def command(operation, opts = {}) txn_read_pref = if opts[:session] && opts[:session].in_transaction? opts[:session].txn_read_preference else nil end txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) preference = ServerSelector.get(txn_read_pref) client.send(:with_session, opts) do |session| read_with_retry(session, preference) do |server| Operation::Command.new({ :selector => operation.dup, :db_name => name, :read => preference, :session => session }).execute(server) end end end
ruby
def command(operation, opts = {}) txn_read_pref = if opts[:session] && opts[:session].in_transaction? opts[:session].txn_read_preference else nil end txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) preference = ServerSelector.get(txn_read_pref) client.send(:with_session, opts) do |session| read_with_retry(session, preference) do |server| Operation::Command.new({ :selector => operation.dup, :db_name => name, :read => preference, :session => session }).execute(server) end end end
[ "def", "command", "(", "operation", ",", "opts", "=", "{", "}", ")", "txn_read_pref", "=", "if", "opts", "[", ":session", "]", "&&", "opts", "[", ":session", "]", ".", "in_transaction?", "opts", "[", ":session", "]", ".", "txn_read_preference", "else", "nil", "end", "txn_read_pref", "||=", "opts", "[", ":read", "]", "||", "ServerSelector", "::", "PRIMARY", "Lint", ".", "validate_underscore_read_preference", "(", "txn_read_pref", ")", "preference", "=", "ServerSelector", ".", "get", "(", "txn_read_pref", ")", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "read_with_retry", "(", "session", ",", "preference", ")", "do", "|", "server", "|", "Operation", "::", "Command", ".", "new", "(", "{", ":selector", "=>", "operation", ".", "dup", ",", ":db_name", "=>", "name", ",", ":read", "=>", "preference", ",", ":session", "=>", "session", "}", ")", ".", "execute", "(", "server", ")", "end", "end", "end" ]
Execute a command on the database. @example Execute a command. database.command(:ismaster => 1) @param [ Hash ] operation The command to execute. @param [ Hash ] opts The command options. @option opts :read [ Hash ] The read preference for this command. @option opts :session [ Session ] The session to use for this command. @return [ Hash ] The result of the command execution.
[ "Execute", "a", "command", "on", "the", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/database.rb#L158-L178
13,176
mongodb/mongo-ruby-driver
lib/mongo/database.rb
Mongo.Database.drop
def drop(options = {}) operation = { :dropDatabase => 1 } client.send(:with_session, options) do |session| Operation::DropDatabase.new({ selector: operation, db_name: name, write_concern: write_concern, session: session }).execute(next_primary) end end
ruby
def drop(options = {}) operation = { :dropDatabase => 1 } client.send(:with_session, options) do |session| Operation::DropDatabase.new({ selector: operation, db_name: name, write_concern: write_concern, session: session }).execute(next_primary) end end
[ "def", "drop", "(", "options", "=", "{", "}", ")", "operation", "=", "{", ":dropDatabase", "=>", "1", "}", "client", ".", "send", "(", ":with_session", ",", "options", ")", "do", "|", "session", "|", "Operation", "::", "DropDatabase", ".", "new", "(", "{", "selector", ":", "operation", ",", "db_name", ":", "name", ",", "write_concern", ":", "write_concern", ",", "session", ":", "session", "}", ")", ".", "execute", "(", "next_primary", ")", "end", "end" ]
Drop the database and all its associated information. @example Drop the database. database.drop @param [ Hash ] options The options for the operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
[ "Drop", "the", "database", "and", "all", "its", "associated", "information", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/database.rb#L192-L202
13,177
mongodb/mongo-ruby-driver
lib/mongo/socket.rb
Mongo.Socket.read
def read(length) handle_errors do data = read_from_socket(length) raise IOError unless (data.length > 0 || length == 0) while data.length < length chunk = read_from_socket(length - data.length) raise IOError unless (chunk.length > 0 || length == 0) data << chunk end data end end
ruby
def read(length) handle_errors do data = read_from_socket(length) raise IOError unless (data.length > 0 || length == 0) while data.length < length chunk = read_from_socket(length - data.length) raise IOError unless (chunk.length > 0 || length == 0) data << chunk end data end end
[ "def", "read", "(", "length", ")", "handle_errors", "do", "data", "=", "read_from_socket", "(", "length", ")", "raise", "IOError", "unless", "(", "data", ".", "length", ">", "0", "||", "length", "==", "0", ")", "while", "data", ".", "length", "<", "length", "chunk", "=", "read_from_socket", "(", "length", "-", "data", ".", "length", ")", "raise", "IOError", "unless", "(", "chunk", ".", "length", ">", "0", "||", "length", "==", "0", ")", "data", "<<", "chunk", "end", "data", "end", "end" ]
Create the new socket for the provided family - ipv4, piv6, or unix. @example Create a new ipv4 socket. Socket.new(Socket::PF_INET) @param [ Integer ] family The socket domain. @since 2.0.0 Will read all data from the socket for the provided number of bytes. If no data is returned, an exception will be raised. @example Read all the requested data from the socket. socket.read(4096) @param [ Integer ] length The number of bytes to read. @raise [ Mongo::SocketError ] If not all data is returned. @return [ Object ] The data from the socket. @since 2.0.0
[ "Create", "the", "new", "socket", "for", "the", "provided", "family", "-", "ipv4", "piv6", "or", "unix", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/socket.rb#L123-L134
13,178
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.end_session
def end_session if !ended? && @client if within_states?(TRANSACTION_IN_PROGRESS_STATE) begin abort_transaction rescue Mongo::Error end end @client.cluster.session_pool.checkin(@server_session) end ensure @server_session = nil end
ruby
def end_session if !ended? && @client if within_states?(TRANSACTION_IN_PROGRESS_STATE) begin abort_transaction rescue Mongo::Error end end @client.cluster.session_pool.checkin(@server_session) end ensure @server_session = nil end
[ "def", "end_session", "if", "!", "ended?", "&&", "@client", "if", "within_states?", "(", "TRANSACTION_IN_PROGRESS_STATE", ")", "begin", "abort_transaction", "rescue", "Mongo", "::", "Error", "end", "end", "@client", ".", "cluster", ".", "session_pool", ".", "checkin", "(", "@server_session", ")", "end", "ensure", "@server_session", "=", "nil", "end" ]
End this session. @example session.end_session @return [ nil ] Always nil. @since 2.5.0
[ "End", "this", "session", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L168-L180
13,179
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.add_txn_num!
def add_txn_num!(command) command.tap do |c| c[:txnNumber] = BSON::Int64.new(@server_session.txn_num) if in_transaction? end end
ruby
def add_txn_num!(command) command.tap do |c| c[:txnNumber] = BSON::Int64.new(@server_session.txn_num) if in_transaction? end end
[ "def", "add_txn_num!", "(", "command", ")", "command", ".", "tap", "do", "|", "c", "|", "c", "[", ":txnNumber", "]", "=", "BSON", "::", "Int64", ".", "new", "(", "@server_session", ".", "txn_num", ")", "if", "in_transaction?", "end", "end" ]
Add the transaction number to a command document if applicable. @example session.add_txn_num!(cmd) @return [ Hash, BSON::Document ] The command document. @since 2.6.0 @api private
[ "Add", "the", "transaction", "number", "to", "a", "command", "document", "if", "applicable", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L248-L252
13,180
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.add_txn_opts!
def add_txn_opts!(command, read) command.tap do |c| # The read preference should be added for all read operations. if read && txn_read_pref = txn_read_preference Mongo::Lint.validate_underscore_read_preference(txn_read_pref) txn_read_pref = txn_read_pref.dup txn_read_pref[:mode] = txn_read_pref[:mode].to_s.gsub(/(_\w)/) { |match| match[1].upcase } Mongo::Lint.validate_camel_case_read_preference(txn_read_pref) c['$readPreference'] = txn_read_pref end # The read concern should be added to any command that starts a transaction. if starting_transaction? # https://jira.mongodb.org/browse/SPEC-1161: transaction's # read concern overrides collection/database/client read concerns, # even if transaction's read concern is not set. # Read concern here is the one sent to the server and may # include afterClusterTime. if rc = c[:readConcern] rc = rc.dup rc.delete(:level) end if txn_read_concern if rc rc.update(txn_read_concern) else rc = txn_read_concern.dup end end if rc.nil? || rc.empty? c.delete(:readConcern) else c[:readConcern ] = rc end end # We need to send the read concern level as a string rather than a symbol. if c[:readConcern] && c[:readConcern][:level] c[:readConcern][:level] = c[:readConcern][:level].to_s end # The write concern should be added to any abortTransaction or commitTransaction command. if (c[:abortTransaction] || c[:commitTransaction]) if @already_committed wc = BSON::Document.new(c[:writeConcern] || txn_write_concern || {}) wc.merge!(w: :majority) wc[:wtimeout] ||= 10000 c[:writeConcern] = wc elsif txn_write_concern c[:writeConcern] ||= txn_write_concern end end # A non-numeric write concern w value needs to be sent as a string rather than a symbol. if c[:writeConcern] && c[:writeConcern][:w] && c[:writeConcern][:w].is_a?(Symbol) c[:writeConcern][:w] = c[:writeConcern][:w].to_s end end end
ruby
def add_txn_opts!(command, read) command.tap do |c| # The read preference should be added for all read operations. if read && txn_read_pref = txn_read_preference Mongo::Lint.validate_underscore_read_preference(txn_read_pref) txn_read_pref = txn_read_pref.dup txn_read_pref[:mode] = txn_read_pref[:mode].to_s.gsub(/(_\w)/) { |match| match[1].upcase } Mongo::Lint.validate_camel_case_read_preference(txn_read_pref) c['$readPreference'] = txn_read_pref end # The read concern should be added to any command that starts a transaction. if starting_transaction? # https://jira.mongodb.org/browse/SPEC-1161: transaction's # read concern overrides collection/database/client read concerns, # even if transaction's read concern is not set. # Read concern here is the one sent to the server and may # include afterClusterTime. if rc = c[:readConcern] rc = rc.dup rc.delete(:level) end if txn_read_concern if rc rc.update(txn_read_concern) else rc = txn_read_concern.dup end end if rc.nil? || rc.empty? c.delete(:readConcern) else c[:readConcern ] = rc end end # We need to send the read concern level as a string rather than a symbol. if c[:readConcern] && c[:readConcern][:level] c[:readConcern][:level] = c[:readConcern][:level].to_s end # The write concern should be added to any abortTransaction or commitTransaction command. if (c[:abortTransaction] || c[:commitTransaction]) if @already_committed wc = BSON::Document.new(c[:writeConcern] || txn_write_concern || {}) wc.merge!(w: :majority) wc[:wtimeout] ||= 10000 c[:writeConcern] = wc elsif txn_write_concern c[:writeConcern] ||= txn_write_concern end end # A non-numeric write concern w value needs to be sent as a string rather than a symbol. if c[:writeConcern] && c[:writeConcern][:w] && c[:writeConcern][:w].is_a?(Symbol) c[:writeConcern][:w] = c[:writeConcern][:w].to_s end end end
[ "def", "add_txn_opts!", "(", "command", ",", "read", ")", "command", ".", "tap", "do", "|", "c", "|", "# The read preference should be added for all read operations.", "if", "read", "&&", "txn_read_pref", "=", "txn_read_preference", "Mongo", "::", "Lint", ".", "validate_underscore_read_preference", "(", "txn_read_pref", ")", "txn_read_pref", "=", "txn_read_pref", ".", "dup", "txn_read_pref", "[", ":mode", "]", "=", "txn_read_pref", "[", ":mode", "]", ".", "to_s", ".", "gsub", "(", "/", "\\w", "/", ")", "{", "|", "match", "|", "match", "[", "1", "]", ".", "upcase", "}", "Mongo", "::", "Lint", ".", "validate_camel_case_read_preference", "(", "txn_read_pref", ")", "c", "[", "'$readPreference'", "]", "=", "txn_read_pref", "end", "# The read concern should be added to any command that starts a transaction.", "if", "starting_transaction?", "# https://jira.mongodb.org/browse/SPEC-1161: transaction's", "# read concern overrides collection/database/client read concerns,", "# even if transaction's read concern is not set.", "# Read concern here is the one sent to the server and may", "# include afterClusterTime.", "if", "rc", "=", "c", "[", ":readConcern", "]", "rc", "=", "rc", ".", "dup", "rc", ".", "delete", "(", ":level", ")", "end", "if", "txn_read_concern", "if", "rc", "rc", ".", "update", "(", "txn_read_concern", ")", "else", "rc", "=", "txn_read_concern", ".", "dup", "end", "end", "if", "rc", ".", "nil?", "||", "rc", ".", "empty?", "c", ".", "delete", "(", ":readConcern", ")", "else", "c", "[", ":readConcern", "]", "=", "rc", "end", "end", "# We need to send the read concern level as a string rather than a symbol.", "if", "c", "[", ":readConcern", "]", "&&", "c", "[", ":readConcern", "]", "[", ":level", "]", "c", "[", ":readConcern", "]", "[", ":level", "]", "=", "c", "[", ":readConcern", "]", "[", ":level", "]", ".", "to_s", "end", "# The write concern should be added to any abortTransaction or commitTransaction command.", "if", "(", "c", "[", ":abortTransaction", "]", "||", "c", "[", ":commitTransaction", "]", ")", "if", "@already_committed", "wc", "=", "BSON", "::", "Document", ".", "new", "(", "c", "[", ":writeConcern", "]", "||", "txn_write_concern", "||", "{", "}", ")", "wc", ".", "merge!", "(", "w", ":", ":majority", ")", "wc", "[", ":wtimeout", "]", "||=", "10000", "c", "[", ":writeConcern", "]", "=", "wc", "elsif", "txn_write_concern", "c", "[", ":writeConcern", "]", "||=", "txn_write_concern", "end", "end", "# A non-numeric write concern w value needs to be sent as a string rather than a symbol.", "if", "c", "[", ":writeConcern", "]", "&&", "c", "[", ":writeConcern", "]", "[", ":w", "]", "&&", "c", "[", ":writeConcern", "]", "[", ":w", "]", ".", "is_a?", "(", "Symbol", ")", "c", "[", ":writeConcern", "]", "[", ":w", "]", "=", "c", "[", ":writeConcern", "]", "[", ":w", "]", ".", "to_s", "end", "end", "end" ]
Add the transactions options if applicable. @example session.add_txn_opts!(cmd) @return [ Hash, BSON::Document ] The command document. @since 2.6.0 @api private
[ "Add", "the", "transactions", "options", "if", "applicable", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L263-L321
13,181
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.validate_read_preference!
def validate_read_preference!(command) return unless in_transaction? && non_primary_read_preference_mode?(command) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::INVALID_READ_PREFERENCE) end
ruby
def validate_read_preference!(command) return unless in_transaction? && non_primary_read_preference_mode?(command) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::INVALID_READ_PREFERENCE) end
[ "def", "validate_read_preference!", "(", "command", ")", "return", "unless", "in_transaction?", "&&", "non_primary_read_preference_mode?", "(", "command", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "::", "INVALID_READ_PREFERENCE", ")", "end" ]
Ensure that the read preference of a command primary. @example session.validate_read_preference!(command) @raise [ Mongo::Error::InvalidTransactionOperation ] If the read preference of the command is not primary. @since 2.6.0 @api private
[ "Ensure", "that", "the", "read", "preference", "of", "a", "command", "primary", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L351-L356
13,182
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.start_transaction
def start_transaction(options = nil) if options Lint.validate_read_concern_option(options[:read_concern]) end check_if_ended! if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::TRANSACTION_ALREADY_IN_PROGRESS) end next_txn_num @txn_options = options || @options[:default_transaction_options] || {} if txn_write_concern && WriteConcern.send(:unacknowledged?, txn_write_concern) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::UNACKNOWLEDGED_WRITE_CONCERN) end @state = STARTING_TRANSACTION_STATE @already_committed = false end
ruby
def start_transaction(options = nil) if options Lint.validate_read_concern_option(options[:read_concern]) end check_if_ended! if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::TRANSACTION_ALREADY_IN_PROGRESS) end next_txn_num @txn_options = options || @options[:default_transaction_options] || {} if txn_write_concern && WriteConcern.send(:unacknowledged?, txn_write_concern) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::UNACKNOWLEDGED_WRITE_CONCERN) end @state = STARTING_TRANSACTION_STATE @already_committed = false end
[ "def", "start_transaction", "(", "options", "=", "nil", ")", "if", "options", "Lint", ".", "validate_read_concern_option", "(", "options", "[", ":read_concern", "]", ")", "end", "check_if_ended!", "if", "within_states?", "(", "STARTING_TRANSACTION_STATE", ",", "TRANSACTION_IN_PROGRESS_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "::", "TRANSACTION_ALREADY_IN_PROGRESS", ")", "end", "next_txn_num", "@txn_options", "=", "options", "||", "@options", "[", ":default_transaction_options", "]", "||", "{", "}", "if", "txn_write_concern", "&&", "WriteConcern", ".", "send", "(", ":unacknowledged?", ",", "txn_write_concern", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "::", "UNACKNOWLEDGED_WRITE_CONCERN", ")", "end", "@state", "=", "STARTING_TRANSACTION_STATE", "@already_committed", "=", "false", "end" ]
Places subsequent operations in this session into a new transaction. Note that the transaction will not be started on the server until an operation is performed after start_transaction is called. @example Start a new transaction session.start_transaction(options) @param [ Hash ] options The options for the transaction being started. @option options [ Hash ] read_concern The read concern options hash, with the following optional keys: - *:level* -- the read preference level as a symbol; valid values are *:local*, *:majority*, and *:snapshot* @option options [ Hash ] :write_concern The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean. @option options [ Hash ] :read The read preference options. The hash may have the following items: - *:mode* -- read preference specified as a symbol; the only valid value is *:primary*. @raise [ Error::InvalidTransactionOperation ] If a transaction is already in progress or if the write concern is unacknowledged. @since 2.6.0
[ "Places", "subsequent", "operations", "in", "this", "session", "into", "a", "new", "transaction", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L580-L602
13,183
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.commit_transaction
def commit_transaction(options=nil) check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :abortTransaction, :commitTransaction)) end options ||= {} begin # If commitTransaction is called twice, we need to run the same commit # operation again, so we revert the session to the previous state. if within_states?(TRANSACTION_COMMITTED_STATE) @state = @last_commit_skipped ? STARTING_TRANSACTION_STATE : TRANSACTION_IN_PROGRESS_STATE @already_committed = true end if starting_transaction? @last_commit_skipped = true else @last_commit_skipped = false write_concern = options[:write_concern] || txn_options[:write_concern] if write_concern && !write_concern.is_a?(WriteConcern::Base) write_concern = WriteConcern.get(write_concern) end write_with_retry(self, write_concern, true) do |server, txn_num, is_retry| if is_retry if write_concern wco = write_concern.options.merge(w: :majority) wco[:wtimeout] ||= 10000 write_concern = WriteConcern.get(wco) else write_concern = WriteConcern.get(w: :majority, wtimeout: 10000) end end Operation::Command.new( selector: { commitTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num, write_concern: write_concern, ).execute(server) end end rescue Mongo::Error::NoServerAvailable, Mongo::Error::SocketError => e e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) raise e rescue Mongo::Error::OperationFailure => e err_doc = e.instance_variable_get(:@result).send(:first_document) if e.write_retryable? || (err_doc['writeConcernError'] && !UNLABELED_WRITE_CONCERN_CODES.include?(err_doc['writeConcernError']['code'])) e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) end raise e ensure @state = TRANSACTION_COMMITTED_STATE end end
ruby
def commit_transaction(options=nil) check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :abortTransaction, :commitTransaction)) end options ||= {} begin # If commitTransaction is called twice, we need to run the same commit # operation again, so we revert the session to the previous state. if within_states?(TRANSACTION_COMMITTED_STATE) @state = @last_commit_skipped ? STARTING_TRANSACTION_STATE : TRANSACTION_IN_PROGRESS_STATE @already_committed = true end if starting_transaction? @last_commit_skipped = true else @last_commit_skipped = false write_concern = options[:write_concern] || txn_options[:write_concern] if write_concern && !write_concern.is_a?(WriteConcern::Base) write_concern = WriteConcern.get(write_concern) end write_with_retry(self, write_concern, true) do |server, txn_num, is_retry| if is_retry if write_concern wco = write_concern.options.merge(w: :majority) wco[:wtimeout] ||= 10000 write_concern = WriteConcern.get(wco) else write_concern = WriteConcern.get(w: :majority, wtimeout: 10000) end end Operation::Command.new( selector: { commitTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num, write_concern: write_concern, ).execute(server) end end rescue Mongo::Error::NoServerAvailable, Mongo::Error::SocketError => e e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) raise e rescue Mongo::Error::OperationFailure => e err_doc = e.instance_variable_get(:@result).send(:first_document) if e.write_retryable? || (err_doc['writeConcernError'] && !UNLABELED_WRITE_CONCERN_CODES.include?(err_doc['writeConcernError']['code'])) e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) end raise e ensure @state = TRANSACTION_COMMITTED_STATE end end
[ "def", "commit_transaction", "(", "options", "=", "nil", ")", "check_if_ended!", "check_if_no_transaction!", "if", "within_states?", "(", "TRANSACTION_ABORTED_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "cannot_call_after_msg", "(", ":abortTransaction", ",", ":commitTransaction", ")", ")", "end", "options", "||=", "{", "}", "begin", "# If commitTransaction is called twice, we need to run the same commit", "# operation again, so we revert the session to the previous state.", "if", "within_states?", "(", "TRANSACTION_COMMITTED_STATE", ")", "@state", "=", "@last_commit_skipped", "?", "STARTING_TRANSACTION_STATE", ":", "TRANSACTION_IN_PROGRESS_STATE", "@already_committed", "=", "true", "end", "if", "starting_transaction?", "@last_commit_skipped", "=", "true", "else", "@last_commit_skipped", "=", "false", "write_concern", "=", "options", "[", ":write_concern", "]", "||", "txn_options", "[", ":write_concern", "]", "if", "write_concern", "&&", "!", "write_concern", ".", "is_a?", "(", "WriteConcern", "::", "Base", ")", "write_concern", "=", "WriteConcern", ".", "get", "(", "write_concern", ")", "end", "write_with_retry", "(", "self", ",", "write_concern", ",", "true", ")", "do", "|", "server", ",", "txn_num", ",", "is_retry", "|", "if", "is_retry", "if", "write_concern", "wco", "=", "write_concern", ".", "options", ".", "merge", "(", "w", ":", ":majority", ")", "wco", "[", ":wtimeout", "]", "||=", "10000", "write_concern", "=", "WriteConcern", ".", "get", "(", "wco", ")", "else", "write_concern", "=", "WriteConcern", ".", "get", "(", "w", ":", ":majority", ",", "wtimeout", ":", "10000", ")", "end", "end", "Operation", "::", "Command", ".", "new", "(", "selector", ":", "{", "commitTransaction", ":", "1", "}", ",", "db_name", ":", "'admin'", ",", "session", ":", "self", ",", "txn_num", ":", "txn_num", ",", "write_concern", ":", "write_concern", ",", ")", ".", "execute", "(", "server", ")", "end", "end", "rescue", "Mongo", "::", "Error", "::", "NoServerAvailable", ",", "Mongo", "::", "Error", "::", "SocketError", "=>", "e", "e", ".", "send", "(", ":add_label", ",", "Mongo", "::", "Error", "::", "UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL", ")", "raise", "e", "rescue", "Mongo", "::", "Error", "::", "OperationFailure", "=>", "e", "err_doc", "=", "e", ".", "instance_variable_get", "(", ":@result", ")", ".", "send", "(", ":first_document", ")", "if", "e", ".", "write_retryable?", "||", "(", "err_doc", "[", "'writeConcernError'", "]", "&&", "!", "UNLABELED_WRITE_CONCERN_CODES", ".", "include?", "(", "err_doc", "[", "'writeConcernError'", "]", "[", "'code'", "]", ")", ")", "e", ".", "send", "(", ":add_label", ",", "Mongo", "::", "Error", "::", "UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL", ")", "end", "raise", "e", "ensure", "@state", "=", "TRANSACTION_COMMITTED_STATE", "end", "end" ]
Commit the currently active transaction on the session. @example Commits the transaction. session.commit_transaction @option options :write_concern [ nil | WriteConcern::Base ] The write concern to use for this operation. @raise [ Error::InvalidTransactionOperation ] If there is no active transaction. @since 2.6.0
[ "Commit", "the", "currently", "active", "transaction", "on", "the", "session", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L615-L678
13,184
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.abort_transaction
def abort_transaction check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_COMMITTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :commitTransaction, :abortTransaction)) end if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction)) end begin unless starting_transaction? write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num| Operation::Command.new( selector: { abortTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num ).execute(server) end end @state = TRANSACTION_ABORTED_STATE rescue Mongo::Error::InvalidTransactionOperation raise rescue Mongo::Error @state = TRANSACTION_ABORTED_STATE rescue Exception @state = TRANSACTION_ABORTED_STATE raise end end
ruby
def abort_transaction check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_COMMITTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :commitTransaction, :abortTransaction)) end if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction)) end begin unless starting_transaction? write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num| Operation::Command.new( selector: { abortTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num ).execute(server) end end @state = TRANSACTION_ABORTED_STATE rescue Mongo::Error::InvalidTransactionOperation raise rescue Mongo::Error @state = TRANSACTION_ABORTED_STATE rescue Exception @state = TRANSACTION_ABORTED_STATE raise end end
[ "def", "abort_transaction", "check_if_ended!", "check_if_no_transaction!", "if", "within_states?", "(", "TRANSACTION_COMMITTED_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "cannot_call_after_msg", "(", ":commitTransaction", ",", ":abortTransaction", ")", ")", "end", "if", "within_states?", "(", "TRANSACTION_ABORTED_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "cannot_call_twice_msg", "(", ":abortTransaction", ")", ")", "end", "begin", "unless", "starting_transaction?", "write_with_retry", "(", "self", ",", "txn_options", "[", ":write_concern", "]", ",", "true", ")", "do", "|", "server", ",", "txn_num", "|", "Operation", "::", "Command", ".", "new", "(", "selector", ":", "{", "abortTransaction", ":", "1", "}", ",", "db_name", ":", "'admin'", ",", "session", ":", "self", ",", "txn_num", ":", "txn_num", ")", ".", "execute", "(", "server", ")", "end", "end", "@state", "=", "TRANSACTION_ABORTED_STATE", "rescue", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "raise", "rescue", "Mongo", "::", "Error", "@state", "=", "TRANSACTION_ABORTED_STATE", "rescue", "Exception", "@state", "=", "TRANSACTION_ABORTED_STATE", "raise", "end", "end" ]
Abort the currently active transaction without making any changes to the database. @example Abort the transaction. session.abort_transaction @raise [ Error::InvalidTransactionOperation ] If there is no active transaction. @since 2.6.0
[ "Abort", "the", "currently", "active", "transaction", "without", "making", "any", "changes", "to", "the", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L688-L724
13,185
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.with_transaction
def with_transaction(options=nil) # Non-configurable 120 second timeout for the entire operation deadline = Time.now + 120 transaction_in_progress = false loop do commit_options = {} if options commit_options[:write_concern] = options[:write_concern] end start_transaction(options) transaction_in_progress = true begin rv = yield self rescue Exception => e if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) abort_transaction transaction_in_progress = false end if Time.now >= deadline transaction_in_progress = false raise end if e.is_a?(Mongo::Error) && e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) next end raise else if within_states?(TRANSACTION_ABORTED_STATE, NO_TRANSACTION_STATE, TRANSACTION_COMMITTED_STATE) transaction_in_progress = false return rv end begin commit_transaction(commit_options) transaction_in_progress = false return rv rescue Mongo::Error => e if e.label?(Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) # WriteConcernFailed if e.is_a?(Mongo::Error::OperationFailure) && e.code == 64 && e.wtimeout? transaction_in_progress = false raise end if Time.now >= deadline transaction_in_progress = false raise end wc_options = case v = commit_options[:write_concern] when WriteConcern::Base v.options when nil {} else v end commit_options[:write_concern] = wc_options.merge(w: :majority) retry elsif e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) if Time.now >= deadline transaction_in_progress = false raise end next else transaction_in_progress = false raise end end end end ensure if transaction_in_progress log_warn('with_transaction callback altered with_transaction loop, aborting transaction') begin abort_transaction rescue Error::OperationFailure, Error::InvalidTransactionOperation end end end
ruby
def with_transaction(options=nil) # Non-configurable 120 second timeout for the entire operation deadline = Time.now + 120 transaction_in_progress = false loop do commit_options = {} if options commit_options[:write_concern] = options[:write_concern] end start_transaction(options) transaction_in_progress = true begin rv = yield self rescue Exception => e if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) abort_transaction transaction_in_progress = false end if Time.now >= deadline transaction_in_progress = false raise end if e.is_a?(Mongo::Error) && e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) next end raise else if within_states?(TRANSACTION_ABORTED_STATE, NO_TRANSACTION_STATE, TRANSACTION_COMMITTED_STATE) transaction_in_progress = false return rv end begin commit_transaction(commit_options) transaction_in_progress = false return rv rescue Mongo::Error => e if e.label?(Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) # WriteConcernFailed if e.is_a?(Mongo::Error::OperationFailure) && e.code == 64 && e.wtimeout? transaction_in_progress = false raise end if Time.now >= deadline transaction_in_progress = false raise end wc_options = case v = commit_options[:write_concern] when WriteConcern::Base v.options when nil {} else v end commit_options[:write_concern] = wc_options.merge(w: :majority) retry elsif e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) if Time.now >= deadline transaction_in_progress = false raise end next else transaction_in_progress = false raise end end end end ensure if transaction_in_progress log_warn('with_transaction callback altered with_transaction loop, aborting transaction') begin abort_transaction rescue Error::OperationFailure, Error::InvalidTransactionOperation end end end
[ "def", "with_transaction", "(", "options", "=", "nil", ")", "# Non-configurable 120 second timeout for the entire operation", "deadline", "=", "Time", ".", "now", "+", "120", "transaction_in_progress", "=", "false", "loop", "do", "commit_options", "=", "{", "}", "if", "options", "commit_options", "[", ":write_concern", "]", "=", "options", "[", ":write_concern", "]", "end", "start_transaction", "(", "options", ")", "transaction_in_progress", "=", "true", "begin", "rv", "=", "yield", "self", "rescue", "Exception", "=>", "e", "if", "within_states?", "(", "STARTING_TRANSACTION_STATE", ",", "TRANSACTION_IN_PROGRESS_STATE", ")", "abort_transaction", "transaction_in_progress", "=", "false", "end", "if", "Time", ".", "now", ">=", "deadline", "transaction_in_progress", "=", "false", "raise", "end", "if", "e", ".", "is_a?", "(", "Mongo", "::", "Error", ")", "&&", "e", ".", "label?", "(", "Mongo", "::", "Error", "::", "TRANSIENT_TRANSACTION_ERROR_LABEL", ")", "next", "end", "raise", "else", "if", "within_states?", "(", "TRANSACTION_ABORTED_STATE", ",", "NO_TRANSACTION_STATE", ",", "TRANSACTION_COMMITTED_STATE", ")", "transaction_in_progress", "=", "false", "return", "rv", "end", "begin", "commit_transaction", "(", "commit_options", ")", "transaction_in_progress", "=", "false", "return", "rv", "rescue", "Mongo", "::", "Error", "=>", "e", "if", "e", ".", "label?", "(", "Mongo", "::", "Error", "::", "UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL", ")", "# WriteConcernFailed", "if", "e", ".", "is_a?", "(", "Mongo", "::", "Error", "::", "OperationFailure", ")", "&&", "e", ".", "code", "==", "64", "&&", "e", ".", "wtimeout?", "transaction_in_progress", "=", "false", "raise", "end", "if", "Time", ".", "now", ">=", "deadline", "transaction_in_progress", "=", "false", "raise", "end", "wc_options", "=", "case", "v", "=", "commit_options", "[", ":write_concern", "]", "when", "WriteConcern", "::", "Base", "v", ".", "options", "when", "nil", "{", "}", "else", "v", "end", "commit_options", "[", ":write_concern", "]", "=", "wc_options", ".", "merge", "(", "w", ":", ":majority", ")", "retry", "elsif", "e", ".", "label?", "(", "Mongo", "::", "Error", "::", "TRANSIENT_TRANSACTION_ERROR_LABEL", ")", "if", "Time", ".", "now", ">=", "deadline", "transaction_in_progress", "=", "false", "raise", "end", "next", "else", "transaction_in_progress", "=", "false", "raise", "end", "end", "end", "end", "ensure", "if", "transaction_in_progress", "log_warn", "(", "'with_transaction callback altered with_transaction loop, aborting transaction'", ")", "begin", "abort_transaction", "rescue", "Error", "::", "OperationFailure", ",", "Error", "::", "InvalidTransactionOperation", "end", "end", "end" ]
Executes the provided block in a transaction, retrying as necessary. Returns the return value of the block. Exact number of retries and when they are performed are implementation details of the driver; the provided block should be idempotent, and should be prepared to be called more than once. The driver may retry the commit command within an active transaction or it may repeat the transaction and invoke the block again, depending on the error encountered if any. Note also that the retries may be executed against different servers. Transactions cannot be nested - InvalidTransactionOperation will be raised if this method is called when the session already has an active transaction. Exceptions raised by the block which are not derived from Mongo::Error stop processing, abort the transaction and are propagated out of with_transaction. Exceptions derived from Mongo::Error may be handled by with_transaction, resulting in retries of the process. Currently, with_transaction will retry commits and block invocations until at least 120 seconds have passed since with_transaction started executing. This timeout is not configurable and may change in a future driver version. @note with_transaction contains a loop, therefore the if with_transaction itself is placed in a loop, its block should not call next or break to control the outer loop because this will instead affect the loop in with_transaction. The driver will warn and abort the transaction if it detects this situation. @example Execute a statement in a transaction session.with_transaction(write_concern: {w: :majority}) do collection.update_one({ id: 3 }, { '$set' => { status: 'Inactive'} }, session: session) end @example Execute a statement in a transaction, limiting total time consumed Timeout.timeout(5) do session.with_transaction(write_concern: {w: :majority}) do collection.update_one({ id: 3 }, { '$set' => { status: 'Inactive'} }, session: session) end end @param [ Hash ] options The options for the transaction being started. These are the same options that start_transaction accepts. @raise [ Error::InvalidTransactionOperation ] If a transaction is already in progress or if the write concern is unacknowledged. @since 2.7.0
[ "Executes", "the", "provided", "block", "in", "a", "transaction", "retrying", "as", "necessary", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L792-L873
13,186
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.txn_read_preference
def txn_read_preference rp = txn_options && txn_options[:read_preference] || @client.read_preference Mongo::Lint.validate_underscore_read_preference(rp) rp end
ruby
def txn_read_preference rp = txn_options && txn_options[:read_preference] || @client.read_preference Mongo::Lint.validate_underscore_read_preference(rp) rp end
[ "def", "txn_read_preference", "rp", "=", "txn_options", "&&", "txn_options", "[", ":read_preference", "]", "||", "@client", ".", "read_preference", "Mongo", "::", "Lint", ".", "validate_underscore_read_preference", "(", "rp", ")", "rp", "end" ]
Get the read preference the session will use in the currently active transaction. This is a driver style hash with underscore keys. @example Get the transaction's read preference session.txn_read_preference @return [ Hash ] The read preference of the transaction. @since 2.6.0
[ "Get", "the", "read", "preference", "the", "session", "will", "use", "in", "the", "currently", "active", "transaction", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L886-L891
13,187
mongodb/mongo-ruby-driver
lib/mongo/server_selector.rb
Mongo.ServerSelector.get
def get(preference = {}) return preference if PREFERENCES.values.include?(preference.class) Mongo::Lint.validate_underscore_read_preference(preference) PREFERENCES.fetch((preference[:mode] || :primary).to_sym).new(preference) end
ruby
def get(preference = {}) return preference if PREFERENCES.values.include?(preference.class) Mongo::Lint.validate_underscore_read_preference(preference) PREFERENCES.fetch((preference[:mode] || :primary).to_sym).new(preference) end
[ "def", "get", "(", "preference", "=", "{", "}", ")", "return", "preference", "if", "PREFERENCES", ".", "values", ".", "include?", "(", "preference", ".", "class", ")", "Mongo", "::", "Lint", ".", "validate_underscore_read_preference", "(", "preference", ")", "PREFERENCES", ".", "fetch", "(", "(", "preference", "[", ":mode", "]", "||", ":primary", ")", ".", "to_sym", ")", ".", "new", "(", "preference", ")", "end" ]
Create a server selector object. @example Get a server selector object for selecting a secondary with specific tag sets. Mongo::ServerSelector.get(:mode => :secondary, :tag_sets => [{'dc' => 'nyc'}]) @param [ Hash ] preference The server preference. @since 2.0.0
[ "Create", "a", "server", "selector", "object", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server_selector.rb#L72-L76
13,188
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.read_with_retry_cursor
def read_with_retry_cursor(session, server_selector, view, &block) read_with_retry(session, server_selector) do |server| result = yield server Cursor.new(view, result, server, session: session) end end
ruby
def read_with_retry_cursor(session, server_selector, view, &block) read_with_retry(session, server_selector) do |server| result = yield server Cursor.new(view, result, server, session: session) end end
[ "def", "read_with_retry_cursor", "(", "session", ",", "server_selector", ",", "view", ",", "&", "block", ")", "read_with_retry", "(", "session", ",", "server_selector", ")", "do", "|", "server", "|", "result", "=", "yield", "server", "Cursor", ".", "new", "(", "view", ",", "result", ",", "server", ",", "session", ":", "session", ")", "end", "end" ]
Execute a read operation returning a cursor with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and this exception corresponds to a read retryable error, and read retries are enabled for the client, this method will perform server selection again and yield to the block again (with potentially a different server). If the block returns successfully, the result of the block (which should be a Mongo::Operation::Result) is used to construct a Mongo::Cursor object for the result set. The cursor is then returned. If modern retry reads are on (which is the default), the initial read operation will be retried once. If legacy retry reads are on, the initial read operation will be retried zero or more times depending on the :max_read_retries client setting, the default for which is 1. To disable read retries, turn off modern read retries by setting retry_reads: false and set :max_read_retries to 0 on the client. @api private @example Execute a read returning a cursor. cursor = read_with_retry_cursor(session, server_selector, view) do |server| # return a Mongo::Operation::Result ... end @param [ Mongo::Session ] session The session that the operation is being run on. @param [ Mongo::ServerSelector::Selectable ] server_selector Server selector for the operation. @param [ CollectionView ] view The +CollectionView+ defining the query. @param [ Proc ] block The block to execute. @return [ Cursor ] The cursor for the result set.
[ "Execute", "a", "read", "operation", "returning", "a", "cursor", "with", "retrying", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L59-L64
13,189
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.read_with_retry
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy driver behavior # here but upgrading Mongoid is strongly recommended. unless $_mongo_read_with_retry_warned $_mongo_read_with_retry_warned = true Logger.logger.warn("Legacy read_with_retry invocation - please update the application and/or its dependencies") end # Since we don't have a session, we cannot use the modern read retries. # And we need to select a server but we don't have a server selector. # Use PrimaryPreferred which will work as long as there is a data # bearing node in the cluster; the block may select a different server # which is fine. server_selector = ServerSelector.get(mode: :primary_preferred) legacy_read_with_retry(nil, server_selector, &block) elsif session && session.retry_reads? modern_read_with_retry(session, server_selector, &block) elsif client.max_read_retries > 0 legacy_read_with_retry(session, server_selector, &block) else server = select_server(cluster, server_selector) yield server end end
ruby
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy driver behavior # here but upgrading Mongoid is strongly recommended. unless $_mongo_read_with_retry_warned $_mongo_read_with_retry_warned = true Logger.logger.warn("Legacy read_with_retry invocation - please update the application and/or its dependencies") end # Since we don't have a session, we cannot use the modern read retries. # And we need to select a server but we don't have a server selector. # Use PrimaryPreferred which will work as long as there is a data # bearing node in the cluster; the block may select a different server # which is fine. server_selector = ServerSelector.get(mode: :primary_preferred) legacy_read_with_retry(nil, server_selector, &block) elsif session && session.retry_reads? modern_read_with_retry(session, server_selector, &block) elsif client.max_read_retries > 0 legacy_read_with_retry(session, server_selector, &block) else server = select_server(cluster, server_selector) yield server end end
[ "def", "read_with_retry", "(", "session", "=", "nil", ",", "server_selector", "=", "nil", ",", "&", "block", ")", "if", "session", ".", "nil?", "&&", "server_selector", ".", "nil?", "# Older versions of Mongoid call read_with_retry without arguments.", "# This is already not correct in a MongoDB 3.6+ environment with", "# sessions. For compatibility we emulate the legacy driver behavior", "# here but upgrading Mongoid is strongly recommended.", "unless", "$_mongo_read_with_retry_warned", "$_mongo_read_with_retry_warned", "=", "true", "Logger", ".", "logger", ".", "warn", "(", "\"Legacy read_with_retry invocation - please update the application and/or its dependencies\"", ")", "end", "# Since we don't have a session, we cannot use the modern read retries.", "# And we need to select a server but we don't have a server selector.", "# Use PrimaryPreferred which will work as long as there is a data", "# bearing node in the cluster; the block may select a different server", "# which is fine.", "server_selector", "=", "ServerSelector", ".", "get", "(", "mode", ":", ":primary_preferred", ")", "legacy_read_with_retry", "(", "nil", ",", "server_selector", ",", "block", ")", "elsif", "session", "&&", "session", ".", "retry_reads?", "modern_read_with_retry", "(", "session", ",", "server_selector", ",", "block", ")", "elsif", "client", ".", "max_read_retries", ">", "0", "legacy_read_with_retry", "(", "session", ",", "server_selector", ",", "block", ")", "else", "server", "=", "select_server", "(", "cluster", ",", "server_selector", ")", "yield", "server", "end", "end" ]
Execute a read operation with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and this exception corresponds to a read retryable error, and read retries are enabled for the client, this method will perform server selection again and yield to the block again (with potentially a different server). If the block returns successfully, the result of the block is returned. If modern retry reads are on (which is the default), the initial read operation will be retried once. If legacy retry reads are on, the initial read operation will be retried zero or more times depending on the :max_read_retries client setting, the default for which is 1. To disable read retries, turn off modern read retries by setting retry_reads: false and set :max_read_retries to 0 on the client. @api private @example Execute the read. read_with_retry(session, server_selector) do |server| ... end @param [ Mongo::Session ] session The session that the operation is being run on. @param [ Mongo::ServerSelector::Selectable ] server_selector Server selector for the operation. @param [ Proc ] block The block to execute. @return [ Result ] The result of the operation.
[ "Execute", "a", "read", "operation", "with", "retrying", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L99-L124
13,190
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.read_with_one_retry
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
ruby
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
[ "def", "read_with_one_retry", "(", "options", "=", "nil", ")", "yield", "rescue", "Error", "::", "SocketError", ",", "Error", "::", "SocketTimeoutError", "=>", "e", "retry_message", "=", "options", "&&", "options", "[", ":retry_message", "]", "log_retry", "(", "e", ",", "message", ":", "retry_message", ")", "yield", "end" ]
Execute a read operation with a single retry on network errors. This method is used by the driver for some of the internal housekeeping operations. Application-requested reads should use read_with_retry rather than this method. @api private @example Execute the read. read_with_one_retry do ... end @note This only retries read operations on socket errors. @param [ Hash ] options Options. @param [ Proc ] block The block to execute. @option options [ String ] :retry_message Message to log when retrying. @return [ Result ] The result of the operation. @since 2.2.6
[ "Execute", "a", "read", "operation", "with", "a", "single", "retry", "on", "network", "errors", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L149-L155
13,191
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.write_with_retry
def write_with_retry(session, write_concern, ending_transaction = false, &block) if ending_transaction && !session raise ArgumentError, 'Cannot end a transaction without a session' end unless ending_transaction || retry_write_allowed?(session, write_concern) return legacy_write_with_retry(nil, session, &block) end # If we are here, session is not nil. A session being nil would have # failed retry_write_allowed? check. server = cluster.next_primary unless ending_transaction || server.retry_writes? return legacy_write_with_retry(server, session, &block) end begin txn_num = session.in_transaction? ? session.txn_num : session.next_txn_num yield(server, txn_num, false) rescue Error::SocketError, Error::SocketTimeoutError => e if session.in_transaction? && !ending_transaction raise end retry_write(e, txn_num, &block) rescue Error::OperationFailure => e if (session.in_transaction? && !ending_transaction) || !e.write_retryable? raise end retry_write(e, txn_num, &block) end end
ruby
def write_with_retry(session, write_concern, ending_transaction = false, &block) if ending_transaction && !session raise ArgumentError, 'Cannot end a transaction without a session' end unless ending_transaction || retry_write_allowed?(session, write_concern) return legacy_write_with_retry(nil, session, &block) end # If we are here, session is not nil. A session being nil would have # failed retry_write_allowed? check. server = cluster.next_primary unless ending_transaction || server.retry_writes? return legacy_write_with_retry(server, session, &block) end begin txn_num = session.in_transaction? ? session.txn_num : session.next_txn_num yield(server, txn_num, false) rescue Error::SocketError, Error::SocketTimeoutError => e if session.in_transaction? && !ending_transaction raise end retry_write(e, txn_num, &block) rescue Error::OperationFailure => e if (session.in_transaction? && !ending_transaction) || !e.write_retryable? raise end retry_write(e, txn_num, &block) end end
[ "def", "write_with_retry", "(", "session", ",", "write_concern", ",", "ending_transaction", "=", "false", ",", "&", "block", ")", "if", "ending_transaction", "&&", "!", "session", "raise", "ArgumentError", ",", "'Cannot end a transaction without a session'", "end", "unless", "ending_transaction", "||", "retry_write_allowed?", "(", "session", ",", "write_concern", ")", "return", "legacy_write_with_retry", "(", "nil", ",", "session", ",", "block", ")", "end", "# If we are here, session is not nil. A session being nil would have", "# failed retry_write_allowed? check.", "server", "=", "cluster", ".", "next_primary", "unless", "ending_transaction", "||", "server", ".", "retry_writes?", "return", "legacy_write_with_retry", "(", "server", ",", "session", ",", "block", ")", "end", "begin", "txn_num", "=", "session", ".", "in_transaction?", "?", "session", ".", "txn_num", ":", "session", ".", "next_txn_num", "yield", "(", "server", ",", "txn_num", ",", "false", ")", "rescue", "Error", "::", "SocketError", ",", "Error", "::", "SocketTimeoutError", "=>", "e", "if", "session", ".", "in_transaction?", "&&", "!", "ending_transaction", "raise", "end", "retry_write", "(", "e", ",", "txn_num", ",", "block", ")", "rescue", "Error", "::", "OperationFailure", "=>", "e", "if", "(", "session", ".", "in_transaction?", "&&", "!", "ending_transaction", ")", "||", "!", "e", ".", "write_retryable?", "raise", "end", "retry_write", "(", "e", ",", "txn_num", ",", "block", ")", "end", "end" ]
Implements write retrying functionality by yielding to the passed block one or more times. If the session is provided (hence, the deployment supports sessions), and modern retry writes are enabled on the client, the modern retry logic is invoked. Otherwise the legacy retry logic is invoked. If ending_transaction parameter is true, indicating that a transaction is being committed or aborted, the operation is executed exactly once. Note that, since transactions require sessions, this method will raise ArgumentError if ending_transaction is true and session is nil. @api private @example Execute the write. write_with_retry do ... end @note This only retries operations on not master failures, since it is the only case we can be sure a partial write did not already occur. @param [ nil | Session ] session Optional session to use with the operation. @param [ nil | Hash | WriteConcern::Base ] write_concern The write concern. @param [ true | false ] ending_transaction True if the write operation is abortTransaction or commitTransaction, false otherwise. @param [ Proc ] block The block to execute. @yieldparam [ Server ] server The server to which the write should be sent. @yieldparam [ Integer ] txn_num Transaction number (NOT the ACID kind). @return [ Result ] The result of the operation. @since 2.1.0
[ "Implements", "write", "retrying", "functionality", "by", "yielding", "to", "the", "passed", "block", "one", "or", "more", "times", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L191-L223
13,192
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.log_retry
def log_retry(e, options = nil) message = if options && options[:message] options[:message] else "Retry" end Logger.logger.warn "#{message} due to: #{e.class.name} #{e.message}" end
ruby
def log_retry(e, options = nil) message = if options && options[:message] options[:message] else "Retry" end Logger.logger.warn "#{message} due to: #{e.class.name} #{e.message}" end
[ "def", "log_retry", "(", "e", ",", "options", "=", "nil", ")", "message", "=", "if", "options", "&&", "options", "[", ":message", "]", "options", "[", ":message", "]", "else", "\"Retry\"", "end", "Logger", ".", "logger", ".", "warn", "\"#{message} due to: #{e.class.name} #{e.message}\"", "end" ]
Log a warning so that any application slow down is immediately obvious.
[ "Log", "a", "warning", "so", "that", "any", "application", "slow", "down", "is", "immediately", "obvious", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L358-L365
13,193
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.create
def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_session, opts) do |session| Operation::Create.new({ selector: operation, db_name: database.name, write_concern: write_concern, session: session }).execute(server) end end
ruby
def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_session, opts) do |session| Operation::Create.new({ selector: operation, db_name: database.name, write_concern: write_concern, session: session }).execute(server) end end
[ "def", "create", "(", "opts", "=", "{", "}", ")", "operation", "=", "{", ":create", "=>", "name", "}", ".", "merge", "(", "options", ")", "operation", ".", "delete", "(", ":write", ")", "server", "=", "next_primary", "if", "(", "options", "[", ":collation", "]", "||", "options", "[", "Operation", "::", "COLLATION", "]", ")", "&&", "!", "server", ".", "features", ".", "collation_enabled?", "raise", "Error", "::", "UnsupportedCollation", ".", "new", "end", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "Operation", "::", "Create", ".", "new", "(", "{", "selector", ":", "operation", ",", "db_name", ":", "database", ".", "name", ",", "write_concern", ":", "write_concern", ",", "session", ":", "session", "}", ")", ".", "execute", "(", "server", ")", "end", "end" ]
Force the collection to be created in the database. @example Force the collection to be created. collection.create @param [ Hash ] opts The options for the create operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
[ "Force", "the", "collection", "to", "be", "created", "in", "the", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L184-L199
13,194
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.drop
def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session }).execute(next_primary) end rescue Error::OperationFailure => ex raise ex unless ex.message =~ /ns not found/ false end
ruby
def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session }).execute(next_primary) end rescue Error::OperationFailure => ex raise ex unless ex.message =~ /ns not found/ false end
[ "def", "drop", "(", "opts", "=", "{", "}", ")", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "Operation", "::", "Drop", ".", "new", "(", "{", "selector", ":", "{", ":drop", "=>", "name", "}", ",", "db_name", ":", "database", ".", "name", ",", "write_concern", ":", "write_concern", ",", "session", ":", "session", "}", ")", ".", "execute", "(", "next_primary", ")", "end", "rescue", "Error", "::", "OperationFailure", "=>", "ex", "raise", "ex", "unless", "ex", ".", "message", "=~", "/", "/", "false", "end" ]
Drop the collection. Will also drop all indexes associated with the collection. @note An error returned if the collection doesn't exist is suppressed. @example Drop the collection. collection.drop @param [ Hash ] opts The options for the drop operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
[ "Drop", "the", "collection", ".", "Will", "also", "drop", "all", "indexes", "associated", "with", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L216-L228
13,195
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.distinct
def distinct(field_name, filter = nil, options = {}) View.new(self, filter || {}, options).distinct(field_name, options) end
ruby
def distinct(field_name, filter = nil, options = {}) View.new(self, filter || {}, options).distinct(field_name, options) end
[ "def", "distinct", "(", "field_name", ",", "filter", "=", "nil", ",", "options", "=", "{", "}", ")", "View", ".", "new", "(", "self", ",", "filter", "||", "{", "}", ",", "options", ")", ".", "distinct", "(", "field_name", ",", "options", ")", "end" ]
Get a list of distinct values for a specific field. @example Get the distinct values. collection.distinct('name') @param [ Symbol, String ] field_name The name of the field. @param [ Hash ] filter The documents from which to retrieve the distinct values. @param [ Hash ] options The distinct command options. @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run. @option options [ Hash ] :read The read preference options. @option options [ Hash ] :collation The collation to use. @option options [ Session ] :session The session to use. @return [ Array<Object> ] The list of distinct values. @since 2.1.0
[ "Get", "a", "list", "of", "distinct", "values", "for", "a", "specific", "field", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L430-L432
13,196
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.insert_one
def insert_one(document, opts = {}) client.send(:with_session, opts) do |session| write_with_retry(session, write_concern) do |server, txn_num| Operation::Insert.new( :documents => [ document ], :db_name => database.name, :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!opts[:bypass_document_validation], :options => opts, :id_generator => client.options[:id_generator], :session => session, :txn_num => txn_num ).execute(server) end end end
ruby
def insert_one(document, opts = {}) client.send(:with_session, opts) do |session| write_with_retry(session, write_concern) do |server, txn_num| Operation::Insert.new( :documents => [ document ], :db_name => database.name, :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!opts[:bypass_document_validation], :options => opts, :id_generator => client.options[:id_generator], :session => session, :txn_num => txn_num ).execute(server) end end end
[ "def", "insert_one", "(", "document", ",", "opts", "=", "{", "}", ")", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "write_with_retry", "(", "session", ",", "write_concern", ")", "do", "|", "server", ",", "txn_num", "|", "Operation", "::", "Insert", ".", "new", "(", ":documents", "=>", "[", "document", "]", ",", ":db_name", "=>", "database", ".", "name", ",", ":coll_name", "=>", "name", ",", ":write_concern", "=>", "write_concern", ",", ":bypass_document_validation", "=>", "!", "!", "opts", "[", ":bypass_document_validation", "]", ",", ":options", "=>", "opts", ",", ":id_generator", "=>", "client", ".", "options", "[", ":id_generator", "]", ",", ":session", "=>", "session", ",", ":txn_num", "=>", "txn_num", ")", ".", "execute", "(", "server", ")", "end", "end", "end" ]
Insert a single document into the collection. @example Insert a document into the collection. collection.insert_one({ name: 'test' }) @param [ Hash ] document The document to insert. @param [ Hash ] opts The insert options. @option opts [ Session ] :session The session to use for the operation. @return [ Result ] The database response wrapper. @since 2.0.0
[ "Insert", "a", "single", "document", "into", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L476-L492
13,197
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.insert_many
def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end
ruby
def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end
[ "def", "insert_many", "(", "documents", ",", "options", "=", "{", "}", ")", "inserts", "=", "documents", ".", "map", "{", "|", "doc", "|", "{", ":insert_one", "=>", "doc", "}", "}", "bulk_write", "(", "inserts", ",", "options", ")", "end" ]
Insert the provided documents into the collection. @example Insert documents into the collection. collection.insert_many([{ name: 'test' }]) @param [ Array<Hash> ] documents The documents to insert. @param [ Hash ] options The insert options. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The database response wrapper. @since 2.0.0
[ "Insert", "the", "provided", "documents", "into", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L507-L510
13,198
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.replace_one
def replace_one(filter, replacement, options = {}) find(filter, options).replace_one(replacement, options) end
ruby
def replace_one(filter, replacement, options = {}) find(filter, options).replace_one(replacement, options) end
[ "def", "replace_one", "(", "filter", ",", "replacement", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "replace_one", "(", "replacement", ",", "options", ")", "end" ]
Replaces a single document in the collection with the new document. @example Replace a single document. collection.replace_one({ name: 'test' }, { name: 'test1' }) @param [ Hash ] filter The filter to use. @param [ Hash ] replacement The replacement document.. @param [ Hash ] options The options. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :collation The collation to use. @option options [ Session ] :session The session to use. @return [ Result ] The response from the database. @since 2.1.0
[ "Replaces", "a", "single", "document", "in", "the", "collection", "with", "the", "new", "document", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L613-L615
13,199
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.update_many
def update_many(filter, update, options = {}) find(filter, options).update_many(update, options) end
ruby
def update_many(filter, update, options = {}) find(filter, options).update_many(update, options) end
[ "def", "update_many", "(", "filter", ",", "update", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "update_many", "(", "update", ",", "options", ")", "end" ]
Update documents in the collection. @example Update multiple documents in the collection. collection.update_many({ name: 'test'}, '$set' => { name: 'test1' }) @param [ Hash ] filter The filter to use. @param [ Hash ] update The update statement. @param [ Hash ] options The options. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :collation The collation to use. @option options [ Array ] :array_filters A set of filters specifying to which array elements an update should apply. @option options [ Session ] :session The session to use. @return [ Result ] The response from the database. @since 2.1.0
[ "Update", "documents", "in", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L638-L640