Class Class
In: lib/facets/core-uncommon/facets/module/class_extend.rb
lib/facets/core-uncommon/facets/class/singleton.rb
lib/facets/core-uncommon/facets/class/preallocate.rb
Parent: Object

Methods

Public Instance methods

For Class, Module#class_extend is similar to class_eval.

The alternative is to "undef_method :class_extend", but this seems uneccessarily limited.

[Source]

# File lib/facets/core-uncommon/facets/module/class_extend.rb, line 77
  def class_extend(*mods, &block)
    class_extension = Module.new
    class_extension.__send__(:include, *mods)
    class_extension.module_eval(&block) if block
    extend(class_extension)
    class_extensions << class_extension
  end

Designate aspect modules to be added to a object at instantiation.

  class Firetruck
    def put_out_fire(option)
      "Put out #{option}"
    end
  end

  module FastFiretruck
    def put_out_fire(option)
      super("very #{option}!")
    end
  end

  Firetruck.preallocate(FastFiretruck)

  ft = Firetruck.new
  ft.put_out_fire('fast') #=> "Put out very fast!"

This method is very similar to the idea of prepend, but it has some limitations in that it works by overriding new and allocate and extends an object with the aspect modules on instantiation. A true prepend implementation would not have to do this —but would be a natural part of the class heirarchy instead. For this reason, this method has been named preallocate, rather than prepend.

NOTE: This is not (presently) a common core extension and is not loaded automatically when using require ‘facets‘.

CREDIT: Trans

[Source]

# File lib/facets/core-uncommon/facets/class/preallocate.rb, line 34
  def preallocate(aspect)
    _new      = method(:new)
    _allocate = method(:allocate)
    (class << self; self; end).class_eval do
      define_method(:new) do |*args|
        o = _new.call(*args)
        o.extend aspect
        o
      end
      define_method(:allocate) do |*args|
        o = _allocate.call(*args)
        o.extend aspect
        o
      end
    end
  end

[Source]

# File lib/facets/core-uncommon/facets/class/singleton.rb, line 4
  def singleton? 
    ! ancestors.include?( self ) rescue false 
  end

[Validate]