Dynamically adding methods to a Rails model24 Jan 2011
I’ve been using CanCan for implementing role-based access in my rails app and it’s been great so far. I had created a separate convenience method in the User model for testing each possible user role, e.g.
def admin? self.role == 'admin' end
This was great and allowed me to do a simple
user.admin? to test for role membership. After changing my roles around a few times I wanted a way to avoid the tedium of creating/editing those methods. I began experimenting with Ruby’s powerful class manipulation abilities and came up with this:
It dynamically adds all those methods based on a simple list of possible roles. I’ve only been using Ruby for a short while and the ease with which I was able to accomplish such a feat was pretty impressive. Score one for Ruby.