_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q12200
AttrEncrypted.InstanceMethods.encrypt
train
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
{ "resource": "" }
q12201
AttrEncrypted.InstanceMethods.encrypted_attributes
train
def encrypted_attributes @encrypted_attributes ||= begin duplicated= {} self.class.encrypted_attributes.map { |key, value| duplicated[key] = value.dup } duplicated end end
ruby
{ "resource": "" }
q12202
Colorize.InstanceMethods.colorize
train
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
{ "resource": "" }
q12203
Colorize.InstanceMethods.colorized?
train
def colorized? scan_for_colors.inject([]) do |colors, match| colors << match.tap(&:pop) end.flatten.compact.any? end
ruby
{ "resource": "" }
q12204
Colorize.InstanceMethods.colors_from_params
train
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
{ "resource": "" }
q12205
Colorize.InstanceMethods.colors_from_hash
train
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
{ "resource": "" }
q12206
Colorize.ClassMethods.color_methods
train
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
{ "resource": "" }
q12207
Racc.GrammarFileParser.parse_user_code
train
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
{ "resource": "" }
q12208
Racc.SimulatedAutomaton.consume!
train
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
{ "resource": "" }
q12209
Racc.States.path
train
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
{ "resource": "" }
q12210
Racc.States.walk_graph
train
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
{ "resource": "" }
q12211
Racc.States.detailed_transition_graph
train
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
{ "resource": "" }
q12212
Racc.Rule.replace
train
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
{ "resource": "" }
q12213
Racc.Sym.expand
train
def expand @expand ||= Racc.set_closure(@heads.dup) do |ptr| if (sym = ptr.symbol) && sym.nonterminal? sym.heads end end.freeze end
ruby
{ "resource": "" }
q12214
Refile.AttachmentHelper.attachment_image_tag
train
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
{ "resource": "" }
q12215
Refile.AttachmentHelper.attachment_cache_field
train
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
{ "resource": "" }
q12216
Refile.Attachment.accepts_attachments_for
train
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
{ "resource": "" }
q12217
Refile.File.download
train
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
{ "resource": "" }
q12218
VCR.Response.to_hash
train
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
{ "resource": "" }
q12219
VCR.Configuration.around_http_request
train
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
{ "resource": "" }
q12220
Phony.DSL.country
train
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
{ "resource": "" }
q12221
Phony.DSL.fixed
train
def fixed length, options = {} options[:zero] = true if options[:zero].nil? NationalSplitters::Fixed.instance_for length, options end
ruby
{ "resource": "" }
q12222
Phony.CountryCodes.add
train
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
{ "resource": "" }
q12223
Phony.CountryCodes.split
train
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
{ "resource": "" }
q12224
Phony.CountryCodes.format
train
def format number, options = {} country, _, national_number = partial_split number country.format national_number, options end
ruby
{ "resource": "" }
q12225
Phony.CountryCodes.plausible?
train
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
{ "resource": "" }
q12226
Phony.CountryCodes.vanity?
train
def vanity? number country, _, national = partial_split number country.vanity? national end
ruby
{ "resource": "" }
q12227
Phony.CountryCodes.partial_split
train
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
{ "resource": "" }
q12228
Phony.Country.split
train
def split national_number _, trunk, ndc, *rest = internal_split national_number [trunk, ndc, *rest] end
ruby
{ "resource": "" }
q12229
Phony.Country.format
train
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
{ "resource": "" }
q12230
Phony.Country.normalize
train
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
{ "resource": "" }
q12231
Phony.Country.plausible?
train
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
{ "resource": "" }
q12232
Mongoid.Criteria.merge!
train
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
{ "resource": "" }
q12233
Mongoid.Criteria.only
train
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
{ "resource": "" }
q12234
Mongoid.Criteria.read
train
def read(value = nil) clone.tap do |criteria| criteria.options.merge!(read: value) end end
ruby
{ "resource": "" }
q12235
Mongoid.Criteria.respond_to?
train
def respond_to?(name, include_private = false) super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private) end
ruby
{ "resource": "" }
q12236
Mongoid.Criteria.check_for_missing_documents!
train
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
{ "resource": "" }
q12237
Mongoid.Criteria.initialize_copy
train
def initialize_copy(other) @inclusions = other.inclusions.dup @scoping_options = other.scoping_options @documents = other.documents.dup @context = nil super end
ruby
{ "resource": "" }
q12238
Mongoid.Criteria.type_selection
train
def type_selection klasses = klass._types if klasses.size > 1 { _type: { "$in" => klass._types }} else { _type: klass._types[0] } end end
ruby
{ "resource": "" }
q12239
Mongoid.Positional.positionally
train
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
{ "resource": "" }
q12240
Mongoid.Touchable.define_touchable!
train
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
{ "resource": "" }
q12241
Mongoid.Loggable.default_logger
train
def default_logger logger = Logger.new($stdout) logger.level = Mongoid::Config.log_level logger end
ruby
{ "resource": "" }
q12242
Mongoid.Copyable.process_localized_attributes
train
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
{ "resource": "" }
q12243
Mongoid.Shardable.shard_key_selector
train
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
{ "resource": "" }
q12244
Mongoid.Reloadable.reload
train
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
{ "resource": "" }
q12245
Mongoid.Reloadable.reload_root_document
train
def reload_root_document {}.merge(collection.find({ _id: _id }, session: _session).read(mode: :primary).first || {}) end
ruby
{ "resource": "" }
q12246
Mongoid.Reloadable.reload_embedded_document
train
def reload_embedded_document extract_embedded_attributes({}.merge( collection(_root).find(_id: _root._id).read(mode: :primary).first )) end
ruby
{ "resource": "" }
q12247
Mongoid.Reloadable.extract_embedded_attributes
train
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
{ "resource": "" }
q12248
Mongoid.Attributes.attribute_present?
train
def attribute_present?(name) attribute = read_raw_attribute(name) !attribute.blank? || attribute == false rescue ActiveModel::MissingAttributeError false end
ruby
{ "resource": "" }
q12249
Mongoid.Attributes.read_attribute
train
def read_attribute(name) field = fields[name.to_s] raw = read_raw_attribute(name) field ? field.demongoize(raw) : raw end
ruby
{ "resource": "" }
q12250
Mongoid.Attributes.read_attribute_before_type_cast
train
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
{ "resource": "" }
q12251
Mongoid.Attributes.remove_attribute
train
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
{ "resource": "" }
q12252
Mongoid.Attributes.write_attribute
train
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
{ "resource": "" }
q12253
Mongoid.Attributes.attribute_missing?
train
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
{ "resource": "" }
q12254
Mongoid.Attributes.typed_value_for
train
def typed_value_for(key, value) fields.key?(key) ? fields[key].mongoize(value) : value.mongoize end
ruby
{ "resource": "" }
q12255
Mongoid.Attributes.validate_attribute_value
train
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
{ "resource": "" }
q12256
Mongoid.Factory.build
train
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
{ "resource": "" }
q12257
Mongoid.Factory.from_db
train
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
{ "resource": "" }
q12258
Mongoid.Atomic.add_atomic_pull
train
def add_atomic_pull(document) document.flagged_for_destroy = true (delayed_atomic_pulls[document.association_name.to_s] ||= []).push(document) end
ruby
{ "resource": "" }
q12259
Mongoid.Atomic.add_atomic_unset
train
def add_atomic_unset(document) document.flagged_for_destroy = true (delayed_atomic_unsets[document.association_name.to_s] ||= []).push(document) end
ruby
{ "resource": "" }
q12260
Mongoid.Atomic.atomic_updates
train
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
{ "resource": "" }
q12261
Mongoid.Atomic.atomic_pulls
train
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
{ "resource": "" }
q12262
Mongoid.Atomic.atomic_unsets
train
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
{ "resource": "" }
q12263
Mongoid.Atomic.generate_atomic_updates
train
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
{ "resource": "" }
q12264
Mongoid.PersistenceContext.collection
train
def collection(parent = nil) parent ? parent.collection.with(client_options) : client[collection_name.to_sym] end
ruby
{ "resource": "" }
q12265
Mongoid.PersistenceContext.client
train
def client @client ||= (client = Clients.with_name(client_name) client = client.use(database_name) if database_name_option client.with(client_options)) end
ruby
{ "resource": "" }
q12266
Mongoid.Changeable.changes
train
def changes _changes = {} changed.each do |attr| change = attribute_change(attr) _changes[attr] = change if change end _changes.with_indifferent_access end
ruby
{ "resource": "" }
q12267
Mongoid.Changeable.move_changes
train
def move_changes @previous_changes = changes Atomic::UPDATES.each do |update| send(update).clear end changed_attributes.clear end
ruby
{ "resource": "" }
q12268
Mongoid.Changeable.attribute_change
train
def attribute_change(attr) attr = database_field_name(attr) [changed_attributes[attr], attributes[attr]] if attribute_changed?(attr) end
ruby
{ "resource": "" }
q12269
Mongoid.Changeable.attribute_changed?
train
def attribute_changed?(attr) attr = database_field_name(attr) return false unless changed_attributes.key?(attr) changed_attributes[attr] != attributes[attr] end
ruby
{ "resource": "" }
q12270
Mongoid.Changeable.attribute_changed_from_default?
train
def attribute_changed_from_default?(attr) field = fields[attr] return false unless field attributes[attr] != field.eval_default(self) end
ruby
{ "resource": "" }
q12271
Mongoid.Changeable.attribute_was
train
def attribute_was(attr) attr = database_field_name(attr) attribute_changed?(attr) ? changed_attributes[attr] : attributes[attr] end
ruby
{ "resource": "" }
q12272
Mongoid.Changeable.attribute_will_change!
train
def attribute_will_change!(attr) unless changed_attributes.key?(attr) changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__ end end
ruby
{ "resource": "" }
q12273
Mongoid.Changeable.reset_attribute!
train
def reset_attribute!(attr) attr = database_field_name(attr) attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr) end
ruby
{ "resource": "" }
q12274
Rails.Mongoid.load_models
train
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
{ "resource": "" }
q12275
Rails.Mongoid.load_model
train
def load_model(file) begin require_dependency(file) rescue Exception => e Logger.new($stdout).warn(e.message) end end
ruby
{ "resource": "" }
q12276
Mongoid.Fields.apply_default
train
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
{ "resource": "" }
q12277
Mongoid.Persistable.post_process_persist
train
def post_process_persist(result, options = {}) post_persist unless result == false errors.clear unless performing_validations?(options) true end
ruby
{ "resource": "" }
q12278
Mongoid.Persistable.process_atomic_operations
train
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
{ "resource": "" }
q12279
Mongoid.Persistable.persist_or_delay_atomic_operation
train
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
{ "resource": "" }
q12280
Mongoid.Persistable.persist_atomic_operations
train
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
{ "resource": "" }
q12281
Mongoid.Serializable.serializable_hash
train
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
{ "resource": "" }
q12282
Mongoid.Serializable.field_names
train
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
{ "resource": "" }
q12283
Mongoid.Serializable.serialize_attribute
train
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
{ "resource": "" }
q12284
Mongoid.Serializable.serialize_relations
train
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
{ "resource": "" }
q12285
Mongoid.Serializable.relation_names
train
def relation_names(inclusions) inclusions.is_a?(Hash) ? inclusions.keys : Array.wrap(inclusions) end
ruby
{ "resource": "" }
q12286
Mongoid.Serializable.relation_options
train
def relation_options(inclusions, options, name) if inclusions.is_a?(Hash) inclusions[name] else { except: options[:except], only: options[:only] } end end
ruby
{ "resource": "" }
q12287
Mongoid.Threaded.current_scope
train
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
{ "resource": "" }
q12288
Mongoid.Threaded.set_current_scope
train
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
{ "resource": "" }
q12289
Mongoid.Scopable.apply_default_scoping
train
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
{ "resource": "" }
q12290
Mongoid.Validatable.read_attribute_for_validation
train
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
{ "resource": "" }
q12291
Mongoid.Traversable.collect_children
train
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
{ "resource": "" }
q12292
Mongoid.Traversable.remove_child
train
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
{ "resource": "" }
q12293
Mongoid.Traversable.reset_persisted_children
train
def reset_persisted_children _children.each do |child| child.move_changes child.new_record = false end _reset_memoized_children! end
ruby
{ "resource": "" }
q12294
Mongoid.Document.becomes
train
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
{ "resource": "" }
q12295
Mongoid.Association.reload_relations
train
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
{ "resource": "" }
q12296
Mongoid.Inspectable.inspect_fields
train
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
{ "resource": "" }
q12297
Mongoid.Interceptable.run_callbacks
train
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
{ "resource": "" }
q12298
Mongoid.Interceptable.cascadable_children
train
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
{ "resource": "" }
q12299
Mongoid.Interceptable.cascadable_child?
train
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
{ "resource": "" }