I am trying to understand in rails
, how ruby gems
become available to used automatically without being required
in the files that are using the gems?
The RubyGems software allows you to easily download, install, and use ruby software packages on your system. The software package is called a “gem” which contains a packaged Ruby application or library. Gems can be used to extend or modify functionality in Ruby applications.
Rails uses Ruby to dynamically assemble HTML, CSS, and JavaScript files from component files (often adding content from a database). Why create a web application? A web browser needs only a single HTML file to display a web page (CSS and JavaScript files are optional).
Gems in Rails are libraries that allow any Ruby on Rails developer to add functionalities without writing code. You can also call Ruby on Rails gems as plugins for adding features. A Ruby gem enables adding features without creating the code again and again.
What does gem install do? gem install , in its simplest form, does something kind of like this. It grabs the gem and puts its files into a special directory on your system. You can see where gem install will install your gems if you run gem environment (look for the INSTALLATION DIRECTORY: line):
This is done through bundler/setup
: http://bundler.io/v1.3/bundler_setup.html. It is required inside your config/boot.rb
file. In short it firstly sets environmental variable to point to your Gemfile:
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
Then it adds paths for all your gems to LOAD_PATH, by requiring bundler/setup
:
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
Then it requires all the needed gems (config/application.rb):
Bundler.require(*Rails.groups)
Rails applications use bundler (that's the thing using the Gemfile
). When bundler loads the Gemfile
on startup of a rails application, it automatically requires all gems listed there, thus you don't have to do this yourself.
I recomend you to read "Crafting Rails 4 Applications: Expert Practices for Everyday Rails Development" Chapter 1. Creating Our Own Renderer:
Notice the gem has the same name as the file inside the lib directory, which is pdf_renderer . By following this convention, whenever you declare this gem in a Rails application’s Gemfile , the file at lib/pdf_renderer.rb will be automatically required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With