I have a class that looks like this:
class Base < Library
prelude "some-value" # from Library
def foo; ...; end
prelude "some-other-value" # from Library
def bar; ...; end
# ... others
end
I’d like to refactor it into something like the following:
class Base < Library
# what goes here to bring FooSupport and BarSupport in?
end
class FooSupport (< ... inherit from something?)
prelude "..." # Need a way to get Library prelude.
def foo; ...; end
end
class BarSupport (< ... inherit from something?)
prelude "..." # Need a way to get Library prelude.
def bar; ...; end
end
How can I do that?
What you need is
include. You may have used it before in modules, but it works in classes too, since Class inherits from Module in Ruby. Place your support methods in a module andincludethem in your main class.As for the
preludeclass method, simply call that on the object you’re given in the module’sincludedmethod.base.rb:
foo.rb:
Edit: If you need to intersperse calls to
preludeand method definitions, you may need to use something more like this: