gpt4 book ai didi

ruby - 命名空间和混合

转载 作者:行者123 更新时间:2023-12-04 17:00:48 27 4
gpt4 key购买 nike

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

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 '<<prefix>> 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 m.m #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 )。此外,您会得到一个类似于前缀的方法。此方法将调用转发到原始模块方法。请参阅代码末尾的示例。

关于ruby - 命名空间和混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7574445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com