Say you have an app not dissimilar to StackOverflow where users vote on posts. Say an Up Vote causes the voter to receive one reputation point. You might see something like this in the vote_up model:
class UpVote < ActiveRecord::Base
user = self.user
user.reputation == user.reputation + 1
There is one issue with this code: The value 1 is hard coded. Where does such a value belong? Another issue is that some UpVote should have no knowledge of user.reputation. We solve this by changing the callback:
Then we add an instance method to User:
self.reputation = self.reputation + reputation
- Who’s responsible for calling save! ? The increase_user_reputation inside the UpVote model or the modify_reputation method inside the user model?
- The +1 one to reputation doesn’t seem like a good idea to hard code. Where does Rails keep such configuration settings?
- Does the code look reasonable? Are there any shortcuts?