Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ruby gem works in a rails environment

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?

like image 566
I-am-batman Avatar asked Aug 28 '14 20:08

I-am-batman


People also ask

How does Ruby gem works?

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.

How does ruby on rails work?

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).

What is gem Ruby on Rails?

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.

How does gem install work?

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):


3 Answers

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)
like image 84
BroiSatse Avatar answered Oct 12 '22 13:10

BroiSatse


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.

like image 33
Holger Just Avatar answered Oct 12 '22 13:10

Holger Just


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.

like image 1
Vitaly Avatar answered Oct 12 '22 11:10

Vitaly