Fork me on GitHub

Move code into model

24 Jul 2010

Wen-Tien Chang

Bad Smell

<% if current_user && (current_user == @post.user ||
                       @post.editors.include?(current_user)) %>
  <%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>

In this example, we check the edit permission in view with a complex code, but complex logic codes should not be placed in view, we should move it to model.

Refactor

<% if @post.editable_by?(current_user)) %>
  <%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>

class Post < ActiveRecord::Base
  def editable_by?(user)
    user && (user == self.user || self.editors.include?(user))
  end
end

Now it's clear that we move the permission logic into editable_by? method in model, that makes the view code more readable and we can easily reuse the editable_by? logic in other view files.

Tags