简体   繁体   中英

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. The first file is Rails.root/lib/assets/myscript.rb , and the second is under Rails.root/resources/repo/lib/myotherscript.rb . How would I reference myotherscript in myscript ? 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.

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

EDIT: I've just realize that require works too if you specify the full path. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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