Rails
Using Separate Database Users for Migrations in Rails
In the past year I have done a lot of work with PostgreSQL (PG) and managing DDL (Data Definition Language) changes. This work has been focused on Java applications which use Flyway to manage migrations, which has less abstractions than Rails migrations. I have been thinking about how to apply some of the lessons I’ve learnt to Rails applications.
Heroku Build Pipelines
Heroku Pipelines is a feature that allows you to manage multiple environments through a workflow where changes are verified and then promoted through the pipeline.
Heroku Error Pages Gem
I wrote a gem - heroku_error_pages - for Rails applications running on Heroku that allows you to build custom error pages and automatically host the pages in S3. This allows you to easily build custom error pages for Heroku - and keep them up to date as part of the release process as your application styles change.
How and Why to Use Service Objects in Rails
If you’re following trends in Rails you’ve probably heard the word ‘service’ being tossed around. I was surprised to find that even though there seems to be consensus that service objects are a good idea, there is no standard pattern for building or consuming them.
Zero Downtime Migrations in Rails
It is possible to do database migrations without incurring any downtime as long as we follow certain patterns. These patterns are not really specific to Rails - they apply to pretty much any web framework - but there are a few nuances that are specific to Rails which I will cover here.
Dealing with N+1 Queries in Rails
One of the most common problems in Rails applications is N+1 queries. As an example, let’s use a simple blogging application, with a Post
model and a Tag
model. When you visit the application you are presented with a snippet for the 10 most recent blog posts.
Validate Uniqueness in Rails
Uniquess constraints are an everyday fact of life. For example, in our application we might want to validate that all usernames are unique. We can easily achieve this with a unique validation.
The Minimum Arel Every Rails Developer Should Know
Most Rails developers are familiar with ActiveRecord queries, but not so much with Arel. Arel allows us to really customize our queries and gives us control over our queries without having to do manual SQL and string interpolation. While Arel is a very powerful and feature-rich technology, I’m going to focus and the features that you use most often.
Special Functions for dealing with Whitespace in HAML
Sometimes HAML will generate an unwanted space in your HTML, especially when you mix HAML markup and rails helpers.
Overriding Named Route Parameters in Rails
Rails will use :id
as the default parameter in resourceful routes.
Data Migrations with Serialized Fields in Rails
A while ago I blogged about the different patterns available for doing data migrations in Rails. Today I am going to look at how to deal with serialized fields in data migrations.
Creating Irreversible Migrations in Rails
This is not something I do very often (or that I recommend at all), but when you need to mark a migration as irreversible, this is how you would do it.
Patterns for Data Migrations in Rails
In my experience with developing Rails applications I have found migrations to be one of the most error-prone areas. As I result I have come up with a few loose patterns on what to do (and what not to do) when doing migrations.
Adding Custom Fields to Your Devise User Model in Rails 4
I am currently working with Rails 4 and Devise 3.2.2. Devise already creates all the routes and controllers for allowing users to sign up, but as with most applications I want to customize the user model and add additional fields. Let’s take a look at how we would go about making these changes by adding a first and last name to the user.
Faster CSV Imports with Rails
On my current project we deal with quite a few CSV imports. While writing a basic CSV import is reasonably straightforward, we ran into performance issues when we started scaling the solution. Basically we could import 3,000 users in around 30 minutes (the domain model being rather complicated), but we needed to scale this solution to import 180,000 users every night. It was obvious that we needed to put some effort into the performance of our solution.
Using Pluralize in your Models in Rails
One of the really nice helpers in Rails is pluralize. It basically provides a really simple way of finding the plural form of a word, courtesy of ActionView::Helpers::TextHelper.
Streaming Data with Rails and Heroku
A reasonably common feature in Rails is to export data to CSV. I find this is often a quick-and-easy solution to many problems, since it’s very easy to analyze and filter the data with Excel.
Rails File Size methods on Fixnum
As a Rails developer I have often seen the shorthands for specifying different dates using the built-in methods on Fixnum. For example, if you want to specify the date for 5 days ago, you can simply use:
Book Review: Crafting Rails 4 Applications
One of my goals for 2014 is to read more programming books. Since I am starting work on a Rails 4 application, Crafting Rails 4 Applications seemed like a good fit since it’s aimed at experienced Rails developers.
All Rails db Rake Tasks and What They Do
I sometimes get confused between the different db rake tasks – what is the difference between db:setup and db:reset, for example? So to clear up some of my confusion – and maybe some of yours – I have compiled this list of tasks with explanations.
Force Page to Reload on Browser Back in Rails
On my current project we do some heavy modification of the DOM via JavaScript. This causes some issues when the users navigate via the back button – quite often the page will not contain the changes the user made, or the information they see will be out of date. (Our users are also unfamiliar with websites and tend to find this confusing)
Creating a New Rails App without Installing the Gem
I usually keep a Gemset for each separate project I have. This means I have a lot of duplicate Gems across my system, but it has the advantage of keeping every project self-contained. This is especially useful since it means I can’t accidentally break a project by running bundle on some new project from Github.
Index Name too Long in Rails
Today I ran into the issue with creating an Index in Rails (the database being PostgreSQL). The migration looked something like this:
Allow Users to Remove Uploaded Images with Paperclip
Allowing users to upload images is pretty straightforward in Rails – especially if you’re using the excellent Paperclip gem. I’ve blogged before about how easy it is to configure Paperclip to upload images to S3. However, there are no nice examples (that I could find) of allowing your users to remove images that are already uploaded.
Tips for Implementing Emails in Rails
Sending emails from your Rails application is a pretty common requirement. User signup, forgotten password, order creation, nightly reports – they all require emails. This is pretty straightforward in Rails – we already have the concept of mailers (with views) – you simply need to configure your mail service and you’re done!
RSpec Best Practices
I’ve been using RSpec on and off for the past 2 years. I’ve learnt that it’s easy to write tests that are bloated, slow and don’t offer any value. I’ve also learnt a few tricks and best practices that will make your RSpec life a bit easier.
Integrating EJS Templates into Rails
I’ve been on few projects where we need to have client-side view templates. This would mostly involve making an AJAX request to the server, getting back some JSON data at which point we need to convert this into HTML. EJS is one of a number of solutions to this problem.
Testing ActiveRecord Callbacks
I’m not a big fan of ActiveRecord callbacks – it usually seems like a quick-and-easy solution, but in the long term it makes testing difficult and can often create unexpected side-effects. However, sometimes there really is no other option which means we need to test these callbacks!
Integrating Solr Search with Spree
For the past 2 months I’ve been working on an e-commerce website where we’ve been using Spree. The built-in searching with Spree is pretty decent and simply builds SQL queries to execute against the database. While this is a great starting point we quickly got to a point where we needed to do more advanced searching – for example, we wanted the user to be able to filter by size, which is not something you can really accomplish with basic SQL queries.
E-Commerce in Rails with Spree
My current project is an e-commerce website for a high-end retailer. This project started out as being completely Greenfield – the requirements outlined a basic e-commerce website with some added features and a intra-day ETL process.
Using Rails Helpers inside a Controller
Rails helpers are designed to be used inside views, but sometimes you might want the functionality from a helper inside your controller. For example, you might be generating a simple JSON string and you want to use a view helper to format some element of the JSON.
Intercept Emails in Rails
On any project where emails get sent automatically testing can become a problem. Ideally you want to be able to see the emails that get generated, but avoid sending test emails to real services or users. On the other hand, you still need to send emails to the real services and users in your production environment.
Configuring S3 with Rails, Paperclip and Heroku
On my current project we are storing images on Amazon S3. We are using the very popular Paperclip gem to interact with images through ActiveRecord. Paperclip is very easy to configure with S3, you simply need to specify the name of your S3 bucket and Amazon access keys and you’re good to go.
Enabling Basic HTTP Auth on Rails
On my current project we are hosting our Rails application on Heroku. While this is great in allowing our client to see changes almost immediately, it also means we have a public site which could in theory be accessed by anyone with the correct URL. To alleviate any concerns around this we decided to simply add basic HTTP authentication to the site as a temporary stopgap.
Populating form values through a link in Rails
Today I was asked to help with creating a link on a website that should take the user to a different page where a form should be filled out based on paramaters supplied through the link URL.
Authenticating Rails Engines with Devise
Devise is a very popular authentication engine for Rails. It comes packaged as a gem and takes care of a large amount of the boilerplate code you usually need to write around user management/authentication.
Debugging in Ruby
Before I started doing Ruby I was doing mostly C#. This meant I did pretty much all my development in Visual Studio, giving me access to a very powerful debugger. Coming into the world of Ruby meant switching to Vim, which meant my editor started up in less than a second (instead of a few minutes), but it also meant I had to give up all the debugging power.
Using Spine.js mobile
For the past 3 weeks I’ve been working on a mobile website for a hybrid iPhone app. We were already using Spine.js – as I mentioned in a previous post – and therefore Spine.js mobile was an attractive choice for building the mobile part of our website.
Rails Session not being persisted
I ran into an issue today around the session object in Rails. The session object works pretty much like a hash and allows you to store data between requests. A number of persistent stores exist, but overall it acts like a hash that is persisted between requests.
Rails – The next five years
One of the talks that I was able to attend at this year’s RailsConf was ‘Rails – The Next Five Years’ by Yehuda Katz. I thought it was a really interesting presentation – Yehuda discussed why Rails is still relevant (after being around for 8 years) and the direction that he thinks Rails should be going for the next few years.
RailsConf 2012
This week I was lucky enough to be able to attend RailsConf in Austin, Texas. As far as I know this is the biggest Rails conference in the world and it was really exciting to see all the big names in the Rails community.
[BUG] cross-thread violation on rb_gc()
I was recently involved in upgrading a project from Ruby 1.9.2 to 1.9.3. As part of this upgrade we also upgraded several of our gems (including Rails) to the latest versions. Everything went smoothly, but when I tried to run the latest version of the code on my laptop (MacBook Pro) I got the following error:
Scopes in Rails
Scopes is one of the features in Rails that I only learned about through reading The Rails 3 Way. It doesn’t seem to be a feature that’s used very often, but I think it can make your code a lot neater if it’s used correctly.
Keeping your routes RESTful
A while ago I blogged about RESTful routing in Rails. While Rails does help us in getting started with RESTful routing, it’s still very easy to lose your way and make a real mess of your routes.
Checking if variables are defined in Rails Partial Views
During this week I was working on a Rails app when I ran into an issue where I needed to check if a variable has been defined in my view. The standard way to check if a variable is defined in Ruby is with the defined? operator.
Book Review: The Rails 3 Way
TLDR Version: This is quite possibly the best programming book I have ever read. It’s packed with examples, covers an enormous amount of Rails feature in great detail while also serving as an excellent reference guide for everyday programming. Bought it, read it, love it.
Symbol#to_proc in Ruby
In the reading I’ve been doing around Ruby I tend to come across quite a few snippets which I don’t fully understand. The following is a line from ‘The Rails 3 Way’:
Build a Collection of Unique Values in Ruby
One of the really cool things about working with Rails is that you can actually look at the source code – it’s a bit like seeing how a magician does all his tricks. I’m always interested in this type of code since it’s usually a very good indication of best practices.
RESTful Routing in Rails 3
This post deals with generating RESTful routes in Rails 3. If you want to look at the basics of routing (which also helps in understanding RESTful routes), take a look at Routing in Rails 3.
Routing in Rails 3
This post deals with the basics of routing in Rails 3. If you want to look at the more advanced RESTful routing, take a look at RESTful Routing in Rails 3.
Setting up a Rails Development Environment on Windows
I recently had to setup my Rails development environment on my laptop (running Windows 7). I’m going to briefly run through the different applications I use when developing on a Windows environment.