I’ve got a repeated code block that initializes a few variables in a bunch of different controller methods. Is there a way for me to make this DRY with a model method as opposed to repeating the same code block in each controller method?
Basically, it’s for a social site, and it’s pulling up a user’s list of friends, and then building buckets of friends based on the permissions the user has which are stored in a friendship model. This repeated initialization of buckets is what I’m trying to make DRY.
Normally I would use a model method, but in this case, 3 separate variables are being initialized based on one database pull, and this is called often enough I don’t want to make it unnecessarily inefficient by hitting the database 3 times. In C, I would just use pointers passed in as variables.
It goes something like this:
def example_method
friendships = @user.friendships
view_permission_friends = []
write_permission_friends = []
message_permission_friends = []
for friendship in friendships
if friendship.view_permission then view_permission_friends << friendship.friend_id end
if friendship.write_permission then write_permission_friends << friendship.friend_id end
if friendship.message_permission then message_permission_friends << friendship.friend_id end
end
#Do something with the 3 initialized arrays here
end
I thought about it for a bit, and I think this code should go into your User model. (Or whatever class @user is in your example above.) Two reasons:
The quick and easy way which relies on Rails’ internal query caching would look like this. Added into the User model:
Your controllers then simply do this:
(Note – there’s more room for optimization and better flexibility here via lazy caching and parameterizing the permission.)