在Ruby中有条理地定义函数

Chr*_*rgh 5 ruby architecture

我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的较大程序的一部分,以及在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()
Run Code Online (Sandbox Code Playgroud)

这导致:

Testing nested functions defined
Command Line Version
Run Code Online (Sandbox Code Playgroud)

我从未遇到过在Ruby中有条件定义的函数.这样做安全吗?

这不是我构建大部分代码的方式,但是有一些函数需要每个系统完全重写.

saw*_*awa 7

我认为这不是一个干净的方式.

我的建议是在不同的模块中定义相同的方法集(具有不同的定义主体),并有条件地将相关模块包含在要调用方法的类/模块中.

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
Run Code Online (Sandbox Code Playgroud)

如果您每次运行只使用一种模式,并认为定义最终未使用的模块是浪费,那么您可以采取进一步措施; 在单独的文件中定义相应的模块(CLI,, SomeOtherMode...),并使用autoload.

autoload :CLI, "path/to/CLI"
autoload :SomeOtherMode, "path/to/SomeOtherMode"
Run Code Online (Sandbox Code Playgroud)