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
  end
end
 
0
Kudos
 
0
Kudos

Now read this

What is SSL?

Secure Socket Layer, otherwise known as TLS (Transport Layer Security) keeps the internet safe. I’ll use the two acronyms interchangeably, despite TLS being the correct one. If you’ve ever heard someone say, “don’t give sensitive... Continue →