takes a descendant of ActiveRecord::Base
 builds the lines to be put into the top of the file
173935
def build
      results = [%w[Field Type Null Default]]
      @klass.columns_hash.each do |name, column|
        default = case column.default
        when NilClass then ''
        when TrueClass then '1'
        when FalseClass then '0'
        else column.default
        end
        results << [name, column.sql_type, column.null ? 'YES' : 'NO', default]
      end
      lengths = results.transpose.map { |list| list.max_by { |segment| segment.to_s.length }.length + 1 }
      
      definition = results.map do |line|
        '# ' + line.map.with_index { |segment, index| "| %-#{lengths[index]}s" % segment }.join + "|\n"
      end
      header_line = '# ' + lengths.map { |length| '+' + '-' * (length + 1) }.join + "+\n"
      [header_line, definition.first, header_line] + definition[1..-1] + [header_line]
    end
209086
def stack(me, children)
      children = children.map{|c| c.is_a?(::Layers::LayerBase) ? c.to_node([]) : c}
      me.to_node(children)
    end
1092288
def load_database
      if dir_exists?
        config = {
          'adapter' => 'sqlite3',
          'database' => File.join(config_dir, DATABASE_FILE),
          'pool' => 5,
          'timeout' => 5000
        }

        begin
          ActiveRecord::Base.establish_connection(config)
          ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), \
            '../../db/migrate'), ENV['VERSION'] ? ENV['VERSION'].to_i : nil )

        rescue StandardError => e
          raise DatabaseAccessError, e.message
        end
      else
        raise ConfigDirMissingError, 'Config dir missing. Run init command'
      end
    end
784049
function flattenRecord(record) {
    var data = {
        __internal: {
            id: record.id,
            type: record.type,
        },
    };
    objectForEach(record.attributes, function (key) {
        data[key] = record.attributes[key];
    });
    objectForEach(record.relationships, function (key) {
        var rel = record.relationships[key];
        if (rel.meta) {
            data[key + "Meta"] = rel.meta;
        }
        if (rel.links) {
            data.__internal.relationships = data.__internal.relationships || {};
            data.__internal.relationships[key] = rel.links;
        }
    });
    objectForEach(record.links, function (key) {
        /* istanbul ignore else */
        if (record.links[key]) {
            data.__internal.links = data.__internal.links || {};
            data.__internal.links[key] = record.links[key];
        }
    });
    objectForEach(record.meta, function (key) {
        /* istanbul ignore else */
        if (record.meta[key] !== undefined) {
            data.__internal.meta = data.__internal.meta || {};
            data.__internal.meta[key] = record.meta[key];
        }
    });
    return data;
}
801386
def pbt_top_parent
      record = self
      return nil unless record.pbt_parent
      no_repeat = PolyBelongsTo::SingletonSet.new
      while !no_repeat.include?(record.pbt_parent) && !record.pbt_parent.nil?
        no_repeat.add?(record)
        record = record.pbt_parent
      end
      record
    end
1173573
def snap
      serialize_attribute = lambda do |attribute| 
        # If a proc, do nothing, cannot be serialized
        # XXX: raise warning on passing in a proc?
        if attribute.is_a? Proc
          # noop
         
        # Is an ActiveRecord, serialize as hash instead of serializing the object
        elsif attribute.class.ancestors.include?(ActiveRecord::Base)            
          attribute.serializable_hash

        # If an array, such as from an association, serialize the elements in the array
        elsif attribute.is_a?(Array) || attribute.is_a?(ActiveRecord::Associations::CollectionProxy)
          attribute.map { |element| serialize_attribute.call(element) }

        # otherwise, return val
        else
          attribute
        end
      end

      {}.tap do |s|
        self.class.audited_attributes.each do |attr|
          val = self.send attr
          s[attr.to_s] = serialize_attribute.call(val)
        end
      end
    end
1248386
def models(parent = nil)
      model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"]
      model_paths.each{ |path| require path }
      sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') }
      model_constants = sanitized_model_paths.map do |path|
        path.split('/').map { |token| token.camelize }.join('::').constantize
      end
      model_constants.select { |model| superclasses(model).include?(::Ohm::Model) }

      if parent
        model_constants.select { |model| model.included_modules.include?(parent) }
      else
        model_constants
      end
    end
1176483
def build_results

      # Now we uinq the attributes
      @attributes_to_pluck.uniq!{|f| f[:name] }

      # Obtain both the names and SQL columns
      names_to_pluck = @attributes_to_pluck.map{|f| f[:name] }
      sql_to_pluck = @attributes_to_pluck.map{|f| f[:sql] }


      # And perform the real ActiveRecord pluck.
      pluck_records(sql_to_pluck).each_with_index do |record, index|
        # After the pluck we have to create the hash for each record.

        # If there's only a field we will not receive an array. But we need it
        # so we built it.
        record = [record] unless record.is_a? Array
        # Now we zip it with the attribute names and create a hash. If we have
        # have a record: [1, "Test title 1", "Test text 1"] and the
        # names_to_pluck are [:id, :title, :text] we will end with {:id=>1,
        # :title=>"Test title 1", :text=>"Test text 1"}
        attributes_to_return = Hash[names_to_pluck.zip(record)]

        # Now we store it in the results hash
        @results[attributes_to_return[:id]] = attributes_to_return
      end
    end
1048668
def base
      base = Base.new

      type = @parser.graph.fetch("og:type", "website").downcase

      validate_type type

      @parser.graph.each do |property|
        build_property base, property
      end

      synthesize_required_properties base
      drop_empty_children base
      validate base

      base
    end
820785
def parse(code, file = '(ruby-lint)', line = 1)
      buffer        = ::Parser::Source::Buffer.new(file, line)
      buffer.source = code
      ast, comments = internal_parser.parse_with_comments(buffer)

      internal_parser.reset

      associated = associate_comments(ast, comments)

      return create_root_node(ast), associated
    end
907645
static QueryMeta buildCountSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        StringBuilder sqlBuf    = new StringBuilder("SELECT COUNT(*) FROM " + activeRecord.getTableName());
        int[]         pos       = {1};
        List<Object>  list      = parseWhere(activeRecord, pos, sqlBuf);

        List<Object> temp = andWhere(activeRecord, pos, sqlBuf);
        if (null != temp) {
            list.addAll(temp);
        }

        String   sql  = sqlFilter(sqlBuf.toString());
        Object[] args = list.toArray();
        queryMeta.setSql(sql);
        queryMeta.setParams(args);
        return queryMeta;
    }
807714
function(node, lines, parentName, depth) {

    // Default depth.
    if (_.isUndefined(depth)) {
      depth = 0;
    }

    // Default parentName.
    if (_.isUndefined(parentName)) {
      parentName = 'root';
    }

    if (isTask(node)) {

      // This is a task so add to lines and nothing further.
      lines.push({
        depth: depth,
        name: getName(node),
        parentName: parentName,
        description: node.description
      });

    } else if (isBranch(node)) {

      lines.push({
        depth: depth,
        name: getName(node),
        parentName: parentName
      });
      node.children.forEach(function(child) {
        recAdd(child, lines, getName(node), depth + 1);
      });

    } else {

      // This should never happen.
      assert(false);

    }

  }
541011
def descendant_get(desc_name)
      return self if desc_name == name || desc_name.nil?
      klass = descendants.find { |desc| desc.name == desc_name }
      raise ArgumentError, "#{desc_name} is not a descendant of #{name}" unless klass
      klass
    end
36170
def lookup_ancestors #:nodoc:
      klass = self
      classes = [klass]
      return classes if klass == ActiveRecord::Base

      while !klass.base_class?
        classes << klass = klass.superclass
      end
      classes
    end
57990
def add_file(filename, parent = @root_iter)
      my_path = File.dirname(filename)
      model.each do |model, path, iter|
        return if iter[id(:path)] == filename # duplicate
        parent = iter if iter[id(:path)] == my_path
      end
      fn = filename.gsub("\\", "/")
      parent[id(:empty)] = false unless parent.nil?
      child = add_row(parent)
      child[:pix] = @icons.get_icon(File.directory?(fn) ? "x.folder" : fn)   if @icons
      child[:file_name] = File.basename(fn)
      child[:path] = fn
      if File.directory?(fn)
        child[:sort_on] = "0" + child[:file_name]
        child[:empty] = true
        add_row(child) # dummy record so expander appears  
      else
        child[id(:sort_on)] = "1" + child[id(:file_name)]      
      end
      return child
    end
764589
def create_migrations
      Dir["#{self.class.source_root}/migrations/*.rb"].sort.each do |filepath|
        name = File.basename(filepath)
        template "migrations/#{name}", "db/migrate/#{name}"
        sleep 1
      end
    end
303183
def build_hash_tree(tree_scope)
      tree = ActiveSupport::OrderedHash.new
      id_to_hash = {}

      tree_scope.each do |ea|
        h = id_to_hash[ea.id] = ActiveSupport::OrderedHash.new
        (id_to_hash[ea._ct_parent_id] || tree)[ea] = h
      end
      tree
    end