All, This is more of a theoretical question I suppose - I'm looking for what the consensus is for the "correct" approach in Rails/MVC. I have a standard security model where a User can have many Roles. There is a User model, a Role model, and in the db, a linking table, etc. Each role has a name as well as a category (say, name="waiter", category="restaurant worker", for example). I can check to see of a user has a particular role by doing something along the lines of @session[:user].roles.include?(Role.find_by_category("restaurant worker")) There is probably a shorter way of doing this, but the point is this: Would it be "correct" in the Rails/MVC world to add a method to the User model so that you could do @session[:user].has_role_category?("restaurant worker") (with a better name, of course :-) Any downside to taking this approach? Is there a "better" one that I should consider? Thoughts? TIA, Keith
on 2005-12-16 17:15
on 2005-12-16 19:15
I would say if it improves code readability you should always add a method. In your example it's arguable whether that's the case (both seem pretty readable to me). I wouldn't do it for the sake of it.
on 2005-12-16 19:21
The user should be responsible for itself. Your second approach is the more object-oriented way. Although you might even ask it to report its actual category, not whether it is a certain kind. e.g. session[:user].role >> 'restaurant worker' - Rabbit ---
on 2005-12-19 07:09
On Friday 16 December, Keith L. wrote: > @session[:user].roles.include?(Role.find_by_category("restaurant worker")) Look up the law of demeter. I forget the exact wording, but the way I think of it is something like this: "it's okay to play with your friends, and it's acceptable to play with your friends' friends, but that's it". In other words, it's okay for a user to know about methods on a role object, but you shouldn't really go further afield than that without wrapping stuff up in methods. I find this approach reduces the number of things that need changing when something needs refactoring, which is great as anything that puts you off refactoring is likely to reduce the readability of your code. It also makes the code you write easier to understand. > @session[:user].has_role_category?("restaurant worker") This one leaves little room for doubt about it's intent, and is therefore preferable in my opinion.