The classic way in rails of implementing model behaviour control of controllers and views is to decorate your model classes with methods which expose behavioural information.
For instance, for this message, we will consider an application which has users and meetings.
Now, my question is, which direction is best?
user.can_edit_meeting?(
meeting) is natural. But does not fit with RSPEC, where you would test this by
user.should be_can_edit_meeting?(
meeting).
But thats not natural, so how about
user.should be_able_to_edit_meeting?(
meeting), Yeah, thats better.
As we develop the application, we are going to be embedding lots of knowledge in the user that should really be in the other model classes.
So, that would lead to
gathering.should be_editable_by(
user)
to give us…
class Gathering
def editable_by?(user)
…
end
end
So, now we have the logic where it should be, but a truely HORRIBLE name.
Final step, the method is nicer to name from the user side, but cleaner in OO terms from the Meeting class side.
We can resolve this by adding the user side too, and delegating to the Meeting side.
This gives us
class User < ActiveRecord::Base
def able_to_edit_meeting?(meeting)
meeting.editable_by?(meeting)
end
end
class Meeting < ActiveRecord::Base
def editable_by?(user)
…
end
end
Is this the best way? Am I missing something? Does anyone think there is a better way?