Ruby 2.0 vs alias_method_chain

Tue Feb 26 00:00:00 -0800 2013

One cool feature in Ruby 2.0 is Module#prepend. This allows Modules to override local methods. Previously we used things like alias_method_chain to accomplish the same effect.

Before (Ruby 1.8, Ruby 1.9)

require 'rubygems'
require 'active_support'
require 'active_support/core_ext/module'

module Foo
  def self.included(base)
    base.alias_method_chain :hello, 'mom'
  end

  def hello_with_mom
    hello_without_mom + ' mom'
  end
end

class Bar
  def hello
    'hello'
  end

  include Foo
end

After (Ruby 2.0)

module Foo
  def hello
    super + ' mom'
  end
end

class Bar
  prepend Foo

  def hello
    'hello'
  end
end

Retrying an Exception in Ruby

Fri Oct 28 00:00:00 -0700 2011
When dealing with over-the-wire services, I've found it helpful to retry certain errors automatically. This small helper makes it easy!

mass_assignment v1.0 is a gem

Wed Apr 13 00:00:00 -0700 2011

For two years now I've been using my mass_assignment plugin to improve the security and readability of my Ruby on Rails code. Today I decided to get with the program and make it a gem. Since it's been stable and production-tested for a long time now I think it deserves the 1.0 version.

What It Is

A robust mass assignment method with a small and obvious syntax.

The Traditional Approach

The normal mass assignment protection comes from attr_protected and attr_accessible. There are a few problems with this approach:

  • Often never implemented, leaving a wide-open system. Rails blogs are full of dire warnings about forgetting your attr_protected.
  • Once implemented, easy to forget when adding new attributes, leading to bugs (in an attr_accessible system) or security holes (in an attr_protected system).
  • Restricts coding syntax. You can’t easily use update_attributes() or attributes= because your whitelist/blacklist gets in your own way.
  • Not contextual. The list of allowed attributes can’t change to accomodate different user permissions or situations.

The MassAssignment Approach

This plugin’s solution is to let you specify an obvious and explicit list of allowed attributes when you mass assign attributes.

  • The list of allowed attributes is in your controller at calltime, so it’s easier to remember and update (it’s not a hidden, magical system).
  • The list of allowed attributes is optional, so it doesn’t get in your way. You can use update_attributes() and attributes= for your own code again.
  • Assignment permissions are enforced by the controller, where permissions belong. You can evaluate the current user or current situation and write the whitelist on the fly.

See the README on github for examples and more.