Skinny Controller, Fat Model

Track this spec on Launchpad
Target: Undecided

Inspired by "Skinny Controller, Fat Model" by Jamis Buck, our controllers should contain less code, that could be ported to the models. Code repetition can be minimized with this technique, and our code could be made more clean.

Also relevant is the article "Tell, Don't Ask".

Examples in the code

Some places where this applies:

  • The code to get comments/pingbacks/trackbacks only in BlogController#show could be moved to Comment#all_comments/pingbacks/etc.
@comments = @entry.comments.find(:all,
  :conditions => "comment_type = 'C' AND approved = 1",
  :order => "date")

@pingbacks = @entry.comments.find(:all,
  :conditions => "comment_type = 'P' AND approved = 1",
  :order => "date")

@trackbacks = @entry.comments.find(:all,
  :conditions => "comment_type = 'T' AND approved = 1",
  :order => "date")
  • Ditto for the approved vs. spam comments: Comment#all_approved/spam. Also see the variable @spam_count in Admin::CommentsController#manage.
@spam_count = Comment.count_by_sql("SELECT COUNT(*) FROM comments WHERE approved = 0")
  • And the code to get the count of published posts or drafts in Admin::DashboardController.
@total_entries = Entry.count
@total_entries_published = Entry.count(:conditions => "state = 'P'")
@total_entries_draft = Entry.count(:conditions => "state = 'D'")
  • @latest_entries in Admin::UserController#edit => User#latest_entries. (Done.)
  • @total_entries in BlogController#archive => Entry#published_in(year, month).
  • In BlogController, the following code is often repeated at the start of actions:
begin
  if params[:id]
    @entry = Entry.find(params[:id])
  else
    @entry = Entry.find_by_slug(params[:slug])
  end
rescue ActiveRecord::RecordNotFound
  notfound()
  return
end
if @entry.nil? # ActiveRecord doesn't seem to always return an exception,
               # so we need to double-check.
  notfound()
  return
end
page_revision: 5, last_edited: 1208967583|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 2.5 License.