2010-08-14 117 views
0

我有一個類,看起來像這樣:我該如何重構這個簡單的Ruby代碼片段?

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 

我怎樣才能做到這一點?

回答

1

你需要的是include。您可能以前在模塊中使用過它,但它也適用於類,因爲Class在Ruby中從Module繼承。將你的支持方法放在模塊中,並將它們放在你的主類中。

至於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 
+0

這工作!非常感謝你。 – 2010-08-14 14:57:04