Project

General

Profile

Actions

Feature #8781

closed

Use require_relative() instead of require() if possible

Added by ko1 (Koichi Sasada) over 10 years ago. Updated over 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:56569]

Description

I wrote a attached small script rrc.rb, stand for "RequireRelativeChecker".

This small script points out that require() can be replaced with require_relative().

"Detecting replace-able require()" algorithm is easy (and not perfect):
(1) If loaded file is at sub (or same) directory of requiring file.
(2) If requiring file foo.rb is at $LOAD_PATH, then check only foo/*.
See attached script for details.

This is a part of output.

/home/ko1/tmp/trunk/lib/ruby/2.1.0/cgi.rb:294: WARNING: Use require_relative() to require /home/ko1/tmp/trunk/lib/ruby/2.1.0/cgi/core.rb.
/home/ko1/tmp/trunk/lib/ruby/2.1.0/cgi.rb:295: WARNING: Use require_relative() to require /home/ko1/tmp/trunk/lib/ruby/2.1.0/cgi/cookie.rb.
/home/ko1/tmp/trunk/lib/ruby/2.1.0/date.rb:4: WARNING: Use require_relative() to require /home/ko1/tmp/trunk/lib/ruby/2.1.0/date/format.rb.
/home/ko1/tmp/trunk/lib/ruby/2.1.0/net/http.rb:1541: WARNING: Use require_relative() to require /home/ko1/tmp/trunk/lib/ruby/2.1.0/net/http/exceptions.rb.
/home/ko1/tmp/trunk/lib/ruby/2.1.0/net/http.rb:1543: WARNING: Use require_relative() to require /home/ko1/tmp/trunk/lib/ruby/2.1.0/net/http/header.rb.
/home/ko1/tmp/trunk/lib/ruby/2.1.0/net/http.rb:1545: WARNING: Use require_relative() to require /home/ko1/tmp/trunk/lib/ruby/2.1.0/net/http/generic_request.rb.

(all of warnings are attached)

How about to replace require() with require_relative() if it is possible?

Advantage:

  • require_relative() is faster than require() especially with many gems.
  • Easy to detect which file is loaded.

Disadvantage (incompatibility)

  • We can't replace loading file with $LOAD_PATH trick.
    (But I believe nobody expect such behavior)

(I also recommend other gem authors to use require_relative)

Any comments?


Files

rrc.rb (841 Bytes) rrc.rb ko1 (Koichi Sasada), 08/12/2013 03:35 PM
log (145 KB) log ko1 (Koichi Sasada), 08/12/2013 03:35 PM

Related issues 2 (0 open2 closed)

Related to Ruby master - Feature #12973: [RFC] net/http: use require_relative to reduce syscallsClosednormalperson (Eric Wong)Actions
Has duplicate Ruby master - Bug #15206: require_relative in std_libClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0