57 Best Ruby Gems We Use at RubyGarage
- 40925 views
Here at RubyGarage we work closely with Ruby and Ruby on Rails technologies. We like Ruby for its resourcefulness and a 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 – For pagination, try a gem with the enigmatic name Kaminari, Japanese for “thunder.” Kaminari is a flexible out-of-the-box paginator (no configuration required) that uses scopes to handle ActiveRecord queries.
Categorization – To implement better classification and structuring of data on a blog, a news website, or a social network, you might want to add tags. The gem ActsAsTaggableOn allows you to tag objects (models and controllers) according to several attributes depending on your application’s content.
Clone – If you need to create a copy of an Active Record object and its associations, look at the gem deep_cloneable, which adds a method to objects to copy themselves. Deep_cloneable gives you an accurate copy with minimal effort.
Soft delete – Paranoia, which replaces acts_as_paranoid, implements a soft delete function. After you call destroy on an Active Record object, Paranoia doesn’t destroy those records in the database. Instead, this gem hides the object by scoping queries on a model. You need to use really_destroy to really destroy a Rails object.
Finite state machines – AASM, which replaces the theacts_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 – The PaperTrail gem enables you to prevent frustrating situations when you can’t undo or redo changes to your models. With PaperTrail, you can version your models, add, undo, and redo behavior, restore data, work with model associations, and more.
Internationalization – When it comes to 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 translation of non-static database content.
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_girl, Capybara, shoulda-matchers, database_cleaner and simplecov to save time and effort.
We write our unit tests with RSpec – a testing framework mainly used in BDD and TDD environments. RSpec’s syntax is neat and descriptive, so tests (or specs) are written as closely as possible to ‘human’ language. RSpec is an effective tool for testing 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 the factory_girl gem. Factory_girl lets you create a factory (a data set) for models, so there’s no need to manually enter data every time you implement unit tests. We also use another gem called Faker to generate fake data within our models, such as phone numbers, emails, and usernames.
We then use Capybara, an acceptance testing framework, 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 console.
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 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 results of analysis 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 only show the refactoring suggestions you want it to. And the great thing about RuboCop is that it automatically fixes issues like line breaks, syntax, and amount of gaps.
The RubyCritic gem helps provide reports on code quality. RubyCritic leaves no chances for Ruby code smells by generating HTML reports with names of files, their smells and ratings: files receive ratings of ‘A’ through ‘F.’
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.
The default Rails error page is quite dull, so our developers prefer alternatives. Better Errors offers a static error page for Rack applications, but it’s a bit inconvenient because you can’t see what caused a crash except through the stack trace. The binding_of_caller gem, however, offers a more helpful error page screen and lets you inspect variables inside your application when it crashes.
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 quick email preview. With Letter Opener you don’t have to wait for an email to be delivered to your mailbox, but 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 an 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 some developers 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. 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!
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 to CanCanCan and Devise to extend their capabilities of user management.
When you build complex applications in which users have multiples roles, you might want to set access restrictions for specific user roles. In this case, the gem CanCanCan allows you to define abilities of specific users in a single location, which our RubyGarage team finds quite convenient.
In a nutshell, APIs are set 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 ActiveModelSerializers, which builds a JSON response from a server depending on a passed record or collection. We also benefit from Apipie-rails – a DSL for documenting RESTful APIs. Apipie literally describes the code with the Ruby syntax, which is convenient for rubyists.
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.
In case if you want to check your application’s gems for vulnerabilities, take a look at bundler-audit, which runs on the 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 about 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 and Stripe Ruby Bindings 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.
Deployment is an important stage of the software development cycle, when we get your web application ready to go live. There are countless web servers that can host Rails web apps. For example, Puma and Unicorn are popular HTTP web servers commonly used for deploying Rails applications. And when it comes to deploying web applications on these particular servers, we simply use the Puma and unicorn-rails Ruby gems.
A web application goes through a number of steps before being deployed, including copying files, migrating databases, and compiling assets. These tedious tasks can be completed with the automated deployment tool – Capistrano. Capistrano handles many operations including tagging servers for different roles, handling multiple stages, and executing parallel deployments. Capistrano works effectively with the Chef, which sets up and manages a server by installing packages, putting files in specified locations, and so on. Chef is rarely used for deploying Rails applications since it has few resources for customization and automated deployment.
Quite often we build web applications that allow users to upload files of various kinds: documents, images, audio, and video. And when it comes to images in particular, one of the most effective solutions available is the CarrierWave gem. CarrierWave functions as a file uploader as well as an image processor, which crops and resizes images. Moreover, CarrierWave caches files (so a user doesn’t have to re-upload a file in case something goes wrong) and processes files, so you can extract EXIF data or parse uploaded text files. A nice bonus of CarrierWave is that it stores all data in uploader classes, so your code stays neat and tidy.
Minimagick is another gem that handles image processing. Minimagick efficiently saves your RAM resources and deals with miscellaneous tasks like image resizing, flipping, rotating, blurring, as well as conversion to popular image formats, including PNG.
Finally, you might want to upload and store your files on external servers like Amazon’s S3 or Google’s Cloud Storage. In this case, we use the Fog gem, which works with a variety of cloud services including AWS, Rackspace Servers, and Brightbox.
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 instance, 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.
Next, one of the most popular background processing tools is Resque. Resque is a powerful tool to manage background jobs that’s very similar to Sidekiq. But Resque and Sidekiq execute background jobs in different ways. Resque uses only single-threaded processes, while Sidekiq handles multi-threaded processes, which is why it takes more memory for Resque to handle queues.
One more useful background processing library is Sucker Punch, inspired by the girl_friday gem. Sucker Punch is different from similar solutions because it runs inside the application’s process, so it doesn’t require any dependencies (like Sidekiq requires Redis). According to GitHub, Sucker Punch is effective when working on small tasks like logs and emails; however, in case of system failures when your application is restarted, background jobs are lost.
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.
Another gem, which connects Active Record to the full-text search tool called Sphinx, is Thinking Sphinx. With Thinking Sphinx, you can use Sphinx’s capabilities like search daemon, console analog for debugging and search testing, indexing and more.
“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 this doesn’t stop its popularity.
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. However, it’s sometimes not efficient to set environment variables on a development machine or a continuous integration server to run multiple projects. The Dotenv gem loads environment variables from a dotfile, which can be located outside the root of your project. Therefore, you’re able to keep your application’s secrets secure.
Being a website owner or administrator, you need a dashboard where you’re able to manage your website. In the Ruby world, the two most common admin panel tools are Active Admin and RailsAdmin. Both Active Admin and RailsAdmin provide their 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. Even though these admin gems have a lot of features in common, they’re actually quite different. In general, RailsAdmin is ready-to-use straight after it’s installed, while Active Admin requires manual modifications and customization since it has its own view/controller pattern.
One final Administrate gem comes in handy when it’s necessary to replace Active Admin and RailsAdmin. Administrate generates admin dashboards that are easy to customize even for non-technical users, which is a common problem for all admin panels that are too generalized.
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 which 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 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!