Format Mongoid class object.
------------------------------------------------------------------------------
165762
def awesome_mongoid_class(object)
      return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:fields)

      data = object.fields.sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
        hash[c[1].name.to_sym] = (c[1].type || 'undefined').to_s.underscore.intern
        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
1111596
def define_callbacks(klass)
      observer = self
      observer_name = observer.class.name.underscore.gsub('/', '__')
      Mongoid::Interceptable.observables.each do |callback|
        next unless respond_to?(callback)
        callback_meth = :"_notify_#{observer_name}_for_#{callback}"
        unless klass.respond_to?(callback_meth)
          klass.send(:define_method, callback_meth) do |&block|
            if value = observer.update(callback, self, &block)
              value
            else
              block.call if block
            end
          end
          klass.send(callback, callback_meth)
        end
      end
      self
    end
728977
def format_attributes(attributes)
      attributes.each do |k,v|
        attributes[k] = v.join(";") if v.is_a?(Array)
      end
      return attributes
    end
250291
def convert(cls, **kwargsql):
        
        filters = []
        for k, v in kwargsql.items():
            terms = k.split('__')
            if terms[-1] in cls.KWARGQL_SUPPORTED_MONGO_OPS:
                v = {
                    '$' + terms[-1]: v
                }
                if terms[-1] == 'exists':
                    v['$exists'] = bool(v['$exists'])
                terms = terms[:-1]
            elif terms[-1] in cls.KWARGSQL_REGEX_OPS:
                config = cls.KWARGSQL_REGEX_OPS[terms[-1]]
                pattern = '^{prefix}{pattern}{suffix}$'.format(
                    prefix=config.get('prefix', ''),
                    pattern=re.escape(v),
                    suffix=config.get('suffix', '')
                )
                v = {
                    '$regex': pattern,
                    '$options': config.get('options', ''),
                }
                terms = terms[:-1]
            k = '.'.join(terms)
            filters.append({k: v})
        if len(filters) == 0:
            return {}
        if len(filters) == 1:
            return filters[0]
        else:
            return {
                '$and': filters
            }
994580
public static function mongoID($mongoID)
    {
        if (empty($mongoID)) {
            return null;
        }

        if (!is_object($mongoID)) {
            //Old versions of mongo api does not throws exception on invalid mongo id (1.2.1)
            if (!is_string($mongoID) || !preg_match('/[0-9a-f]{24}/', $mongoID)) {
                return null;
            }

            try {
                $mongoID = new ObjectID($mongoID);
            } catch (\Exception $e) {
                return null;
            }
        }

        return $mongoID;
    }
268014
def format
      raise FormatError.new(self) unless formattable?

      REXML::Element.new(type).tap do |attribute|
        attribute.attributes["key"] = @key
        attribute.attributes["value"] = format_value
        meta.each {|m| attribute.elements << m.format if m.formattable?}
      end
    end
395492
function format(extensions) {
  return Object.keys(extensions)
    .map((extension) => {
      let configurations = extensions[extension];
      if (!Array.isArray(configurations)) configurations = [configurations];
      return configurations
        .map((params) => {
          return [extension]
            .concat(
              Object.keys(params).map((k) => {
                let values = params[k];
                if (!Array.isArray(values)) values = [values];
                return values
                  .map((v) => (v === true ? k : `${k}=${v}`))
                  .join('; ');
              })
            )
            .join('; ');
        })
        .join(', ');
    })
    .join(', ');
}
386091
function classOf (obj) {
  const class2type = {}
  'Boolean Number String Function Array Date RegExp Object tips'.split(' ')
  .forEach((e, i) => {
    class2type['[object ' + e + ']'] = e.toLowerCase()
  })
  if (obj == null) {
    return String(obj)
  }
  return typeof obj === 'object' || typeof obj === 'function'
    ? class2type[ class2type.toString.call(obj) ] || 'object'
    : typeof obj
}
170248
function (object) {
		if (!object || object._bsontype)
			return object;

		if (_.isString(object))
			return object.replace(/\./g, "U+FF0E").replace(/\$/g, "U+FF04");

		var newObject = _.isArray(object) ? [ ] : { };

		Object.keys(object).forEach(function (key) {
			var sKey = key;
			
			if (/[.|$]/.test(key)) {
				sKey = mongojs.util.sanitise(key);
				newObject[sKey] = object[key];
			} else {
				newObject[key] = object[key];
			}
			
			// Recurse
			if (isObject(newObject[sKey]))
				newObject[sKey] = this.sanitise(newObject[sKey]);
		}.bind(this));
		
		return newObject;
	}
1162630
def format_item(self, item):
        
        # http://jsonapi.org/format/#document-top-level
        # Primary data MUST be either... a single resource object, a single resource
        # identifier object, or null, for requests that target single resources
        if not item:
            return None

        ret = self.dict_class()
        ret[TYPE] = self.opts.type_

        # Get the schema attributes so we can confirm `dump-to` values exist
        attributes = {
            (get_dump_key(self.fields[field]) or field): field
            for field in self.fields
        }

        for field_name, value in iteritems(item):
            attribute = attributes[field_name]
            if attribute == ID:
                ret[ID] = value
            elif isinstance(self.fields[attribute], DocumentMeta):
                if not self.document_meta:
                    self.document_meta = self.dict_class()
                self.document_meta.update(value)
            elif isinstance(self.fields[attribute], ResourceMeta):
                if 'meta' not in ret:
                    ret['meta'] = self.dict_class()
                ret['meta'].update(value)
            elif isinstance(self.fields[attribute], BaseRelationship):
                if value:
                    if 'relationships' not in ret:
                        ret['relationships'] = self.dict_class()
                    ret['relationships'][self.inflect(field_name)] = value
            else:
                if 'attributes' not in ret:
                    ret['attributes'] = self.dict_class()
                ret['attributes'][self.inflect(field_name)] = value

        links = self.get_resource_links(item)
        if links:
            ret['links'] = links
        return ret
1351113
def format(options = {})
      options = options.dup
      o = {}
      o[k = :color] = (v = options.delete(k)).nil?? true : v
      raise ArgumentError, "Unknown option(s): #{options.inspect}" if not options.empty?

      require_valid

      Colorize.colorize *[
        (own?? [[:list_method, :own_marker], OWN_MARKER[0]] : [[:list_method, :not_own_marker], OWN_MARKER[1]]),
        [[:list_method, :obj_module_name], obj_module_name],
        ([[:list_method, :owner_name], "(#{owner_name})"] if not own?),
        [[:list_method, :access], access],
        [[:list_method, :name], method_name],
        ([[:list_method, :visibility], " [#{visibility}]"] if not public?),
        [[:reset]],
      ].compact.flatten(1).reject {|v| v.is_a? Array and not o[:color]}
    end
81821
protected function ensureMongoId($rawId)
    {
        if (is_array($rawId)) {
            $result = [];
            foreach ($rawId as $key => $value) {
                $result[$key] = $this->ensureMongoId($value);
            }

            return $result;
        } elseif (is_object($rawId)) {
            if ($rawId instanceof ObjectID) {
                return $rawId;
            } else {
                $rawId = (string) $rawId;
            }
        }
        try {
            $mongoId = new ObjectID($rawId);
        } catch (InvalidArgumentException $e) {
            // invalid id format
            $mongoId = $rawId;
        }

        return $mongoId;
    }
249066
function format(obj) {
  var parameters = obj.parameters
  var type = obj.type

  if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) {
    throw new TypeError('invalid type')
  }

  // start with normalized type
  var string = String(type).toLowerCase()

  // append parameters
  if (parameters && typeof parameters === 'object') {
    var param
    var params = Object.keys(parameters).sort()

    for (var i = 0; i < params.length; i++) {
      param = params[i]

      var val = param.substr(-1) === '*'
        ? ustring(parameters[param])
        : qstring(parameters[param])

      string += '; ' + param + '=' + val
    }
  }

  return string
}
1034150
function format(template, values) {
	return Object
		.entries(values)
		.filter(
			([key]) => /^[a-z0-9_-]+$/gi.test(key)
		)
		.map(
			([key, value]) =>
				[new RegExp(`([^{]|^){${key}}([^}]|$)`,'g'), `$1${value}$2`]
		)
		.reduce(
			(str, [regexp, replacement]) => {
				return str.replace(regexp, replacement)
			}, template
		)
		.replace(/({|}){2}/g, '$1')
}
1118366
final function onFormInitialized() {
		parent::onFormInitialized();
		$this->addClass('df-array');
		// 2015-12-29 It is an invisible template row.
		df_hide($this->field('template', $this->itemFormElement()));
		$itemId = 0; /** @var int $itemId */
		foreach ($this->v() as $key => $data) {
			/** @var string|int $key */ /** @var string|array(string => mixed) $data */
			/**
			 * 2016-07-30
			 * Раньше тут стоял код:
			 *	// 2015-12-30
			 *	// https://github.com/mage2pro/core/tree/b1f6809b7723d8426636bb892b852f408bdc5650/Framework/view/adminhtml/web/formElement/array/main.js#L131
			 *	if (\Df\Config\A::FAKE !== $key) {
			 *		$this->field($itemId++, $this->itemType(), null, $data);
			 *	}
			 * Теперь у нас ключ @see \Df\Config\A::FAKE удаляется в методе
			 * @see \Df\Config\Backend\ArrayT::processA()
			 * поэтому здесь его уже быть не должно.
			 */
			df_assert_ne(\Df\Config\A::FAKE, $key);
			$this->field($itemId++, $this->itemFormElement(), null, $data);
		}
		df_fe_init($this, __CLASS__, df_fa(), [], 'array');
	}
343594
def format
      rows = @children
      rows = @children[1..-1] if @skip_first_row
      rows ||= []
      rows = rows.collect { |row| row.format }.join("\n")

      return nil if rows.length == 0
      rows
    end
1176226
def _format_obj(self, item=None):
        
        # Order here matters, odd behavior with tuples
        if item is None:
            return getattr(self, 'number')(item)
        elif isinstance(item, self.str_):
            #: String
            return item + " "
        elif isinstance(item, bytes):
            #: Bytes
            return getattr(self, 'bytes')(item)
        elif isinstance(item, self.numeric_):
            #: Float, int, etc.
            return getattr(self, 'number')(item)
        elif isinstance(item, self.dict_):
            #: Dict
            return getattr(self, 'dict')(item)
        elif isinstance(item, self.list_):
            #: List
            return getattr(self, 'list')(item)
        elif isinstance(item, tuple):
            #: Tuple
            return getattr(self, 'tuple')(item)
        elif isinstance(item, types.GeneratorType):
            #: Generator
            return getattr(self, 'generator')(item)
        elif isinstance(item, self.set_):
            #: Set
            return getattr(self, 'set')(item)
        elif isinstance(item, deque):
            #: Deque
            return getattr(self, 'deque')(item)
        elif isinstance(item, Sequence):
            #: Sequence
            return getattr(self, 'sequence')(item)
        #: Any other object
        return getattr(self, 'object')(item)