views:

37

answers:

1

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?

+1  A: 

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 and include them in your main class.

As for the prelude class method, simply call that on the object you’re given in the module’s included method.

base.rb:

require "foo"
require "bar"

class Base < Library
  include FooSupport
  include BarSupport
end

foo.rb:

module FooSupport
  def self.included (klass)
    klass.prelude "..."
  end

  def foo; "..." end
end

Edit: If you need to intersperse calls to prelude and method definitions, you may need to use something more like this:

module FooSupport
  def self.included (klass)
    klass.class_eval do
      prelude "..."
      def foo; "..." end

      prelude "..."
      def bar; "..." end
    end
  end
end
Todd Yandell
This worked! Thank you very much.
Kyle Kaitan