Over a million developers have joined DZone.

10 Ruby on Rails Gems for Web Development

A list of great, useful plugins for Ruby on Rails web development including Capistrano and Foreigner.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

I have been programming on Ruby on Rails for many years and have solved a variety of rather complex tasks using this excellent framework. Based on my experience, I put together a short list of gems which I consider to be the most useful. In this article, I would like to share this list and show you how to find the helpful gems for RoR.

Unfortunately, the format of gemís specification does not include defining categories and tags. Thatís why, when searching for gems to do certain tasks, we may only hope that the author of the gem has mentioned some keywords in the description. You can find many gems on rubygems.org or github.com. The searching can be done by description (on GitHub, you also have to select Ruby from the list of languages).

Another thing worth being mentioned is the Ruby Toolbox. It allows searching for gems by categories and popularity. But do not rely only on this source because the author of Ruby Toolbox adds new gems manually.


This gem helps to create foreign keys for tables. It is very easy to use. You may simply put it to Gemfile and it will add two new methods to your migrations: add_foreign_key and remove_foreign_key. Also, you will be able to add/delete keys right from create_table and change_table with foreign_key and remove_foreign_key methods.

Letís imagine that we need to add a key from the comment table to the posts table. We can do it the next way:

class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
# … t.references :post
# ...
t.foreign_key :posts
# …

These methods have some extra options, e.g. name, column, dependent. You can read more about them in documentation.

Someone may say that it is not actual for new versions of Rails, but itís only starting from version 4.2 (where such functionality is already available out of the box). In all other cases, in my opinion, this gem deserves to be in the list of useful ones.

Link to GitHub


A simple but very helpful gem. In fact, it is a plug for saving emails in files instead of sending them. To activate this gem, you have to set letter_opener as the delivery method in the appís configuration (for example in config/enviroments/development.rb).

config.action_mailer.delivery_method = :letter_opener

Bingo! Now all outgoing messages will be stored in /tmp/letter_opener folder and new emails will be previewed in browser right after sending. It is easy and practical.

Link to GitHub.


This gem allows to easily create paginators of any complexity. Kaminari supports several ORMs (ActiveRecord, Mongoid, MongoMapper) and template engines (ERB, Haml, Slim).

Kaminari does not embed in basic classes: array, hash, Object and ActiveRecord::Base.

To start using Kaminari, it is enough to put it in Gemfile. After that some functions will become available, e.g. page, per and padding. Now you can effortlessly convert your array into a paginatable one with the help of Kaminari.paginate_array method and then lots of useful pagination features will become accessible.

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

The default configuration can be made in Kaminari.configure initializer. default_per_page, max_per_page, max_pages - this is just a brief list of options which can be set.

Besides, the pagination can be configured individually for each model:

class User < ActiveRecord::Base 
paginates_per 50

If you need to customize the paginator, you can create templates by running a generator:

% rails g kaminari:views default # -e haml - if you want to use  HAML template engine.

The templates will be created in app/views/kaminari/ and now you can easily edit them.

Localization (I18n) and labels, themes and friendly urls, as well as other useful options can be found in the documentation for this gem.

Link to GitHub.


With CarrierWave you are able to upload any files from your RoR application. All you need to do is:

Create an uploader:

rails generate uploader ProductPhotoUploader

Add some options:

class ProductPhotoUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick

storage :file

def store_dir

def extension_white_list
%w(jpg jpeg gif png)

def filename
Digest::SHA1.hexdigest(self.read) + File.extname(original_filename)

And you can already use uploader to save files in storage.

uploader = ProductPhotoUploader.new

CarrierWave also allows storing files in temporary storage, filesystem, and even in the cloud.

You can connect CarrierWave uploader to AR (there are adapters for other ORMs as well) model and save your files by saving a record in the database:

class Retailer < ActiveRecord::Base
mount_uploader :logo, RetailerLogoUploader

retailer = Retailer.new
File.open('logo.jpg') { |f| retailer.logo = f }
retailer.logo.url # => '/url/to/logo.png'

Also, it is possible to change the quality of an uploaded image, crop it, encrypt files and many more on the fly, while uploading them - all this can be found in the documentation.

Link to GitHub.


A simple and easy to use gem for converting diacritic strings to ASCII-safe URI strings. After installing this gem, you can call the urlify function for any string and it will immediately be converted to a URI-compatible equivalent.

URLify.urlify('Kj?le Test') #=> kjoele_test


URLify.urlify('Kj?le Test', '-') #=> kjoele-test

Link to GitHub.


It is a plugin for RoR, which helps to generate PDF from html. After adding this gem, you need to do the next steps:

Create the initializer:

rails generate wicked_pdf

Register mine-type:

Mime::Type.register "application/pdf", :pdf

Take into account that this gem uses wkhtmltopdf utility and the path to this utility should be specified in the gemís settings.

WickedPdf.config = { exe_path: '/usr/local/bin/wkhtmltopdf' }

Link to GitHub.


If you have faced with a task which requires having different information about countries, this gem will provide all data you need to solve it. There is a search by country name and by region, currency information (symbol, code), various formats of phone numbers, coordinates, etc. All that is needed after installing it is to create a country object (or get it from a global helper) and then you can draw the necessary information:

c = ISO3166::Country.new('UA')
# or to use global helper  = Country['UA']

c.name      #=> "Ukraine"
c.alpha2#=> "UK" c.alpha3#=> "UKR"
c.longitude #=> "49 00 N"
c.latitude  #=> "32 00 E"

And this is how to get information about the currency:

c.currency.code   #=> "UAH"
c.currency.symbol #=> "?"
c.currency.name   #=> "Hryvnia"

Or check whether the country is the EU member or not:

c.in_eu? #=> false

Here is an example of a search for a country by name and currency code:

c = ISO3166::Country.find_country_by_name('Ukraine') 
c = ISO3166::Country.find_country_by_currency('UAH')

Link to GitHub.


This library allows you to conveniently configure authorization in RoR. With its help you can easily restrict access to certain resources. Its convenience lies in the fact that managing permissions is set apart from the user and all permissions are stored in a single place. Thatís why you do not have to duplicate them in your controllers, views or database requests.

The library needs a current_user method to be defined in the controller. So, at first you have to configure authentication (this time I have used Devise, but there are other gems). Then, generate an ability:

rails g cancan:ability

Specify the user permissions (can/cannot methods) with the commands :read, :create, :update and :destroy (you can find more in documentation).

class Article::Ability  
  include CanCan::Ability
  def initialize(user)
case user   
  when Admin     
    cannot :manage, :profile     
    can :read, :all       
  when Moderator     
    can :manage, [Apartment, RoomPrice], { lessor_id: user.id }        
    can :manage, Photo, { photographer_id: user.id }     
    can :manage, Lessor, { id: user.id }     
    can :manage, :profile 

After that, in the views you can use can? and cannot? helpers to check current user's permissions for given actions:

<% if can? :update, @article %> <%= link_to "Edit", edit_article_path(@article) %> <% end %>

Also, you can use the authorize! method to authorize actions in the controller:

def show  
  @article = Article.find(params[:id])  
  authorize! :read, @article

Or you can use before filter load_and_authorize_resource which will load the resource and will try to authorize it.

To handle authorization errors you can catch an exception raised by CanCan::AccessDenied in the following way:

class ApplicationController < ActionController::Base 
rescue_from CanCan::AccessDenied do |exception| 
redirect_to root_url, :alert => exception.message 

Additional information can be found in the documentation on GitHub.

Link to GitHub.


This gem provides a great DSL, by means of which, you can very easily create beautiful, clearly readable and semantically rich forms. This DSL is very handy to use: just list the fields in a semantic_form_for block for the required object and you will get a nice form:

<%= semantic_form_for @post do |f| %> 
<%= f.inputs "Basic", :id => "basic" do %> 
<%= f.input :title %> 
<%= f.input :body %> 
<% end %> 
<%= f.inputs :name => "Advanced Options", :id => "advanced" do %> 
<%= f.input :slug, :label => "URL Title", :hint => "Created automatically if left blank", :required => false %> 
<%= f.input :section, :as => :radio %> 
<%= f.input :user, :label => "Author" %> 
<%= f.input :categories, :required => false %> 
<%= f.input :created_at, :as => :string, :label => "Publication Date", :required => false %> 
<% end %>
<%= f.actions do %>
<%= f.action :submit %> 
<% end %>
<% end %>

Here you can also work with nested resources:

<%= semantic_form_for [@author, @post] do |f| %>

Nested forms are provided too. You can use a f.semantic_form_for (usual Rails style) but the Formtastic style looks even more beautiful with the :for option.

<%= semantic_form_for @post do |f| %>
<%= f.inputs :title, :body, :created_at %> 
<%= f.inputs :first_name, :last_name, :for => :author, :name => "Author" %> 
<%= f.actions %>
<% end %>

You can easily change the behavior of the input:

class StringInput < Formtastic::Inputs::StringInput 
def to_html
puts "this is my modified version of StringInput"

Create your own input based on the existing one:

class FlexibleTextInput < Formtastic::Inputs::StringInput 
def input_html_options 
super.merge(:class => "flexible-text-area")

Or create a completely new input type:

class DatePickerInput 
include Formtastic::Inputs::Base
def to_html
# ...

Afterwards you can use it with:

 :as => :date_picker

Formtastic supports an impressive list of input types (select, check_boxes, radio, time_zone, datetime_select, range), basic and advanced localization, belongs_to, has_many and has_and_belongs_to_many associations and many other features, which you can learn from the documentation.

Link to GitHub.


This tool allows executing commands on multiple remote machines in parallel via SSH. This gem has an easy to use DSL. It enables you to define the tasks that will be applied to the machines with the certain roles. It also supports the tunnel connections through a gateway machine.

After turning on the gem, you have to execute:

bundle exec cap install

This creates folders with configurations.

If you are going to use different environments, you have to add a STAGES parameter, e.g.: STAGES = local, sandbox, qa, production.

To run a cap-script, use the command - bundle exec cap [environments separated by gaps] [command]. For instance, deploy for the staging environment will look like this:

bundle exec cap staging deploy

Capistrano DSL is borrowed from Rake. Below is a simple example of the task:

server 'example.com', roles: [:web, :app]
server 'example.org', roles: [:db, :workers]
desc "Report Uptimes"
task :uptime do 
on roles(:all) do |host|
execute :any_command, "with args", :here, "and here"
info "Host #{host} (#{host.roles.to_a.join(', ')}):\t#{capture(:uptime)}"

See the documentation for all possible parameters, more details about defining tasks, connecting the plug-ins and other things.

Link to GitHub.

Well, we reviewed ten most useful gems for Ruby on Rails and here my story comes to the end. Hopefully, you find this information helpful. Read more about using Ruby on Rails in ‘The eWay Payment Gateway Integration on Ruby on Rails’ written in collaboration with Evgeniy Maslov. Thank you and bye for now dear readers. 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

ruby ,rails ,gems ,web dev

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}