All posts in Ruby

Setting up multiple databases in Rails: the definitive guide

There are different reasons why you might consider having multiple databases in your Ruby on Rails application. In my specific case scenario, I needed to store large quantities of data representing user behavior: clicks, pages visited, historical changes, and so on.

This kind of databases generally are not mission critical, and grow much faster (and larger) than most databases. Their requirements are often different: for instance, they need more storage space, are more tolerant in the face of hardware or software failures, and are write-intensive. For these reasons, sometimes it is interesting to separate them from your application’s primary database. Often, non-RDBMS databases are chosen for these kind of tasks, something which is however beyond the scope of this article.

I googled and read many different solutions, however I couldn’t find one that was able to fully cover how to:

  • Have different and isolated migrations and schemas for every database.
  • Use rails generators to create new migrations for every database, independently.
  • Offer database-specific rake tasks for the most common database operations (i.e. like the ones available for the primary database).
  • Integrate with RSpec’s default spec task.
  • Work with Database Cleaner.
  • Work on Heroku.

This is my take on how to solve all of these – and have a fully working multiple database solution for your Rails application.

Continue Reading…

How to build a Rails API server: Optimizing the framework

I have been developing Rails JSON API applications for quite some time now, and I’d like to share a few of my setups and discuss why I do things this way. I’m starting today a series of articles that will cover up pretty much the steps I take every time I bootstrap a new Rails JSON API application.

One of the first things I do is to ensure I’m optimizing Rails for speed. I basically optimize the framework itself, prior coding any specific application logic.

You may have heard before that “Premature optimization is the root of all evil“. However, “Premature optimization is a phrase used to describe a situation where a programmer lets performance considerations affect the design of a piece of code”, which “can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing” (source: WikiPedia). This is not what we’re doing here: we’re just going to apply a few changes to Rails, and then basically forget about those and start coding in a framework that is optimized to serve our API.

Many of Rails functionalities are simply not needed when building an API server, and by stripping down Rails to a bare minimum we can actually achieve pretty significant performance increases.

Continue Reading…