命名空间和Mixins

我正在尝试清理我们的命名空间。 基本上我们的设置有点像

class myClass include myModule1 include myModule2 @important_var #critical instance variable 

基本上@important_var是一个telnet处理程序,几乎所有方法都需要它。 这适用于它现在设置的方式。 不幸的是myModule1和myModule2变得越来越大。 所以我继续遇到方法的命名空间冲突。

我喜欢用模块包装器访问方法,例如:

 myClass_instance.myModule1.a_method 

但我无法弄清楚如何做到这一点或其他更干净的名字间距的想法?

基于为模块内部方法构建命名约定的想法,我准备了一个自动化版本:

 module MyModule1 def m; "M1#m <#{@important_var }>"; end #method according naming convention def m1_action; "M1#m1 <#{@important_var }>"; end end module MyModule2 def m; "M2#m <#{@important_var }>"; end #method according naming convention def m2_action; "M2#m2 <#{@important_var }>"; end end class MyClass #add prefix to each method of the included module. def self.myinclude( mod, prefix ) include mod #alias each method with selected prefix mod.instance_methods.each{|meth| if meth.to_s[0..prefix.size-1] == prefix #ok, method follows naming convention else #store method as alias rename = "#{prefix}#{meth}".to_sym alias_method(rename, meth) puts "Wrong name for #{mod}##{meth} -> #{rename}" end } #define a method '<> to call the methods define_method(prefix){ |meth, *args, &block | send "#{prefix}#{meth}".to_sym *args, &block } end myinclude MyModule1, 'm1_' myinclude MyModule2, 'm2_' def initialize @important_var = 'important variable' #critical instance variable end end ################### puts "-------Test method calls--------" m = MyClass.new p m.m1_action p m.m2_action p mm #last include wins puts "Use renamed methods" p m.m1_m p m.m2_m puts "Use 'moduled' methods" p m.m1_(:m) p m.m2_(:m) 

myinclude包括模块和检查,如果每个方法都以定义的前缀开头。 如果不是,则定义方法(通过alias )。 此外,您将获得一个名为前缀的方法。 此方法将调用转发到原始模块方法。 请参阅代码末尾的示例。