Ruby 根据选项调用方法(重构的最佳方式)
我有一个函数,其中我传递一个字符串和一个将其用作regexp的选项Ruby 根据选项调用方法(重构的最佳方式),ruby,refactoring,Ruby,Refactoring,我有一个函数,其中我传递一个字符串和一个将其用作regexp的选项 def regexp_this?(string, arg1, arg2, regx = false) if regx method1 %r{#{string}:someconstantstring} method2 %r{#{string}:someconstantstring:#{arg1}} method3 %r{#{string}:someconstantstring:#{arg1}:anoth
def regexp_this?(string, arg1, arg2, regx = false)
if regx
method1 %r{#{string}:someconstantstring}
method2 %r{#{string}:someconstantstring:#{arg1}}
method3 %r{#{string}:someconstantstring:#{arg1}:anotherconstant:#{#arg2}}
else
method1 "#{string}:someconstantstring"
method2 "#{string}:someconstantstring:#{arg1}"
method3 "#{string}:someconstantstring:#{arg1}:anotherconstant:#{#arg2}"
end
end
method1
、method2
和method3
是使片段过期的调用。我正在根据页面的当前状态构建缓存。如果arg1或arg2已声明或未声明,则我有不同的缓存密钥,需要使其过期
有办法重构吗?对于一个方法,您有多个职责,请将它们分开并适当命名。一个方法中有一个正则表达式验证、多个参数和多个方法。我建议您阅读。对于有条件的,您至少应该能够执行以下操作:
def regexp_this?(string, arg1, arg2, regx = false)
# Select whether you want a String or Regexp parameter.
argument_klass = (regx ? Regexp : String)
method1 argument_klass.new("#{string}: ...")
method2 argument_klass.new("#{string}: ...")
method3 argument_klass.new("#{string}: ...")
end
我想你已经有条件了。谢谢你,安德鲁。修正了。哈哈,为什么这被否决了。我认为这是一个很好的答案。你需要告诉我
method1
、method2
和method3
是做什么的。您还应该弄清楚regex
是否是布尔标志。猜测这一点是额外的工作。它们实际上是对片段的调用。我正在根据页面的当前状态构建缓存。如果arg1或arg2已声明或未声明,则我有不同的缓存密钥,需要使其过期。