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

Late Night Big O Revelations

Big O complexity describes a relationship between the length of the input and the amount of “steps” it will take to complete some operation. I am observing a function, with no numbers. If there is any multiplication / division of... Continue →