Including commands from separate Ruby file

こ雲淡風輕ζ 提交于 2019-12-25 08:46:35

问题


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
}

回答1:


The answe above will not work in this case because there is no listen_for methods defined in the custom.rb file

wrap whatever you have in custom.rb in a module, like

module Foo
  # commands
end

require your file custom.rb on the top of your script and include it in your class:

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. And in your main class, Read and eval it, like this:

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


来源:https://stackoverflow.com/questions/16449815/including-commands-from-separate-ruby-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!