Ruby Patterns: Mass Assignment

The following is a guest post by Kevin Curtin and originally appeared on his blog. Kevin is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here. A common pattern in programming is to instantiate a new object and assign a bunch of attributes during initialize. You probably recognize code […]

Reading Time 0 mins

The following is a guest post by Kevin Curtin and originally appeared on his blog. Kevin is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

A common pattern in programming is to instantiate a new object and assign a bunch of attributes during initialize. You probably recognize code like this:

Blog post image: tumblr_mevwx9EIow1rtan47.png

While this works, it’s redundant and tedious. You also have to keep track of what order the parameters have to be in when creating the object. Wouldn’t it be nice if we could pass in any number of attributes to be assigned and specify which attributes they should be assigned to without having to write a ton of code?

It turns out that we can. Ruby makes it particularly easy with some metaprogramming magic and the .send method:

Blog post image: tumblr_mevwxh9GeK1rtan47.png

This is mass assignment: a pattern that is extremely common and implemented in a ton of Ruby libraries, including ActiveRecord. It allows us to initialize objects with a hash, where the key corresponds with the attribute we are setting and the values represent the attribute values. It’s more flexible, more fun, and less code.

Disclaimer: The information in this blog is current as of December 16, 2012. Current policies, offerings, procedures, and programs may differ.

About Flatiron School

More articles by Flatiron School