在 Ruby 中有条件地定义函数
Conditionally defining functions in Ruby
我有一些代码 运行 在几个不同的位置之一:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在rails环境。
有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:
print "Testing nested functions defined\n"
CLI = true
if CLI
def test_print
print "Command Line Version\n"
end
else
def test_print
print "Release Version\n"
end
end
test_print()
这导致:
Testing nested functions defined
Command Line Version
我从未遇到过 Ruby 中有条件定义的函数。这样做安全吗?
这不是我构建大部分代码的方式,但有一些函数需要针对每个系统进行完全重写。
它是元编程的一种形式,通常是安全的。真正的风险不是它是否会按预期工作,而是测试您创建的所有变体。
您在此处给出的示例无法执行替代版本。要正确使用这两种方法,您需要一种方法来强制注射其中一种方法。
我认为这不是一个干净的方法。
我的建议是在不同的模块中定义相同的方法集(具有不同的定义主体),并有条件地将相关模块包含到您要从中调用方法的class/module。
module CLI
def test_print
... # definition for CLI
end
end
module SomeOtherMode
def test_print
... # definition for some other mode
end
end
class Foo
include some_condition ? CLI : SomeOtherMode
end
Foo.new.test_print
如果你只打算每个运行只使用一种模式,并且认为定义最终没有被使用的模块是一种浪费,那么你可以更进一步;在单独的文件中定义相应的模块(CLI
、SomeOtherMode
、...),并使用 autoload
.
autoload :CLI, "path/to/CLI"
autoload :SomeOtherMode, "path/to/SomeOtherMode"
我有一些代码 运行 在几个不同的位置之一:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在rails环境。
有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:
print "Testing nested functions defined\n"
CLI = true
if CLI
def test_print
print "Command Line Version\n"
end
else
def test_print
print "Release Version\n"
end
end
test_print()
这导致:
Testing nested functions defined
Command Line Version
我从未遇到过 Ruby 中有条件定义的函数。这样做安全吗?
这不是我构建大部分代码的方式,但有一些函数需要针对每个系统进行完全重写。
它是元编程的一种形式,通常是安全的。真正的风险不是它是否会按预期工作,而是测试您创建的所有变体。
您在此处给出的示例无法执行替代版本。要正确使用这两种方法,您需要一种方法来强制注射其中一种方法。
我认为这不是一个干净的方法。
我的建议是在不同的模块中定义相同的方法集(具有不同的定义主体),并有条件地将相关模块包含到您要从中调用方法的class/module。
module CLI
def test_print
... # definition for CLI
end
end
module SomeOtherMode
def test_print
... # definition for some other mode
end
end
class Foo
include some_condition ? CLI : SomeOtherMode
end
Foo.new.test_print
如果你只打算每个运行只使用一种模式,并且认为定义最终没有被使用的模块是一种浪费,那么你可以更进一步;在单独的文件中定义相应的模块(CLI
、SomeOtherMode
、...),并使用 autoload
.
autoload :CLI, "path/to/CLI"
autoload :SomeOtherMode, "path/to/SomeOtherMode"