Ruby: require vs require_relative - best practice to workaround running in both Ruby <1>=1.9.2

后端 未结 11 1869
臣服心动
臣服心动 2020-11-27 08:50

What is the best practice if I want to require a relative file in Ruby and I want it to work in both 1.8.x and >=1.9.2?

I see a few options:

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 09:47

    Before I made the jump to 1.9.2 I used the following for relative requires:

    require File.expand_path('../relative/path', __FILE__)
    

    It's a bit weird the first time you see it, because it looks like there's an extra '..' at the start. The reason is that expand_path will expand a path relative to the second argument, and the second argument will be interpreted as if it were a directory. __FILE__ obviously isn't a directory, but that doesn't matter since expand_path doesn't care if the files exist or not, it will just apply some rules to expand things like .., . and ~. If you can get over the initial "waitaminute isn't there an extra .. there?" I think that the line above works quite well.

    Assuming that __FILE__ is /absolute/path/to/file.rb, what happens is that expand_path will construct the string /absolute/path/to/file.rb/../relative/path, and then apply a rule that says that .. should remove the path component before it (file.rb in this case), returning /absolute/path/to/relative/path.

    Is this best practice? Depends on what you mean by that, but it seems like it's all over the Rails code base, so I'd say it's at least a common enough idiom.

提交回复
热议问题