Second Refactoring of Security Roles

The wrapper class approach is just fine for a single resource that needs
security applied to it. For a refresher, here’s the model…

classArticle<ActiveRecord::Base# Columns include submitted and acceptedend

And here’s the wrapper that you would use in its place when in an Admin
controller…

classAdminArticledefself.method_missing(method,*args)scope={:find=>{:conditions=>["submitted = ?",true]}}Article.with_scope(scope)do# we've limited the scope, so just pass the method call on...Article.send(method,*args)endenddefself.new(*args)# need to explicitly pass this onself.method_missing(:new,*args)endend

And here’s the wrapper that you would use in its place when in a Member
controller…

classMemberArticledefself.method_missing(method,*args)# We get current_user via a class-level accessor I've left out for sanityscope={:find=>{:conditions=>["approved = ? or user_id = ?",true,current_user]}}Article.with_scope(scope)do# we've limited the scope, so just pass the method call on...Article.send(method,*args)endenddefself.new(*args)# need to explicitly pass this onself.method_missing(:new,*args)endend

You can already see how this isn’t gonna scale as you add more AR classes that
need security? Not to mention the fact that it violates the newly private
nature of ActiveRecord.with\_scope. Finally, it’s not nearly as purty as I’d
like. We all like purty, right? Lemme see some hands!

If you enjoyed this post, you might also like:

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.