Sha256: ece1abd398db44f038f0cb789b81cbaf44f8d91462d4a872eb1d61409681b3e2

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

# = ClassMethods
#
# This allows all classes to be instantiated via methods of the same name,
# rather then having to use #new. Because these methods are capitalized,
# like their class couterpart, parenthesis are required.
#
# == Example
# 
#   require 'carat-dev/class_methods'
#
#   class AClass
#     include ClassMethods
#     def initialize(a)
#       @a = a
#     end
#   end
#
#   aobj = AClass(1)   # same as AClass.new(1)
#
#   class BClass < AClass
#   end
#
#   bobj = BClass(2)   # same as BClass.new(2)
#
module ClassMethods
  
  def self.included( klass )
    Object.instance_eval {
      define_method( klass.name ) do |*args|
        klass.new(*args)
      end
    }
    def klass.inherited( klass )
      Object.instance_eval {
        define_method( klass.name ) do |*args|
          klass.new(*args)
        end
      }
      super if defined? super
    end
  end
  
  def self.include_in_all
    Object.class_eval do
      include ClassMethods
    end
  end
  
end

### OLD CODE
# class Object
#   class << self
#     alias_method( :inherited_without_method_constructor , :inherited ) if respond_to?( :inherited )
#     def inherited( klass )
#       define_method( klass.name ) do |*args|
#         klass.new(*args)
#       end
#       inherited_without_method_constructor( klass ) if respond_to?( :inherited_without_method_constructor )
#     end
#   end
# end


# --- test ---

if $0 == __FILE__

  class AClass
    include ClassMethods
    def initialize(a)
      @a = a
    end
  end
  aobj = AClass(1)   # same as AClass.new(1)
  p aobj
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
carats-0.3.0 lib/carat-dev/class-constructor/constructor_methods.rb