Rails `eval' 中的 3.2.5:参数数量错误(2..3 为 0)(ArgumentError)

Rails 3.2.5 in `eval': wrong number of arguments (0 for 2..3) (ArgumentError)

我写了一个runner(保存在lib文件夹中)。启动跑步者时:rails 跑步者 lib/test.rb

 def aaa
     puts "aaa"
 end

 aaa

它转储: 在“eval”中:参数数量错误(2..3 为 0)(ArgumentError)

为什么?

rails 运行ner 旨在 运行 来自您的应用代码库的代码,如

(来自指南)

rails runner "Model.long_running_method" # parses the string and executes
                                         # the (hypothetical) method [long_running_method]
                                         # from (hypothetical) model [app/models/model.rb]

错误是由于您在调用中没有提供要计算的字符串

无论如何让它以这种方式工作(使用来自 lib 的函数)你应该

  • 将您的方法包含在一些 class 和
  • 使 class 在应用程序启动期间以某种方式需要它可用

!注意:如果你调用 rails runner 'MyClass.my_method' 你调用的是 class 必须正确定义的方法

def self.my_method
  # your code
end

如果你想调用一个实例方法你需要做rails runner 'MyClass.new.my_method'

综上所述,rails 运行ner 启动所有 rails 应用程序。

如果不需要,我可以建议调查 rake 任务是否适合您的需求吗?