0

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.