Models make decisions, views and controllers ask PERMISSION 2
Rails uses MVC.
Its important to correctly partition what each section does.
Views and Controllers should NEVER make decisions.
Models should make decisions, and controllers and views should ask models for permission.
For instance, if you have a a User model and some other model like, for instance something that remembers it position and is owned by a user, the view can ask the model whether it allowed to alter the object before it puts the user interface to allow movement.
in the view…
<% if moveable_thing.editable_by?(logged_in_user) >
… interface to move the object …
< end %>
Well, thats ok, BUT, it embeds a decision in the view.
What decision? well, whether an editable object is moveable of course. Later on, a user may be able to edit the contents of the object but not its position, and to make that change you have to now scan all controllers and views.
Better by far…
<% if moveable_thing.movable_by?(logged_in_user) %>
Now, we have removed ALL decision making from the view.
If this means we have to do silly things in the model like….
def editable_by?(user)
…
end
def moveable_by?(user)
editable_by?(user)
end
then, so be it, its a small price to pay.
How is “if
moveable_thing.editable_by?(logged_in_user)” and “ifmoveable_thing.movable_by?(logged_in_user)” any different. Because they really are not.Well, for instance, the initial implementation of movable_by? is
def moveable_by?(user)
editable_by?(user)
end
so, in essence, you are right. But.
next week, the user is going to ask to be able to allow an expanded group of users to be able to move, but keep the definition of people who can EDIT, the same.
Now, in the intermediate code (using editable_by?) it makes the decision that people who can edit it, can also move it, and that people who can move it, can edit it. Thats a decision that should not be made in the view.
‘re enverbing’ (hehe, just made that up) the method in the model used to ask permission allows us to control from the model any changes to the specification of those two groups. (editors and movers)
I like to choose the verbs for my permission methods (on the models) as specific to the task at hand, even if they are just delegating to a more generic name internally.