Module#refine
method takes a class and a block and returns a refinement module, so I thought I could define:
class Class
def include_refined(klass)
_refinement = Module.new do
include refine(klass) {
yield if block_given?
}
end
self.send :include, _refinement
end
end
and the following test passes
class Base
def foo
"foo"
end
end
class Receiver
include_refined(Base) {
def foo
"refined " + super
end
}
end
describe Receiver do
it { should respond_to(:foo) }
its(:foo) { should eq("refined foo") }
end
So, using refinements, I can turn a class into a module, refine its behaviour on the fly, and include it in other classes.
- Is there a simpler way to turn a class into a module in Ruby (say in ruby < 2)?
In the C-implementation of rb_mod_refine we see
refinement = rb_module_new(); RCLASS_SET_SUPER(refinement, klass);
Is this just setting the superclass of refinement to
klass
that copies the implementation of the class inside the refinement module?- I am aware that multiple inheritance IS
done via Modules, but what would the community think of the above
Class#include_refined
? Would it be reasonable to extract this aspect out of refinements? "Locally" patching inside a Class instead of using "using" switches to activate refinements?
ApplicationController
. Take Tolk::LocalesController for instance. – Sorrows