Reputation: 583
I noticed for some gems you must include it in the file where you want to use it like this require 'a_gem'
, but this is not always the case.
I am going to compose a gem by myself. What should I do if I do not want to add the require 'my_gem'
to the .rb file when using it?
Upvotes: 5
Views: 2073
Reputation: 54213
This doesn't make sense. If you want to write a Gem and use it, it needs to be required somewhere.
This "somewhere" could be explicit in one of your scripts, it could be written in a Gemfile or it could be required by another script/gem that is required by your script.
If you write a gem, Ruby will not include it automatically in all your scripts.
Finally, if you publish it, should every single Ruby script on earth magically require it and execute your code?
I suppose that the project you have seen which didn't use require 'a_gem'
was using a Gemfile.
Upvotes: 0
Reputation: 107959
Usually, an application that is using a gem needs to require the gem:
require "my_awesome_gem"
MyAwesomeGem.do_something_great
However, if an application is using bundler, which defines the application's gem in a file called "Gemfile":
source 'http://rubygems.org'
gem 'my_awesome_gem'
then the application may invoke bundler in a way that automatically requires all of the gems specified in the Gemfile:
require "bundler"
Bundler.require
MyAwesomeGem.do_something_great
Rails projects use Bundler.require
, so a Rails application will not need to explicitly require a gem in order to use it: Just add the gem to the Gemfile and go.
For more about Bundler.require
, see the bundler documentation
For more about how Rails uses Bundler, see How Does Rails Handle Gems? by Justin Weiss.
Upvotes: 10