我有一个看起来像这样的课程:
class Base < Library
prelude "some-value" # from Library
def foo; ...; end
prelude "some-other-value" # from Library
def bar; ...; end
# ... others
end
我想将其重构为以下内容:
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
我该怎么做?
答案 0 :(得分:1)
您需要的是include
。您可能以前在模块中使用它,但它也可以在类中工作,因为Class继承自Ruby中的Module。将支持方法放在模块中,并将include
放在主类中。
至于prelude
类方法,只需在模块的included
方法中给出的对象上调用它。
<强> 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
修改:如果您需要散布对prelude
的调用和方法定义,您可能需要使用更像这样的内容:
module FooSupport
def self.included (klass)
klass.class_eval do
prelude "..."
def foo; "..." end
prelude "..."
def bar; "..." end
end
end
end