Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

ruby - When do you need a require in a rails Gemfile?

In my gemfile I have things like:

gem 'net-sftp', '2.1.1', :require => 'net/sftp'
gem 'backup', '3.0.27'
gem 'watu_table_builder', :require => 'table_builder'
gem 'browser', '0.1.6'

When in a Gemfile do you need a require? I've also found things like :require => false. Help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you omit the :require option, by default Bundler will attempt to require the gem by using the standard name-to-file conversion rule:

dashes are considered namespace separators and underscore classname separators

It means that the following gem statements

gem 'net-sftp'
gem 'backup'
gem 'foo_bar'

are equivalent to

gem 'net-sftp', require: 'net/sftp'
gem 'backup', require: 'backup'
gem 'foo_bar', require: 'foo_bar'

This works well if the gem author has followed the standard conventions. But in some cases, for a variety of reasons, this doesn't happen.

For instance, there are gems called foo-bar where the main filename is /foo_bar.rb or even /foo.rb. In this case you provide the :require option to tell Bundler which file you want to require.

Finally, require: false is used when you want a gem to be part of the bundle, but you don't want Bundler to load it by default.

This is useful, for instance, to lazy-load a gem in case it is used only in certain circumstances. Think about a rake task that includes an heavy gem. You don't want your application to load it on boot, but it needs to be part of the bundle or it will not be found.

In this case you pass the option require: false. Then, in your rake task you will require it manually as usual

require 'library'

The library will be loaded only when the task is invoked, not in the normal application execution.

A good example is whenever. The library must be part of the bundler because it must be bundled when you deploy the app, but it is intended to be run as a command line script. For this reason, you don't want Bundler to require it when the Rails application is started.

There are cases where you use groups instead of require: false.

See also the official Bundler documentation for require.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...