[Nitro] Better than classinherit.rb!

itsme213 itsme213 at hotmail.com
Mon Apr 10 22:20:49 EDT 2006


Nice!

A couple of questions:
- Breaks if mod is enhanced with singleton methods after interlusion?
- Do you know any hooks that would enable the inverse operation: R.is_not(M)

There are advantages to your older ClassMethods (and less so 
InstanceMethods) convention, since they require a module holding methods 
uniformly for either classes or 'other' objects. I have been doing the 
following. Could probably be simplified further by someone more expert than 
I ...

class Module
 # TODO: no need for InstanceMethods sub-module
 # just define module methods directly.
 def inherit *others
  others.each do |other|
   [:ClassMethods, :InstanceMethods].each do |sub_mod|
    if other.const_defined? sub_mod
     if self.const_defined? sub_mod
      self.const_get(sub_mod).send(:include, other.const_get(sub_mod))
     else
      sm = Module.new
      self.const_set sub_mod, other.const_get(sub_mod)
     end
    end
   end
   include other
  end
 end
end

class Class
 def inherit *others
  others.each do |other|
   extend other::ClassMethods if defined? other::ClassMethods
   include other::InstanceMethods if defined? other::InstanceMethods
   super
  end
 end
end

if __FILE__ == $0
 class Object
  def assert x
   raise "Failed" unless x
  end
 end

 module A
  module ClassMethods
   def cm1
   end
  end
  module InstanceMethods
   def im1
   end
  end
  CONST = 0
  def m1
  end
  # def self.m2
  # end
 end

 assert A::ClassMethods.instance_method(:cm1)
 assert A.instance_method(:m1)

 module A1
  module ClassMethods
   def cma1
   end
  end
 end

 module B
  inherit A
  assert B::ClassMethods
  assert B::InstanceMethods
  assert defined? B::CONST
  assert B::instance_method(:m1)
  module ClassMethods
   def cm2
   end
  end
  assert B::ClassMethods.instance_method(:cm1)
  assert B::ClassMethods.instance_method(:cm2)
  module InstanceMethods
   def im2
   end
  end
  inherit A1
  assert B::ClassMethods.instance_method(:cma1)
 end

 assert B::InstanceMethods.instance_method(:im1)
 assert B::InstanceMethods.instance_method(:im2)

 class X
  inherit B
  assert X.method(:cm1)
  assert X.instance_method(:im1)
  assert X.instance_method(:m1)
 end

end





More information about the Nitro-general mailing list