Fix: Including modules on singleton objects in Ruby

Two weeks ago I posted this.

The idea behind adding methods to a single object still hold, but I made a rather egregious error.

I am pulling a row out of the database, (abstracted by ActiveRecord) and then extending that Ruby object with a module to add methods to it.

I was operating under the false assumption that that object, let’s call it x, will persist those methods after dying.

x is pulled out of the database. Methods a and b are added to that object (row). Then, the code moves on, or the user logs out. The data represented by x still exists in the database, but x itself does not. So, those methods get thrown away.

In my example, whenever a Membership was saved, it was extended. But again, that extends becomes useless after that particular object is no longer referenced.

A solution to this, the one I’m taking, is to extend that module whenever the Coinbase membership is referenced from within a user. Like so:

class User
  def coinbase
    self.memberships.find_by_name('Coinbase').extend Coinbase

Now read this

A Distributed Systems Roadmap

Here lives a map for navigating the basics of distributed systems theory. This roadmap is mainly for programmers and researchers interested in learning enough theory to construct and reason about “real” distributed systems. Important... Continue →