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:
Then
rarely_used_gemwould not be required on initial application load. If you had a particular method that needed that functionality, you could do this: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 (i.e. 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.)