简体   繁体   中英

How do Ruby Gems Load in Rails?

Say I have a ruby gem that I want to use, but it's use is only needed in one model or controller.

Is there a way to load that gem exclusively for that one model or controller?

Would it be a waste of resources for it to be available systemwide (callable from any controller)

The answer posted is incorrect, it's perfectly possible to only load a gem for a particular model or controller. Your Gemfile allows you to define groups that Bundler can use to require certain gems. By default, any ungrouped gems along with the gems for the environment you are currently running in are required, and any named groups are not required. So if you had the following Gemfile:

gem 'always_used_gem', '1.0.0'

group :rarely_used do
  gem 'rarely_used_gem', '1.0.0'
end

Then rarely_used_gem would not be required on initial application load. If you had a particular method that needed that functionality, you could do this:

def do_stuff
  Bundler.require :rarely_used
  # use stuff from rarely_used_gem
end

One note: make sure the Bundler.require is inside a method call or something like that, or else the group will be required when the file is parsed (ie application boot)

In terms of whether you want to do this, it should really only be used for exceptional circumstances. You're trading boot speed for execution speed by doing this, which might make sense in development but probably doesn't in production. Also, you can use this method if you have some incompatibilities between two gems (we use this to resolve issues between a couple of AWS gems, for instance.)

No, it's not possible. Once a gem has been loaded it will be available for all controllers / models / everything. This should not be a primary concern for you. RAM and CPU time is cheap, programmer's time is not.

Bundler autoloads/-requires all gems, unless

#Gemfile
gem :somegem, :require => false

Then you can do require it when you need it

#some_ruby_file.rb
#within_some_context 
require 'somegem'

How useful it is and when to do this (except for when the load order is important, as for the mocha gem (needed to be loaded last)), I don't know. I leave this to your own judgement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM