【问题标题】:Including commands from separate Ruby file包括来自单独 Ruby 文件的命令
【发布时间】:2013-05-08 20:41:25
【问题描述】:

我有一段包含命令的代码。我想将更多命令保存在一个单独的文件中并将它们拉入主文件。因此,我的主文件可以更新而不会丢失任何自定义命令。我该怎么办?

{
class myClass()

#commands
listen_for /what is your name/i do

  say "my name is mud"

end

## Insert Custom.rb here ##
# Everything in the custom rb file is just ike the "listen_for" command above

end
}

【问题讨论】:

    标签: ruby siri


    【解决方案1】:

    上面的答案在这种情况下不起作用,因为 custom.rb 文件中没有定义 listen_for 方法

    将custom.rb 中的所有内容包装在一个模块中,例如

    module Foo
      # commands
    end
    

    在脚本顶部需要您的文件 custom.rb 并将其包含在您的课程中:

    require_relative './custom.rb'
    
    class myClass()
      include Foo
      # code here
    end
    

    这是新尝试

    删除listen_for 命令中的module 包装器,而只需将它们列在custom.rb 中,就像在主类定义中所做的那样。在您的主课中,阅读并评估它,如下所示:

    class myClass()
      eval(File.read('./custom.rb'))
      # code here
    end
    

    【讨论】:

    • 部分工作。当我在 custom.rb 文件中包含更多listen_for 命令时,我收到错误未定义方法“listen_for”
    • “包含更多listen_for”命令是什么意思?您能否编辑您的问题并包括您的文件的外观以及错误是什么?
    • 我的课和上面的一模一样。我正在使用 Siri 代理。 listen_for 是它接受的命令。这是主要的 siriproxy.rb 文件。我想要做的是让用户不要编辑这个文件。所以我希望用户将他们所有的“listen_for”命令放在一个单独的文件中并包含它。我已经将它包含在 fontanus 建议中。但是现在我在被拉入时遇到了未定义的方法“listen_for”。
    • 我明白了。编辑我的答案,看看。
    • 仍然获得 main:Object 的未定义方法“listen_for”
    猜你喜欢
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    相关资源
    最近更新 更多