From: Aaron Patterson Date: 2013-08-16T21:13:07-07:00 Subject: [ruby-core:56674] Re: [ruby-trunk - Feature #8781] Use require_relative() instead of require() if possible On Sat, Aug 17, 2013 at 07:17:50AM +0900, trans (Thomas Sawyer) wrote: > > Issue #8781 has been updated by trans (Thomas Sawyer). > > > > $ echo "require_relative '../../foo'" > lib/foo/bar/baz.rb > > Seriously? That is not a real use case. Proper use of require_relative is downward, not upward. *sigh* First, it *is* a real use case (as in, people actually use it in *real* projects): [aaron@higgins ruby (trunk)]$ git grep require_relative | grep '\.\.' | wc -l 45 [aaron@higgins ruby (trunk)]$ If Ruby's source code isn't enough examples for you, try a GitHub seach: https://github.com/search?q=require_relative+..&type=Code&ref=searchresults It's not up to you what is "proper" use. Second, my point remains valid whether you go down or up. Let's do another example. "foo.rb" depends on "foo/bar/baz.rb". $ mkdir -p lib/foo/bar $ touch lib/foo/bar/baz.rb $ echo "require_relative 'foo/bar/baz'" > lib/foo.rb $ ruby -I lib -rfoo -e 0 $ mv lib/foo.rb lib/foo/ $ ruby -I lib -rfoo/foo -e 0 /Users/aaron/git/example/lib/foo/foo.rb:1:in `require_relative': cannot load such file -- /Users/aaron/git/example/lib/foo/foo/bar/baz (LoadError) from /Users/aaron/git/example/lib/foo/foo.rb:1:in `' from /Users/aaron/.rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require' from /Users/aaron/.rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require' $ If we move "foo.rb", we still have to change the call to "require_relative" **even though the file we depend on did not change**. Here is the same example just using `require`: $ mkdir -p lib/foo/bar $ echo "require 'foo/bar/baz'" > lib/foo.rb $ touch lib/foo/bar/baz.rb $ ruby -I lib -rfoo -e 0 $ mv lib/foo.rb lib/foo/ $ ruby -I lib -rfoo/foo -e 0 $ Again, "foo.rb" is completely independent of the filesystem. The files it depends on did not change, so it did not have to change. I am uncertain how to make the coupling between "require_relative" and the filesystem more clear than this. -- Aaron Patterson http://tenderlovemaking.com/