2009-03-31 13 views

cevap

6

Sadece istediğiniz yöntemleri eklemek için temiz bir yol olup olmadığından emin değilsiniz, ancak istemediğiniz yöntemleri undef_method kullanarak kaldırabilirsiniz.

module Foo 
    def function1 
    end 

    def function2 
    end 

    def function3 
    end 
end 

module MiniFoo 
    include Foo 
    not_wanted_methods = Foo.instance_methods - %w(function1 function2) 
    not_wanted_methods.each {|m| undef_method m} 
end 

class Whatever 
    include MiniFoo 
end 
+0

Böyle bir şeyi aklıma aldım, ama belki daha temiz bir yol olduğunu düşündüm. – Geo

5

Benzer çözüm ancak biraz daha otomatik. Ne tür garip şeyler olsa da, hiçbir fikrim yok. Eğer modül için kaynak kodunu kontrol varsayarsak

module Foo 
    def m1 
    puts "Hello from m1" 
    end 

    def m2 
    puts "Hllo from m2" 
    end 
end 

class Module 
    alias :__include__ :include 
    def include(mod, *methods) 
    if methods.size > 0 
     tmp = mod.dup 
     new_mod = Object.const_set("Mod#{tmp.object_id}", tmp) 
     toremove = new_mod.instance_methods.reject { |m| methods.include? m.to_sym } 
     toremove.each { |m| new_mod.send(:undef_method, m) } 
     __include__(new_mod) 
    else 
     __include__(mod) 
    end 
    end 
end 

class Bar 
    include Foo 
end 

class Baz 
    include Foo, :m2 
end 

bar = Bar.new 
baz = Baz.new 
p bar.methods - Object.methods 
p baz.methods - Object.methods 

=> 

["m1", "m2"] 
["m2"] 
4

, ben en temiz yol daha, ah, modüler parçalara modülü bölmek olacağını düşünüyorum.

Yalnızca bir modülün bazı bölümlerini istiyorsanız, bu modülü daha az sorumluluğu olan çok sayıda modülde yeniden düzenleyebileceğinizi gösteren oldukça iyi bir işarettir.

İlgili konular