Nowadays, web developers are able to access ready-made solutions instead of writing the functions from scratch, which of course has great positive impact on the speed of development.
When we look at Ruby from this point of view, it stands out due to extensive libraries called Ruby gems. They offer particular functionalities to Ruby applications you build up. Suppose you want to have an authentication function in your program - you don't need to write one, you can get it in a form of a gem. And this is only one example among thousands of Ruby gems available for free.
In the present article, we are going to uncover top Ruby gems we use in web development at Codica, and what specific tasks each of them helps us carry out.
A Ruby gem: what’s behind it?
Each gem contains a particular element of functionality including any files related to this functionality. With Ruby gems, you can find a solution almost for any task, which will significantly cut the time you need for web development.
These libraries have their own storage called RubyGems, and a package manager - gem bundler. Both of them include tools to easily handle installation of gems and a server for their distribution. The first version of RubyGems was released in 2004.
A robust community is one of Ruby assets. The most proactive Ruby enthusiasts find solutions single-handed and implement them in code. Then they merge these libraries into open source, and that’s where the life of gems begins.
By the moment this article was created, the total gems number was over 148,782.
Such an amount of ready solutions removes the need of “reinventing the wheel” each time you face a challenge. Being in free access, many functions are already written, and they cover all the development aspects: from ensuring code quality to deployment.
Top Ruby gems that we use
We have prepared a list of cool Ruby gems, which is just a small part of all the gems helping us build great products.
One of the basic characteristics of the code is its quality and simplicity. It directly impacts the speed and performance of an application. To discover and remove bulky code blocks and to carry out refactoring properly, we use two libraries.
Rubocop is a tool for analyzing and formatting Ruby static code. Out of the box, it will enforce many of the guidelines outlined in the community Ruby Style Guide. RuboCop is extremely flexible and most aspects of its behaviour can be tweaked via various configuration options. Apart from reporting problems in your code, RuboCop can also automatically fix some issues for you.
Overcommit is a gem for configuring Git hooks. It is excellent for keeping the code quality high. It allows tuning git hooks for linters launch before every commit.
No matter how high the code quality is, sometimes bugs and errors are inevitable. To uncover and eliminate bugs, our team finds the following gems quite useful.
Better_errors is a gem to show errors. It displays helpful information about an error and has an excellent visual impact. Better_errors replaces the standard Rails error page. It is also applied outside Rails in any Rack app as Rack middleware.
Byebug is a simple to use and feature-rich debugger for Ruby. This gem allows line-by-line fulfilling of code, pausing between tasks and executing code, changing the variables on the move.
Subscribe to our monthly newsletter.
Web development process is impossible without quality control of the application created. Here comes testing, which allows you to assess the quality. To run and manage tests smoothly, our team uses the following utilities.
RSpec suggests Behaviour Driven Development for Ruby. The gem provides standards for Ruby on Rails apps testing. It offers more readable DSL, as compared to TestUnit standard testing library. Beyond that, it easily integrates with many other gems that facilitate the testing process.
You may find interesting our GitHub repo on RSpec best practices.
Capybara is an acceptance test framework for web applications. It flawlessly runs in tandem with RSpec. The gem is responsible for integrated tests that imitate users’ actions in a browser. It allows describing the authorization scenario in few lines (go on the homepage, enter a login and password, click the Log-in button), suggesting then various convenient methods for tests debugging.
Capybara Screenshot is a gem for automatic saving of screenshots if a Capybara scenario breaks down. Together with Capybara and Cucumber, RSpec or Minitest, the gem allows view the source code and takes a screenshot (when relevant) for each failure in a test suite. It stores HTML for the failed page, and a screenshot image (when using capybara-webkit, Selenium or poltergeist). Such an option is quite valuable when you need to find a problem in failing rounds.
Parallel_tests makes tests written in TestUnit, RSpec and Cucumber pass faster running them in parallel on multiple CPUs. To accelerate the process, the code uses all cores of the systems. It runs the test and uses additional test databases. The gem supports Rails and other Ruby frameworks.
Factory Bot is a library for setting up Ruby objects as test data. It has a straightforward definition syntax. The library maintains such multiple build strategies as saved instances, unsaved instances, attribute hashes, and stubbed objects. Also, it provides support for numerous factories for the same class (user, admin_user), including factory inheritance.
Chromedriver_helper provides easy installation and use of chromedriver. Above that, it serves as the Chromium project's selenium webdriver adapter. It installs an executable chromedriver-helper in a gem path, enabling Selenium to invoke it as the web driver. When required, the scenario will download the relevant binary for a platform and install it into ~/.chromedriver-helper, then execute it. Here, the gem allows particular projects even to select which version of chromedriver they want to run.
Shoulda Matchers is a gem providing simple one-liner tests for common Rails functionality which accelerates writing the tests for a typical capacity.
Simplecov is one of the useful gems for testing. It shows the percentage of code covered with unit-tests. Thus, the gem encourages developers to write 100%-tested code, which greatly adds to its quality.
Database Cleaner provides code coverage for Ruby 1.9+ with a powerful configuration library and automatic merging of coverage across test suites. It’s often applied in tandem with RSpec and is used to clean a testing database when launching tests. The gem enables tuning the time of the database cleanup: before the tests launching, before/after running each test.
RSpec::Retry is a tool that provides :retry randomly failing RSpec example. It adds a :retry option for occasionally failing RSpec patterns. If a model has the :retry option, RSpec will retry the example the particular number of times until the pattern works.
Faker is a library for generating demo data such as names, addresses, and phone numbers.
Deployment is an important stage of web development, and there’s one library that helps us run the process smoothly.
Mina is a fast deployer and server automation tool. Compared to Capistrano, which is a remote server automation tool, Mina works much quicker. It generates an entire procedure as a Bash script and runs it remotely in the server. In contrast to Capistrano, where each command is run separately on their own SSH sessions, Mina creates one SSH session per deploy. It minimizes the SSH connection workload.
By the way, at Codica we have built our own tool for Mina, which is called mina-multideploy. It allows deploying applications on several servers in parallel.
Check our GitHub repository on Mina Multi-deploy for more information.
Authentication and Authorization
Most of the web-solutions require an authentication and authorization system. Be it an e-commerce site or a publishing platform, users’ data protection always ranks first. To implement a secure solution, we use several gems.
Devise is a flexible authentication solution for Rails based on Warden. Devise helps build an identification system of any complexity level - from authentication via email and password to a referral system. In a nutshell, it has 10 modules, including:
- Confirmable: sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in;
- Recoverable: resets the user password and sends reset instructions;
- Rememberable: manages token generation and clearing to remember the user from a saved cookie;
- Trackable: tracks sign-in account, timestamps and IP address.
Ruby-JWT gem is a simple Ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard. As a tool for checking user's authentication, it’s considered to be one of the safest information transfer systems between two parties.
For practical application of this gem, check our article How We Built a Slack Bot for Time Tracking with Vue.js and Ruby on Rails, where we specify how we implemented JWT in this project.
In this scheme, an application server is configured to check whether an incoming JWT is the one generated with the authentication server.
CanCanCan is a super-convenient authorization gem. It allows creating and handling users’ roles and rules in apps, providing a set of helpers for views and controllers. Even ability.rb file in the model directory can contain an understandable and readable instruction with a description of rights for each users group. It smoothly interacts with gems providing users authentication.
OmniAuth is a flexible authentication system utilizing Rack middleware. It’s a library allowing to generate providers for authentication via social networks accounts like Google or Facebook. The library already contains an extensive list of ready-to-use providers.
Sometimes we need to build web applications that allow users to upload different kinds of files, like documentation or pictures. To make this feature as helpful and user-friendly as possible, we apply a few libraries.
Carrierwave is an excellent solution for file uploading and processing for Rails, Sinatra and other Ruby web frameworks. Carrierwave allows to create versions, add, remove and upload them from a remote location. Besides, it has testing and configuring options. Carrierwave gem works with AWS S3, and in such cases, it fits well with Fog gem, which integrates with a large variety of cloud servers, including Rackspace Servers, and Brightbox.
Carrierwave_backgrounder works with carrierwave. It allows moving image processing or compressing into the background. For now, it provides support for Delayed Job, Resque, Sidekiq, SuckerPunch, Girl Friday, Qu, and Queue Classic.
MiniMagick serves as a mini-replacement for RMagick. The gem allows reducing Ruby processes memory. It makes available all the command line options of ImageMagick.
You may also like: 5 Key Principles for a User-Friendly Website.
In some projects the amount of information is too big. In this case, finding the required data might be a challenge. To execute the search option as user-friendly as possible, we take advantage of one utility.
Elasticsearch is a popular search system widely used in enterprises. The gem integrates the Elasticsearch engine into Rails applications with its full set of features, including full-text search.
Related reading: How to Implement Elasticsearch When Developing a Rails Web App.
Building and supplying an extensive web application usually involves managing a vast amount of data. The following utilities help our team implement a comprehensive database administration tool.
Activeadmin is the administration framework for Ruby on Rails applications. The plugin allows generating administration style interfaces. It separates common business application patterns, drastically simplifying the implementation of elegant interfaces for developers.
Administrate is a Rails engine. It helps construct a user-responsive admin dashboard. For now, we haven’t used it yet, though we’re exploring its possibilities and looking forward to implementing it in our future projects.
More awesome gems for various tasks
And as a bonus, we’ll highlight for you extra gems that you may find interesting. We will list them according to their popularity (a number of stars on Github).
Sidekiq is a simple and efficient background processing tool for Ruby. It applies threads to manage many functions in the same process simultaneously. Although Sidekiq does not require Rails, it will closely combine with Rails to simplify background processing as much as possible.
Simple_form is a gem which adds a convenient DSL for forms construction on Rails. It's tied to a simple DSL, with no opinion on markup. Simple Form focuses on flexibility and assistance with effective parts for forms building. The primary purpose of Simple Form is to uphold the basic method of defining the layout, allowing developers to find the most visually pleasant code design. Most of the DSL was derived from Formtastic.
Friendly_Id provides great assistance when working with permalink plugins for ActiveRecord. It allows creating readable good-looking URLs and managing human-friendly strings as if they were digital ids for ActiveRecord models.
Dotenv-rails is a Ruby gem to load environment variables from a dotfile which can be outside the main project folder. This way, Dotenv allows safely storing the app configuration data.
Slim is a template language attempting to reduce the syntax to the essential code elements without becoming cryptic. It started as an exercise to see how much could be removed from a standard HTML template (<, >, closing tags, etc.). The more people showed interest for Slim, the more functionality grew along with the flexibility of the syntax.
Draper attaches an object-oriented layer of presentation logic to a Rails application. Draper helps deal with this functionality in the flow of procedural helpers or adding bulks to models. Draper decorators provide a more efficient way to wrap models with presentation-related logic to organize - and test - this layer of their app.
Redis is a BSD licensed Ruby-client open source library. It represents an in-memory data structure store. The gem is used as a database, cache and message broker. Redis provides support for data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. The gem includes built-in replication, Lua scripting, LRU eviction, transactions and several levels of on-disk persistence. Above that, Redis allows high availability via Redis Sentinel and automatic partitioning with Redis Cluster.
Annotate simplifies work with Rails models. It adds a comment summarizing the current scheme to the models' files. This feature makes code building much easier because there’s no need to check a scheme file every time.
Pg_search builds ActiveRecord named scopes when applying PostgreSQL full-text search. It is quite a decent alternative to Elasticsearch when using PostgreSQL. The utility is easy to configure. Besides, it allows implementing Autocomplete and Search by associations.
Wicked serves for building step-by-step pages (forms of object creation, etc.). Wicked accelerates and simplifies working with controllers.
Config provides the easiest way to combine multi-environment yaml settings with Rails, Sinatra, Pandrino and others of Ruby. It offers an attractive and easy solution for simple management of environment specific parameters.
I18n- tasks is a gem for working with translation in an app. It can be applied with any project that’s using the Ruby I18n gem which is default in Rails. It provides an interface for working with locales, helps find missing translations, normalize files with translations, and add new translations via Google translate API.
Money_rails is a great gem for working with currencies. It allows automating updates in currency rates and converting prices into the required currency.
Impressionist allows counting page views. Above that, it enables logging pageviews many times per request and attributing it to a model. Its purpose is to give customizable stats, making it instantly available in the application, in contrast to Google Analytics and pulling data with their API. Besides, Impressionist allows assigning custom messages to page views.
Route_translator is a tool to help administer the translations of app routes. It has a simple dictionary format. Initially, it was a fork of the translate_routes plugin but later transformed into a fully-fledged translation instrument.
Related reading: How We Created a Multi-site Setup for a Multi-Vendor Marketplace.
At Codica, we appreciate Ruby for all its features, such as focus, clarity, and excellent language readability, which is often considered as the human-like. Ruby gems greatly add up to Ruby advantages, as they bring in high development speed to any project type.
Of course, there are thousands of Ruby gems, and each of them has great value. Even with many years of experience in Ruby, we discover more and more useful Ruby gems and the opportunities they provide. There’s always room for improvement.
We hope our Ruby on Rails gems list will help you with your projects.