class AThe idea being we insert a superclass into the inheritance chain dynamically.
def something
.
.
end
end
class B
def someother
.
.
end
end
B.inherits_from(A)
After digging around a bit, I found this thread at the Ruby archives which says it isn't possible. The last mail on the thread demonstrates how to do it in Python, though :D. Here it is:
class Base(object):However, while that avenue is closed to us, we are still free to make use of
def meth(self):
print 'called B.meth'
class Mixin1(object):
def meth1(self):
print 'called meth1'
class Mixin2(object):
def meth2(self):
print 'called meth2'
class C(Base, Mixin1):
pass
c = C()
c.meth()
c.meth1()
C.__bases__ = (Base, Mixin2) # change the base classes (ick!)
print [methname for methname in dir(c) if methname.startswith('meth')]
c.meth()
c.meth2()
c.meth1() # this gives an error now
extend
and include
in combination with class_eval
to enhance a class and its instances respectively at runtime by adding modules - but removing the module after isn't possible. A quick example.First, let's create a module for us to extend.
module SneakThen let's meddle with some class, say String.
def sneak_me
return "snitch!"
end
end
String.class_eval{We can now do String.sneak_me - the methods of the module have been added as class methods (or static methods, if you prefer) by executing the code in that block in the context of the class. Sort of like having
extend Sneak
}
class Stringbut only at runtime.
extend Sneak
end
Now to change all instances of String.
str = String.new("!")So using
str.respond_to?("sneak_me") # -> check if str has this method. Returns false.
String.class_eval{
include Sneak
}
str.respond_to?("sneak_me") # -> Now returns true.
puts str.sneak_me # -> prints "snitch!"
include
and class_eval
we added a module to all instances of String, including str which we'd instantiated before actually including the module.You may also want to read: Object Oriented and Functional: Is there a middle ground?