简体   繁体   English

包含来自单独Ruby文件的命令

[英]Including commands from separate Ruby file

I have a chunk of code that has commands. 我有一大堆有命令的代码。 I want to keep more commands in a separate file and pull them into the main. 我想将更多命令保存在一个单独的文件中并将它们拉入主文件中。 Thus my main file can be updated without losing any custom commands. 因此,我的主文件可以更新,而不会丢失任何自定义命令。 How would I go about that? 我该怎么办呢?

{
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
}

The answe above will not work in this case because there is no listen_for methods defined in the custom.rb file 上面的answe在这种情况下不起作用,因为custom.rb文件中没有定义listen_for方法

wrap whatever you have in custom.rb in a module, like 在一个模块中包装custom.rb中的任何内容,比如

module Foo
  # commands
end

require your file custom.rb on the top of your script and include it in your class: 需要在脚本顶部使用您的文件custom.rb并将其包含在您的类中:

require_relative './custom.rb'

class myClass()
  include Foo
  # code here
end

This is the new try 这是新尝试

Remove the module wrapper in the listen_for commands, and instead simply list them in the custom.rb as you would do inside your main class definition. 在listen_for命令中删除module包装器,而不是像在主类定义中那样将它们列在custom.rb中。 And in your main class, Read and eval it, like this: 在您的主要课程中,阅读并评估它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM