53 Best Ruby Gems We Use at RubyGarage
- 110580 views
- 16 min
- Feb 26, 2021
Here at RubyGarage we work closely with Ruby and Ruby on Rails technologies. We like Ruby for its resourcefulness and vibrant community, while Ruby on Rails is appreciated for its multiple ready-made solutions that allow for rapid software development.
Such rapidity is mainly achieved through using Ruby gems – libraries with specific functionalities that allow us to extend and customize our apps. In Ruby on Rails, there are gems for every purpose: from authentication and authorization, to payments processing and testing.
Check out our Ruby gems list that features the best libraries we regularly use in our projects – and recommend. Enjoy!
Active Record is the default ORM for Ruby on Rails. Though it offers rich functionality, some projects require custom solutions or additional features. We’ve picked out a few gems that extend Active Record’s functionality making it more powerful, flexible, and versatile.
Pagination – Try the pagy gem that is very modular, completely agnostic, and does not load any unnecessary code in your app. Its updated version is faster, lighter, simpler, and more efficient than other pagination gems.
Clone – If you need to create a copy of an Active Record object and its associations, check out the clowne. This is a flexible and easy-to-use tool that provides the ability to connect various ORM adapters.
Soft delete – To add conventions for flagging records as discarded, try discard, a simple ActiveRecord mixin. It doesn't override any ActiveRecord methods and provides convenience methods and scopes for hiding, restoring, and querying records.
Finite state machines – AASM, which replaces the acts_as_state_machine plugin, works with any Ruby object, including ActiveRecord. AASM adds finite state machines (sets of rules that dictate what an application or a device should do) to Ruby classes.
Versioning – For logging DB records changes, try logidze. The gem allows you to create a DB-level log, providing you with an API to browse this log. The log is stored with the record itself in JSONB column. No additional tables are required.
Internationalization – When translating your application into foreign languages, globalize, powered by I18n API, comes in handy. Globalize adds translations of your website’s content to ActiveRecord models, which is especially useful when you deal with the translation of non-static database content.
Encryption – To ensure security, we choose lockbox that provides modern encryption for Ruby and Rails. We like it because it has zero dependencies, many integrations, and makes migrating existing data easy. This gem works with database fields, files, and strings, maximizing compatibility with existing code and libraries.
If you’re going to write automated tests for your applications (which is integral to building RoR apps), there are several awesome Ruby gems that will come in handy. While working on our projects, we use RSpec, factory_bot, Capybara, shoulda-matchers, database_cleaner and simplecov to save time and effort.
We use RSpec – a framework mainly used in BDD and TDD environments – to create tests. Its syntax is neat and descriptive, which allows us to write tests (or specs) as closely as possible to “human” language. We also like RSpec because it’s an effective tool for testing the behavior of a model or a library.
Database_cleaner is often used with RSpec for cleaning up databases during tests. Database_cleaner provides you with the flexibility to configure when your database will be cleaned up: before tests are launched or both before and after each test. And if you face the problem of external requests during tests, you might want to find a solution like the VCR gem, which snatches all external requests with responses and records them to a file so you can “replay” them during testing.
In order to create test data, we use factory_bot. This is a gem with a straightforward definition syntax, support for multiple build strategies, and multiple factories for the same class.
We also use capybara, an acceptance testing library, which effectively automates a user’s interactions in a browser. With Capybara, we’re able to test clickthroughs, form completion (data entry fields, dropdown boxes, checkboxes), availability of items on a page, and more. Bundled with Poltergeist, a popular PhantomJS driver, Capybara provides us with the ability to run testing scenarios in a WebKit from the console.
For generating fake data such as names, addresses, and phone numbers, faker libraries can \help. Another useful gem is site_prism - a page Object Model DSL for Capybara. It gives you a simple, clean, and semantic DSL for describing your site.
Another gem, shoulda-matchers, lets us easily test typical Rails functionality such as validations and associations by writing compact one-line tests compatible with RSpec. In other words, shoulda-matchers offers matchers that help developers to test basic Rails functionality quickly and easily.
Lastly, the simplecov gem allows us to see the percentage of code covered by unit tests. This gem helps us to track how much code we’ve tested and strive for better results (though achieving 100% coverage is quite challenging).
Coding style is important. In order to write quality code, skillful Rubyists follow the best practices found in The Ruby Style Guide. But why do developers care so much about style? According to the Ruby Style Guide, well-written Ruby reads like a natural language and can be understood even by non-developers. Moreover, well-written code is easy to maintain, modify, and scale.
To assure code quality, developers apply gems that analyze their code and suggest improvements. Let’s see which gems our RubyGarage team prefers.
The rails_best_practices gem is a static code metric tool that analyzes code to find code smells: pieces of code that aren’t technically bugs but that may lead to software issues in the future. Rails_best_practices offers suggestions to improve your code – for example, suggesting the removal of tabs, annotation of models, or additional database indexes. You can share the analysis results with your collaborators and track your results over time to see how your code has improved.
Another code analyzer – with the menacing name RuboCop – assures that your code conforms to the Ruby Style Guide. Style guide freaks and geeks adore RuboCop since it leaves no chance for style violations – they’re reported right in the command line. Some developers find this pretty annoying, but you can configure RuboCop to show only the refactoring suggestions you want. The great thing about RuboCop is that it automatically fixes issues like line breaks, syntax, and the amount of gaps.
We also use lefthook to automatically support our clean code writing. This is a fast and powerful Git hooks manager for any type of projects. It features parallel execution, flexible list of files, gGlob, regexp filters and optional output.
Errors happen all the time when you’re writing code. Whether you make a typo or a gem doesn’t integrate properly, you get unpleasant results. To eliminate these issues, there are a few handy tools we use for debugging errors in Ruby code.
Pry-byebug is another tool we use, and it actually extends the functionality of the Pry and Byebug gems. With pry-byebug, you’re able to implement step-by-step code debugging by setting breakpoints. Pry-byebug allows you to set console (IRB or Rails console) break points so you can check how a piece of code is executed at a certain point.
Last but not least, we must mention the Letter Opener gem, which allows you to preview emails sent from an application straight in your browser’s tab. This is quite useful for applications that send emails (for example, notifications) to multiple users or in cases when you require a quick email preview. With Letter Opener, you don’t have to wait for an email to be delivered to your mailbox but you can quickly preview emails in your browser and make changes if necessary.
Authentication and Authorization
Whether you’re building a social network, an ecommerce solution, or nearly any other kind of application, you generally need to offer login functionality, which means you need to provide authentication and authorization. Some developers prefer to write their own user authentication and authorization solutions, but others use popular ready-to-go Ruby gems that save a whole bunch of time and effort.
It’s hard to find a Ruby developer who hasn’t heard about the Devise gem. It is a flexible authentication solution for Rails based on Warden that should be used together with activeadmin or for monolithic applications. This monstrous gem, based on the Rails MVC stack, adds OmniAuth support to verify users, resetting passwords, if necessary, and storing passwords in the database to simplify authentication. Moreover, Devise tracks metrics including IP addresses and timestamps, expires user sessions after a specified period of time, and locks accounts in case of multiple failed login attempts. Devise can do even more for you – check their GitHub page for more details.
Logging into websites using social accounts such as Facebook or LinkedIn is a regular practice that saves users’ time and nerves. As a rule, social logins in Rails applications are powered by the OmniAuth gem, which creates authentication providers (for social networks including Facebook, Google, and even GitHub), which are integrated into a Rails application. Easy as a pie!
If you need a flexible tool to build an authorization layer for your application, try action_policy. Being composable and extensible, it outperforms older solutions with similar functionality, such as Pundit and CanCanCan.
Another helpful library is Rolify, which allows you to establish and manage user roles – definitions of what users can do while using an application. For example, when building a marketplace like Airbnb, you’ll probably define two user roles: hosts, who provide their apartments for rent, and users, who rent apartments and receive a completely different set of functions. Rolify is also easily integrated with CanCanCan and Devise to extend their capabilities of user management.
Finally, for providing configurable, manageable, and safe stateful sessions based on JSON Web Tokens, try jwt_sessions. It is designed to be framework agnostic yet easily integrable, and Rails integration is available out of the box.
In a nutshell, APIs are sets of requirements for exchanging data between applications. You can log in to online stores with your Facebook account thanks to APIs or look for nearby restaurants on Foursquare via Google Maps – also thanks to APIs. Building APIs can sometimes be challenging, but in other cases only requires a few lines of code.
Thanks to many existing Ruby gems for APIs, you don’t have to reinvent the wheel. One great time saver is a gem called jsonapi-serializer - a fast JSON:API serializer for Ruby. It declares syntax similar to active model serializer and features optimized serialization of compound documents. You can also benefit from dox to automate the documentation writing process. This gem generates API documentation from Rspec controller/request specs in a Rails application.
When developing applications that store users’ personal information or financial details, it’s important to ensure data security.
Brakeman is a static security scanner that identifies vulnerabilities in Rails applications. While it may report vulnerabilities even if there aren’t any (since it’s static), you can easily configure a list of warnings in order not to receive unnecessary notifications. If you need to block abusive requests, try rack-attack.
In case you want to check your application’s gems for vulnerabilities, take a look at bundler-audit, which runs on top of Bundler. With bundler-audit you can sleep tight and save plenty of time not checking every single gem in your Rails application since the bundler-audit reviews your gemfile.lock for vulnerable gem versions and prevents unreliable gem fetching.
The gem which takes care of applying security-related HTTP headers to Rails application’s responses is Secure Headers. Secure Headers allows you to apply headers like CSP to prevent cross-site scripting and mixed-content attacks and XFO to prevent your content from potential clickjacking attacks.
If you build an ecommerce solution, you’ll definitely need to provide fast, secure, and convenient payment options.
Active Merchant is a library from the creators of Shopify that provides a centralized API to integrate with many popular payment gateways. This open-source library is well maintained by the Shopify team and currently supports 145 payment gateways available all around the globe.
At RubyGarage, we prefer to work with popular gateways like PayPal, Stripe, and Braintree. But even though Active Merchant handles Stripe and Braintree integration, we often use Braintree Ruby, stripe-ruby, and stripe_event in order to provide lightweight solutions for our applications. Since Active Merchant is a large library, which might slow down an application’s performance, it’s more effective to integrate several payment gateways and not to overload the app.
Quite often we build web applications that allow users to upload files of various kinds: documents, images, audio, and video. shrinerb/shrine: is a useful toolkit for handling file uploads in Ruby. It’s memory friendly, has a modular design and flexible processing.
When it comes to images, one of the most effective solutions available is image_processing. It provides higher-level helpers that are commonly needed when handling image uploads.
Scheduled and Recurring Jobs
Background jobs in Ruby applications are processed outside the normal request/response flow and are literally operations in a queue, executed one after another. Processing background jobs is critical for an application’s performance. To provide you with a vivid example, let’s imagine we build an application that sends an email to a user after they sign up. Obviously, an email should be delivered as fast as possible: we all hate to wait two or three seconds expecting a message to pop up in our mailbox. To speed things up, we need to leverage background jobs for operations like sending emails, importing data, calling third-party APIs, and resizing images.
For scheduled jobs the RubyGarage team employs the Sidekiq Redis-supported library that uses Redis as a job management store. This gem impresses developers with its multi-threading capabilities, resulting in impressive speed. Other benefits include convenient monitoring of job processing status the opportunity to execute jobs in parallel.
There’s also an add-on for Sidekiq – sidekiq-cron. It checks for new jobs to schedule every 30 seconds and doesn't schedule the same job multiple times when more than one Sidekiq worker is running. This gem allows you to set up any kind of jobs, like sending congratulation messages to your app users on New Year’s Eve and other holidays.
Most web applications require a built-in search functionality. To power your application with a search, you might want to take a look at a few helpful gems.
Elasticsearch is a popular search engine for enterprises. By leveraging Elasticsearch, you’re able to implement search on a website, index catalogs of goods (if you’re running an ecommerce store), enable automatic insertion of data, develop a solution for price notifications by indexing prices, implement reverse search, store transactions and actions, and analyze and retrieve data to get comprehensive statistics. We use the Elasticsearch gem for Ruby integrations in Rails applications.
“Awesome,” “great,” “amazing” – these are the words our developers use to describe the Ransack gem. Ransack is appreciated by Ruby developers because it helps them create smart and simple, yet advanced, search forms. Unfortunately, the gem currently isn’t maintained on GitHub, but it doesn’t prevent it from being popular.
Finally, to enable full-text search in a PostgreSQL database, we use the PgSearch gem.
Storing application configurations in environment variables is a widely used practice derived from the principle of a twelve-factor application; by doing so, you’re able to keep sensitive data like passwords or API keys outside the code repository, but the data is still available during execution. The library that might be helpful in this case is anyway_config. It allows abstractize the configuration layer by introducing configuration classes that describe available parameters and their defaults.
Being a website owner or administrator, you need a dashboard where you’re able to manage your website. In the Ruby world, the most common admin panel tool is Active Admin. It provides its users with out-of-the-box features, including data export to CSV, JSON, and XML, custom search and filtering by types, as well as custom authentication and authorization to differentiate user roles. Active Admin requires manual modifications and customization since it has its own view/controller pattern.
Recently, the trend has been towards keeping models, views, and controllers as skinny as possible. So how can we keep everything skinny? View Helpers are modules that contain methods to help you write DRY (Don’t Repeat Yourself), clean, and maintainable code. Let’s look at a few gems that save a whole bunch of time for our developers here at RubyGarage.
In Rails, we have objects everywhere. Draper is a gem-decorator that adds an object-oriented presentation to your web application. If you find the logic in your templates and helpers overly complex, then this gem might be what you need – Draper helps you clean things up with a more object-oriented approach by adding, replacing, or extending an object’s behavior.
Simple Form is a gem that does what its name suggests: it helps you create forms for your Rails applications. In a nutshell, Simple Form helps developers write more elegant code, as well as quicky create dropdown lists, and offers amazing flexibility when working with checkboxes and radio buttons. It can even help you internationalize form elements.
Another useful gem is MetaTags, which helps you create SEO-friendly Rails applications by adding View Helpers for meta tags. MetaTags makes SEO management efficient by giving a more straightforward way to create meta tags while sticking to SEO best practices.
Finally, when developing an ecommerce solution, we need to consider money and currency conversions. The Money-Rails gem solves these tasks in your Rails application by integrating with the Money gem. The Money-Rails gem offers a number of benefits over the Money gem, such as a money class, monetary values, and currency conversion. Moreover, you’re able to create fancy money entry fields which are automatically split into hundreds and thousands with decimal points.
It’s a standard practice to use Ruby gems when working with Ruby on Rails applications. Popular gems solve common problems in Rails applications, including file uploads, authentication, authorization, and testing. Ruby gems also eliminate the need to reinvent the wheel and build your own solutions for each unique app. That said, gems aren’t the silver bullet for all your problems. Gems are more like frozen food from the store; they’re mostly ready to go, but you can’t eat them straight out of the box. Use gems frequently, but remember about serving them right!
Subscribe via email and know it all first!