Add ActiveRecord class names to the dispatcher pipeline.
------------------------------------------------------------------------------
190474
def cast_with_active_record(object, type)
      cast = cast_without_active_record(object, type)
      return cast if !defined?(::ActiveRecord::Base)

      if object.is_a?(::ActiveRecord::Base)
        cast = :active_record_instance
      elsif object.is_a?(::ActiveModel::Errors)
        cast = :active_model_error
      elsif object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base)
        cast = :active_record_class
      elsif type == :activerecord_relation || object.class.ancestors.include?(::ActiveRecord::Relation)
        cast = :array
      end
      cast
    end
21862
def inspect_attributes
      if active_record.abstract_class?
        Traits::AttributeList.new([])
      else
        columns = active_record.columns_hash.values

        if features.try(:translates_with_globalize?)
          globalize       = features.globalize
          tr_class        = globalize.model_class_for_translations
          tr_columns_hash = tr_class.columns_hash

          columns += globalize.translated_attribute_names.map do |el|
            tr_columns_hash[el.to_s]
          end
        end

        list = columns.map do |column|
          Traits::Attribute.new(active_record, column)
        end

        Traits::AttributeList.new(list)
      end
    end
1296316
def __load_child_classes(self, ac: AssetClass):
        
        # load child classes for ac
        db = self.__get_session()
        entities = (
            db.query(dal.AssetClass)
            .filter(dal.AssetClass.parentid == ac.id)
            .order_by(dal.AssetClass.sortorder)
            .all()
        )
        # map
        for entity in entities:
            child_ac = self.__map_entity(entity)
            # depth
            child_ac.depth = ac.depth + 1
            ac.classes.append(child_ac)
            # Add to index
            self.model.asset_classes.append(child_ac)

            self.__load_child_classes(child_ac)
507662
def add_platform_methods
      # Redo clean name if there is a detect override
      clean_name(force: true) unless @platform[:name].nil?

      # Add in family methods
      family_list = Train::Platforms.families
      family_list.each_value do |k|
        next if respond_to?(k.name + '?')
        define_singleton_method(k.name + '?') do
          family_hierarchy.include?(k.name)
        end
      end

      # Helper methods for direct platform info
      @platform.each_key do |m|
        next if respond_to?(m)
        define_singleton_method(m) do
          @platform[m]
        end
      end

      # Create method for name if its not already true
      m = name + '?'
      return if respond_to?(m)
      define_singleton_method(m) do
        true
      end
    end
1342417
def contribute_to_related_class(self, cls, related):
        
        super(VersionedManyToManyField, self). \
            contribute_to_related_class(cls, related)
        accessor_name = related.get_accessor_name()
        if accessor_name and hasattr(cls, accessor_name):
            descriptor = VersionedManyToManyDescriptor(related, accessor_name)
            setattr(cls, accessor_name, descriptor)
            if hasattr(cls._meta, 'many_to_many_related') and isinstance(
                    cls._meta.many_to_many_related, list):
                cls._meta.many_to_many_related.append(descriptor)
            else:
                cls._meta.many_to_many_related = [descriptor]
597636
def add_class(cls)
      old_cls = @classes[cls[:name]]
      if !old_cls && @alt_names[cls[:name]]
        old_cls = @alt_names[cls[:name]]
        warn_alt_name(cls)
      end

      if old_cls
        merge_classes(old_cls, cls)
        @current_class = old_cls
      else
        @current_class = cls
        @classes[cls[:name]] = cls

        # Register all alternate names of class for lookup too
        cls[:alternateClassNames].each do |altname|
          if cls[:name] == altname
            # A buggy documentation, warn.
            warn_alt_name(cls)
          else
            @alt_names[altname] = cls
            # When an alternate name has been used as a class name before,
            # then this is one crappy documentation, but attempt to handle
            # it by merging the class with alt-name into this class.
            if @classes[altname]
              merge_classes(cls, @classes[altname])
              @classes.delete(altname)
              warn_alt_name(cls)
            end
          end
        end

        insert_orphans(cls)
      end
    end
338243
def construct_has_many_or_belongs_to_attributes(reflection, association_class, table_ids)
      # Determine the alias used for remote_table_name, if any. In all cases this will already
      # have been assigned an ID in table_ids (either through being involved in a previous join,
      # or - if it's the first table in the query - as the default value of table_ids)
      remote_table_alias = remote_table_name = association_class.table_name
      remote_table_alias += "_#{table_ids[remote_table_name]}" unless table_ids[remote_table_name] == 1

      # Assign a new alias for the local table.
      local_table_alias = local_table_name = reflection.active_record.table_name
      if table_ids[local_table_name]
        table_id = table_ids[local_table_name] += 1
        local_table_alias += "_#{table_id}"
      else
        table_ids[local_table_name] = 1
      end

      conditions = ''
      # Add type_condition, if applicable
      conditions += " AND #{association_class.send(:type_condition).to_sql}" if association_class.finder_needs_type_condition?
      # Add custom conditions
      conditions += " AND (#{association_class.send(:sanitize_sql, reflection.options[:conditions])})" if reflection.options[:conditions]

      if reflection.macro == :belongs_to
        if reflection.options[:polymorphic]
          conditions += " AND #{local_table_alias}.#{reflection.options[:foreign_type]} = #{reflection.active_record.quote_value(association_class.base_class.name.to_s)}"
        end
        {
          :joins => reflection.options[:joins],
          :remote_key => "#{remote_table_alias}.#{association_class.primary_key}",
          :local_key => reflection.primary_key_name,
          :conditions => conditions
        }
      else
        # Association is has_many (without :through)
        if reflection.options[:as]
          conditions += " AND #{remote_table_alias}.#{reflection.options[:as]}_type = #{reflection.active_record.quote_value(reflection.active_record.base_class.name.to_s)}"
        end
        {
          :joins => "#{reflection.options[:joins]}",
          :remote_key => "#{remote_table_alias}.#{reflection.primary_key_name}",
          :local_key => reflection.klass.primary_key,
          :conditions => conditions
        }
      end
    end
15763
def add_class(class_name)
      @fragment.children.each do |c|
        c['class'] = ((c['class']||'').split(' ') + [class_name]).join(' ')
      end
    end
161438
function ActiveRecord(name) {

    var cfg = {};
    
    var ext = {
        format:'txt',
        location:'database'
    };

    function buildFileName(name) {
        return ext.location + '/' + name + '.' + ext.format;
    }

    ActiveRecord._config &&
    _.extend(cfg, ActiveRecord._config);

    cfg.format &&
    (ext.format = cfg.format) &&
    (delete cfg.format);

    cfg.location &&
    (ext.location = cfg.location) &&
    (delete cfg.location);

    if(name) {
        cfg.filename = buildFileName(name);
    } else {
        throw new Error("Required parameter 'name' is not defined!");
    }

    var db = new DB(cfg);

    !cfg.autoload && db.loadDatabase();

    var flow = new Flow();

    /**
     * The exported class is responsible for a specific collection
     *
     * @param params
     * @constructor
     */
    function F(params) {
        params && (_.extend(this, params));
        generateId(this);
    }

    F.prototype.save = function() {
        var buffer = _.clone(this),
            refreshBuffer = function() {
                this.createdAt &&
                (buffer.createdAt = this.createdAt);
            },
            syncData = function(data){
                return _.isArray(data) &&
                    _.extend(this, data[1]) || data;
            };

        return F.pre(refreshBuffer.bind(this))
            .update({_id: this._id}, buffer, { upsert: true })
            .then(syncData.bind(this));
    };

    F.prototype.remove = function() {
        return F.remove({_id: this._id}, {});
    };

    /**
     * Cursor for methods: find, findOne or count
     *
     * @param dbCursor
     * @constructor
     */
    function C(dbCursor) {
        var chain = dbCursor;

        _.each(['sort', 'skip', 'limit', 'projection'], function(fName) {
            this[fName] = function() {
                chain = chain[fName].apply(chain, arguments);
                return this;
            }
        }.bind(this));

        this.exec = function(){
            return convertToPromise(chain, 'exec', [], function(data) {
                if(_.isArray(data)) return dbCallbacks.find(data);
                if(_.isObject(data)) return dbCallbacks.findOne(data);
                return data;
            });
        };
    }

    function generateId(o){
        o && !o._id && (o._id = db.createNewId());
    }

    /**
     * Generator of functions using Cursor API: sort, limit, skip, projection
     *
     * @example {$$sort:{planet: 1}, $$skip:1, $$limit:2, $$projection: { planet: 1, system: 1 }, $not: { planet: 'Earth' }}
     * @param fnName
     * @returns {*}
     */
    function generateCursorApi(fnName) {
        return function (query, projections) {
            var cursorOptions = _.pick(query, '$$sort', '$$skip', '$$limit', '$$projection');
            query = _.omit.apply(_, _.flatten([query, _.keys(cursorOptions)]));

            if (_.keys(cursorOptions).length || projections) {
                projections && (cursorOptions.$$projection = projections);

                var cursor = new C(db[fnName](query));
                _.reduce(_.keys(cursorOptions), function (c, method) {
                    return c[method.replace('$$','')](cursorOptions[method]);
                }, cursor);

                return cursor.exec();
            }

            return convertToPromise(db, fnName, arguments,
                (fnName === 'find' ? dbCallbacks.find : (fnName === 'findOne' ? dbCallbacks.findOne : null)));
        };
    }

    function convertToPromise(ctx, method, args, success) {
        return flow.execute(function(){
            var promise = Q.nfapply(ctx[method].bind(ctx), args);
            return success
                ? promise.then(success)
                : promise;
        });
    }

    function createRecord(doc) {
        return doc ? new F(doc) : null;
    }

    var dbCallbacks = {
        insert: function(docs){
            return _.isArray(docs)
                ? _.map(docs, createRecord)
                : createRecord(docs);
        },

        find: function(docs) {
            return _.map(docs, createRecord);
        },

        findOne: function(doc) {
            return createRecord(doc);
        },

        update: function(data) {
            _.isArray(data) &&
            (data[1] = createRecord(data[1]));
            return data;
        }
    };

    F.pre = function(fn) {
        return flow.execute(fn) && F;
    };

    F.update = function(){
        return convertToPromise(db, 'update', arguments, dbCallbacks.update);
    };

    F.insert = function(){
        return convertToPromise(db, 'insert', arguments, dbCallbacks.insert);
    };

    F.remove = function(){
        return convertToPromise(db, 'remove', arguments);
    };

    F.ensureIndex = function(){
        return convertToPromise(db, 'ensureIndex', arguments);
    };

    F.removeIndex = function(){
        return convertToPromise(db, 'removeIndex', arguments);
    };

    F.find = generateCursorApi('find');

    F.count = generateCursorApi('count');

    F.findOne = generateCursorApi('findOne');

    return F;
}
894109
def register_model(klass)
      LOCK.synchronize do
        models.push(klass) unless models.include?(klass)
      end
    end
1117048
def setup_generic_relations(model_class):
    
    Action = apps.get_model('actstream', 'action')

    if Action is None:
        raise RegistrationError(
            'Unable get actstream.Action. Potential circular imports '
            'in initialisation. Try moving actstream app to come after the '
            'apps which have models to register in the INSTALLED_APPS setting.'
        )

    related_attr_name = 'related_query_name'
    related_attr_value = 'actions_with_%s' % label(model_class)

    relations = {}
    for field in ('actor', 'target', 'action_object'):
        attr = '%s_actions' % field
        attr_value = '%s_as_%s' % (related_attr_value, field)
        kwargs = {
            'content_type_field': '%s_content_type' % field,
            'object_id_field': '%s_object_id' % field,
            related_attr_name: attr_value
        }
        rel = GenericRelation('actstream.Action', **kwargs)
        rel.contribute_to_class(model_class, attr)
        relations[field] = rel

        # @@@ I'm not entirely sure why this works
        setattr(Action, attr_value, None)
    return relations
1310577
def lookup_ancestors #:nodoc:
      klass = self
      classes = [klass]
      return classes if klass == ActiveRecord::Base

      while klass != klass.base_class
        classes << klass = klass.superclass
      end
      classes
    end
179936
private ActiveRecordPlugin getActiveRecordPlugin(String ds, DruidPlugin dp){
		ActiveRecordPlugin arp = new ActiveRecordPlugin(ds, dp);
		arp.setShowSql(this.getPropertyToBoolean("db.showsql"));

		// auto mapping
		if (!this.geRuned) {
			try {
				Class<?> clazz = Class.forName(this.getModelPackage()+"."+ds.toUpperCase()+this.getMappingKitClassName());
				Method mapping = clazz.getMethod("mapping", ActiveRecordPlugin.class);
				mapping.invoke(clazz, arp);
			} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException
					| IllegalArgumentException | InvocationTargetException e) {
				throw (new RuntimeException(String.valueOf(e) + ",may be your table is not contain `PrimaryKey`."));
			}
		}
		return arp;
	}
656632
def awesome_active_record_class(object)
      return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:columns) || object.to_s == 'ActiveRecord::Base'
      return awesome_class(object) if object.respond_to?(:abstract_class?) && object.abstract_class?

      data = object.columns.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
        hash[c.name.to_sym] = c.type
        hash
      end

      name = "class #{awesome_simple(object.to_s, :class)}"
      base = "< #{awesome_simple(object.superclass.to_s, :class)}"

      [name, base, awesome_hash(data)].join(' ')
    end
151267
def _create_record(attribute_names = self.attribute_names)
      attribute_names = attributes_for_create(attribute_names)

      new_id = self.class._insert_record(
        attributes_with_values(attribute_names)
      )

      self.id ||= new_id if @primary_key

      @new_record = false

      yield(self) if block_given?

      id
    end
1000747
def configure_query
      @query_to_pluck = @records
      @attributes_to_pluck = [{ name: @query_to_pluck.primary_key.to_sym, sql: "\"#{@query_to_pluck.table_name}\".#{@query_to_pluck.primary_key}" }]
      @results = {}
      @klass_reflections = @query_to_pluck.reflections.with_indifferent_access

      pluck_reflections = @options[:reflections] || {}

      # Validate that all relations exists in the model
      if (missing_reflections = pluck_reflections.symbolize_keys.keys - @klass_reflections.symbolize_keys.keys).any?
        raise ArgumentError.new("Plucker reflections '#{missing_reflections.to_sentence}', are missing in #{@records.klass}")
      end
    end
394771
async def add(self, *instances, using_db=None) -> None:
        
        if not instances:
            return
        if self.instance.id is None:
            raise OperationalError(
                "You should first call .save() on {model}".format(model=self.instance)
            )
        db = using_db if using_db else self.model._meta.db
        through_table = Table(self.field.through)
        select_query = (
            db.query_class.from_(through_table)
            .where(getattr(through_table, self.field.backward_key) == self.instance.id)
            .select(self.field.backward_key, self.field.forward_key)
        )
        query = db.query_class.into(through_table).columns(
            getattr(through_table, self.field.forward_key),
            getattr(through_table, self.field.backward_key),
        )

        if len(instances) == 1:
            criterion = getattr(through_table, self.field.forward_key) == instances[0].id
        else:
            criterion = getattr(through_table, self.field.forward_key).isin(
                [i.id for i in instances]
            )

        select_query = select_query.where(criterion)

        already_existing_relations_raw = await db.execute_query(str(select_query))
        already_existing_relations = {
            (r[self.field.backward_key], r[self.field.forward_key])
            for r in already_existing_relations_raw
        }

        insert_is_required = False
        for instance_to_add in instances:
            if instance_to_add.id is None:
                raise OperationalError(
                    "You should first call .save() on {model}".format(model=instance_to_add)
                )
            if (self.instance.id, instance_to_add.id) in already_existing_relations:
                continue
            query = query.insert(instance_to_add.id, self.instance.id)
            insert_is_required = True
        if insert_is_required:
            await db.execute_query(str(query))