How to refactor this Ruby on Rails code?

Posted by yuval on Stack Overflow See other posts from Stack Overflow or by yuval
Published on 2010-06-02T21:55:25Z Indexed on 2010/06/02 22:04 UTC
Read the original article Hit count: 230

I want to fetch posts based on their status, so I have this code inside my PostsController index action. It seems to be cluttering the index action, though, and I'm not sure it belongs here.

How could I make it more concise and where would I move it in my application so it doesn't clutter up my index action (if that is the correct thing to do)?

if params[:status].empty?
      status = 'active'
    else
      status = ['active', 'deleted', 'commented'].include?(params[:status]) ? params[:status] : 'active'
    end


    case status
    when 'active'
      #active posts are not marked as deleted and have no comments
      is_deleted = false
      comments_count_sign = "="
    when 'deleted'
      #deleted posts are marked as deleted and have no comments
      is_deleted = true
      comments_count_sign = "="
    when 'commented'
      #commented posts are not marked as deleted and do have comments
      is_deleted = false
      comments_count_sign = ">"
    end

    @posts = Post.find(:all, :conditions => ["is_deleted = ? and comments_count_sign #{comments_count_sign} 0", is_deleted])

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about best-practices