Friday, 2 June 2017

Applied Rails : Gems I Use

In this article, I discuss key gems that I have used in my Rails application. For each gem, I state what it is used for, a brief description of how I used it and the code snippet(s) pertaining to my use case.

I use the devise gem for user authentication. It has 10 modules: Database Authenticatable, Omniauthable, Confirmable, Recoverable, Registerable, Rememberable, Trackable, Timeoutable, Validatable, and Lockable. The cool thing is you can use only the modules that you want.

I use the cancan gem for user authorization. All I had to do was run a simple command and override the initialize method in the User class.
In the following code snippet, users in role commercial_officer are allowed to execute the claimsForChecking action in the ExpensesClaim class. A caveat: cancan is no longer supported, and if you are starting afresh, you got to use cancancan.

I use the role_model gem to provide role based access. The cool thing about it is that you can control the roles by just altering a number in the database table. Let's say you have six roles: guest, executive, manager, sales, cxo, admin. Since it works on bit mask, each of the role gets the value of 2n where n ranges 0 to total number of roles minus 1. In the six roles I mentioned, guest gets 1 and admin gets 32. So if a CXO also has a sales role, give her record's roles_mask column a value of 8 + 16 = 24 in the database.

In the following code snippet, a user is given their role at the time of user creation. The set_roles_mask method takes the email used for registration, checks if the email is present in the Employees master table and if yes, sets the Users table roles_mask to the value in the Employees table. If the user is not an employee the user is given a roles_mask of 1 (guest). The checking code in the UI layer looks like the following code; here only some users (either in the CXO role or those in the Bulk_email_team) are given access to a particular menu item in the navigation bar. With the combination of devise, cancan and role_model you will have a robust production-ready security layer for your application, all with a few lines of code. Java developers who use Spring frameworks will be surprised at the level of functionality that we achieve with a few lines of code in Rails. This, despite Spring Boot.

I use the prawn gem for generating pdf documents. It provides most of the features I require. For bulleted text with proper alignment, I had to write a small function that prints asterisks in the first column. See an earlier blog post of mine[1] post for more details.

I use the prawn-table gem for displaying content in tables inside pdf documents.
In the following code snippet, I check whether there is enough space on the page to render the table. If not, I display the table on a new page. fiscali
I use the fiscali gem for date calculations based on fiscal year.

In the following code snippet, first the time zone is set to India. If the user did not enter a starting date, the beginning of the Indian financial year (1st April) is taken. If the user did not enter a end date, today's date is taken as the end date. Using the two dates, records created in the table between the start date and end date are fetched.

config/initializers/fiscali.rb Code in controller date_validator
Data entered by users in the browser screens (HTML forms) is validated in the model classes. the date_validator gem eases the validation of date rules.

In the following code snippet, I validate that a travel record should be in the past or on today. First I check that there is an end date, it is after or on the start date and it is today or before. The start date has to be in the past or on today. But the nice trick here is, there is no validation code for the travel start date because the two validation rules of the end date automatically take care of it. The Rails data validation approach is explained as: "Nothing to do with our application comes out of the database or gets stored into the database that doesn't get first go through the model. This makes models and ideal place to put validations: it doesn't matter whether the data comes from a form or from some programmatic manipulation in our application. If a model checks it before writing to the database, then the database will be protected from bad data."[2]

I use the wice_grid gem to filter tabular data. You can also sort the data.

The following code snippet displays Offers in a wice grid and allows user to filter on the customer name. It even pulls the associated records from the customer and employee tables. The simplicity of Rails is evident in the link_to 'view or edit' the offer entity. paperclip
I use paperclip gem for attaching uploaded files to a particular entity. The use cases I have tackled using this gem are: 1) Allow the user too select from a pre-loaded set of documents. 2) Allow the user to upload any random file. Code snippets for these use cases are given below: Kaminari
I use the Kaminari gem when I have to display paginated data.

The following code snippet shows employee records in a paginated HTML table. axlsx_rails
I use the axlsx_rails gem to generate Microsoft Excel files. The following code snippet generates a xlsx file of customer, their location and contacts at each location. The header row having cells with blue fill. custom_error_message
I use the custom_error_message gem for customizing my error message not to have the attribute name prefixed.

This plugin uses the carat (^) to omit the name of the attribute from error messages. Here's an example: select2-rails
I use the select2-rails gem for selecting entries in ajax style from a drop-down. The following code shows how users select employee email ids from a select drop down and they get shortened list with each letter they enter. The extraordinary simplicity of Ruby and the amazing functionality offered by its gems make working with Ruby on Rails a pleasure. To quote David Hansson, the creator of Ruby on Rails[3]:
...two basic tenets of Rails appeal in 2017: 1) We have a unique ideological foundation that’s still controversial today and offers the same benefits against the mainstream choices as it did 13 years ago, 2) We have a pragmatic, full-stack answer that could be formulated based on that ideology that still offers amazing productivity from the second you run the rails new command.
Oh, and on top of all that, I’ve saved the cherry for last. You get to use Ruby, which, even in a world that has rediscovered the benefits of functional programming and immutability, remains the most extraordinarily beautiful and luxurious language I’ve yet to encounter. Just look at some code. I dare you not to fall in love.
[2] Agile Web Development with Rails4 by Sam Ruby, Dave Thomas, David Heinemeier Hansson. 2013, The Pragmatic Programmers, LLC.


  1. This blog post has been republished by dzone. Please see

  2. myTectra Placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance

  3. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    Data science Course Training in Chennai |Best Data Science Training Institute in Chennai