简体   繁体   English

Ruby:如何从完全独立的文件树中请求文件

[英]Ruby: How to require a file from a completely separate file tree

I have two separate paths for some Ruby scripts I want to reference in a Rails application. 对于要在Rails应用程序中引用的某些Ruby脚本,我有两个单独的路径。 The first file is Rails.root/lib/assets/myscript.rb , and the second is under Rails.root/resources/repo/lib/myotherscript.rb . 第一个文件是Rails.root/lib/assets/myscript.rb ,第二个文件在Rails.root/resources/repo/lib/myotherscript.rb How would I reference myotherscript in myscript ? 如何在myscript引用myotherscript I already know about requiring files from relative paths and such, but how would referencing be done from completely separate file trees? 我已经知道要从相对路径等中请求文件,但是如何从完全独立的文件树中进行引用呢?

As Stefan said. 正如斯特凡所说。
You could just use require_relative to load any file in any file tree. 您可以只使用require_relative加载任何文件树中的任何文件。

look: 看:

 $ cat /etc/hello.rb 
 module Hello
   def say_hello
     puts "Hello"
   end 
 end

============================== =============================

 $ cat /Users/amalrik/code/use_hello.rb 
 require_relative '/etc/hello'

 include Hello

 say_hello

============================== =============================

 $ ruby use_hello.rb 
 Hello

EDIT: Here you can take a look in an example of that in rails context and compare with your solution: https://github.com/amalrik/require_relative_on_rails 编辑:在这里您可以看一下在Rails上下文中的示例,并与您的解决方案进行比较: https : //github.com/amalrik/require_relative_on_rails

EDIT: I've just realize that require works too if you specify the full path. 编辑:我只是意识到,如果您指定完整路径,那么require也会起作用。 So i suggest double check your code for typos. 因此,我建议仔细检查您的代码是否有错别字。 Look: 看:

 $ cat /etc/hello.rb 
 module Hello
   def say_hello
     puts "Hello"
   end 
 end

============================== =============================

 $ cat /Users/amalrik/code/use_hello.rb 
 require '/etc/hello'

 include Hello

 say_hello

============================== =============================

 $ ruby use_hello.rb 
 Hello

For a more detail explanation of ruby load path i suggest this read: $: == $LOAD_PATH 有关ruby加载路径的更多详细说明,建议阅读: $:== $ LOAD_PATH

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

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