How can I refactor this simple Ruby snippet?
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开发者_如何学Go 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 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
加载中,请稍侯......
精彩评论