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
12,200
attr-encrypted/attr_encrypted
lib/attr_encrypted.rb
AttrEncrypted.InstanceMethods.encrypt
def encrypt(attribute, value) encrypted_attributes[attribute.to_sym][:operation] = :encrypting encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(value) self.class.encrypt(attribute, value, evaluated_attr_encrypted_options_for(attribute)) end
ruby
def encrypt(attribute, value) encrypted_attributes[attribute.to_sym][:operation] = :encrypting encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(value) self.class.encrypt(attribute, value, evaluated_attr_encrypted_options_for(attribute)) end
[ "def", "encrypt", "(", "attribute", ",", "value", ")", "encrypted_attributes", "[", "attribute", ".", "to_sym", "]", "[", ":operation", "]", "=", ":encrypting", "encrypted_attributes", "[", "attribute", ".", "to_sym", "]", "[", ":value_present", "]", "=", "self", ".", "class", ".", "not_empty?", "(", "value", ")", "self", ".", "class", ".", "encrypt", "(", "attribute", ",", "value", ",", "evaluated_attr_encrypted_options_for", "(", "attribute", ")", ")", "end" ]
Encrypts a value for the attribute specified using options evaluated in the current object's scope Example class User attr_accessor :secret_key attr_encrypted :email, key: :secret_key def initialize(secret_key) self.secret_key = secret_key end end @user = User.new('some-secret-key') @user.encrypt(:email, 'test@example.com')
[ "Encrypts", "a", "value", "for", "the", "attribute", "specified", "using", "options", "evaluated", "in", "the", "current", "object", "s", "scope" ]
11df93aef14c661dd0c03169d382a0412f93124e
https://github.com/attr-encrypted/attr_encrypted/blob/11df93aef14c661dd0c03169d382a0412f93124e/lib/attr_encrypted.rb#L349-L353
12,201
attr-encrypted/attr_encrypted
lib/attr_encrypted.rb
AttrEncrypted.InstanceMethods.encrypted_attributes
def encrypted_attributes @encrypted_attributes ||= begin duplicated= {} self.class.encrypted_attributes.map { |key, value| duplicated[key] = value.dup } duplicated end end
ruby
def encrypted_attributes @encrypted_attributes ||= begin duplicated= {} self.class.encrypted_attributes.map { |key, value| duplicated[key] = value.dup } duplicated end end
[ "def", "encrypted_attributes", "@encrypted_attributes", "||=", "begin", "duplicated", "=", "{", "}", "self", ".", "class", ".", "encrypted_attributes", ".", "map", "{", "|", "key", ",", "value", "|", "duplicated", "[", "key", "]", "=", "value", ".", "dup", "}", "duplicated", "end", "end" ]
Copies the class level hash of encrypted attributes with virtual attribute names as keys and their corresponding options as values to the instance
[ "Copies", "the", "class", "level", "hash", "of", "encrypted", "attributes", "with", "virtual", "attribute", "names", "as", "keys", "and", "their", "corresponding", "options", "as", "values", "to", "the", "instance" ]
11df93aef14c661dd0c03169d382a0412f93124e
https://github.com/attr-encrypted/attr_encrypted/blob/11df93aef14c661dd0c03169d382a0412f93124e/lib/attr_encrypted.rb#L358-L364
12,202
fazibear/colorize
lib/colorize/instance_methods.rb
Colorize.InstanceMethods.colorize
def colorize(params) return self if self.class.disable_colorization require_windows_libs scan_for_colors.inject(self.class.new) do |str, match| colors_from_params(match, params) defaults_colors(match) str << "\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\033[0m" end end
ruby
def colorize(params) return self if self.class.disable_colorization require_windows_libs scan_for_colors.inject(self.class.new) do |str, match| colors_from_params(match, params) defaults_colors(match) str << "\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\033[0m" end end
[ "def", "colorize", "(", "params", ")", "return", "self", "if", "self", ".", "class", ".", "disable_colorization", "require_windows_libs", "scan_for_colors", ".", "inject", "(", "self", ".", "class", ".", "new", ")", "do", "|", "str", ",", "match", "|", "colors_from_params", "(", "match", ",", "params", ")", "defaults_colors", "(", "match", ")", "str", "<<", "\"\\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\\033[0m\"", "end", "end" ]
Change color of string Examples: puts "This is blue".colorize(:blue) puts "This is light blue".colorize(:light_blue) puts "This is also blue".colorize(:color => :blue) puts "This is light blue with red background".colorize(:color => :light_blue, :background => :red) puts "This is light blue with red background".colorize(:light_blue ).colorize( :background => :red) puts "This is blue text on red".blue.on_red puts "This is red on blue".colorize(:red).on_blue puts "This is red on blue and underline".colorize(:red).on_blue.underline puts "This is blue text on red".blue.on_red.blink puts "This is uncolorized".blue.on_red.uncolorize
[ "Change", "color", "of", "string" ]
526654c6d7dfc5483b70184d06b994eba8359514
https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L19-L27
12,203
fazibear/colorize
lib/colorize/instance_methods.rb
Colorize.InstanceMethods.colorized?
def colorized? scan_for_colors.inject([]) do |colors, match| colors << match.tap(&:pop) end.flatten.compact.any? end
ruby
def colorized? scan_for_colors.inject([]) do |colors, match| colors << match.tap(&:pop) end.flatten.compact.any? end
[ "def", "colorized?", "scan_for_colors", ".", "inject", "(", "[", "]", ")", "do", "|", "colors", ",", "match", "|", "colors", "<<", "match", ".", "tap", "(", ":pop", ")", "end", ".", "flatten", ".", "compact", ".", "any?", "end" ]
Return true if string is colorized
[ "Return", "true", "if", "string", "is", "colorized" ]
526654c6d7dfc5483b70184d06b994eba8359514
https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L41-L45
12,204
fazibear/colorize
lib/colorize/instance_methods.rb
Colorize.InstanceMethods.colors_from_params
def colors_from_params(match, params) case params when Hash then colors_from_hash(match, params) when Symbol then color_from_symbol(match, params) end end
ruby
def colors_from_params(match, params) case params when Hash then colors_from_hash(match, params) when Symbol then color_from_symbol(match, params) end end
[ "def", "colors_from_params", "(", "match", ",", "params", ")", "case", "params", "when", "Hash", "then", "colors_from_hash", "(", "match", ",", "params", ")", "when", "Symbol", "then", "color_from_symbol", "(", "match", ",", "params", ")", "end", "end" ]
Set color from params
[ "Set", "color", "from", "params" ]
526654c6d7dfc5483b70184d06b994eba8359514
https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L61-L66
12,205
fazibear/colorize
lib/colorize/instance_methods.rb
Colorize.InstanceMethods.colors_from_hash
def colors_from_hash(match, hash) match[0] = mode(hash[:mode]) if mode(hash[:mode]) match[1] = color(hash[:color]) if color(hash[:color]) match[2] = background_color(hash[:background]) if background_color(hash[:background]) end
ruby
def colors_from_hash(match, hash) match[0] = mode(hash[:mode]) if mode(hash[:mode]) match[1] = color(hash[:color]) if color(hash[:color]) match[2] = background_color(hash[:background]) if background_color(hash[:background]) end
[ "def", "colors_from_hash", "(", "match", ",", "hash", ")", "match", "[", "0", "]", "=", "mode", "(", "hash", "[", ":mode", "]", ")", "if", "mode", "(", "hash", "[", ":mode", "]", ")", "match", "[", "1", "]", "=", "color", "(", "hash", "[", ":color", "]", ")", "if", "color", "(", "hash", "[", ":color", "]", ")", "match", "[", "2", "]", "=", "background_color", "(", "hash", "[", ":background", "]", ")", "if", "background_color", "(", "hash", "[", ":background", "]", ")", "end" ]
Set colors from params hash
[ "Set", "colors", "from", "params", "hash" ]
526654c6d7dfc5483b70184d06b994eba8359514
https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/instance_methods.rb#L71-L75
12,206
fazibear/colorize
lib/colorize/class_methods.rb
Colorize.ClassMethods.color_methods
def color_methods colors.each do |key| next if key == :default define_method key do colorize(:color => key) end define_method "on_#{key}" do colorize(:background => key) end end end
ruby
def color_methods colors.each do |key| next if key == :default define_method key do colorize(:color => key) end define_method "on_#{key}" do colorize(:background => key) end end end
[ "def", "color_methods", "colors", ".", "each", "do", "|", "key", "|", "next", "if", "key", "==", ":default", "define_method", "key", "do", "colorize", "(", ":color", "=>", "key", ")", "end", "define_method", "\"on_#{key}\"", "do", "colorize", "(", ":background", "=>", "key", ")", "end", "end", "end" ]
Generate color and on_color methods
[ "Generate", "color", "and", "on_color", "methods" ]
526654c6d7dfc5483b70184d06b994eba8359514
https://github.com/fazibear/colorize/blob/526654c6d7dfc5483b70184d06b994eba8359514/lib/colorize/class_methods.rb#L93-L105
12,207
ruby/racc
lib/racc/grammar_file_parser.rb
Racc.GrammarFileParser.parse_user_code
def parse_user_code epilogue = @scanner.epilogue return unless epilogue.text epilogue.text.scan(/^----([^\n\r]*)(?:\n|\r\n|\r)(.*?)(?=^----|\Z)/m) do label = canonical_label($~[1]) range = epilogue.slice($~.begin(2), $~.end(2)) add_user_code(label, range) end end
ruby
def parse_user_code epilogue = @scanner.epilogue return unless epilogue.text epilogue.text.scan(/^----([^\n\r]*)(?:\n|\r\n|\r)(.*?)(?=^----|\Z)/m) do label = canonical_label($~[1]) range = epilogue.slice($~.begin(2), $~.end(2)) add_user_code(label, range) end end
[ "def", "parse_user_code", "epilogue", "=", "@scanner", ".", "epilogue", "return", "unless", "epilogue", ".", "text", "epilogue", ".", "text", ".", "scan", "(", "/", "\\n", "\\r", "\\n", "\\r", "\\n", "\\r", "\\Z", "/m", ")", "do", "label", "=", "canonical_label", "(", "$~", "[", "1", "]", ")", "range", "=", "epilogue", ".", "slice", "(", "$~", ".", "begin", "(", "2", ")", ",", "$~", ".", "end", "(", "2", ")", ")", "add_user_code", "(", "label", ",", "range", ")", "end", "end" ]
User Code Block
[ "User", "Code", "Block" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/grammar_file_parser.rb#L255-L263
12,208
ruby/racc
lib/racc/simulated_automaton.rb
Racc.SimulatedAutomaton.consume!
def consume!(token) return self if @error action = @state.action[token] || @state.defact case action when Shift @sstack.push(@state) @state = action.goto_state shifted(token) when Reduce reduce_by!(action.rule) consume!(token) when Accept done when Error @error = true error else raise "Illegal action type: #{action.class}" end self end
ruby
def consume!(token) return self if @error action = @state.action[token] || @state.defact case action when Shift @sstack.push(@state) @state = action.goto_state shifted(token) when Reduce reduce_by!(action.rule) consume!(token) when Accept done when Error @error = true error else raise "Illegal action type: #{action.class}" end self end
[ "def", "consume!", "(", "token", ")", "return", "self", "if", "@error", "action", "=", "@state", ".", "action", "[", "token", "]", "||", "@state", ".", "defact", "case", "action", "when", "Shift", "@sstack", ".", "push", "(", "@state", ")", "@state", "=", "action", ".", "goto_state", "shifted", "(", "token", ")", "when", "Reduce", "reduce_by!", "(", "action", ".", "rule", ")", "consume!", "(", "token", ")", "when", "Accept", "done", "when", "Error", "@error", "=", "true", "error", "else", "raise", "\"Illegal action type: #{action.class}\"", "end", "self", "end" ]
consuming a terminal may set off a series of reduces before the terminal is shifted
[ "consuming", "a", "terminal", "may", "set", "off", "a", "series", "of", "reduces", "before", "the", "terminal", "is", "shifted" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/simulated_automaton.rb#L36-L58
12,209
ruby/racc
lib/racc/state.rb
Racc.States.path
def path(state, rule) rule.symbols.each_with_object([]) do |tok, path| goto = state.gotos[tok] path << goto state = goto.to_state end end
ruby
def path(state, rule) rule.symbols.each_with_object([]) do |tok, path| goto = state.gotos[tok] path << goto state = goto.to_state end end
[ "def", "path", "(", "state", ",", "rule", ")", "rule", ".", "symbols", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "tok", ",", "path", "|", "goto", "=", "state", ".", "gotos", "[", "tok", "]", "path", "<<", "goto", "state", "=", "goto", ".", "to_state", "end", "end" ]
Sequence of state transitions which would be taken when starting from 'state', then following the RHS of 'rule' right to the end
[ "Sequence", "of", "state", "transitions", "which", "would", "be", "taken", "when", "starting", "from", "state", "then", "following", "the", "RHS", "of", "rule", "right", "to", "the", "end" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/state.rb#L208-L214
12,210
ruby/racc
lib/racc/state.rb
Racc.States.walk_graph
def walk_graph(bitmap, graph) index = Array.new(graph.size, nil) traversed = Set.new graph.nodes do |node| next if traversed.include?(node) traverse(node, traversed, index, [], bitmap, graph) end end
ruby
def walk_graph(bitmap, graph) index = Array.new(graph.size, nil) traversed = Set.new graph.nodes do |node| next if traversed.include?(node) traverse(node, traversed, index, [], bitmap, graph) end end
[ "def", "walk_graph", "(", "bitmap", ",", "graph", ")", "index", "=", "Array", ".", "new", "(", "graph", ".", "size", ",", "nil", ")", "traversed", "=", "Set", ".", "new", "graph", ".", "nodes", "do", "|", "node", "|", "next", "if", "traversed", ".", "include?", "(", "node", ")", "traverse", "(", "node", ",", "traversed", ",", "index", ",", "[", "]", ",", "bitmap", ",", "graph", ")", "end", "end" ]
traverse a directed graph each entry in 'bitmap' corresponds to a graph node after the traversal, the bitmap for each node will be the union of its original value, and ALL the values for all the nodes which are reachable from it
[ "traverse", "a", "directed", "graph", "each", "entry", "in", "bitmap", "corresponds", "to", "a", "graph", "node", "after", "the", "traversal", "the", "bitmap", "for", "each", "node", "will", "be", "the", "union", "of", "its", "original", "value", "and", "ALL", "the", "values", "for", "all", "the", "nodes", "which", "are", "reachable", "from", "it" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/state.rb#L221-L229
12,211
ruby/racc
lib/racc/state.rb
Racc.States.detailed_transition_graph
def detailed_transition_graph @dtgraph ||= each_with_object(Graph::Labeled.new(size)) do |s, graph| s.gotos.each do |tok, goto| path = if tok.terminal? [tok] else actions_to_reach_reduce(s.ident, tok) end graph.add_vector(s.ident, goto.to_state.ident, path) end end.tap { |graph| graph.start = 0 }.freeze end
ruby
def detailed_transition_graph @dtgraph ||= each_with_object(Graph::Labeled.new(size)) do |s, graph| s.gotos.each do |tok, goto| path = if tok.terminal? [tok] else actions_to_reach_reduce(s.ident, tok) end graph.add_vector(s.ident, goto.to_state.ident, path) end end.tap { |graph| graph.start = 0 }.freeze end
[ "def", "detailed_transition_graph", "@dtgraph", "||=", "each_with_object", "(", "Graph", "::", "Labeled", ".", "new", "(", "size", ")", ")", "do", "|", "s", ",", "graph", "|", "s", ".", "gotos", ".", "each", "do", "|", "tok", ",", "goto", "|", "path", "=", "if", "tok", ".", "terminal?", "[", "tok", "]", "else", "actions_to_reach_reduce", "(", "s", ".", "ident", ",", "tok", ")", "end", "graph", ".", "add_vector", "(", "s", ".", "ident", ",", "goto", ".", "to_state", ".", "ident", ",", "path", ")", "end", "end", ".", "tap", "{", "|", "graph", "|", "graph", ".", "start", "=", "0", "}", ".", "freeze", "end" ]
Like `transition_graph`, but rather than vectors labeled with NTs, we have vectors labeled with the shortest series of terminals and reduce operations which could take us through the same transition
[ "Like", "transition_graph", "but", "rather", "than", "vectors", "labeled", "with", "NTs", "we", "have", "vectors", "labeled", "with", "the", "shortest", "series", "of", "terminals", "and", "reduce", "operations", "which", "could", "take", "us", "through", "the", "same", "transition" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/state.rb#L430-L441
12,212
ruby/racc
lib/racc/grammar.rb
Racc.Rule.replace
def replace(placeholder, actual) raise 'wrong placeholder' if placeholder != @target @target.heads.delete(ptrs[0]) if @target @target = actual @target.heads << @ptrs[0] @symbols.map! { |s| s == placeholder ? actual : s } end
ruby
def replace(placeholder, actual) raise 'wrong placeholder' if placeholder != @target @target.heads.delete(ptrs[0]) if @target @target = actual @target.heads << @ptrs[0] @symbols.map! { |s| s == placeholder ? actual : s } end
[ "def", "replace", "(", "placeholder", ",", "actual", ")", "raise", "'wrong placeholder'", "if", "placeholder", "!=", "@target", "@target", ".", "heads", ".", "delete", "(", "ptrs", "[", "0", "]", ")", "if", "@target", "@target", "=", "actual", "@target", ".", "heads", "<<", "@ptrs", "[", "0", "]", "@symbols", ".", "map!", "{", "|", "s", "|", "s", "==", "placeholder", "?", "actual", ":", "s", "}", "end" ]
sometimes a Rule is instantiated before the target is actually known it may be given a "placeholder" target first, which is later replaced with the real one
[ "sometimes", "a", "Rule", "is", "instantiated", "before", "the", "target", "is", "actually", "known", "it", "may", "be", "given", "a", "placeholder", "target", "first", "which", "is", "later", "replaced", "with", "the", "real", "one" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/grammar.rb#L470-L476
12,213
ruby/racc
lib/racc/grammar.rb
Racc.Sym.expand
def expand @expand ||= Racc.set_closure(@heads.dup) do |ptr| if (sym = ptr.symbol) && sym.nonterminal? sym.heads end end.freeze end
ruby
def expand @expand ||= Racc.set_closure(@heads.dup) do |ptr| if (sym = ptr.symbol) && sym.nonterminal? sym.heads end end.freeze end
[ "def", "expand", "@expand", "||=", "Racc", ".", "set_closure", "(", "@heads", ".", "dup", ")", "do", "|", "ptr", "|", "if", "(", "sym", "=", "ptr", ".", "symbol", ")", "&&", "sym", ".", "nonterminal?", "sym", ".", "heads", "end", "end", ".", "freeze", "end" ]
If an instance of this NT comes next, then what rules could we be starting?
[ "If", "an", "instance", "of", "this", "NT", "comes", "next", "then", "what", "rules", "could", "we", "be", "starting?" ]
d3244edfa11dd6e86e43f570c6444d41c7e3552a
https://github.com/ruby/racc/blob/d3244edfa11dd6e86e43f570c6444d41c7e3552a/lib/racc/grammar.rb#L738-L744
12,214
refile/refile
lib/refile/rails/attachment_helper.rb
Refile.AttachmentHelper.attachment_image_tag
def attachment_image_tag(record, name, *args, fallback: nil, host: nil, prefix: nil, format: nil, **options) file = record && record.public_send(name) classes = ["attachment", (record.class.model_name.singular if record), name, *options[:class]] if file image_tag(attachment_url(record, name, *args, host: host, prefix: prefix, format: format), options.merge(class: classes)) elsif fallback classes << "fallback" image_tag(fallback, options.merge(class: classes)) end end
ruby
def attachment_image_tag(record, name, *args, fallback: nil, host: nil, prefix: nil, format: nil, **options) file = record && record.public_send(name) classes = ["attachment", (record.class.model_name.singular if record), name, *options[:class]] if file image_tag(attachment_url(record, name, *args, host: host, prefix: prefix, format: format), options.merge(class: classes)) elsif fallback classes << "fallback" image_tag(fallback, options.merge(class: classes)) end end
[ "def", "attachment_image_tag", "(", "record", ",", "name", ",", "*", "args", ",", "fallback", ":", "nil", ",", "host", ":", "nil", ",", "prefix", ":", "nil", ",", "format", ":", "nil", ",", "**", "options", ")", "file", "=", "record", "&&", "record", ".", "public_send", "(", "name", ")", "classes", "=", "[", "\"attachment\"", ",", "(", "record", ".", "class", ".", "model_name", ".", "singular", "if", "record", ")", ",", "name", ",", "options", "[", ":class", "]", "]", "if", "file", "image_tag", "(", "attachment_url", "(", "record", ",", "name", ",", "args", ",", "host", ":", "host", ",", "prefix", ":", "prefix", ",", "format", ":", "format", ")", ",", "options", ".", "merge", "(", "class", ":", "classes", ")", ")", "elsif", "fallback", "classes", "<<", "\"fallback\"", "image_tag", "(", "fallback", ",", "options", ".", "merge", "(", "class", ":", "classes", ")", ")", "end", "end" ]
Generates an image tag for the given attachment, adding appropriate classes and optionally falling back to the given fallback image if there is no file attached. Returns `nil` if there is no file attached and no fallback specified. @param [String] fallback The path to an image asset to be used as a fallback @param [Hash] options Additional options for the image tag @see #attachment_url @return [ActiveSupport::SafeBuffer, nil] The generated image tag
[ "Generates", "an", "image", "tag", "for", "the", "given", "attachment", "adding", "appropriate", "classes", "and", "optionally", "falling", "back", "to", "the", "given", "fallback", "image", "if", "there", "is", "no", "file", "attached", "." ]
e910f5ca5a9060c307bd0a5e813f1fec73219ed5
https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/rails/attachment_helper.rb#L51-L61
12,215
refile/refile
lib/refile/rails/attachment_helper.rb
Refile.AttachmentHelper.attachment_cache_field
def attachment_cache_field(object_name, method, object:, **options) options[:data] ||= {} options[:data][:reference] ||= SecureRandom.hex attacher_value = object.send("#{method}_data") hidden_options = { multiple: options[:multiple], value: attacher_value.try(:to_json), object: object, disabled: attacher_value.blank?, id: nil, data: { reference: options[:data][:reference] } } hidden_options.merge!(index: options[:index]) if options.key?(:index) hidden_field(object_name, method, hidden_options) end
ruby
def attachment_cache_field(object_name, method, object:, **options) options[:data] ||= {} options[:data][:reference] ||= SecureRandom.hex attacher_value = object.send("#{method}_data") hidden_options = { multiple: options[:multiple], value: attacher_value.try(:to_json), object: object, disabled: attacher_value.blank?, id: nil, data: { reference: options[:data][:reference] } } hidden_options.merge!(index: options[:index]) if options.key?(:index) hidden_field(object_name, method, hidden_options) end
[ "def", "attachment_cache_field", "(", "object_name", ",", "method", ",", "object", ":", ",", "**", "options", ")", "options", "[", ":data", "]", "||=", "{", "}", "options", "[", ":data", "]", "[", ":reference", "]", "||=", "SecureRandom", ".", "hex", "attacher_value", "=", "object", ".", "send", "(", "\"#{method}_data\"", ")", "hidden_options", "=", "{", "multiple", ":", "options", "[", ":multiple", "]", ",", "value", ":", "attacher_value", ".", "try", "(", ":to_json", ")", ",", "object", ":", "object", ",", "disabled", ":", "attacher_value", ".", "blank?", ",", "id", ":", "nil", ",", "data", ":", "{", "reference", ":", "options", "[", ":data", "]", "[", ":reference", "]", "}", "}", "hidden_options", ".", "merge!", "(", "index", ":", "options", "[", ":index", "]", ")", "if", "options", ".", "key?", "(", ":index", ")", "hidden_field", "(", "object_name", ",", "method", ",", "hidden_options", ")", "end" ]
Generates a hidden form field which tracks the id of the file in the cache before it is permanently stored. @param object_name The name of the object to generate a field for @param method The name of the field @param [Hash] options @option options [Object] object Set by the form builder @return [ActiveSupport::SafeBuffer] The generated hidden form field
[ "Generates", "a", "hidden", "form", "field", "which", "tracks", "the", "id", "of", "the", "file", "in", "the", "cache", "before", "it", "is", "permanently", "stored", "." ]
e910f5ca5a9060c307bd0a5e813f1fec73219ed5
https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/rails/attachment_helper.rb#L105-L122
12,216
refile/refile
lib/refile/attachment.rb
Refile.Attachment.accepts_attachments_for
def accepts_attachments_for(collection_name, collection_class:, accessor_prefix:, attachment: :file, append: false) include MultipleAttachments.new( collection_name, collection_class: collection_class, name: accessor_prefix, attachment: attachment, append: append ) end
ruby
def accepts_attachments_for(collection_name, collection_class:, accessor_prefix:, attachment: :file, append: false) include MultipleAttachments.new( collection_name, collection_class: collection_class, name: accessor_prefix, attachment: attachment, append: append ) end
[ "def", "accepts_attachments_for", "(", "collection_name", ",", "collection_class", ":", ",", "accessor_prefix", ":", ",", "attachment", ":", ":file", ",", "append", ":", "false", ")", "include", "MultipleAttachments", ".", "new", "(", "collection_name", ",", "collection_class", ":", "collection_class", ",", "name", ":", "accessor_prefix", ",", "attachment", ":", "attachment", ",", "append", ":", "append", ")", "end" ]
Macro which generates accessors in pure Ruby classes for assigning multiple attachments at once. This is primarily useful together with multiple file uploads. There is also an Active Record version of this macro. The name of the generated accessors will be the name of the association (represented by an attribute accessor) and the name of the attachment in the associated class. So if a `Post` accepts attachments for `images`, and the attachment in the `Image` class is named `file`, then the accessors will be named `images_files`. @example in associated class class Document extend Refile::Attachment attr_accessor :file_id attachment :file def initialize(attributes = {}) self.file = attributes[:file] end end @example in class class Post extend Refile::Attachment include ActiveModel::Model attr_accessor :documents accepts_attachments_for :documents, accessor_prefix: 'documents_files', collection_class: Document def initialize(attributes = {}) @documents = attributes[:documents] || [] end end @example in form <%= form_for @post do |form| %> <%= form.attachment_field :documents_files, multiple: true %> <% end %> @param [Symbol] collection_name Name of the association @param [Class] collection_class Associated class @param [String] accessor_prefix Name of the generated accessors @param [Symbol] attachment Name of the attachment in the associated class @param [Boolean] append If true, new files are appended instead of replacing the entire list of associated classes. @return [void]
[ "Macro", "which", "generates", "accessors", "in", "pure", "Ruby", "classes", "for", "assigning", "multiple", "attachments", "at", "once", ".", "This", "is", "primarily", "useful", "together", "with", "multiple", "file", "uploads", ".", "There", "is", "also", "an", "Active", "Record", "version", "of", "this", "macro", "." ]
e910f5ca5a9060c307bd0a5e813f1fec73219ed5
https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/attachment.rb#L156-L164
12,217
refile/refile
lib/refile/file.rb
Refile.File.download
def download return io if io.is_a?(Tempfile) Tempfile.new(id, binmode: true).tap do |tempfile| IO.copy_stream(io, tempfile) tempfile.rewind tempfile.fsync end end
ruby
def download return io if io.is_a?(Tempfile) Tempfile.new(id, binmode: true).tap do |tempfile| IO.copy_stream(io, tempfile) tempfile.rewind tempfile.fsync end end
[ "def", "download", "return", "io", "if", "io", ".", "is_a?", "(", "Tempfile", ")", "Tempfile", ".", "new", "(", "id", ",", "binmode", ":", "true", ")", ".", "tap", "do", "|", "tempfile", "|", "IO", ".", "copy_stream", "(", "io", ",", "tempfile", ")", "tempfile", ".", "rewind", "tempfile", ".", "fsync", "end", "end" ]
Downloads the file to a Tempfile on disk and returns this tempfile. @example file = backend.upload(StringIO.new("hello")) tempfile = file.download File.read(tempfile.path) # => "hello" @return [Tempfile] a tempfile with the file's content
[ "Downloads", "the", "file", "to", "a", "Tempfile", "on", "disk", "and", "returns", "this", "tempfile", "." ]
e910f5ca5a9060c307bd0a5e813f1fec73219ed5
https://github.com/refile/refile/blob/e910f5ca5a9060c307bd0a5e813f1fec73219ed5/lib/refile/file.rb#L69-L77
12,218
vcr/vcr
lib/vcr/structs.rb
VCR.Response.to_hash
def to_hash { 'status' => status.to_hash, 'headers' => headers, 'body' => serializable_body, 'http_version' => http_version }.tap do |hash| hash['adapter_metadata'] = adapter_metadata unless adapter_metadata.empty? end end
ruby
def to_hash { 'status' => status.to_hash, 'headers' => headers, 'body' => serializable_body, 'http_version' => http_version }.tap do |hash| hash['adapter_metadata'] = adapter_metadata unless adapter_metadata.empty? end end
[ "def", "to_hash", "{", "'status'", "=>", "status", ".", "to_hash", ",", "'headers'", "=>", "headers", ",", "'body'", "=>", "serializable_body", ",", "'http_version'", "=>", "http_version", "}", ".", "tap", "do", "|", "hash", "|", "hash", "[", "'adapter_metadata'", "]", "=", "adapter_metadata", "unless", "adapter_metadata", ".", "empty?", "end", "end" ]
Builds a serializable hash from the response data. @return [Hash] hash that represents this response and can be easily serialized. @see Response.from_hash
[ "Builds", "a", "serializable", "hash", "from", "the", "response", "data", "." ]
945ca793a4b25c7ffc406b9fd7da1e94cbbb8141
https://github.com/vcr/vcr/blob/945ca793a4b25c7ffc406b9fd7da1e94cbbb8141/lib/vcr/structs.rb#L345-L354
12,219
vcr/vcr
lib/vcr/configuration.rb
VCR.Configuration.around_http_request
def around_http_request(*filters, &block) unless VCR.fibers_available? raise Errors::NotSupportedError.new \ "VCR::Configuration#around_http_request requires fibers, " + "which are not available on your ruby intepreter." end fibers = {} fiber_errors = {} hook_allowed, hook_declaration = false, caller.first before_http_request(*filters) do |request| hook_allowed = true start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, block) end after_http_request(lambda { hook_allowed }) do |request, response| fiber = fibers.delete(Thread.current) resume_fiber(fiber, fiber_errors, response, hook_declaration) end end
ruby
def around_http_request(*filters, &block) unless VCR.fibers_available? raise Errors::NotSupportedError.new \ "VCR::Configuration#around_http_request requires fibers, " + "which are not available on your ruby intepreter." end fibers = {} fiber_errors = {} hook_allowed, hook_declaration = false, caller.first before_http_request(*filters) do |request| hook_allowed = true start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, block) end after_http_request(lambda { hook_allowed }) do |request, response| fiber = fibers.delete(Thread.current) resume_fiber(fiber, fiber_errors, response, hook_declaration) end end
[ "def", "around_http_request", "(", "*", "filters", ",", "&", "block", ")", "unless", "VCR", ".", "fibers_available?", "raise", "Errors", "::", "NotSupportedError", ".", "new", "\"VCR::Configuration#around_http_request requires fibers, \"", "+", "\"which are not available on your ruby intepreter.\"", "end", "fibers", "=", "{", "}", "fiber_errors", "=", "{", "}", "hook_allowed", ",", "hook_declaration", "=", "false", ",", "caller", ".", "first", "before_http_request", "(", "filters", ")", "do", "|", "request", "|", "hook_allowed", "=", "true", "start_new_fiber_for", "(", "request", ",", "fibers", ",", "fiber_errors", ",", "hook_declaration", ",", "block", ")", "end", "after_http_request", "(", "lambda", "{", "hook_allowed", "}", ")", "do", "|", "request", ",", "response", "|", "fiber", "=", "fibers", ".", "delete", "(", "Thread", ".", "current", ")", "resume_fiber", "(", "fiber", ",", "fiber_errors", ",", "response", ",", "hook_declaration", ")", "end", "end" ]
Adds a callback that will be executed around each HTTP request. @example VCR.configure do |c| c.around_http_request(lambda {|r| r.uri =~ /api.geocoder.com/}) do |request| # extract an address like "1700 E Pine St, Seattle, WA" # from a query like "address=1700+E+Pine+St%2C+Seattle%2C+WA" address = CGI.unescape(URI(request.uri).query.split('=').last) VCR.use_cassette("geocoding/#{address}", &request) end end @yield the callback @yieldparam request [VCR::Request::FiberAware] the request that is being made @raise [VCR::Errors::NotSupportedError] if the fiber library cannot be loaded. @param filters [optional splat of #to_proc] one or more filters to apply. The objects provided will be converted to procs using `#to_proc`. If provided, the callback will only be invoked if these procs all return `true`. @note This method can only be used on ruby interpreters that support fibers (i.e. 1.9+). On 1.8 you can use separate `before_http_request` and `after_http_request` hooks. @note You _must_ call `request.proceed` or pass the request as a proc on to a method that yields to a block (i.e. `some_method(&request)`). @see #before_http_request @see #after_http_request
[ "Adds", "a", "callback", "that", "will", "be", "executed", "around", "each", "HTTP", "request", "." ]
945ca793a4b25c7ffc406b9fd7da1e94cbbb8141
https://github.com/vcr/vcr/blob/945ca793a4b25c7ffc406b9fd7da1e94cbbb8141/lib/vcr/configuration.rb#L395-L414
12,220
floere/phony
lib/phony/dsl.rb
Phony.DSL.country
def country country_code, definition, options = {} return unless Phony.config.load?(country_code) definition.with country_code, options Phony::CountryCodes.instance.add country_code, definition end
ruby
def country country_code, definition, options = {} return unless Phony.config.load?(country_code) definition.with country_code, options Phony::CountryCodes.instance.add country_code, definition end
[ "def", "country", "country_code", ",", "definition", ",", "options", "=", "{", "}", "return", "unless", "Phony", ".", "config", ".", "load?", "(", "country_code", ")", "definition", ".", "with", "country_code", ",", "options", "Phony", "::", "CountryCodes", ".", "instance", ".", "add", "country_code", ",", "definition", "end" ]
Define a country's rules. Use the other DSL methods to define the country's rules. @param [String] country_code The country code of the country. @param [Phony::CountryCodes] definition Rules for this country. @return Undefined. @example Add a country with country code 27. country '27', # CC, followed by rules, for example fixed(2) >> ...
[ "Define", "a", "country", "s", "rules", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/dsl.rb#L43-L48
12,221
floere/phony
lib/phony/dsl.rb
Phony.DSL.fixed
def fixed length, options = {} options[:zero] = true if options[:zero].nil? NationalSplitters::Fixed.instance_for length, options end
ruby
def fixed length, options = {} options[:zero] = true if options[:zero].nil? NationalSplitters::Fixed.instance_for length, options end
[ "def", "fixed", "length", ",", "options", "=", "{", "}", "options", "[", ":zero", "]", "=", "true", "if", "options", "[", ":zero", "]", ".", "nil?", "NationalSplitters", "::", "Fixed", ".", "instance_for", "length", ",", "options", "end" ]
National matcher & splitters. By default, a fixed length NDC uses a zero prefix when formatted with format :national. @param [Fixnum] length The length of the fixed length NDC. @param [Hash] options An options hash (set zero: false to not add a zero on format :national). @return NationalSplitters::Fixed A fixed length national splitter. @example France. Uses a fixed NDC of size 1. country '33', fixed(1) >> split(2,2,2,2)
[ "National", "matcher", "&", "splitters", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/dsl.rb#L110-L113
12,222
floere/phony
lib/phony/country_codes.rb
Phony.CountryCodes.add
def add country_code, country country_code = country_code.to_s optimized_country_code_access = country_code.size @countries ||= {} @countries[optimized_country_code_access] ||= {} @countries[optimized_country_code_access][country_code] = country end
ruby
def add country_code, country country_code = country_code.to_s optimized_country_code_access = country_code.size @countries ||= {} @countries[optimized_country_code_access] ||= {} @countries[optimized_country_code_access][country_code] = country end
[ "def", "add", "country_code", ",", "country", "country_code", "=", "country_code", ".", "to_s", "optimized_country_code_access", "=", "country_code", ".", "size", "@countries", "||=", "{", "}", "@countries", "[", "optimized_country_code_access", "]", "||=", "{", "}", "@countries", "[", "optimized_country_code_access", "]", "[", "country_code", "]", "=", "country", "end" ]
Add the given country to the mapping under the given country code.
[ "Add", "the", "given", "country", "to", "the", "mapping", "under", "the", "given", "country", "code", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L21-L28
12,223
floere/phony
lib/phony/country_codes.rb
Phony.CountryCodes.split
def split number # Split the number into country, cc, and national part. country, cc, national_number = partial_split number # Split the national number into ndc and local part. _, ndc, *local = country.split national_number [cc, ndc, *local] end
ruby
def split number # Split the number into country, cc, and national part. country, cc, national_number = partial_split number # Split the national number into ndc and local part. _, ndc, *local = country.split national_number [cc, ndc, *local] end
[ "def", "split", "number", "# Split the number into country, cc, and national part.", "country", ",", "cc", ",", "national_number", "=", "partial_split", "number", "# Split the national number into ndc and local part.", "_", ",", "ndc", ",", "*", "local", "=", "country", ".", "split", "national_number", "[", "cc", ",", "ndc", ",", "local", "]", "end" ]
Splits this number into cc, ndc and locally split number parts.
[ "Splits", "this", "number", "into", "cc", "ndc", "and", "locally", "split", "number", "parts", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L75-L83
12,224
floere/phony
lib/phony/country_codes.rb
Phony.CountryCodes.format
def format number, options = {} country, _, national_number = partial_split number country.format national_number, options end
ruby
def format number, options = {} country, _, national_number = partial_split number country.format national_number, options end
[ "def", "format", "number", ",", "options", "=", "{", "}", "country", ",", "_", ",", "national_number", "=", "partial_split", "number", "country", ".", "format", "national_number", ",", "options", "end" ]
Format the number.
[ "Format", "the", "number", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L87-L90
12,225
floere/phony
lib/phony/country_codes.rb
Phony.CountryCodes.plausible?
def plausible? number, hints = {} normalized = clean number # False if it fails the basic check. # return false unless (4..16) === normalized.size country, cc, rest = partial_split normalized # Country code plausible? # cc_needed = hints[:cc] return false if cc_needed && !(cc_needed === cc) # Country specific tests. # country.plausible? rest, hints rescue StandardError return false end
ruby
def plausible? number, hints = {} normalized = clean number # False if it fails the basic check. # return false unless (4..16) === normalized.size country, cc, rest = partial_split normalized # Country code plausible? # cc_needed = hints[:cc] return false if cc_needed && !(cc_needed === cc) # Country specific tests. # country.plausible? rest, hints rescue StandardError return false end
[ "def", "plausible?", "number", ",", "hints", "=", "{", "}", "normalized", "=", "clean", "number", "# False if it fails the basic check.", "#", "return", "false", "unless", "(", "4", "..", "16", ")", "===", "normalized", ".", "size", "country", ",", "cc", ",", "rest", "=", "partial_split", "normalized", "# Country code plausible?", "#", "cc_needed", "=", "hints", "[", ":cc", "]", "return", "false", "if", "cc_needed", "&&", "!", "(", "cc_needed", "===", "cc", ")", "# Country specific tests.", "#", "country", ".", "plausible?", "rest", ",", "hints", "rescue", "StandardError", "return", "false", "end" ]
Is this number plausible?
[ "Is", "this", "number", "plausible?" ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L95-L114
12,226
floere/phony
lib/phony/country_codes.rb
Phony.CountryCodes.vanity?
def vanity? number country, _, national = partial_split number country.vanity? national end
ruby
def vanity? number country, _, national = partial_split number country.vanity? national end
[ "def", "vanity?", "number", "country", ",", "_", ",", "national", "=", "partial_split", "number", "country", ".", "vanity?", "national", "end" ]
Is the given number a vanity number?
[ "Is", "the", "given", "number", "a", "vanity", "number?" ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L118-L121
12,227
floere/phony
lib/phony/country_codes.rb
Phony.CountryCodes.partial_split
def partial_split number cc = '' 1.upto(3) do |i| cc << number.slice!(0..0) country = countries[i][cc] return [country, cc, number] if country end # This line is never reached as CCs are in prefix code. end
ruby
def partial_split number cc = '' 1.upto(3) do |i| cc << number.slice!(0..0) country = countries[i][cc] return [country, cc, number] if country end # This line is never reached as CCs are in prefix code. end
[ "def", "partial_split", "number", "cc", "=", "''", "1", ".", "upto", "(", "3", ")", "do", "|", "i", "|", "cc", "<<", "number", ".", "slice!", "(", "0", "..", "0", ")", "country", "=", "countries", "[", "i", "]", "[", "cc", "]", "return", "[", "country", ",", "cc", ",", "number", "]", "if", "country", "end", "# This line is never reached as CCs are in prefix code.", "end" ]
Split off the country and the cc, and also return the national number part.
[ "Split", "off", "the", "country", "and", "the", "cc", "and", "also", "return", "the", "national", "number", "part", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country_codes.rb#L140-L148
12,228
floere/phony
lib/phony/country.rb
Phony.Country.split
def split national_number _, trunk, ndc, *rest = internal_split national_number [trunk, ndc, *rest] end
ruby
def split national_number _, trunk, ndc, *rest = internal_split national_number [trunk, ndc, *rest] end
[ "def", "split", "national_number", "_", ",", "trunk", ",", "ndc", ",", "*", "rest", "=", "internal_split", "national_number", "[", "trunk", ",", "ndc", ",", "rest", "]", "end" ]
A number is split with the code handlers as given in the initializer. Note: If the ndc is nil, it will not return it. @return [Trunk, String (ndc), Array<String> (national pieces)]
[ "A", "number", "is", "split", "with", "the", "code", "handlers", "as", "given", "in", "the", "initializer", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L55-L58
12,229
floere/phony
lib/phony/country.rb
Phony.Country.format
def format national_number, options = {} type = options[:format] || @format space = options[:spaces] || @space || @@default_space local_space = options[:local_spaces] || @local_space || space || @@default_local_space parentheses = options[:parentheses] parentheses = @parentheses || @@default_parentheses if parentheses.nil? use_trunk = options[:trunk] trunk, ndc, *local_pieces = split national_number local = format_local local_pieces, local_space format_cc_ndc trunk, ndc, local, type, space, parentheses, use_trunk end
ruby
def format national_number, options = {} type = options[:format] || @format space = options[:spaces] || @space || @@default_space local_space = options[:local_spaces] || @local_space || space || @@default_local_space parentheses = options[:parentheses] parentheses = @parentheses || @@default_parentheses if parentheses.nil? use_trunk = options[:trunk] trunk, ndc, *local_pieces = split national_number local = format_local local_pieces, local_space format_cc_ndc trunk, ndc, local, type, space, parentheses, use_trunk end
[ "def", "format", "national_number", ",", "options", "=", "{", "}", "type", "=", "options", "[", ":format", "]", "||", "@format", "space", "=", "options", "[", ":spaces", "]", "||", "@space", "||", "@@default_space", "local_space", "=", "options", "[", ":local_spaces", "]", "||", "@local_space", "||", "space", "||", "@@default_local_space", "parentheses", "=", "options", "[", ":parentheses", "]", "parentheses", "=", "@parentheses", "||", "@@default_parentheses", "if", "parentheses", ".", "nil?", "use_trunk", "=", "options", "[", ":trunk", "]", "trunk", ",", "ndc", ",", "*", "local_pieces", "=", "split", "national_number", "local", "=", "format_local", "local_pieces", ",", "local_space", "format_cc_ndc", "trunk", ",", "ndc", ",", "local", ",", "type", ",", "space", ",", "parentheses", ",", "use_trunk", "end" ]
Format the number, given the national part of it.
[ "Format", "the", "number", "given", "the", "national", "part", "of", "it", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L77-L90
12,230
floere/phony
lib/phony/country.rb
Phony.Country.normalize
def normalize national_number clean! national_number normalized = @codes.reduce national_number do |number, code| result = code.normalize number break result if result number end normalized end
ruby
def normalize national_number clean! national_number normalized = @codes.reduce national_number do |number, code| result = code.normalize number break result if result number end normalized end
[ "def", "normalize", "national_number", "clean!", "national_number", "normalized", "=", "@codes", ".", "reduce", "national_number", "do", "|", "number", ",", "code", "|", "result", "=", "code", ".", "normalize", "number", "break", "result", "if", "result", "number", "end", "normalized", "end" ]
Removes 0s from partially normalized numbers such as 410443643533. Example: 410443643533 -> 41443643533 In some cases it doesn't, like Italy.
[ "Removes", "0s", "from", "partially", "normalized", "numbers", "such", "as", "410443643533", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L159-L167
12,231
floere/phony
lib/phony/country.rb
Phony.Country.plausible?
def plausible? rest, hints = {} local, _, ndc, *rest = internal_split rest # Element based checking. # # Note: ndc == false means the country has none. # return false if ndc.nil? return false if ndc && ndc.empty? return false if @invalid_ndcs && @invalid_ndcs === ndc # # A valid range for the rest is 0 or 3+ total digits. # # # return false if (1..2) === rest_size # National destination code plausible? # ndc_needed = hints[:ndc] return false if ndc_needed && !(ndc_needed === ndc) # If there is no local part, we can assume it's not a plausible number. # (Or, not defined correctly in Phony yet) return false unless local # Local code specific checks. # return local.plausible? rest, hints end
ruby
def plausible? rest, hints = {} local, _, ndc, *rest = internal_split rest # Element based checking. # # Note: ndc == false means the country has none. # return false if ndc.nil? return false if ndc && ndc.empty? return false if @invalid_ndcs && @invalid_ndcs === ndc # # A valid range for the rest is 0 or 3+ total digits. # # # return false if (1..2) === rest_size # National destination code plausible? # ndc_needed = hints[:ndc] return false if ndc_needed && !(ndc_needed === ndc) # If there is no local part, we can assume it's not a plausible number. # (Or, not defined correctly in Phony yet) return false unless local # Local code specific checks. # return local.plausible? rest, hints end
[ "def", "plausible?", "rest", ",", "hints", "=", "{", "}", "local", ",", "_", ",", "ndc", ",", "*", "rest", "=", "internal_split", "rest", "# Element based checking.", "#", "# Note: ndc == false means the country has none.", "#", "return", "false", "if", "ndc", ".", "nil?", "return", "false", "if", "ndc", "&&", "ndc", ".", "empty?", "return", "false", "if", "@invalid_ndcs", "&&", "@invalid_ndcs", "===", "ndc", "# # A valid range for the rest is 0 or 3+ total digits.", "# #", "# return false if (1..2) === rest_size", "# National destination code plausible?", "#", "ndc_needed", "=", "hints", "[", ":ndc", "]", "return", "false", "if", "ndc_needed", "&&", "!", "(", "ndc_needed", "===", "ndc", ")", "# If there is no local part, we can assume it's not a plausible number.", "# (Or, not defined correctly in Phony yet)", "return", "false", "unless", "local", "# Local code specific checks.", "#", "return", "local", ".", "plausible?", "rest", ",", "hints", "end" ]
Tests for plausibility of this national number.
[ "Tests", "for", "plausibility", "of", "this", "national", "number", "." ]
9ca50743499cf478a25fdb927bcdacd29d2c90c7
https://github.com/floere/phony/blob/9ca50743499cf478a25fdb927bcdacd29d2c90c7/lib/phony/country.rb#L171-L198
12,232
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.merge!
def merge!(other) criteria = other.to_criteria selector.merge!(criteria.selector) options.merge!(criteria.options) self.documents = criteria.documents.dup unless criteria.documents.empty? self.scoping_options = criteria.scoping_options self.inclusions = (inclusions + criteria.inclusions).uniq self end
ruby
def merge!(other) criteria = other.to_criteria selector.merge!(criteria.selector) options.merge!(criteria.options) self.documents = criteria.documents.dup unless criteria.documents.empty? self.scoping_options = criteria.scoping_options self.inclusions = (inclusions + criteria.inclusions).uniq self end
[ "def", "merge!", "(", "other", ")", "criteria", "=", "other", ".", "to_criteria", "selector", ".", "merge!", "(", "criteria", ".", "selector", ")", "options", ".", "merge!", "(", "criteria", ".", "options", ")", "self", ".", "documents", "=", "criteria", ".", "documents", ".", "dup", "unless", "criteria", ".", "documents", ".", "empty?", "self", ".", "scoping_options", "=", "criteria", ".", "scoping_options", "self", ".", "inclusions", "=", "(", "inclusions", "+", "criteria", ".", "inclusions", ")", ".", "uniq", "self", "end" ]
Merge the other criteria into this one. @example Merge another criteria into this criteria. criteria.merge(Person.where(name: "bob")) @param [ Criteria ] other The criteria to merge in. @return [ Criteria ] The merged criteria. @since 3.0.0
[ "Merge", "the", "other", "criteria", "into", "this", "one", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L242-L250
12,233
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.only
def only(*args) return clone if args.flatten.empty? args = args.flatten if (args & Fields::IDS).empty? args.unshift(:_id) end if klass.hereditary? super(*args.push(:_type)) else super(*args) end end
ruby
def only(*args) return clone if args.flatten.empty? args = args.flatten if (args & Fields::IDS).empty? args.unshift(:_id) end if klass.hereditary? super(*args.push(:_type)) else super(*args) end end
[ "def", "only", "(", "*", "args", ")", "return", "clone", "if", "args", ".", "flatten", ".", "empty?", "args", "=", "args", ".", "flatten", "if", "(", "args", "&", "Fields", "::", "IDS", ")", ".", "empty?", "args", ".", "unshift", "(", ":_id", ")", "end", "if", "klass", ".", "hereditary?", "super", "(", "args", ".", "push", "(", ":_type", ")", ")", "else", "super", "(", "args", ")", "end", "end" ]
Overriden to include _type in the fields. @example Limit the fields returned from the database. Band.only(:name) @param [ Array<Symbol> ] args The names of the fields. @return [ Criteria ] The cloned criteria. @since 1.0.0
[ "Overriden", "to", "include", "_type", "in", "the", "fields", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L287-L298
12,234
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.read
def read(value = nil) clone.tap do |criteria| criteria.options.merge!(read: value) end end
ruby
def read(value = nil) clone.tap do |criteria| criteria.options.merge!(read: value) end end
[ "def", "read", "(", "value", "=", "nil", ")", "clone", ".", "tap", "do", "|", "criteria", "|", "criteria", ".", "options", ".", "merge!", "(", "read", ":", "value", ")", "end", "end" ]
Set the read preference for the criteria. @example Set the read preference. criteria.read(mode: :primary_preferred) @param [ Hash ] value The mode preference. @return [ Criteria ] The cloned criteria. @since 5.0.0
[ "Set", "the", "read", "preference", "for", "the", "criteria", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L310-L314
12,235
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.respond_to?
def respond_to?(name, include_private = false) super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private) end
ruby
def respond_to?(name, include_private = false) super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private) end
[ "def", "respond_to?", "(", "name", ",", "include_private", "=", "false", ")", "super", "||", "klass", ".", "respond_to?", "(", "name", ")", "||", "CHECK", ".", "respond_to?", "(", "name", ",", "include_private", ")", "end" ]
Returns true if criteria responds to the given method. @example Does the criteria respond to the method? crtiteria.respond_to?(:each) @param [ Symbol ] name The name of the class method on the +Document+. @param [ true, false ] include_private Whether to include privates. @return [ true, false ] If the criteria responds to the method.
[ "Returns", "true", "if", "criteria", "responds", "to", "the", "given", "method", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L340-L342
12,236
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.check_for_missing_documents!
def check_for_missing_documents!(result, ids) if (result.size < ids.size) && Mongoid.raise_not_found_error raise Errors::DocumentNotFound.new(klass, ids, ids - result.map(&:_id)) end end
ruby
def check_for_missing_documents!(result, ids) if (result.size < ids.size) && Mongoid.raise_not_found_error raise Errors::DocumentNotFound.new(klass, ids, ids - result.map(&:_id)) end end
[ "def", "check_for_missing_documents!", "(", "result", ",", "ids", ")", "if", "(", "result", ".", "size", "<", "ids", ".", "size", ")", "&&", "Mongoid", ".", "raise_not_found_error", "raise", "Errors", "::", "DocumentNotFound", ".", "new", "(", "klass", ",", "ids", ",", "ids", "-", "result", ".", "map", "(", ":_id", ")", ")", "end", "end" ]
Are documents in the query missing, and are we configured to raise an error? @api private @example Check for missing documents. criteria.check_for_missing_documents!([], [ 1 ]) @param [ Array<Document> ] result The result. @param [ Array<Object> ] ids The ids. @raise [ Errors::DocumentNotFound ] If none are found and raising an error. @since 3.0.0
[ "Are", "documents", "in", "the", "query", "missing", "and", "are", "we", "configured", "to", "raise", "an", "error?" ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L459-L463
12,237
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.initialize_copy
def initialize_copy(other) @inclusions = other.inclusions.dup @scoping_options = other.scoping_options @documents = other.documents.dup @context = nil super end
ruby
def initialize_copy(other) @inclusions = other.inclusions.dup @scoping_options = other.scoping_options @documents = other.documents.dup @context = nil super end
[ "def", "initialize_copy", "(", "other", ")", "@inclusions", "=", "other", ".", "inclusions", ".", "dup", "@scoping_options", "=", "other", ".", "scoping_options", "@documents", "=", "other", ".", "documents", ".", "dup", "@context", "=", "nil", "super", "end" ]
Clone or dup the current +Criteria+. This will return a new criteria with the selector, options, klass, embedded options, etc intact. @api private @example Clone a criteria. criteria.clone @example Dup a criteria. criteria.dup @param [ Criteria ] other The criteria getting cloned. @return [ nil ] nil. @since 1.0.0
[ "Clone", "or", "dup", "the", "current", "+", "Criteria", "+", ".", "This", "will", "return", "a", "new", "criteria", "with", "the", "selector", "options", "klass", "embedded", "options", "etc", "intact", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L481-L487
12,238
mongodb/mongoid
lib/mongoid/criteria.rb
Mongoid.Criteria.type_selection
def type_selection klasses = klass._types if klasses.size > 1 { _type: { "$in" => klass._types }} else { _type: klass._types[0] } end end
ruby
def type_selection klasses = klass._types if klasses.size > 1 { _type: { "$in" => klass._types }} else { _type: klass._types[0] } end end
[ "def", "type_selection", "klasses", "=", "klass", ".", "_types", "if", "klasses", ".", "size", ">", "1", "{", "_type", ":", "{", "\"$in\"", "=>", "klass", ".", "_types", "}", "}", "else", "{", "_type", ":", "klass", ".", "_types", "[", "0", "]", "}", "end", "end" ]
Get the selector for type selection. @api private @example Get a type selection hash. criteria.type_selection @return [ Hash ] The type selection. @since 3.0.3
[ "Get", "the", "selector", "for", "type", "selection", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L552-L559
12,239
mongodb/mongoid
lib/mongoid/positional.rb
Mongoid.Positional.positionally
def positionally(selector, operations, processed = {}) if selector.size == 1 || selector.values.any? { |val| val.nil? } return operations end keys = selector.keys.map{ |m| m.sub('._id','') } - ['_id'] keys = keys.sort_by { |s| s.length*-1 } process_operations(keys, operations, processed) end
ruby
def positionally(selector, operations, processed = {}) if selector.size == 1 || selector.values.any? { |val| val.nil? } return operations end keys = selector.keys.map{ |m| m.sub('._id','') } - ['_id'] keys = keys.sort_by { |s| s.length*-1 } process_operations(keys, operations, processed) end
[ "def", "positionally", "(", "selector", ",", "operations", ",", "processed", "=", "{", "}", ")", "if", "selector", ".", "size", "==", "1", "||", "selector", ".", "values", ".", "any?", "{", "|", "val", "|", "val", ".", "nil?", "}", "return", "operations", "end", "keys", "=", "selector", ".", "keys", ".", "map", "{", "|", "m", "|", "m", ".", "sub", "(", "'._id'", ",", "''", ")", "}", "-", "[", "'_id'", "]", "keys", "=", "keys", ".", "sort_by", "{", "|", "s", "|", "s", ".", "length", "-", "1", "}", "process_operations", "(", "keys", ",", "operations", ",", "processed", ")", "end" ]
Takes the provided selector and atomic operations and replaces the indexes of the embedded documents with the positional operator when needed. @note The only time we can accurately know when to use the positional operator is at the exact time we are going to persist something. So we can tell by the selector that we are sending if it is actually possible to use the positional operator at all. For example, if the selector is: { "_id" => 1 }, then we could not use the positional operator for updating embedded documents since there would never be a match - we base whether we can based on the number of levels deep the selector goes, and if the id values are not nil. @example Process the operations. positionally( { "_id" => 1, "addresses._id" => 2 }, { "$set" => { "addresses.0.street" => "hobrecht" }} ) @param [ Hash ] selector The selector. @param [ Hash ] operations The update operations. @param [ Hash ] processed The processed update operations. @return [ Hash ] The new operations. @since 3.1.0
[ "Takes", "the", "provided", "selector", "and", "atomic", "operations", "and", "replaces", "the", "indexes", "of", "the", "embedded", "documents", "with", "the", "positional", "operator", "when", "needed", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/positional.rb#L37-L44
12,240
mongodb/mongoid
lib/mongoid/touchable.rb
Mongoid.Touchable.define_touchable!
def define_touchable!(association) name = association.name method_name = define_relation_touch_method(name, association) association.inverse_class.tap do |klass| klass.after_save method_name klass.after_destroy method_name klass.after_touch method_name end end
ruby
def define_touchable!(association) name = association.name method_name = define_relation_touch_method(name, association) association.inverse_class.tap do |klass| klass.after_save method_name klass.after_destroy method_name klass.after_touch method_name end end
[ "def", "define_touchable!", "(", "association", ")", "name", "=", "association", ".", "name", "method_name", "=", "define_relation_touch_method", "(", "name", ",", "association", ")", "association", ".", "inverse_class", ".", "tap", "do", "|", "klass", "|", "klass", ".", "after_save", "method_name", "klass", ".", "after_destroy", "method_name", "klass", ".", "after_touch", "method_name", "end", "end" ]
Add the association to the touchable associations if the touch option was provided. @example Add the touchable. Model.define_touchable!(assoc) @param [ Association ] association The association metadata. @return [ Class ] The model class. @since 3.0.0
[ "Add", "the", "association", "to", "the", "touchable", "associations", "if", "the", "touch", "option", "was", "provided", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/touchable.rb#L55-L63
12,241
mongodb/mongoid
lib/mongoid/loggable.rb
Mongoid.Loggable.default_logger
def default_logger logger = Logger.new($stdout) logger.level = Mongoid::Config.log_level logger end
ruby
def default_logger logger = Logger.new($stdout) logger.level = Mongoid::Config.log_level logger end
[ "def", "default_logger", "logger", "=", "Logger", ".", "new", "(", "$stdout", ")", "logger", ".", "level", "=", "Mongoid", "::", "Config", ".", "log_level", "logger", "end" ]
Gets the default Mongoid logger - stdout. @api private @example Get the default logger. Loggable.default_logger @return [ Logger ] The default logger. @since 3.0.0
[ "Gets", "the", "default", "Mongoid", "logger", "-", "stdout", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/loggable.rb#L50-L54
12,242
mongodb/mongoid
lib/mongoid/copyable.rb
Mongoid.Copyable.process_localized_attributes
def process_localized_attributes(klass, attrs) klass.localized_fields.keys.each do |name| if value = attrs.delete(name) attrs["#{name}_translations"] = value end end klass.embedded_relations.each do |_, association| next unless attrs.present? && attrs[association.key].present? if association.is_a?(Association::Embedded::EmbedsMany) attrs[association.key].each do |attr| embedded_klass = attr.fetch('_type', association.class_name).constantize process_localized_attributes(embedded_klass, attr) end else process_localized_attributes(association.klass, attrs[association.key]) end end end
ruby
def process_localized_attributes(klass, attrs) klass.localized_fields.keys.each do |name| if value = attrs.delete(name) attrs["#{name}_translations"] = value end end klass.embedded_relations.each do |_, association| next unless attrs.present? && attrs[association.key].present? if association.is_a?(Association::Embedded::EmbedsMany) attrs[association.key].each do |attr| embedded_klass = attr.fetch('_type', association.class_name).constantize process_localized_attributes(embedded_klass, attr) end else process_localized_attributes(association.klass, attrs[association.key]) end end end
[ "def", "process_localized_attributes", "(", "klass", ",", "attrs", ")", "klass", ".", "localized_fields", ".", "keys", ".", "each", "do", "|", "name", "|", "if", "value", "=", "attrs", ".", "delete", "(", "name", ")", "attrs", "[", "\"#{name}_translations\"", "]", "=", "value", "end", "end", "klass", ".", "embedded_relations", ".", "each", "do", "|", "_", ",", "association", "|", "next", "unless", "attrs", ".", "present?", "&&", "attrs", "[", "association", ".", "key", "]", ".", "present?", "if", "association", ".", "is_a?", "(", "Association", "::", "Embedded", "::", "EmbedsMany", ")", "attrs", "[", "association", ".", "key", "]", ".", "each", "do", "|", "attr", "|", "embedded_klass", "=", "attr", ".", "fetch", "(", "'_type'", ",", "association", ".", "class_name", ")", ".", "constantize", "process_localized_attributes", "(", "embedded_klass", ",", "attr", ")", "end", "else", "process_localized_attributes", "(", "association", ".", "klass", ",", "attrs", "[", "association", ".", "key", "]", ")", "end", "end", "end" ]
When cloning, if the document has localized fields we need to ensure they are properly processed in the clone. @api private @example Process localized attributes. model.process_localized_attributes(attributes) @param [ Hash ] attrs The attributes. @since 3.0.20
[ "When", "cloning", "if", "the", "document", "has", "localized", "fields", "we", "need", "to", "ensure", "they", "are", "properly", "processed", "in", "the", "clone", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/copyable.rb#L67-L85
12,243
mongodb/mongoid
lib/mongoid/shardable.rb
Mongoid.Shardable.shard_key_selector
def shard_key_selector selector = {} shard_key_fields.each do |field| selector[field.to_s] = new_record? ? send(field) : attribute_was(field) end selector end
ruby
def shard_key_selector selector = {} shard_key_fields.each do |field| selector[field.to_s] = new_record? ? send(field) : attribute_was(field) end selector end
[ "def", "shard_key_selector", "selector", "=", "{", "}", "shard_key_fields", ".", "each", "do", "|", "field", "|", "selector", "[", "field", ".", "to_s", "]", "=", "new_record?", "?", "send", "(", "field", ")", ":", "attribute_was", "(", "field", ")", "end", "selector", "end" ]
Get the document selector with the defined shard keys. @example Get the selector for the shard keys. person.shard_key_selector @return [ Hash ] The shard key selector. @since 2.0.0
[ "Get", "the", "document", "selector", "with", "the", "defined", "shard", "keys", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/shardable.rb#L38-L44
12,244
mongodb/mongoid
lib/mongoid/reloadable.rb
Mongoid.Reloadable.reload
def reload reloaded = _reload if Mongoid.raise_not_found_error && reloaded.empty? raise Errors::DocumentNotFound.new(self.class, _id, _id) end @attributes = reloaded @attributes_before_type_cast = {} changed_attributes.clear reset_readonly apply_defaults reload_relations run_callbacks(:find) unless _find_callbacks.empty? run_callbacks(:initialize) unless _initialize_callbacks.empty? self end
ruby
def reload reloaded = _reload if Mongoid.raise_not_found_error && reloaded.empty? raise Errors::DocumentNotFound.new(self.class, _id, _id) end @attributes = reloaded @attributes_before_type_cast = {} changed_attributes.clear reset_readonly apply_defaults reload_relations run_callbacks(:find) unless _find_callbacks.empty? run_callbacks(:initialize) unless _initialize_callbacks.empty? self end
[ "def", "reload", "reloaded", "=", "_reload", "if", "Mongoid", ".", "raise_not_found_error", "&&", "reloaded", ".", "empty?", "raise", "Errors", "::", "DocumentNotFound", ".", "new", "(", "self", ".", "class", ",", "_id", ",", "_id", ")", "end", "@attributes", "=", "reloaded", "@attributes_before_type_cast", "=", "{", "}", "changed_attributes", ".", "clear", "reset_readonly", "apply_defaults", "reload_relations", "run_callbacks", "(", ":find", ")", "unless", "_find_callbacks", ".", "empty?", "run_callbacks", "(", ":initialize", ")", "unless", "_initialize_callbacks", ".", "empty?", "self", "end" ]
Reloads the +Document+ attributes from the database. If the document has not been saved then an error will get raised if the configuration option was set. This can reload root documents or embedded documents. @example Reload the document. person.reload @raise [ Errors::DocumentNotFound ] If the document was deleted. @return [ Document ] The document, reloaded. @since 1.0.0
[ "Reloads", "the", "+", "Document", "+", "attributes", "from", "the", "database", ".", "If", "the", "document", "has", "not", "been", "saved", "then", "an", "error", "will", "get", "raised", "if", "the", "configuration", "option", "was", "set", ".", "This", "can", "reload", "root", "documents", "or", "embedded", "documents", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L22-L36
12,245
mongodb/mongoid
lib/mongoid/reloadable.rb
Mongoid.Reloadable.reload_root_document
def reload_root_document {}.merge(collection.find({ _id: _id }, session: _session).read(mode: :primary).first || {}) end
ruby
def reload_root_document {}.merge(collection.find({ _id: _id }, session: _session).read(mode: :primary).first || {}) end
[ "def", "reload_root_document", "{", "}", ".", "merge", "(", "collection", ".", "find", "(", "{", "_id", ":", "_id", "}", ",", "session", ":", "_session", ")", ".", "read", "(", "mode", ":", ":primary", ")", ".", "first", "||", "{", "}", ")", "end" ]
Reload the root document. @example Reload the document. document.reload_root_document @return [ Hash ] The reloaded attributes. @since 2.3.2
[ "Reload", "the", "root", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L61-L63
12,246
mongodb/mongoid
lib/mongoid/reloadable.rb
Mongoid.Reloadable.reload_embedded_document
def reload_embedded_document extract_embedded_attributes({}.merge( collection(_root).find(_id: _root._id).read(mode: :primary).first )) end
ruby
def reload_embedded_document extract_embedded_attributes({}.merge( collection(_root).find(_id: _root._id).read(mode: :primary).first )) end
[ "def", "reload_embedded_document", "extract_embedded_attributes", "(", "{", "}", ".", "merge", "(", "collection", "(", "_root", ")", ".", "find", "(", "_id", ":", "_root", ".", "_id", ")", ".", "read", "(", "mode", ":", ":primary", ")", ".", "first", ")", ")", "end" ]
Reload the embedded document. @example Reload the document. document.reload_embedded_document @return [ Hash ] The reloaded attributes. @since 2.3.2
[ "Reload", "the", "embedded", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L73-L77
12,247
mongodb/mongoid
lib/mongoid/reloadable.rb
Mongoid.Reloadable.extract_embedded_attributes
def extract_embedded_attributes(attributes) atomic_position.split(".").inject(attributes) do |attrs, part| attrs = attrs[part =~ /\d/ ? part.to_i : part] attrs end end
ruby
def extract_embedded_attributes(attributes) atomic_position.split(".").inject(attributes) do |attrs, part| attrs = attrs[part =~ /\d/ ? part.to_i : part] attrs end end
[ "def", "extract_embedded_attributes", "(", "attributes", ")", "atomic_position", ".", "split", "(", "\".\"", ")", ".", "inject", "(", "attributes", ")", "do", "|", "attrs", ",", "part", "|", "attrs", "=", "attrs", "[", "part", "=~", "/", "\\d", "/", "?", "part", ".", "to_i", ":", "part", "]", "attrs", "end", "end" ]
Extract only the desired embedded document from the attributes. @example Extract the embedded document. document.extract_embedded_attributes(attributes) @param [ Hash ] attributes The document in the db. @return [ Hash ] The document's extracted attributes. @since 2.3.2
[ "Extract", "only", "the", "desired", "embedded", "document", "from", "the", "attributes", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/reloadable.rb#L89-L94
12,248
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.attribute_present?
def attribute_present?(name) attribute = read_raw_attribute(name) !attribute.blank? || attribute == false rescue ActiveModel::MissingAttributeError false end
ruby
def attribute_present?(name) attribute = read_raw_attribute(name) !attribute.blank? || attribute == false rescue ActiveModel::MissingAttributeError false end
[ "def", "attribute_present?", "(", "name", ")", "attribute", "=", "read_raw_attribute", "(", "name", ")", "!", "attribute", ".", "blank?", "||", "attribute", "==", "false", "rescue", "ActiveModel", "::", "MissingAttributeError", "false", "end" ]
Determine if an attribute is present. @example Is the attribute present? person.attribute_present?("title") @param [ String, Symbol ] name The name of the attribute. @return [ true, false ] True if present, false if not. @since 1.0.0
[ "Determine", "if", "an", "attribute", "is", "present", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L32-L37
12,249
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.read_attribute
def read_attribute(name) field = fields[name.to_s] raw = read_raw_attribute(name) field ? field.demongoize(raw) : raw end
ruby
def read_attribute(name) field = fields[name.to_s] raw = read_raw_attribute(name) field ? field.demongoize(raw) : raw end
[ "def", "read_attribute", "(", "name", ")", "field", "=", "fields", "[", "name", ".", "to_s", "]", "raw", "=", "read_raw_attribute", "(", "name", ")", "field", "?", "field", ".", "demongoize", "(", "raw", ")", ":", "raw", "end" ]
Read a value from the document attributes. If the value does not exist it will return nil. @example Read an attribute. person.read_attribute(:title) @example Read an attribute (alternate syntax.) person[:title] @param [ String, Symbol ] name The name of the attribute to get. @return [ Object ] The value of the attribute. @since 1.0.0
[ "Read", "a", "value", "from", "the", "document", "attributes", ".", "If", "the", "value", "does", "not", "exist", "it", "will", "return", "nil", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L95-L99
12,250
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.read_attribute_before_type_cast
def read_attribute_before_type_cast(name) attr = name.to_s if attributes_before_type_cast.key?(attr) attributes_before_type_cast[attr] else read_raw_attribute(attr) end end
ruby
def read_attribute_before_type_cast(name) attr = name.to_s if attributes_before_type_cast.key?(attr) attributes_before_type_cast[attr] else read_raw_attribute(attr) end end
[ "def", "read_attribute_before_type_cast", "(", "name", ")", "attr", "=", "name", ".", "to_s", "if", "attributes_before_type_cast", ".", "key?", "(", "attr", ")", "attributes_before_type_cast", "[", "attr", "]", "else", "read_raw_attribute", "(", "attr", ")", "end", "end" ]
Read a value from the attributes before type cast. If the value has not yet been assigned then this will return the attribute's existing value using read_raw_attribute. @example Read an attribute before type cast. person.read_attribute_before_type_cast(:price) @param [ String, Symbol ] name The name of the attribute to get. @return [ Object ] The value of the attribute before type cast, if available. Otherwise, the value of the attribute. @since 3.1.0
[ "Read", "a", "value", "from", "the", "attributes", "before", "type", "cast", ".", "If", "the", "value", "has", "not", "yet", "been", "assigned", "then", "this", "will", "return", "the", "attribute", "s", "existing", "value", "using", "read_raw_attribute", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L115-L122
12,251
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.remove_attribute
def remove_attribute(name) as_writable_attribute!(name) do |access| _assigning do attribute_will_change!(access) delayed_atomic_unsets[atomic_attribute_name(access)] = [] unless new_record? attributes.delete(access) end end end
ruby
def remove_attribute(name) as_writable_attribute!(name) do |access| _assigning do attribute_will_change!(access) delayed_atomic_unsets[atomic_attribute_name(access)] = [] unless new_record? attributes.delete(access) end end end
[ "def", "remove_attribute", "(", "name", ")", "as_writable_attribute!", "(", "name", ")", "do", "|", "access", "|", "_assigning", "do", "attribute_will_change!", "(", "access", ")", "delayed_atomic_unsets", "[", "atomic_attribute_name", "(", "access", ")", "]", "=", "[", "]", "unless", "new_record?", "attributes", ".", "delete", "(", "access", ")", "end", "end", "end" ]
Remove a value from the +Document+ attributes. If the value does not exist it will fail gracefully. @example Remove the attribute. person.remove_attribute(:title) @param [ String, Symbol ] name The name of the attribute to remove. @raise [ Errors::ReadonlyAttribute ] If the field cannot be removed due to being flagged as reaodnly. @since 1.0.0
[ "Remove", "a", "value", "from", "the", "+", "Document", "+", "attributes", ".", "If", "the", "value", "does", "not", "exist", "it", "will", "fail", "gracefully", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L136-L144
12,252
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.write_attribute
def write_attribute(name, value) access = database_field_name(name) if attribute_writable?(access) _assigning do validate_attribute_value(access, value) localized = fields[access].try(:localized?) attributes_before_type_cast[name.to_s] = value typed_value = typed_value_for(access, value) unless attributes[access] == typed_value || attribute_changed?(access) attribute_will_change!(access) end if localized attributes[access] ||= {} attributes[access].merge!(typed_value) else attributes[access] = typed_value end typed_value end end end
ruby
def write_attribute(name, value) access = database_field_name(name) if attribute_writable?(access) _assigning do validate_attribute_value(access, value) localized = fields[access].try(:localized?) attributes_before_type_cast[name.to_s] = value typed_value = typed_value_for(access, value) unless attributes[access] == typed_value || attribute_changed?(access) attribute_will_change!(access) end if localized attributes[access] ||= {} attributes[access].merge!(typed_value) else attributes[access] = typed_value end typed_value end end end
[ "def", "write_attribute", "(", "name", ",", "value", ")", "access", "=", "database_field_name", "(", "name", ")", "if", "attribute_writable?", "(", "access", ")", "_assigning", "do", "validate_attribute_value", "(", "access", ",", "value", ")", "localized", "=", "fields", "[", "access", "]", ".", "try", "(", ":localized?", ")", "attributes_before_type_cast", "[", "name", ".", "to_s", "]", "=", "value", "typed_value", "=", "typed_value_for", "(", "access", ",", "value", ")", "unless", "attributes", "[", "access", "]", "==", "typed_value", "||", "attribute_changed?", "(", "access", ")", "attribute_will_change!", "(", "access", ")", "end", "if", "localized", "attributes", "[", "access", "]", "||=", "{", "}", "attributes", "[", "access", "]", ".", "merge!", "(", "typed_value", ")", "else", "attributes", "[", "access", "]", "=", "typed_value", "end", "typed_value", "end", "end", "end" ]
Write a single attribute to the document attribute hash. This will also fire the before and after update callbacks, and perform any necessary typecasting. @example Write the attribute. person.write_attribute(:title, "Mr.") @example Write the attribute (alternate syntax.) person[:title] = "Mr." @param [ String, Symbol ] name The name of the attribute to update. @param [ Object ] value The value to set for the attribute. @since 1.0.0
[ "Write", "a", "single", "attribute", "to", "the", "document", "attribute", "hash", ".", "This", "will", "also", "fire", "the", "before", "and", "after", "update", "callbacks", "and", "perform", "any", "necessary", "typecasting", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L160-L180
12,253
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.attribute_missing?
def attribute_missing?(name) selection = __selected_fields return false unless selection field = fields[name] (selection.values.first == 0 && selection_excluded?(name, selection, field)) || (selection.values.first == 1 && !selection_included?(name, selection, field)) end
ruby
def attribute_missing?(name) selection = __selected_fields return false unless selection field = fields[name] (selection.values.first == 0 && selection_excluded?(name, selection, field)) || (selection.values.first == 1 && !selection_included?(name, selection, field)) end
[ "def", "attribute_missing?", "(", "name", ")", "selection", "=", "__selected_fields", "return", "false", "unless", "selection", "field", "=", "fields", "[", "name", "]", "(", "selection", ".", "values", ".", "first", "==", "0", "&&", "selection_excluded?", "(", "name", ",", "selection", ",", "field", ")", ")", "||", "(", "selection", ".", "values", ".", "first", "==", "1", "&&", "!", "selection_included?", "(", "name", ",", "selection", ",", "field", ")", ")", "end" ]
Determine if the attribute is missing from the document, due to loading it from the database with missing fields. @example Is the attribute missing? document.attribute_missing?("test") @param [ String ] name The name of the attribute. @return [ true, false ] If the attribute is missing. @since 4.0.0
[ "Determine", "if", "the", "attribute", "is", "missing", "from", "the", "document", "due", "to", "loading", "it", "from", "the", "database", "with", "missing", "fields", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L232-L238
12,254
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.typed_value_for
def typed_value_for(key, value) fields.key?(key) ? fields[key].mongoize(value) : value.mongoize end
ruby
def typed_value_for(key, value) fields.key?(key) ? fields[key].mongoize(value) : value.mongoize end
[ "def", "typed_value_for", "(", "key", ",", "value", ")", "fields", ".", "key?", "(", "key", ")", "?", "fields", "[", "key", "]", ".", "mongoize", "(", "value", ")", ":", "value", ".", "mongoize", "end" ]
Return the typecasted value for a field. @example Get the value typecasted. person.typed_value_for(:title, :sir) @param [ String, Symbol ] key The field name. @param [ Object ] value The uncast value. @return [ Object ] The cast value. @since 1.0.0
[ "Return", "the", "typecasted", "value", "for", "a", "field", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L287-L289
12,255
mongodb/mongoid
lib/mongoid/attributes.rb
Mongoid.Attributes.validate_attribute_value
def validate_attribute_value(access, value) return unless fields[access] && value validatable_types = [ Hash, Array ] if validatable_types.include? fields[access].type unless value.is_a? fields[access].type raise Mongoid::Errors::InvalidValue.new(fields[access].type, value.class) end end end
ruby
def validate_attribute_value(access, value) return unless fields[access] && value validatable_types = [ Hash, Array ] if validatable_types.include? fields[access].type unless value.is_a? fields[access].type raise Mongoid::Errors::InvalidValue.new(fields[access].type, value.class) end end end
[ "def", "validate_attribute_value", "(", "access", ",", "value", ")", "return", "unless", "fields", "[", "access", "]", "&&", "value", "validatable_types", "=", "[", "Hash", ",", "Array", "]", "if", "validatable_types", ".", "include?", "fields", "[", "access", "]", ".", "type", "unless", "value", ".", "is_a?", "fields", "[", "access", "]", ".", "type", "raise", "Mongoid", "::", "Errors", "::", "InvalidValue", ".", "new", "(", "fields", "[", "access", "]", ".", "type", ",", "value", ".", "class", ")", "end", "end", "end" ]
Validates an attribute value. This provides validation checking if the value is valid for given a field. For now, only Hash and Array fields are validated. @param [ String, Symbol ] access The name of the attribute to validate. @param [ Object ] value The to be validated. @since 3.0.10
[ "Validates", "an", "attribute", "value", ".", "This", "provides", "validation", "checking", "if", "the", "value", "is", "valid", "for", "given", "a", "field", ".", "For", "now", "only", "Hash", "and", "Array", "fields", "are", "validated", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L349-L357
12,256
mongodb/mongoid
lib/mongoid/factory.rb
Mongoid.Factory.build
def build(klass, attributes = nil) attributes ||= {} type = attributes[TYPE] || attributes[TYPE.to_sym] if type && klass._types.include?(type) type.constantize.new(attributes) else klass.new(attributes) end end
ruby
def build(klass, attributes = nil) attributes ||= {} type = attributes[TYPE] || attributes[TYPE.to_sym] if type && klass._types.include?(type) type.constantize.new(attributes) else klass.new(attributes) end end
[ "def", "build", "(", "klass", ",", "attributes", "=", "nil", ")", "attributes", "||=", "{", "}", "type", "=", "attributes", "[", "TYPE", "]", "||", "attributes", "[", "TYPE", ".", "to_sym", "]", "if", "type", "&&", "klass", ".", "_types", ".", "include?", "(", "type", ")", "type", ".", "constantize", ".", "new", "(", "attributes", ")", "else", "klass", ".", "new", "(", "attributes", ")", "end", "end" ]
Builds a new +Document+ from the supplied attributes. @example Build the document. Mongoid::Factory.build(Person, { "name" => "Durran" }) @param [ Class ] klass The class to instantiate from if _type is not present. @param [ Hash ] attributes The document attributes. @return [ Document ] The instantiated document.
[ "Builds", "a", "new", "+", "Document", "+", "from", "the", "supplied", "attributes", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/factory.rb#L20-L28
12,257
mongodb/mongoid
lib/mongoid/factory.rb
Mongoid.Factory.from_db
def from_db(klass, attributes = nil, criteria = nil, selected_fields = nil) if criteria selected_fields ||= criteria.options[:fields] end type = (attributes || {})[TYPE] if type.blank? obj = klass.instantiate(attributes, selected_fields) if criteria && criteria.association && criteria.parent_document obj.set_relation(criteria.association.inverse, criteria.parent_document) end obj else camelized = type.camelize # Check if the class exists begin constantized = camelized.constantize rescue NameError raise Errors::UnknownModel.new(camelized, type) end # Check if the class is a Document class if !constantized.respond_to?(:instantiate) raise Errors::UnknownModel.new(camelized, type) end constantized.instantiate(attributes, selected_fields) end end
ruby
def from_db(klass, attributes = nil, criteria = nil, selected_fields = nil) if criteria selected_fields ||= criteria.options[:fields] end type = (attributes || {})[TYPE] if type.blank? obj = klass.instantiate(attributes, selected_fields) if criteria && criteria.association && criteria.parent_document obj.set_relation(criteria.association.inverse, criteria.parent_document) end obj else camelized = type.camelize # Check if the class exists begin constantized = camelized.constantize rescue NameError raise Errors::UnknownModel.new(camelized, type) end # Check if the class is a Document class if !constantized.respond_to?(:instantiate) raise Errors::UnknownModel.new(camelized, type) end constantized.instantiate(attributes, selected_fields) end end
[ "def", "from_db", "(", "klass", ",", "attributes", "=", "nil", ",", "criteria", "=", "nil", ",", "selected_fields", "=", "nil", ")", "if", "criteria", "selected_fields", "||=", "criteria", ".", "options", "[", ":fields", "]", "end", "type", "=", "(", "attributes", "||", "{", "}", ")", "[", "TYPE", "]", "if", "type", ".", "blank?", "obj", "=", "klass", ".", "instantiate", "(", "attributes", ",", "selected_fields", ")", "if", "criteria", "&&", "criteria", ".", "association", "&&", "criteria", ".", "parent_document", "obj", ".", "set_relation", "(", "criteria", ".", "association", ".", "inverse", ",", "criteria", ".", "parent_document", ")", "end", "obj", "else", "camelized", "=", "type", ".", "camelize", "# Check if the class exists", "begin", "constantized", "=", "camelized", ".", "constantize", "rescue", "NameError", "raise", "Errors", "::", "UnknownModel", ".", "new", "(", "camelized", ",", "type", ")", "end", "# Check if the class is a Document class", "if", "!", "constantized", ".", "respond_to?", "(", ":instantiate", ")", "raise", "Errors", "::", "UnknownModel", ".", "new", "(", "camelized", ",", "type", ")", "end", "constantized", ".", "instantiate", "(", "attributes", ",", "selected_fields", ")", "end", "end" ]
Builds a new +Document+ from the supplied attributes loaded from the database. If a criteria object is given, it is used in two ways: 1. If the criteria has a list of fields specified via #only, only those fields are populated in the returned document. 2. If the criteria has a referencing association (i.e., this document is being instantiated as an association of another document), the other document is also populated in the returned document's reverse association, if one exists. @example Build the document. Mongoid::Factory.from_db(Person, { "name" => "Durran" }) @param [ Class ] klass The class to instantiate from if _type is not present. @param [ Hash ] attributes The document attributes. @param [ Criteria ] criteria Optional criteria object. @param [ Hash ] selected_fields Fields which were retrieved via #only. If selected_fields are specified, fields not listed in it will not be accessible in the returned document. @return [ Document ] The instantiated document.
[ "Builds", "a", "new", "+", "Document", "+", "from", "the", "supplied", "attributes", "loaded", "from", "the", "database", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/factory.rb#L52-L80
12,258
mongodb/mongoid
lib/mongoid/atomic.rb
Mongoid.Atomic.add_atomic_pull
def add_atomic_pull(document) document.flagged_for_destroy = true (delayed_atomic_pulls[document.association_name.to_s] ||= []).push(document) end
ruby
def add_atomic_pull(document) document.flagged_for_destroy = true (delayed_atomic_pulls[document.association_name.to_s] ||= []).push(document) end
[ "def", "add_atomic_pull", "(", "document", ")", "document", ".", "flagged_for_destroy", "=", "true", "(", "delayed_atomic_pulls", "[", "document", ".", "association_name", ".", "to_s", "]", "||=", "[", "]", ")", ".", "push", "(", "document", ")", "end" ]
Add the document as an atomic pull. @example Add the atomic pull. person.add_atomic_pull(address) @param [ Document ] document The embedded document to pull. @since 2.2.0
[ "Add", "the", "document", "as", "an", "atomic", "pull", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L38-L41
12,259
mongodb/mongoid
lib/mongoid/atomic.rb
Mongoid.Atomic.add_atomic_unset
def add_atomic_unset(document) document.flagged_for_destroy = true (delayed_atomic_unsets[document.association_name.to_s] ||= []).push(document) end
ruby
def add_atomic_unset(document) document.flagged_for_destroy = true (delayed_atomic_unsets[document.association_name.to_s] ||= []).push(document) end
[ "def", "add_atomic_unset", "(", "document", ")", "document", ".", "flagged_for_destroy", "=", "true", "(", "delayed_atomic_unsets", "[", "document", ".", "association_name", ".", "to_s", "]", "||=", "[", "]", ")", ".", "push", "(", "document", ")", "end" ]
Add an atomic unset for the document. @example Add an atomic unset. document.add_atomic_unset(doc) @param [ Document ] document The child document. @return [ Array<Document> ] The children. @since 3.0.0
[ "Add", "an", "atomic", "unset", "for", "the", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L53-L56
12,260
mongodb/mongoid
lib/mongoid/atomic.rb
Mongoid.Atomic.atomic_updates
def atomic_updates(_use_indexes = false) process_flagged_destroys mods = Modifiers.new generate_atomic_updates(mods, self) _children.each do |child| child.process_flagged_destroys generate_atomic_updates(mods, child) end mods end
ruby
def atomic_updates(_use_indexes = false) process_flagged_destroys mods = Modifiers.new generate_atomic_updates(mods, self) _children.each do |child| child.process_flagged_destroys generate_atomic_updates(mods, child) end mods end
[ "def", "atomic_updates", "(", "_use_indexes", "=", "false", ")", "process_flagged_destroys", "mods", "=", "Modifiers", ".", "new", "generate_atomic_updates", "(", "mods", ",", "self", ")", "_children", ".", "each", "do", "|", "child", "|", "child", ".", "process_flagged_destroys", "generate_atomic_updates", "(", "mods", ",", "child", ")", "end", "mods", "end" ]
Get all the atomic updates that need to happen for the current +Document+. This includes all changes that need to happen in the entire hierarchy that exists below where the save call was made. @note MongoDB does not allow "conflicting modifications" to be performed in a single operation. Conflicting modifications are detected by the 'haveConflictingMod' function in MongoDB. Examination of the code suggests that two modifications (a $set and a $push with $each, for example) conflict if: (1) the key paths being modified are equal. (2) one key path is a prefix of the other. So a $set of 'addresses.0.street' will conflict with a $push and $each to 'addresses', and we will need to split our update into two pieces. We do not, however, attempt to match MongoDB's logic exactly. Instead, we assume that two updates conflict if the first component of the two key paths matches. @example Get the updates that need to occur. person.atomic_updates(children) @return [ Hash ] The updates and their modifiers. @since 2.1.0
[ "Get", "all", "the", "atomic", "updates", "that", "need", "to", "happen", "for", "the", "current", "+", "Document", "+", ".", "This", "includes", "all", "changes", "that", "need", "to", "happen", "in", "the", "entire", "hierarchy", "that", "exists", "below", "where", "the", "save", "call", "was", "made", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L129-L138
12,261
mongodb/mongoid
lib/mongoid/atomic.rb
Mongoid.Atomic.atomic_pulls
def atomic_pulls pulls = {} delayed_atomic_pulls.each_pair do |_, docs| path = nil ids = docs.map do |doc| path ||= doc.flag_as_destroyed doc._id end pulls[path] = { "_id" => { "$in" => ids }} and path = nil end pulls end
ruby
def atomic_pulls pulls = {} delayed_atomic_pulls.each_pair do |_, docs| path = nil ids = docs.map do |doc| path ||= doc.flag_as_destroyed doc._id end pulls[path] = { "_id" => { "$in" => ids }} and path = nil end pulls end
[ "def", "atomic_pulls", "pulls", "=", "{", "}", "delayed_atomic_pulls", ".", "each_pair", "do", "|", "_", ",", "docs", "|", "path", "=", "nil", "ids", "=", "docs", ".", "map", "do", "|", "doc", "|", "path", "||=", "doc", ".", "flag_as_destroyed", "doc", ".", "_id", "end", "pulls", "[", "path", "]", "=", "{", "\"_id\"", "=>", "{", "\"$in\"", "=>", "ids", "}", "}", "and", "path", "=", "nil", "end", "pulls", "end" ]
Get all the attributes that need to be pulled. @example Get the pulls. person.atomic_pulls @return [ Array<Hash> ] The $pullAll operations. @since 2.2.0
[ "Get", "all", "the", "attributes", "that", "need", "to", "be", "pulled", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L204-L215
12,262
mongodb/mongoid
lib/mongoid/atomic.rb
Mongoid.Atomic.atomic_unsets
def atomic_unsets unsets = [] delayed_atomic_unsets.each_pair do |name, docs| path = nil docs.each do |doc| path ||= doc.flag_as_destroyed end unsets.push(path || name) end unsets end
ruby
def atomic_unsets unsets = [] delayed_atomic_unsets.each_pair do |name, docs| path = nil docs.each do |doc| path ||= doc.flag_as_destroyed end unsets.push(path || name) end unsets end
[ "def", "atomic_unsets", "unsets", "=", "[", "]", "delayed_atomic_unsets", ".", "each_pair", "do", "|", "name", ",", "docs", "|", "path", "=", "nil", "docs", ".", "each", "do", "|", "doc", "|", "path", "||=", "doc", ".", "flag_as_destroyed", "end", "unsets", ".", "push", "(", "path", "||", "name", ")", "end", "unsets", "end" ]
Get all the attributes that need to be unset. @example Get the unsets. person.atomic_unsets @return [ Array<Hash> ] The $unset operations. @since 2.2.0
[ "Get", "all", "the", "attributes", "that", "need", "to", "be", "unset", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L249-L259
12,263
mongodb/mongoid
lib/mongoid/atomic.rb
Mongoid.Atomic.generate_atomic_updates
def generate_atomic_updates(mods, doc) mods.unset(doc.atomic_unsets) mods.pull(doc.atomic_pulls) mods.set(doc.atomic_sets) mods.set(doc.delayed_atomic_sets) mods.push(doc.atomic_pushes) mods.push(doc.atomic_array_pushes) mods.add_to_set(doc.atomic_array_add_to_sets) mods.pull_all(doc.atomic_array_pulls) end
ruby
def generate_atomic_updates(mods, doc) mods.unset(doc.atomic_unsets) mods.pull(doc.atomic_pulls) mods.set(doc.atomic_sets) mods.set(doc.delayed_atomic_sets) mods.push(doc.atomic_pushes) mods.push(doc.atomic_array_pushes) mods.add_to_set(doc.atomic_array_add_to_sets) mods.pull_all(doc.atomic_array_pulls) end
[ "def", "generate_atomic_updates", "(", "mods", ",", "doc", ")", "mods", ".", "unset", "(", "doc", ".", "atomic_unsets", ")", "mods", ".", "pull", "(", "doc", ".", "atomic_pulls", ")", "mods", ".", "set", "(", "doc", ".", "atomic_sets", ")", "mods", ".", "set", "(", "doc", ".", "delayed_atomic_sets", ")", "mods", ".", "push", "(", "doc", ".", "atomic_pushes", ")", "mods", ".", "push", "(", "doc", ".", "atomic_array_pushes", ")", "mods", ".", "add_to_set", "(", "doc", ".", "atomic_array_add_to_sets", ")", "mods", ".", "pull_all", "(", "doc", ".", "atomic_array_pulls", ")", "end" ]
Generates the atomic updates in the correct order. @example Generate the updates. model.generate_atomic_updates(mods, doc) @param [ Modifiers ] mods The atomic modifications. @param [ Document ] doc The document to update for. @since 2.2.0
[ "Generates", "the", "atomic", "updates", "in", "the", "correct", "order", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/atomic.rb#L349-L358
12,264
mongodb/mongoid
lib/mongoid/persistence_context.rb
Mongoid.PersistenceContext.collection
def collection(parent = nil) parent ? parent.collection.with(client_options) : client[collection_name.to_sym] end
ruby
def collection(parent = nil) parent ? parent.collection.with(client_options) : client[collection_name.to_sym] end
[ "def", "collection", "(", "parent", "=", "nil", ")", "parent", "?", "parent", ".", "collection", ".", "with", "(", "client_options", ")", ":", "client", "[", "collection_name", ".", "to_sym", "]", "end" ]
Initialize the persistence context object. @example Create a new persistence context. PersistenceContext.new(model, collection: 'other') @param [ Object ] object The class or model instance for which a persistence context should be created. @param [ Hash ] opts The persistence context options. @since 6.0.0 Get the collection for this persistence context. @example Get the collection for this persistence context. context.collection @param [ Object ] parent The parent object whose collection name is used instead of this persistence context's collection name. @return [ Mongo::Collection ] The collection for this persistence context. @since 6.0.0
[ "Initialize", "the", "persistence", "context", "object", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistence_context.rb#L71-L73
12,265
mongodb/mongoid
lib/mongoid/persistence_context.rb
Mongoid.PersistenceContext.client
def client @client ||= (client = Clients.with_name(client_name) client = client.use(database_name) if database_name_option client.with(client_options)) end
ruby
def client @client ||= (client = Clients.with_name(client_name) client = client.use(database_name) if database_name_option client.with(client_options)) end
[ "def", "client", "@client", "||=", "(", "client", "=", "Clients", ".", "with_name", "(", "client_name", ")", "client", "=", "client", ".", "use", "(", "database_name", ")", "if", "database_name_option", "client", ".", "with", "(", "client_options", ")", ")", "end" ]
Get the client for this persistence context. @example Get the client for this persistence context. context.client @return [ Mongo::Client ] The client for this persistence context. @since 6.0.0
[ "Get", "the", "client", "for", "this", "persistence", "context", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistence_context.rb#L111-L115
12,266
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.changes
def changes _changes = {} changed.each do |attr| change = attribute_change(attr) _changes[attr] = change if change end _changes.with_indifferent_access end
ruby
def changes _changes = {} changed.each do |attr| change = attribute_change(attr) _changes[attr] = change if change end _changes.with_indifferent_access end
[ "def", "changes", "_changes", "=", "{", "}", "changed", ".", "each", "do", "|", "attr", "|", "change", "=", "attribute_change", "(", "attr", ")", "_changes", "[", "attr", "]", "=", "change", "if", "change", "end", "_changes", ".", "with_indifferent_access", "end" ]
Get all the changes for the document. @example Get all the changes. model.changes @return [ Hash<String, Array<Object, Object> ] The changes. @since 2.4.0
[ "Get", "all", "the", "changes", "for", "the", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L67-L74
12,267
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.move_changes
def move_changes @previous_changes = changes Atomic::UPDATES.each do |update| send(update).clear end changed_attributes.clear end
ruby
def move_changes @previous_changes = changes Atomic::UPDATES.each do |update| send(update).clear end changed_attributes.clear end
[ "def", "move_changes", "@previous_changes", "=", "changes", "Atomic", "::", "UPDATES", ".", "each", "do", "|", "update", "|", "send", "(", "update", ")", ".", "clear", "end", "changed_attributes", ".", "clear", "end" ]
Call this method after save, so the changes can be properly switched. This will unset the memoized children array, set new record to false, set the document as validated, and move the dirty changes. @example Move the changes to previous. person.move_changes @since 2.1.0
[ "Call", "this", "method", "after", "save", "so", "the", "changes", "can", "be", "properly", "switched", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L85-L91
12,268
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.attribute_change
def attribute_change(attr) attr = database_field_name(attr) [changed_attributes[attr], attributes[attr]] if attribute_changed?(attr) end
ruby
def attribute_change(attr) attr = database_field_name(attr) [changed_attributes[attr], attributes[attr]] if attribute_changed?(attr) end
[ "def", "attribute_change", "(", "attr", ")", "attr", "=", "database_field_name", "(", "attr", ")", "[", "changed_attributes", "[", "attr", "]", ",", "attributes", "[", "attr", "]", "]", "if", "attribute_changed?", "(", "attr", ")", "end" ]
Get the old and new value for the provided attribute. @example Get the attribute change. model.attribute_change("name") @param [ String ] attr The name of the attribute. @return [ Array<Object> ] The old and new values. @since 2.1.0
[ "Get", "the", "old", "and", "new", "value", "for", "the", "provided", "attribute", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L169-L172
12,269
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.attribute_changed?
def attribute_changed?(attr) attr = database_field_name(attr) return false unless changed_attributes.key?(attr) changed_attributes[attr] != attributes[attr] end
ruby
def attribute_changed?(attr) attr = database_field_name(attr) return false unless changed_attributes.key?(attr) changed_attributes[attr] != attributes[attr] end
[ "def", "attribute_changed?", "(", "attr", ")", "attr", "=", "database_field_name", "(", "attr", ")", "return", "false", "unless", "changed_attributes", ".", "key?", "(", "attr", ")", "changed_attributes", "[", "attr", "]", "!=", "attributes", "[", "attr", "]", "end" ]
Determine if a specific attribute has changed. @example Has the attribute changed? model.attribute_changed?("name") @param [ String ] attr The name of the attribute. @return [ true, false ] Whether the attribute has changed. @since 2.1.6
[ "Determine", "if", "a", "specific", "attribute", "has", "changed", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L184-L188
12,270
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.attribute_changed_from_default?
def attribute_changed_from_default?(attr) field = fields[attr] return false unless field attributes[attr] != field.eval_default(self) end
ruby
def attribute_changed_from_default?(attr) field = fields[attr] return false unless field attributes[attr] != field.eval_default(self) end
[ "def", "attribute_changed_from_default?", "(", "attr", ")", "field", "=", "fields", "[", "attr", "]", "return", "false", "unless", "field", "attributes", "[", "attr", "]", "!=", "field", ".", "eval_default", "(", "self", ")", "end" ]
Get whether or not the field has a different value from the default. @example Is the field different from the default? model.attribute_changed_from_default? @param [ String ] attr The name of the attribute. @return [ true, false ] If the attribute differs. @since 3.0.0
[ "Get", "whether", "or", "not", "the", "field", "has", "a", "different", "value", "from", "the", "default", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L200-L204
12,271
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.attribute_was
def attribute_was(attr) attr = database_field_name(attr) attribute_changed?(attr) ? changed_attributes[attr] : attributes[attr] end
ruby
def attribute_was(attr) attr = database_field_name(attr) attribute_changed?(attr) ? changed_attributes[attr] : attributes[attr] end
[ "def", "attribute_was", "(", "attr", ")", "attr", "=", "database_field_name", "(", "attr", ")", "attribute_changed?", "(", "attr", ")", "?", "changed_attributes", "[", "attr", "]", ":", "attributes", "[", "attr", "]", "end" ]
Get the previous value for the attribute. @example Get the previous value. model.attribute_was("name") @param [ String ] attr The attribute name. @since 2.4.0
[ "Get", "the", "previous", "value", "for", "the", "attribute", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L214-L217
12,272
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.attribute_will_change!
def attribute_will_change!(attr) unless changed_attributes.key?(attr) changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__ end end
ruby
def attribute_will_change!(attr) unless changed_attributes.key?(attr) changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__ end end
[ "def", "attribute_will_change!", "(", "attr", ")", "unless", "changed_attributes", ".", "key?", "(", "attr", ")", "changed_attributes", "[", "attr", "]", "=", "read_raw_attribute", "(", "attr", ")", ".", "__deep_copy__", "end", "end" ]
Flag an attribute as going to change. @example Flag the attribute. model.attribute_will_change!("name") @param [ String ] attr The name of the attribute. @return [ Object ] The old value. @since 2.3.0
[ "Flag", "an", "attribute", "as", "going", "to", "change", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L229-L233
12,273
mongodb/mongoid
lib/mongoid/changeable.rb
Mongoid.Changeable.reset_attribute!
def reset_attribute!(attr) attr = database_field_name(attr) attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr) end
ruby
def reset_attribute!(attr) attr = database_field_name(attr) attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr) end
[ "def", "reset_attribute!", "(", "attr", ")", "attr", "=", "database_field_name", "(", "attr", ")", "attributes", "[", "attr", "]", "=", "changed_attributes", ".", "delete", "(", "attr", ")", "if", "attribute_changed?", "(", "attr", ")", "end" ]
Set the attribute back to its old value. @example Reset the attribute. model.reset_attribute!("name") @param [ String ] attr The name of the attribute. @return [ Object ] The old value. @since 2.4.0
[ "Set", "the", "attribute", "back", "to", "its", "old", "value", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/changeable.rb#L245-L248
12,274
mongodb/mongoid
lib/rails/mongoid.rb
Rails.Mongoid.load_models
def load_models(app) app.config.paths["app/models"].expanded.each do |path| preload = ::Mongoid.preload_models if preload.resizable? files = preload.map { |model| "#{path}/#{model.underscore}.rb" } else files = Dir.glob("#{path}/**/*.rb") end files.sort.each do |file| load_model(file.gsub("#{path}/" , "").gsub(".rb", "")) end end end
ruby
def load_models(app) app.config.paths["app/models"].expanded.each do |path| preload = ::Mongoid.preload_models if preload.resizable? files = preload.map { |model| "#{path}/#{model.underscore}.rb" } else files = Dir.glob("#{path}/**/*.rb") end files.sort.each do |file| load_model(file.gsub("#{path}/" , "").gsub(".rb", "")) end end end
[ "def", "load_models", "(", "app", ")", "app", ".", "config", ".", "paths", "[", "\"app/models\"", "]", ".", "expanded", ".", "each", "do", "|", "path", "|", "preload", "=", "::", "Mongoid", ".", "preload_models", "if", "preload", ".", "resizable?", "files", "=", "preload", ".", "map", "{", "|", "model", "|", "\"#{path}/#{model.underscore}.rb\"", "}", "else", "files", "=", "Dir", ".", "glob", "(", "\"#{path}/**/*.rb\"", ")", "end", "files", ".", "sort", ".", "each", "do", "|", "file", "|", "load_model", "(", "file", ".", "gsub", "(", "\"#{path}/\"", ",", "\"\"", ")", ".", "gsub", "(", "\".rb\"", ",", "\"\"", ")", ")", "end", "end", "end" ]
Use the application configuration to get every model and require it, so that indexing and inheritance work in both development and production with the same results. @example Load all the application models. Rails::Mongoid.load_models(app) @param [ Application ] app The rails application.
[ "Use", "the", "application", "configuration", "to", "get", "every", "model", "and", "require", "it", "so", "that", "indexing", "and", "inheritance", "work", "in", "both", "development", "and", "production", "with", "the", "same", "results", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/rails/mongoid.rb#L15-L28
12,275
mongodb/mongoid
lib/rails/mongoid.rb
Rails.Mongoid.load_model
def load_model(file) begin require_dependency(file) rescue Exception => e Logger.new($stdout).warn(e.message) end end
ruby
def load_model(file) begin require_dependency(file) rescue Exception => e Logger.new($stdout).warn(e.message) end end
[ "def", "load_model", "(", "file", ")", "begin", "require_dependency", "(", "file", ")", "rescue", "Exception", "=>", "e", "Logger", ".", "new", "(", "$stdout", ")", ".", "warn", "(", "e", ".", "message", ")", "end", "end" ]
I don't want to mock out kernel for unit testing purposes, so added this method as a convenience. @example Load the model. Mongoid.load_model("/mongoid/behavior") @param [ String ] file The base filename. @since 2.0.0.rc.3
[ "I", "don", "t", "want", "to", "mock", "out", "kernel", "for", "unit", "testing", "purposes", "so", "added", "this", "method", "as", "a", "convenience", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/rails/mongoid.rb#L49-L55
12,276
mongodb/mongoid
lib/mongoid/fields.rb
Mongoid.Fields.apply_default
def apply_default(name) unless attributes.key?(name) if field = fields[name] default = field.eval_default(self) unless default.nil? || field.lazy? attribute_will_change!(name) attributes[name] = default end end end end
ruby
def apply_default(name) unless attributes.key?(name) if field = fields[name] default = field.eval_default(self) unless default.nil? || field.lazy? attribute_will_change!(name) attributes[name] = default end end end end
[ "def", "apply_default", "(", "name", ")", "unless", "attributes", ".", "key?", "(", "name", ")", "if", "field", "=", "fields", "[", "name", "]", "default", "=", "field", ".", "eval_default", "(", "self", ")", "unless", "default", ".", "nil?", "||", "field", ".", "lazy?", "attribute_will_change!", "(", "name", ")", "attributes", "[", "name", "]", "=", "default", "end", "end", "end", "end" ]
Applies a single default value for the given name. @example Apply a single default. model.apply_default("name") @param [ String ] name The name of the field. @since 2.4.0
[ "Applies", "a", "single", "default", "value", "for", "the", "given", "name", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/fields.rb#L101-L111
12,277
mongodb/mongoid
lib/mongoid/persistable.rb
Mongoid.Persistable.post_process_persist
def post_process_persist(result, options = {}) post_persist unless result == false errors.clear unless performing_validations?(options) true end
ruby
def post_process_persist(result, options = {}) post_persist unless result == false errors.clear unless performing_validations?(options) true end
[ "def", "post_process_persist", "(", "result", ",", "options", "=", "{", "}", ")", "post_persist", "unless", "result", "==", "false", "errors", ".", "clear", "unless", "performing_validations?", "(", "options", ")", "true", "end" ]
Post process the persistence operation. @api private @example Post process the persistence operation. document.post_process_persist(true) @param [ Object ] result The result of the operation. @param [ Hash ] options The options. @return [ true ] true. @since 4.0.0
[ "Post", "process", "the", "persistence", "operation", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistable.rb#L179-L183
12,278
mongodb/mongoid
lib/mongoid/persistable.rb
Mongoid.Persistable.process_atomic_operations
def process_atomic_operations(operations) operations.each do |field, value| access = database_field_name(field) yield(access, value) remove_change(access) unless executing_atomically? end end
ruby
def process_atomic_operations(operations) operations.each do |field, value| access = database_field_name(field) yield(access, value) remove_change(access) unless executing_atomically? end end
[ "def", "process_atomic_operations", "(", "operations", ")", "operations", ".", "each", "do", "|", "field", ",", "value", "|", "access", "=", "database_field_name", "(", "field", ")", "yield", "(", "access", ",", "value", ")", "remove_change", "(", "access", ")", "unless", "executing_atomically?", "end", "end" ]
Process the atomic operations - this handles the common behavior of iterating through each op, getting the aliased field name, and removing appropriate dirty changes. @api private @example Process the atomic operations. document.process_atomic_operations(pulls) do |field, value| ... end @param [ Hash ] operations The atomic operations. @return [ Hash ] The operations. @since 4.0.0
[ "Process", "the", "atomic", "operations", "-", "this", "handles", "the", "common", "behavior", "of", "iterating", "through", "each", "op", "getting", "the", "aliased", "field", "name", "and", "removing", "appropriate", "dirty", "changes", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistable.rb#L220-L226
12,279
mongodb/mongoid
lib/mongoid/persistable.rb
Mongoid.Persistable.persist_or_delay_atomic_operation
def persist_or_delay_atomic_operation(operation) if executing_atomically? operation.each do |(name, hash)| @atomic_context[name] ||= {} @atomic_context[name].merge!(hash) end else persist_atomic_operations(operation) end end
ruby
def persist_or_delay_atomic_operation(operation) if executing_atomically? operation.each do |(name, hash)| @atomic_context[name] ||= {} @atomic_context[name].merge!(hash) end else persist_atomic_operations(operation) end end
[ "def", "persist_or_delay_atomic_operation", "(", "operation", ")", "if", "executing_atomically?", "operation", ".", "each", "do", "|", "(", "name", ",", "hash", ")", "|", "@atomic_context", "[", "name", "]", "||=", "{", "}", "@atomic_context", "[", "name", "]", ".", "merge!", "(", "hash", ")", "end", "else", "persist_atomic_operations", "(", "operation", ")", "end", "end" ]
If we are in an atomically block, add the operations to the delayed group, otherwise persist immediately. @api private @example Persist immediately or delay the operations. document.persist_or_delay_atomic_operation(ops) @param [ Hash ] operation The operation. @since 4.0.0
[ "If", "we", "are", "in", "an", "atomically", "block", "add", "the", "operations", "to", "the", "delayed", "group", "otherwise", "persist", "immediately", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistable.rb#L299-L308
12,280
mongodb/mongoid
lib/mongoid/persistable.rb
Mongoid.Persistable.persist_atomic_operations
def persist_atomic_operations(operations) if persisted? && operations && !operations.empty? selector = atomic_selector _root.collection.find(selector).update_one(positionally(selector, operations), session: _session) end end
ruby
def persist_atomic_operations(operations) if persisted? && operations && !operations.empty? selector = atomic_selector _root.collection.find(selector).update_one(positionally(selector, operations), session: _session) end end
[ "def", "persist_atomic_operations", "(", "operations", ")", "if", "persisted?", "&&", "operations", "&&", "!", "operations", ".", "empty?", "selector", "=", "atomic_selector", "_root", ".", "collection", ".", "find", "(", "selector", ")", ".", "update_one", "(", "positionally", "(", "selector", ",", "operations", ")", ",", "session", ":", "_session", ")", "end", "end" ]
Persist the atomic operations. @api private @example Persist the atomic operations. persist_atomic_operations(ops) @param [ Hash ] operations The atomic operations. @since 4.0.0
[ "Persist", "the", "atomic", "operations", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/persistable.rb#L320-L325
12,281
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.serializable_hash
def serializable_hash(options = nil) options ||= {} attrs = {} names = field_names(options) method_names = Array.wrap(options[:methods]).map do |name| name.to_s if respond_to?(name) end.compact (names + method_names).each do |name| without_autobuild do serialize_attribute(attrs, name, names, options) end end serialize_relations(attrs, options) if options[:include] attrs end
ruby
def serializable_hash(options = nil) options ||= {} attrs = {} names = field_names(options) method_names = Array.wrap(options[:methods]).map do |name| name.to_s if respond_to?(name) end.compact (names + method_names).each do |name| without_autobuild do serialize_attribute(attrs, name, names, options) end end serialize_relations(attrs, options) if options[:include] attrs end
[ "def", "serializable_hash", "(", "options", "=", "nil", ")", "options", "||=", "{", "}", "attrs", "=", "{", "}", "names", "=", "field_names", "(", "options", ")", "method_names", "=", "Array", ".", "wrap", "(", "options", "[", ":methods", "]", ")", ".", "map", "do", "|", "name", "|", "name", ".", "to_s", "if", "respond_to?", "(", "name", ")", "end", ".", "compact", "(", "names", "+", "method_names", ")", ".", "each", "do", "|", "name", "|", "without_autobuild", "do", "serialize_attribute", "(", "attrs", ",", "name", ",", "names", ",", "options", ")", "end", "end", "serialize_relations", "(", "attrs", ",", "options", ")", "if", "options", "[", ":include", "]", "attrs", "end" ]
Gets the document as a serializable hash, used by ActiveModel's JSON serializer. @example Get the serializable hash. document.serializable_hash @example Get the serializable hash with options. document.serializable_hash(:include => :addresses) @param [ Hash ] options The options to pass. @option options [ Symbol ] :include What associations to include. @option options [ Symbol ] :only Limit the fields to only these. @option options [ Symbol ] :except Dont include these fields. @option options [ Symbol ] :methods What methods to include. @return [ Hash ] The document, ready to be serialized. @since 2.0.0.rc.6
[ "Gets", "the", "document", "as", "a", "serializable", "hash", "used", "by", "ActiveModel", "s", "JSON", "serializer", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L38-L55
12,282
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.field_names
def field_names(options) names = (as_attributes.keys + attribute_names).uniq.sort only = Array.wrap(options[:only]).map(&:to_s) except = Array.wrap(options[:except]).map(&:to_s) except |= ['_type'] unless Mongoid.include_type_for_serialization if !only.empty? names &= only elsif !except.empty? names -= except end names end
ruby
def field_names(options) names = (as_attributes.keys + attribute_names).uniq.sort only = Array.wrap(options[:only]).map(&:to_s) except = Array.wrap(options[:except]).map(&:to_s) except |= ['_type'] unless Mongoid.include_type_for_serialization if !only.empty? names &= only elsif !except.empty? names -= except end names end
[ "def", "field_names", "(", "options", ")", "names", "=", "(", "as_attributes", ".", "keys", "+", "attribute_names", ")", ".", "uniq", ".", "sort", "only", "=", "Array", ".", "wrap", "(", "options", "[", ":only", "]", ")", ".", "map", "(", ":to_s", ")", "except", "=", "Array", ".", "wrap", "(", "options", "[", ":except", "]", ")", ".", "map", "(", ":to_s", ")", "except", "|=", "[", "'_type'", "]", "unless", "Mongoid", ".", "include_type_for_serialization", "if", "!", "only", ".", "empty?", "names", "&=", "only", "elsif", "!", "except", ".", "empty?", "names", "-=", "except", "end", "names", "end" ]
Get the names of all fields that will be serialized. @api private @example Get all the field names. document.send(:field_names) @return [ Array<String> ] The names of the fields. @since 3.0.0
[ "Get", "the", "names", "of", "all", "fields", "that", "will", "be", "serialized", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L69-L82
12,283
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.serialize_attribute
def serialize_attribute(attrs, name, names, options) if relations.key?(name) value = send(name) attrs[name] = value ? value.serializable_hash(options) : nil elsif names.include?(name) && !fields.key?(name) attrs[name] = read_raw_attribute(name) elsif !attribute_missing?(name) attrs[name] = send(name) end end
ruby
def serialize_attribute(attrs, name, names, options) if relations.key?(name) value = send(name) attrs[name] = value ? value.serializable_hash(options) : nil elsif names.include?(name) && !fields.key?(name) attrs[name] = read_raw_attribute(name) elsif !attribute_missing?(name) attrs[name] = send(name) end end
[ "def", "serialize_attribute", "(", "attrs", ",", "name", ",", "names", ",", "options", ")", "if", "relations", ".", "key?", "(", "name", ")", "value", "=", "send", "(", "name", ")", "attrs", "[", "name", "]", "=", "value", "?", "value", ".", "serializable_hash", "(", "options", ")", ":", "nil", "elsif", "names", ".", "include?", "(", "name", ")", "&&", "!", "fields", ".", "key?", "(", "name", ")", "attrs", "[", "name", "]", "=", "read_raw_attribute", "(", "name", ")", "elsif", "!", "attribute_missing?", "(", "name", ")", "attrs", "[", "name", "]", "=", "send", "(", "name", ")", "end", "end" ]
Serialize a single attribute. Handles associations, fields, and dynamic attributes. @api private @example Serialize the attribute. document.serialize_attribute({}, "id" , [ "id" ]) @param [ Hash ] attrs The attributes. @param [ String ] name The attribute name. @param [ Array<String> ] names The names of all attributes. @param [ Hash ] options The options. @return [ Object ] The attribute. @since 3.0.0
[ "Serialize", "a", "single", "attribute", ".", "Handles", "associations", "fields", "and", "dynamic", "attributes", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L100-L109
12,284
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.serialize_relations
def serialize_relations(attributes = {}, options = {}) inclusions = options[:include] relation_names(inclusions).each do |name| association = relations[name.to_s] if association && relation = send(association.name) attributes[association.name.to_s] = relation.serializable_hash(relation_options(inclusions, options, name)) end end end
ruby
def serialize_relations(attributes = {}, options = {}) inclusions = options[:include] relation_names(inclusions).each do |name| association = relations[name.to_s] if association && relation = send(association.name) attributes[association.name.to_s] = relation.serializable_hash(relation_options(inclusions, options, name)) end end end
[ "def", "serialize_relations", "(", "attributes", "=", "{", "}", ",", "options", "=", "{", "}", ")", "inclusions", "=", "options", "[", ":include", "]", "relation_names", "(", "inclusions", ")", ".", "each", "do", "|", "name", "|", "association", "=", "relations", "[", "name", ".", "to_s", "]", "if", "association", "&&", "relation", "=", "send", "(", "association", ".", "name", ")", "attributes", "[", "association", ".", "name", ".", "to_s", "]", "=", "relation", ".", "serializable_hash", "(", "relation_options", "(", "inclusions", ",", "options", ",", "name", ")", ")", "end", "end", "end" ]
For each of the provided include options, get the association needed and provide it in the hash. @example Serialize the included associations. document.serialize_relations({}, :include => :addresses) @param [ Hash ] attributes The attributes to serialize. @param [ Hash ] options The serialization options. @option options [ Symbol ] :include What associations to include @option options [ Symbol ] :only Limit the fields to only these. @option options [ Symbol ] :except Dont include these fields. @since 2.0.0.rc.6
[ "For", "each", "of", "the", "provided", "include", "options", "get", "the", "association", "needed", "and", "provide", "it", "in", "the", "hash", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L125-L134
12,285
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.relation_names
def relation_names(inclusions) inclusions.is_a?(Hash) ? inclusions.keys : Array.wrap(inclusions) end
ruby
def relation_names(inclusions) inclusions.is_a?(Hash) ? inclusions.keys : Array.wrap(inclusions) end
[ "def", "relation_names", "(", "inclusions", ")", "inclusions", ".", "is_a?", "(", "Hash", ")", "?", "inclusions", ".", "keys", ":", "Array", ".", "wrap", "(", "inclusions", ")", "end" ]
Since the inclusions can be a hash, symbol, or array of symbols, this is provided as a convenience to parse out the names. @example Get the association names. document.relation_names(:include => [ :addresses ]) @param [ Hash, Symbol, Array<Symbol> ] inclusions The inclusions. @return [ Array<Symbol> ] The names of the included associations. @since 2.0.0.rc.6
[ "Since", "the", "inclusions", "can", "be", "a", "hash", "symbol", "or", "array", "of", "symbols", "this", "is", "provided", "as", "a", "convenience", "to", "parse", "out", "the", "names", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L147-L149
12,286
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.relation_options
def relation_options(inclusions, options, name) if inclusions.is_a?(Hash) inclusions[name] else { except: options[:except], only: options[:only] } end end
ruby
def relation_options(inclusions, options, name) if inclusions.is_a?(Hash) inclusions[name] else { except: options[:except], only: options[:only] } end end
[ "def", "relation_options", "(", "inclusions", ",", "options", ",", "name", ")", "if", "inclusions", ".", "is_a?", "(", "Hash", ")", "inclusions", "[", "name", "]", "else", "{", "except", ":", "options", "[", ":except", "]", ",", "only", ":", "options", "[", ":only", "]", "}", "end", "end" ]
Since the inclusions can be a hash, symbol, or array of symbols, this is provided as a convenience to parse out the options. @example Get the association options. document.relation_names(:include => [ :addresses ]) @param [ Hash, Symbol, Array<Symbol> ] inclusions The inclusions. @param [ Hash ] options The options. @param [ Symbol ] name The name of the association. @return [ Hash ] The options for the association. @since 2.0.0.rc.6
[ "Since", "the", "inclusions", "can", "be", "a", "hash", "symbol", "or", "array", "of", "symbols", "this", "is", "provided", "as", "a", "convenience", "to", "parse", "out", "the", "options", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L164-L170
12,287
mongodb/mongoid
lib/mongoid/threaded.rb
Mongoid.Threaded.current_scope
def current_scope(klass = nil) if klass && Thread.current[CURRENT_SCOPE_KEY].respond_to?(:keys) Thread.current[CURRENT_SCOPE_KEY][ Thread.current[CURRENT_SCOPE_KEY].keys.find { |k| k <= klass } ] else Thread.current[CURRENT_SCOPE_KEY] end end
ruby
def current_scope(klass = nil) if klass && Thread.current[CURRENT_SCOPE_KEY].respond_to?(:keys) Thread.current[CURRENT_SCOPE_KEY][ Thread.current[CURRENT_SCOPE_KEY].keys.find { |k| k <= klass } ] else Thread.current[CURRENT_SCOPE_KEY] end end
[ "def", "current_scope", "(", "klass", "=", "nil", ")", "if", "klass", "&&", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", ".", "respond_to?", "(", ":keys", ")", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", "[", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", ".", "keys", ".", "find", "{", "|", "k", "|", "k", "<=", "klass", "}", "]", "else", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", "end", "end" ]
Get the current Mongoid scope. @example Get the scope. Threaded.current_scope(klass) Threaded.current_scope @param [ Klass ] klass The class type of the scope. @return [ Criteria ] The scope. @since 5.0.0
[ "Get", "the", "current", "Mongoid", "scope", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/threaded.rb#L228-L236
12,288
mongodb/mongoid
lib/mongoid/threaded.rb
Mongoid.Threaded.set_current_scope
def set_current_scope(scope, klass) if scope.nil? if Thread.current[CURRENT_SCOPE_KEY] Thread.current[CURRENT_SCOPE_KEY].delete(klass) Thread.current[CURRENT_SCOPE_KEY] = nil if Thread.current[CURRENT_SCOPE_KEY].empty? end else Thread.current[CURRENT_SCOPE_KEY] ||= {} Thread.current[CURRENT_SCOPE_KEY][klass] = scope end end
ruby
def set_current_scope(scope, klass) if scope.nil? if Thread.current[CURRENT_SCOPE_KEY] Thread.current[CURRENT_SCOPE_KEY].delete(klass) Thread.current[CURRENT_SCOPE_KEY] = nil if Thread.current[CURRENT_SCOPE_KEY].empty? end else Thread.current[CURRENT_SCOPE_KEY] ||= {} Thread.current[CURRENT_SCOPE_KEY][klass] = scope end end
[ "def", "set_current_scope", "(", "scope", ",", "klass", ")", "if", "scope", ".", "nil?", "if", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", ".", "delete", "(", "klass", ")", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", "=", "nil", "if", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", ".", "empty?", "end", "else", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", "||=", "{", "}", "Thread", ".", "current", "[", "CURRENT_SCOPE_KEY", "]", "[", "klass", "]", "=", "scope", "end", "end" ]
Set the current Mongoid scope. Safe for multi-model scope chaining. @example Set the scope. Threaded.current_scope(scope, klass) @param [ Criteria ] scope The current scope. @param [ Class ] klass The current model class. @return [ Criteria ] The scope. @since 5.0.1
[ "Set", "the", "current", "Mongoid", "scope", ".", "Safe", "for", "multi", "-", "model", "scope", "chaining", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/threaded.rb#L263-L273
12,289
mongodb/mongoid
lib/mongoid/scopable.rb
Mongoid.Scopable.apply_default_scoping
def apply_default_scoping if default_scoping default_scoping.call.selector.each do |field, value| attributes[field] = value unless value.respond_to?(:each) end end end
ruby
def apply_default_scoping if default_scoping default_scoping.call.selector.each do |field, value| attributes[field] = value unless value.respond_to?(:each) end end end
[ "def", "apply_default_scoping", "if", "default_scoping", "default_scoping", ".", "call", ".", "selector", ".", "each", "do", "|", "field", ",", "value", "|", "attributes", "[", "field", "]", "=", "value", "unless", "value", ".", "respond_to?", "(", ":each", ")", "end", "end", "end" ]
Apply the default scoping to the attributes of the document, as long as they are not complex queries. @api private @example Apply the default scoping. document.apply_default_scoping @return [ true, false ] If default scoping was applied. @since 4.0.0
[ "Apply", "the", "default", "scoping", "to", "the", "attributes", "of", "the", "document", "as", "long", "as", "they", "are", "not", "complex", "queries", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/scopable.rb#L32-L38
12,290
mongodb/mongoid
lib/mongoid/validatable.rb
Mongoid.Validatable.read_attribute_for_validation
def read_attribute_for_validation(attr) attribute = database_field_name(attr) if relations.key?(attribute) begin_validate relation = without_autobuild { send(attr) } exit_validate relation.do_or_do_not(:in_memory) || relation elsif fields[attribute].try(:localized?) attributes[attribute] else send(attr) end end
ruby
def read_attribute_for_validation(attr) attribute = database_field_name(attr) if relations.key?(attribute) begin_validate relation = without_autobuild { send(attr) } exit_validate relation.do_or_do_not(:in_memory) || relation elsif fields[attribute].try(:localized?) attributes[attribute] else send(attr) end end
[ "def", "read_attribute_for_validation", "(", "attr", ")", "attribute", "=", "database_field_name", "(", "attr", ")", "if", "relations", ".", "key?", "(", "attribute", ")", "begin_validate", "relation", "=", "without_autobuild", "{", "send", "(", "attr", ")", "}", "exit_validate", "relation", ".", "do_or_do_not", "(", ":in_memory", ")", "||", "relation", "elsif", "fields", "[", "attribute", "]", ".", "try", "(", ":localized?", ")", "attributes", "[", "attribute", "]", "else", "send", "(", "attr", ")", "end", "end" ]
Overrides the default ActiveModel behavior since we need to handle validations of associations slightly different than just calling the getter. @example Read the value. person.read_attribute_for_validation(:addresses) @param [ Symbol ] attr The name of the field or association. @return [ Object ] The value of the field or the association. @since 2.0.0.rc.1
[ "Overrides", "the", "default", "ActiveModel", "behavior", "since", "we", "need", "to", "handle", "validations", "of", "associations", "slightly", "different", "than", "just", "calling", "the", "getter", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/validatable.rb#L70-L82
12,291
mongodb/mongoid
lib/mongoid/traversable.rb
Mongoid.Traversable.collect_children
def collect_children children = [] embedded_relations.each_pair do |name, association| without_autobuild do child = send(name) Array.wrap(child).each do |doc| children.push(doc) children.concat(doc._children) end if child end end children end
ruby
def collect_children children = [] embedded_relations.each_pair do |name, association| without_autobuild do child = send(name) Array.wrap(child).each do |doc| children.push(doc) children.concat(doc._children) end if child end end children end
[ "def", "collect_children", "children", "=", "[", "]", "embedded_relations", ".", "each_pair", "do", "|", "name", ",", "association", "|", "without_autobuild", "do", "child", "=", "send", "(", "name", ")", "Array", ".", "wrap", "(", "child", ")", ".", "each", "do", "|", "doc", "|", "children", ".", "push", "(", "doc", ")", "children", ".", "concat", "(", "doc", ".", "_children", ")", "end", "if", "child", "end", "end", "children", "end" ]
Collect all the children of this document. @example Collect all the children. document.collect_children @return [ Array<Document> ] The children. @since 2.4.0
[ "Collect", "all", "the", "children", "of", "this", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/traversable.rb#L42-L54
12,292
mongodb/mongoid
lib/mongoid/traversable.rb
Mongoid.Traversable.remove_child
def remove_child(child) name = child.association_name if child.embedded_one? remove_ivar(name) else relation = send(name) relation.send(:delete_one, child) end end
ruby
def remove_child(child) name = child.association_name if child.embedded_one? remove_ivar(name) else relation = send(name) relation.send(:delete_one, child) end end
[ "def", "remove_child", "(", "child", ")", "name", "=", "child", ".", "association_name", "if", "child", ".", "embedded_one?", "remove_ivar", "(", "name", ")", "else", "relation", "=", "send", "(", "name", ")", "relation", ".", "send", "(", ":delete_one", ",", "child", ")", "end", "end" ]
Remove a child document from this parent. If an embeds one then set to nil, otherwise remove from the embeds many. This is called from the +RemoveEmbedded+ persistence command. @example Remove the child. document.remove_child(child) @param [ Document ] child The child (embedded) document to remove. @since 2.0.0.beta.1
[ "Remove", "a", "child", "document", "from", "this", "parent", ".", "If", "an", "embeds", "one", "then", "set", "to", "nil", "otherwise", "remove", "from", "the", "embeds", "many", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/traversable.rb#L104-L112
12,293
mongodb/mongoid
lib/mongoid/traversable.rb
Mongoid.Traversable.reset_persisted_children
def reset_persisted_children _children.each do |child| child.move_changes child.new_record = false end _reset_memoized_children! end
ruby
def reset_persisted_children _children.each do |child| child.move_changes child.new_record = false end _reset_memoized_children! end
[ "def", "reset_persisted_children", "_children", ".", "each", "do", "|", "child", "|", "child", ".", "move_changes", "child", ".", "new_record", "=", "false", "end", "_reset_memoized_children!", "end" ]
After children are persisted we can call this to move all their changes and flag them as persisted in one call. @example Reset the children. document.reset_persisted_children @return [ Array<Document> ] The children. @since 2.1.0
[ "After", "children", "are", "persisted", "we", "can", "call", "this", "to", "move", "all", "their", "changes", "and", "flag", "them", "as", "persisted", "in", "one", "call", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/traversable.rb#L123-L129
12,294
mongodb/mongoid
lib/mongoid/document.rb
Mongoid.Document.becomes
def becomes(klass) unless klass.include?(Mongoid::Document) raise ArgumentError, "A class which includes Mongoid::Document is expected" end became = klass.new(clone_document) became._id = _id became.instance_variable_set(:@changed_attributes, changed_attributes) became.instance_variable_set(:@errors, ActiveModel::Errors.new(became)) became.errors.instance_variable_set(:@messages, errors.instance_variable_get(:@messages)) became.instance_variable_set(:@new_record, new_record?) became.instance_variable_set(:@destroyed, destroyed?) became.changed_attributes["_type"] = self.class.to_s became._type = klass.to_s # mark embedded docs as persisted embedded_relations.each_pair do |name, meta| without_autobuild do relation = became.__send__(name) Array.wrap(relation).each do |r| r.instance_variable_set(:@new_record, new_record?) end end end became end
ruby
def becomes(klass) unless klass.include?(Mongoid::Document) raise ArgumentError, "A class which includes Mongoid::Document is expected" end became = klass.new(clone_document) became._id = _id became.instance_variable_set(:@changed_attributes, changed_attributes) became.instance_variable_set(:@errors, ActiveModel::Errors.new(became)) became.errors.instance_variable_set(:@messages, errors.instance_variable_get(:@messages)) became.instance_variable_set(:@new_record, new_record?) became.instance_variable_set(:@destroyed, destroyed?) became.changed_attributes["_type"] = self.class.to_s became._type = klass.to_s # mark embedded docs as persisted embedded_relations.each_pair do |name, meta| without_autobuild do relation = became.__send__(name) Array.wrap(relation).each do |r| r.instance_variable_set(:@new_record, new_record?) end end end became end
[ "def", "becomes", "(", "klass", ")", "unless", "klass", ".", "include?", "(", "Mongoid", "::", "Document", ")", "raise", "ArgumentError", ",", "\"A class which includes Mongoid::Document is expected\"", "end", "became", "=", "klass", ".", "new", "(", "clone_document", ")", "became", ".", "_id", "=", "_id", "became", ".", "instance_variable_set", "(", ":@changed_attributes", ",", "changed_attributes", ")", "became", ".", "instance_variable_set", "(", ":@errors", ",", "ActiveModel", "::", "Errors", ".", "new", "(", "became", ")", ")", "became", ".", "errors", ".", "instance_variable_set", "(", ":@messages", ",", "errors", ".", "instance_variable_get", "(", ":@messages", ")", ")", "became", ".", "instance_variable_set", "(", ":@new_record", ",", "new_record?", ")", "became", ".", "instance_variable_set", "(", ":@destroyed", ",", "destroyed?", ")", "became", ".", "changed_attributes", "[", "\"_type\"", "]", "=", "self", ".", "class", ".", "to_s", "became", ".", "_type", "=", "klass", ".", "to_s", "# mark embedded docs as persisted", "embedded_relations", ".", "each_pair", "do", "|", "name", ",", "meta", "|", "without_autobuild", "do", "relation", "=", "became", ".", "__send__", "(", "name", ")", "Array", ".", "wrap", "(", "relation", ")", ".", "each", "do", "|", "r", "|", "r", ".", "instance_variable_set", "(", ":@new_record", ",", "new_record?", ")", "end", "end", "end", "became", "end" ]
Returns an instance of the specified class with the attributes, errors, and embedded documents of the current document. @example Return a subclass document as a superclass instance. manager.becomes(Person) @raise [ ArgumentError ] If the class doesn't include Mongoid::Document @param [ Class ] klass The class to become. @return [ Document ] An instance of the specified class. @since 2.0.0
[ "Returns", "an", "instance", "of", "the", "specified", "class", "with", "the", "attributes", "errors", "and", "embedded", "documents", "of", "the", "current", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/document.rb#L223-L249
12,295
mongodb/mongoid
lib/mongoid/association.rb
Mongoid.Association.reload_relations
def reload_relations relations.each_pair do |name, meta| if instance_variable_defined?("@_#{name}") if _parent.nil? || instance_variable_get("@_#{name}") != _parent remove_instance_variable("@_#{name}") end end end end
ruby
def reload_relations relations.each_pair do |name, meta| if instance_variable_defined?("@_#{name}") if _parent.nil? || instance_variable_get("@_#{name}") != _parent remove_instance_variable("@_#{name}") end end end end
[ "def", "reload_relations", "relations", ".", "each_pair", "do", "|", "name", ",", "meta", "|", "if", "instance_variable_defined?", "(", "\"@_#{name}\"", ")", "if", "_parent", ".", "nil?", "||", "instance_variable_get", "(", "\"@_#{name}\"", ")", "!=", "_parent", "remove_instance_variable", "(", "\"@_#{name}\"", ")", "end", "end", "end", "end" ]
Convenience method for iterating through the loaded associations and reloading them. @example Reload the associations. document.reload_relations @return [ Hash ] The association metadata. @since 2.1.6
[ "Convenience", "method", "for", "iterating", "through", "the", "loaded", "associations", "and", "reloading", "them", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/association.rb#L141-L149
12,296
mongodb/mongoid
lib/mongoid/inspectable.rb
Mongoid.Inspectable.inspect_fields
def inspect_fields fields.map do |name, field| unless name == "_id" as = field.options[:as] "#{name}#{as ? "(#{as})" : nil}: #{@attributes[name].inspect}" end end.compact end
ruby
def inspect_fields fields.map do |name, field| unless name == "_id" as = field.options[:as] "#{name}#{as ? "(#{as})" : nil}: #{@attributes[name].inspect}" end end.compact end
[ "def", "inspect_fields", "fields", ".", "map", "do", "|", "name", ",", "field", "|", "unless", "name", "==", "\"_id\"", "as", "=", "field", ".", "options", "[", ":as", "]", "\"#{name}#{as ? \"(#{as})\" : nil}: #{@attributes[name].inspect}\"", "end", "end", ".", "compact", "end" ]
Get an array of inspected fields for the document. @api private @example Inspect the defined fields. document.inspect_fields @return [ String ] An array of pretty printed field values. @since 1.0.0
[ "Get", "an", "array", "of", "inspected", "fields", "for", "the", "document", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/inspectable.rb#L37-L44
12,297
mongodb/mongoid
lib/mongoid/interceptable.rb
Mongoid.Interceptable.run_callbacks
def run_callbacks(kind, *args, &block) cascadable_children(kind).each do |child| if child.run_callbacks(child_callback_type(kind, child), *args) == false return false end end callback_executable?(kind) ? super(kind, *args, &block) : true end
ruby
def run_callbacks(kind, *args, &block) cascadable_children(kind).each do |child| if child.run_callbacks(child_callback_type(kind, child), *args) == false return false end end callback_executable?(kind) ? super(kind, *args, &block) : true end
[ "def", "run_callbacks", "(", "kind", ",", "*", "args", ",", "&", "block", ")", "cascadable_children", "(", "kind", ")", ".", "each", "do", "|", "child", "|", "if", "child", ".", "run_callbacks", "(", "child_callback_type", "(", "kind", ",", "child", ")", ",", "args", ")", "==", "false", "return", "false", "end", "end", "callback_executable?", "(", "kind", ")", "?", "super", "(", "kind", ",", "args", ",", "block", ")", ":", "true", "end" ]
Run the callbacks for the document. This overrides active support's functionality to cascade callbacks to embedded documents that have been flagged as such. @example Run the callbacks. run_callbacks :save do save! end @param [ Symbol ] kind The type of callback to execute. @param [ Array ] args Any options. @return [ Document ] The document @since 2.3.0
[ "Run", "the", "callbacks", "for", "the", "document", ".", "This", "overrides", "active", "support", "s", "functionality", "to", "cascade", "callbacks", "to", "embedded", "documents", "that", "have", "been", "flagged", "as", "such", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/interceptable.rb#L127-L134
12,298
mongodb/mongoid
lib/mongoid/interceptable.rb
Mongoid.Interceptable.cascadable_children
def cascadable_children(kind, children = Set.new) embedded_relations.each_pair do |name, association| next unless association.cascading_callbacks? without_autobuild do delayed_pulls = delayed_atomic_pulls[name] delayed_unsets = delayed_atomic_unsets[name] children.merge(delayed_pulls) if delayed_pulls children.merge(delayed_unsets) if delayed_unsets relation = send(name) Array.wrap(relation).each do |child| next if children.include?(child) children.add(child) if cascadable_child?(kind, child, association) child.send(:cascadable_children, kind, children) end end end children.to_a end
ruby
def cascadable_children(kind, children = Set.new) embedded_relations.each_pair do |name, association| next unless association.cascading_callbacks? without_autobuild do delayed_pulls = delayed_atomic_pulls[name] delayed_unsets = delayed_atomic_unsets[name] children.merge(delayed_pulls) if delayed_pulls children.merge(delayed_unsets) if delayed_unsets relation = send(name) Array.wrap(relation).each do |child| next if children.include?(child) children.add(child) if cascadable_child?(kind, child, association) child.send(:cascadable_children, kind, children) end end end children.to_a end
[ "def", "cascadable_children", "(", "kind", ",", "children", "=", "Set", ".", "new", ")", "embedded_relations", ".", "each_pair", "do", "|", "name", ",", "association", "|", "next", "unless", "association", ".", "cascading_callbacks?", "without_autobuild", "do", "delayed_pulls", "=", "delayed_atomic_pulls", "[", "name", "]", "delayed_unsets", "=", "delayed_atomic_unsets", "[", "name", "]", "children", ".", "merge", "(", "delayed_pulls", ")", "if", "delayed_pulls", "children", ".", "merge", "(", "delayed_unsets", ")", "if", "delayed_unsets", "relation", "=", "send", "(", "name", ")", "Array", ".", "wrap", "(", "relation", ")", ".", "each", "do", "|", "child", "|", "next", "if", "children", ".", "include?", "(", "child", ")", "children", ".", "add", "(", "child", ")", "if", "cascadable_child?", "(", "kind", ",", "child", ",", "association", ")", "child", ".", "send", "(", ":cascadable_children", ",", "kind", ",", "children", ")", "end", "end", "end", "children", ".", "to_a", "end" ]
Get all the child embedded documents that are flagged as cascadable. @example Get all the cascading children. document.cascadable_children(:update) @param [ Symbol ] kind The type of callback. @return [ Array<Document> ] The children. @since 2.3.0
[ "Get", "all", "the", "child", "embedded", "documents", "that", "are", "flagged", "as", "cascadable", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/interceptable.rb#L163-L180
12,299
mongodb/mongoid
lib/mongoid/interceptable.rb
Mongoid.Interceptable.cascadable_child?
def cascadable_child?(kind, child, association) return false if kind == :initialize || kind == :find || kind == :touch return false if kind == :validate && association.validate? child.callback_executable?(kind) ? child.in_callback_state?(kind) : false end
ruby
def cascadable_child?(kind, child, association) return false if kind == :initialize || kind == :find || kind == :touch return false if kind == :validate && association.validate? child.callback_executable?(kind) ? child.in_callback_state?(kind) : false end
[ "def", "cascadable_child?", "(", "kind", ",", "child", ",", "association", ")", "return", "false", "if", "kind", "==", ":initialize", "||", "kind", "==", ":find", "||", "kind", "==", ":touch", "return", "false", "if", "kind", "==", ":validate", "&&", "association", ".", "validate?", "child", ".", "callback_executable?", "(", "kind", ")", "?", "child", ".", "in_callback_state?", "(", "kind", ")", ":", "false", "end" ]
Determine if the child should fire the callback. @example Should the child fire the callback? document.cascadable_child?(:update, doc) @param [ Symbol ] kind The type of callback. @param [ Document ] child The child document. @return [ true, false ] If the child should fire the callback. @since 2.3.0
[ "Determine", "if", "the", "child", "should", "fire", "the", "callback", "." ]
56976e32610f4c2450882b0bfe14da099f0703f4
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/interceptable.rb#L193-L197