Examples of how to use require in Ruby _ruby special topics

Source: Internet
Author: User
Tags require

Files in the same directory, such as/USR/LOCAL/RUBY/FOO.RB and/usr/local/ruby/bar.rb two files.
If you are directly in the FOO.RB

Require ' bar '

A bar.rb error cannot be found at execution time.
This is because the running

/home/oldsong$ ruby/usr/local/ruby/foo.rb

The BAR.RB is found in the Lib directory and the/home/oldsong/directory where Ruby is installed. Instead of looking under the directory/usr/local/ruby/of the RB file.
So in addition to referencing system RB, a relative path cannot be used in require.

Here's a couple of ways to refer to all RB in a single and directory context, combined with my personal experience.
1. Reference a file

Example: referencing the current RB file_to_require.rb under the same directory
Introduce 3 methods First

Require File.join (__file_, '. /file_to_require ').
require File.expand_path ('.. /file_to_require ', __file__)
require file.dirname (__file__) + '/file_to_require '

Among them, File.expand_path is the common practice of rails.
__FILE__ is a constant that represents the absolute path of the current file, such as/home/oldsong/test.rb

Law four:

$LOAD _path.unshift (File.dirname (__file__))
require ' bar '

First add the directory to the Load_path variable, and then refer to the file name directly.
2. Refer to all files in a directory

Ruby does not have the import java.io.* in Java;
You cannot use wildcard characters when referencing, and it is estimated that future versions may be added.

Example: Refer to all *.rb files under lib/files under the same directory as current RB.
Law I:

Dir[file.dirname (__file__) + '/lib/*.rb '].each {|file| require File}

Law II:
A gem to fix

Https://rubygems.org/gems/require_all

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.