Rails Icon


Ruby on Rails (Rails) is a web application framework written in Ruby.
105 Stories
All Topics

Rails changelog.com/posts

Rails 4.1 to get a Spring in its step

A lot of focus lately has been put on improving Rails’ speed in dev mode. John Leighton’s Spring gem is a result of some of that focus. It preloads your Rails application and keeps it running in the background so you don’t need to boot it every time you run a test, rake task, or migration.

As of this commit Spring will be installed by default on newly generated Rails 4.1 apps.

Rails changelog.com/posts

View Rails debug messages in the browser console with Rconsole

Using log messages in Rails can be a huge timesaver when you are debugging. With Rconsole you can save even more time by having those messages appear in the browser console. Rconsole is a fairly new gem with a lot of potential.

Installation is super simple. First add it to your Gemfile:

group :development do
  gem 'rconsole', '~> 0.1.0'

Then run bundle install. Add to your layout view:

javascript_include_tag(:rconsole) if Rails.env.development?

To use Rconsole simply add rconsole.log messages where you would normally insert logger.debug, etc.

def show
  rconsole.log 'Hello, Changeloggers!'

Now your browser will display your messages:

Rconsole output

In addition to debugging, Rconsole is particularly useful when working with students or new rubyists to show the connection between what's happening in the controller and the view.

The entire code base is open source and available on GitHub.

Ruby changelog.com/posts

A startup template for Ruby on Rails 4 applications

Way back in January, I wrote a blog post called “Rails has two default stacks”. In it, I discussed how people like to customize the defaults that Ruby on Rails gives you. Your company might prefer Postgres/HAML/RSpec, for example, over the default MySQL/ERB/MiniTest.

There’s an under-used feature of Rails that allows you to automate the creation of your own stack: templates. Check it:

$ rails --help

  rails new APP_PATH [options]


-r, [--ruby=PATH]              # Path to the Ruby binary of your choice
                               # Default: /opt/rubies/ruby-2.0.0-p195/bin/ruby
-m, [--template=TEMPLATE]      # Path to some application template (can be a filesystem path or URL)

Application template? Yep. There’s very little documentation on this feature, unfortunately. There is a work in progress Rails Guide that gives some answers, but it’s not done yet.

Anyway, the TL;DR is this: you can write a little script to help initialize a Rails app just the way you want to. And Rails startup template is exactly that.

Here’s some of the things it gives you out of the box:

  1. Adds analytics-ruby, simple_form, uuidtools, rspec, guard-rspec, and bourbon gems, as well as a few more.
  2. Creates a new git repository, and optionally a new one on GitHub
  3. Sets up foreman for easy environment variable and background service config.
  4. Removes include_tree . from your application.css, since the author prefers to require things manually.

There are some other features, as well.

Check it out on GitHub and vote it up on Hacker News.

JavaScript changelog.com/posts

Create beautiful JavaScript charts with one line of Ruby using Chartkick

So many web apps need to visualize data for their users that a high quality charting library is a huge boon for developers. Andrew Kane’s Chartkick might be just the library for Ruby developers.

Chartkick sample

Chartkick works with Rails 3.1+ and makes adding beautiful charts to your web app as easy as a one liner. Create a simple line chart like this:

<%= line_chart User.group_by_day(:created_at).count %>

Or one with multiple series of data like this:

<%= line_chart @goals.map { |goal| 
    :name => goal.name, 
    :data => goal.feats.group_by_week(:created_at).count 
} %>

A pie chart is as easy as:

<%= pie_chart Goal.group("name").count %>

Chartkick is mostly a JavaScript library with Ruby helpers to generate the required markup that the JavaScript turns into charts. It requires either Google Charts or Highcharts to work, but it doesn’t require Ruby! If you want to use the JavaScript bits from another language, check out Chartkick.js instead.

Chartkick is MIT licensed and hosted on GitHub.

Ruby changelog.com/posts

fast_blank: String#blank? in C

Sam Saffron is part of the team doing Discourse, an open-source Rails-based discussion platform. He’s been kicking all kinds of ass all over Ruby-land lately, but I wanted to share a specific bit of that with you. It’s a new gem, fast_blank.

Basically, due to these awesome-looking flame graphs that Sam added to his MiniProfiler gem. Here’s what it does: it samples stack traces while your app runs, and then lays them all next to each other so you can see where they’re especially deep. He has a demo here, which you can click around and check out what was going on on Discourse’s home page before Sam started working on making it faster.

Anyway, so what’s this has to do with fast_blank? Well, Sam noticed that a ton of time in Discourse’s code was being spent in String#blank?, a method which was added to Rails by _why the lucky stiff way back in the day. Sam attempted to fix it, but making it 100% compatible, yet fast, was difficult.

This lead him to notice that Ruby and Rails have different implementations of #blank?, he decided to fix the issue in Discourse by writing a #blank? in C so that it was super fast.

To use fast_blank, just add it to your Gemfile:

gem 'fast_blank'

That’s it! Your String#blank? will be faster.

Actually, that’s not quite it. Over on GitHub, Sam told me that it’s not up on Rubygems yet, but will be in a few days. For now, you need to clone it down and use Bundler’s :github option:

gem 'fast_blank', github: "SamSaffron/fast_blank"

That’s it.

Now, you may be wondering why I’m making such a big deal out of all of this. Well, this is pretty much an absolutely model open source interaction between a bunch of different projects.

  1. A performance issue was found. Rather than wonder or speculate, measurements were taken.
  2. A new tool was developed to help make sense of the measurements.
  3. Attempting to fix performance in the main project itself, with a pull request.
  4. Recognizing that there was a lot going on here, so fixing it from himself via a patch.
  5. Sharing the fix with everyone until the details in the main projects could be sorted out.

Obviously, this isn’t the end of this story. What will happen next? Will Rails and MRI end up with the same implementation? Can we make it work in Ruby as fast as the C version? Will fast_blank just replace the implementation of #blank? in MRI?

I guess you’ll have to stay tuned to find out. ;)

Ruby changelog.com/posts

Spring: pre-load your Rails apps

When you’re working on a big app, Rails’ startup time can be slow. It’s a hard problem, and there’s been a lot of work done in Ruby and Rails to help solve this pain.

Rails Core member Jon Leighton has a new gem that helps solve this problem: it’s called spring. Basically, Spring is in the same ‘genre’ of gems as Spork and Zeus: it loads your app up and keeps it running in the background, so the next time you run your tests, things are fast.

Using spring is easy:

$  cat >> Gemfile
gem "spring"
$ bundle
$ spring testunit

This boots up your app, runs the tests, and keeps the app running in the background. You can see that your app is running with spring status:

$ spring status
Spring is running:

26150 spring server | rails-3-2 | started 3 secs ago
26155 spring app    | rails-3-2 | started 3 secs ago | test mode 

Now, adding spring before every command is a lot of effort, so similar to bundle, spring can generate binstubs that take care of this for you:

$ spring binstub testunit
$ bin/testunit


If you haven’t used Spring before, check out the README. If you were using earlier versions of Spring, Jon just released 0.8, so check out the CHANGELOG for details on what’s new.

Ruby changelog.com/posts

s3_multipart: Multi-part file uploads straight to S3 for Rails

There’s some things that every web application needs, and some they don’t need very often. File uploads are closer to the first category than the second; thinking back, most of my apps needed to upload files. If you need to upload big files, it’s kind of a problem: if you’re building a twelve-factor style app on something like Heroku, your web workers should have pretty short timeouts, since most of your requests are served quickly. But your file uploads take a long time. What to do?

Enter s3_multipart. From the README:

The S3 Multipart gem brings direct multipart uploading to S3 to Rails. Data is piped from the client straight to Amazon S3 and a server-side callback is run when the upload is complete.

Multipart uploading allows files to be split into many chunks and uploaded in parallel or succession (or both). This can result in dramatically increased upload speeds for the client and allows for the pausing and resuming of uploads.

Neat, eh? The README has more details of how to use the gem. It’s a bit complex: you need to set up CORS on your S3 bucket, run some generators, write some JavaScript.

The gem is still young, and looking for contributions. This is a tough problem, and having an easy way to solve it is great!

Ruby changelog.com/posts

New security releases for Rails: Rails 3.2.12, 3.1.11, and 2.3.17

This year has been a rocky start for Rails, with a bunch of security upgrades that have been important to perform. The end result is a more secure Rails for us all, however, so while it’s annoying, it’s worth it.

How do I upgrade?

You need to do two things:

  1. Upgrade your Rails. Make sure to get 3.2.12, 3.1.11, or 2.3.17.
  2. Upgrade your JSON gem. Make sure you get 1.7.7, 1.6.8, 1.5.5.

Most of this can be done by changing your Gemfile to look like this:

gem “rails”, “3.2.12”

And then running bundle update rails. This will probably update your JSON gem as well, but to be sure, check your Gemfile.lock.

Run cat Gemfile.lock | grep “rails” and cat Gemfile.lock | grep “json”, if you see lines that look like rails (= 3.1.12) and json (1.7.7), then you’re good to go.

What are the vulnerabilities?

First, there is one fix in the 3.x series: CVE-2013-0276.

If you’re using attr_protected to blacklist items for mass assignment, a poor regex could allow someone to assign those attributes anyway. If you’re using attr_accessible to whitelist items, you’re fine.

This is also a good time to plug strong_parameters. Released as a gem for Rails 3.x, it will replace attr_accessible as the default security solution for Rails 4. If you’re starting a new Rails 3.x app today, you should default to using it, as it’s a much better solution.

If you’re on Rails 2.3 or 3.0, you have CVE-2013-0277.

If you serialize attributes into the database, they can be deserialized via YAML, with the same implications as the previous YAML vulnerabilities.

Finally, the JSON gem has CVE-2013-0269.

The JSON gem can be made to symbolize user input, which can cause a denial of service attack, since symbols are not garbage collected.

For More

You might also want to see the official release announcement, which includes hashes of the gemfiles.

Discuss at Hacker News if you have questions or thoughts to share.

Ruby changelog.com/posts

Better Rails development with better_errors!

If you are anything like me (a Rails developer that enjoys good design), you will be glad to know that there is a project out there to make the default error pages for Rails development much cleaner! The standard features are simple, and pretty much just a polished version of what Rails offers out of the box:

  • Full stack trace.
  • Source code inspection, with highlighting.

As a bonus, if you install the extra dependency, you get access to the following features:

  • REPL
  • Local/instance variable inspection.

Installing it couldn’t be easier. While the project is usable outside of Rails, let’s assume you are using Rails/Bundler:

group :development do
  gem "better_errors"
  gem "binding_of_caller" # Optional, only for the advanced features

That’s it! Checkout the project on GitHub or view the README.

Ruby changelog.com/posts

Roll your own crowdfunding with Selfstarter

For those of you that follow The Industry Radio Show, you’ll know that we’ve talked quite a bit about Kickstarter and the self-propelled crowdfunding movement they’ve helped foster. In the same vein, there’s this neat open source project built on Ruby on Rails (at the time of this post v3.2.8), nicely titled Selfstarter.

Selfstarter is an open source starting point for building out your own ad-hoc crowdfunding site. After getting rejected by Kickstarter, the fine folks at Lockitron decided to follow in the footsteps of App.net and make their own crowdfunding site for Lockitron.

Selfstarter is a starting point, so you’re going to have to make some additions to tailor it for your project.

Ruby changelog.com/posts

Sextant - view your Rails routes without waiting on Rake

When given the option, I’ll always opt for text mode when completing a task. In Rails that usually means Rake. There’s a point in most Rails apps, however, when the time to boot Rails just to rake -T is painful. So when Richard Schneeman got tired of waiting on Rails to run rake routes, he created Sextant, a gem that lists your routes in development mode right in your browser.


Since your web server is presumably already booted, there’s no startup tax to see your routes. Check out Richard’s blog post or the source on GitHub for more.

Ruby changelog.com/posts

Imperator - Command pattern for Ruby apps

Jon Leighton isn’t the only one picking a fight with Rails controllers. Keith Gaddis suggests in The Problem With Controllers that we’ve relegated the command pattern to the depths of our queuing frameworks:

The problem with controllers in Rails is that they’re a part of the web domain—their job is to respond to requests, and ONLY to respond to requests. Anything that happens between the receipt of a request and sending a response is Somebody Else’s Job™. Commands are that Somebody Else™. Commands are also very commonly utilized to put work into the background.

Why are commands an appropriate place to handle that logic? Commands give you the opportunity to encapsulate all of the logic required for an interaction in one spot. Sometimes that interaction is as simple as a method call—more often there are several method calls involved, not all of which deal with domain logic (and thus, are inappropriate for inclusion on the models). Commands give you a place to bring all of these together in one spot without increasing coupling in your controllers or models.

He’s released Imperator, a Ruby gem to help move that logic, simplify our controllers, and make them less model-dependent.

class DoSomethingCommand < Imperator::Command
  attribute :some_object_id
  attribute :some_value

  validates_presence_of :some_object_id

  action do
    obj = SomeObject.find(self.some_object_id)

The project is brand new and will likely evolve so check the source on GitHub.

Ruby changelog.com/posts

Rails::API - Lightweight Rails stack for headless API apps

“Rails is just an API,” say Alex (featured on episode #71) and others. Rails core team member Santiago Pastorino might not endorse the “just” part, but his Rails::API aims to provide a slimmer stack for those wanting to use Rails as an API backend for their client-side or mobile applications. The result is a fine-tuned subset of Rails, letting the developer opt-in to just the middleware needed. Rails::API requires a small change to your controllers:

# instead of
class ApplicationController < ActionController::Base

# do
class ApplicationController < ActionController::API

Check out the README for installation and advanced usage and Santiago’s blog post for more.

We’ll be covering a similar project, Lightrail, when we chat with Tony Arcieri about Celluloid next week.

Ruby changelog.com/posts

Focused Controller - Aiming for "real OOP" in Rails controllers

While Rails controllers are Ruby classes and have some OOP support as a result, the lack of true encapsulation and awkward before_filter-based sharing of code between actions leave some OOP die hards disappointed. Jon Leighton’s Focused Controller is an early stage project that takes a different approach. Controllers are Ruby modules and actions are classes classes that inherit ultimately from ApplicationController:

module PostsController
  # Action is a common superclass for all the actions
  # inside `PostsController`.
  class Action < ApplicationController
    include FocusedController::Mixin

  class Index < Action
    def run
      # Your code here.

    # No instance variables are shared with the view. Instead,
    # public methods are defined.
    def posts
      @posts ||= Post.all

    # To prevent yourself having to write `controller.posts`
    # in the view, you can declare the method as a helper
    # method which means that calling `posts` automatically
    # delegates to the controller.
    helper_method :posts

  # Actions do not need to declare a `run` method - the default
  # implementation inherited from `FocusedController::Mixin` is an
  # empty method.
  class Show < Action
    def post
      @post ||= Post.find params[:id]
    helper_method :post

Since routes need to be modified to point to this new convention of Controller::Action#run, a helper is provided for your routes file that supports the usual syntax:

focused_controller_routes do
  resources :posts

Jon is looking for feedback so check out the README for advanced usage, especially on how to test this new style of controller.

Ruby changelog.com/posts

Quiet Assets: Silence Asset Pipeline Messages

The Rails 3 Asset Pipeline is super powerful, but it has one thing about it that’s truly annoying: tons of logger output in development mode. Here’s a simple Rails app’s log output when hitting an index page:

Started GET "/" for at 2012-04-16 13:48:27 -0400
Processing by ArticlesController#index as HTML
  Article Load (0.2ms)  SELECT "articles".* FROM "articles" 
  Rendered articles/index.html.erb within layouts/application (2.3ms)
Completed 200 OK in 11ms (Views: 9.5ms | ActiveRecord: 0.2ms)

Started GET "/assets/authors.css?body=1" for at 2012-04-16 13:48:27 -0400
 Served asset /authors.css - 304 Not Modified (0ms)
 [2012-04-16 13:48:27] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Started GET "/assets/tags.css?body=1" for at 2012-04-16 13:48:27 -0400
Served asset /tags.css - 304 Not Modified (0ms)
[2012-04-16 13:48:27] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

 Started GET "/assets/jquery.js?body=1" for at 2012-04-16 13:48:27 -0400
 Served asset /jquery.js - 304 Not Modified (0ms)
 [2012-04-16 13:48:27] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Started GET "/assets/comments.js?body=1" for at 2012-04-16 13:48:27 -0400
Served asset /comments.js - 304 Not Modified (0ms)
[2012-04-16 13:48:27] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Started GET "/assets/tags.js?body=1" for at 2012-04-16 13:48:27 -0400
Served asset /tags.js - 304 Not Modified (0ms)
[2012-04-16 13:48:27] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Started GET "/assets/application.js?body=1" for at 2012-04-16 13:48:27 -0400
Served asset /application.js - 304 Not Modified (0ms)
[2012-04-16 13:48:27] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Seriously, I chopped about half of that out. Really, really annoying.

Enter quiet_assets. This little gem makes all of this junk go away. To install it, just add

gem 'quiet_assets', :group => :development

to your Gemfile, bundle, and breathe. Now, it just looks like this:

Started GET "/" for at 2012-04-16 13:51:54 -0400
Processing by ArticlesController#index as HTML
  Article Load (0.1ms)  SELECT "articles".* FROM "articles" 
  Rendered articles/index.html.erb within layouts/application (2.7ms)
 Completed 200 OK in 115ms (Views: 65.2ms | ActiveRecord: 1.8ms)
[2012-04-16 13:51:54] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
[2012-04-16 13:51:54] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Much nicer. I can actually tell what’s going on!

Check it out on GitHub.

Ruby changelog.com/posts

RailsOneClick - an easy installer for Rails

Apparently, Rails is really hard to install on Mac OSX. It can be easy to forget once you’re an experienced dev, but there’s been a rash of new projects to make it easier if you’re not. Yehuda Katz is working on Tokaido, Jeremy McAnally has Railcar, and now Oscar Del Ben built RailsOneClick.

He’s got a video of how it works, which you can find here.

So many projects that all do the same thing! I smell a merge coming…

Check it out here on GitHub.

Ruby changelog.com/posts

Roundsman - Combine Capistrano and Chef solo for easy Ruby deployment

Capistrano makes deployment a snap. Chef takes the pain out of managing server dependencies. Roundsman from Iain Hecker aims to combine the best from both:

# config/deploy.rb

before "deploy:update_code" do
  roundsman.run_list "recipe[main]"

after "deploy:create_symlink" do
  roundsman.run_list "recipe[main::webserver]"

Check out the README for installation and usage. Also check out Episode 0.3.8 on Chef and DevOps if you missed it.

0:00 / 0:00