Bill Katz
2006-Jul-11 20:36 UTC
[Rails] Should I use exclamation marks for methods that change associations?
I''ve been getting some good feedback on the Authorization plugin (http://www.writertopia.com/developers/authorization). Josh Susser suggested I use exclamation marks when I''m setting roles. The basic ways of setting roles uses the #has_role, #has_no_role, #accepts_role, and #accepts_no_role methods: user.has_role ''site_admin'' user.has_role ''moderator'', group user.has_no_role ''site_admin'' user.has_role ''member'', Group a_model.accepts_role ''moderator'', user a_model.accepts_no_role ''moderator'', user Model.accepts_role ''class moderator'', user With the new dynamic methods, we give the user-like model some flexibility: user.is_moderator_of group --> sets user to have role "moderator" for object group. user.is_administrator --> sets user to have role "administrator" not really tied to any object. user.is_eligible_for award --> sets user to have role "eligible" for object award. In the discussions I''ve read on proper use of exclamation marks, some say it should only be used when destructive effects are not obvious from the name. So #delete doesn''t need an exclamation mark. Exclamation marks might also show when the given object is modified. In the case of roles, a " user.has_role! foo" won''t change the user object but could possible change the join table and the Role table. On the other hand, I''m leaning toward adding the exclamation mark because it clarifies the difference between methods. user.has_role! ''site_admin'' user.has_role? ''site_admin'' user.is_moderator_of_what user.is_moderator_of! group user.is_moderator_of? group group.has_moderators group.has_moderators? The "group.has_moderators" case shows how there might be some ambiguity. Methods like has_blahs on models return an array of user objects that have role "blah". The has_moderators method doesn''t set a role, but it might be clear because saying some model "has moderators" doesn''t mean you are setting those moderators. Comments are appreciated. -Bill