Is require File.expand_path(…, __FILE__) the best practice?

痞子三分冷 提交于 2019-11-29 20:20:22
the Tin Man

In Ruby 1.9.2 + require_relative is probably the more correct way to do it.

require was changed to not include your '.' directory for security reasons. require_relative was added to provide a local-file solution for modules relative to your calling script's path.

You can search here on StackOverflow, particularly in "What is require_relative in Ruby?", and the internets and find usage tricks and the why-for messages explaining how it came about.

Steve Benner

In Ruby 2.x you can use Kernel#__dir__

Unless you modify $LOAD_PATH, which would be a good idea if you keep loading from the same directory structure, you are stuck doing it that way.

The way I've taken to doing it, to ensure things are as cross-platform as possible, is this:

require File.expand_path(File.join(*%w[ ... ]), File.dirname(__FILE__))

It's a little verbose, but it results in the shortest possible path and the least amount of syntax fluff in most cases.

A more specific example would be:

require File.expand_path(File.join(*%w[ .. lib example ]), File.dirname(__FILE__))

You can combine this with a modification to $LOAD_PATH to simplify things if you're loading a lot of files and do this:

$LOAD_PATH << File.expand_path(File.join(*%w[ .. lib ]), File.dirname(__FILE__))

require 'example'
Ken Bloom

In Ruby 1.8.x, where you don't have require_relative in core, File.expand_path(...,__FILE__) won't work.

Suppose __FILE__ == "/home/yourname/foo.rb". File.expand_path("bar.rb",__FILE__) gives "/home/yourname/foo.rb/bar.rb.

What you want is File.expand_path("bar.rb",File.dirname(__FILE__)) which returns "/home/yourname/bar.rb"

You could also get require_relative from the backports gem.

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