Each user has many roles; to find out if the user has the "admin" role, we can use the method has_role?:
some_user.has_role?('admin')
Which is defined as follows:
def has_role?(role_in_question)
roles.map(&:name).include?(role_in_question.to_s)
end
I would like to write some_user.has_role?('admin')how some_user.is_admin?, so I did:
def method_missing(method, *args)
if method.to_s.match(/^is_(\w+)[?]$/)
has_role? $1
else
super
end
end
This works fine for the case some_user.is_admin?, but crashes when trying to call it on a user specified in a different association:
>> Annotation.first.created_by.is_admin?
NoMethodError: undefined method `is_admin?' for "KKadue":User
from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations/association_proxy.rb:215:in `method_missing'
from (irb):345
from :0
What gives?
source
share