Rails Best Practice Snippet: About named_scope.
Reference link to the PDF. Rails-best-practices.

named_scope is a Rails 2.x feature which can simplify your rails code, move your finders into their own Model, and compact the code logically and gracefully. Below code refactoring is a named_scope sample to show the tricky.

BEFORE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class PostController < ApplicationController
  def search
    conditions = { :title => "%#{params[:title]}%" } if params[:title]
    conditions.merge!{ :content => "%#{params[:content]}%" } if params[:content]
    case params[:order]
      when "title" : order = "title desc"
      when "created_at" : order = "created_at"
    end
    if params[:is_published]
      conditions.merge!{ :is_published => true }
    end
    @posts = Post.find(:all, :conditions => conditions, :order => order,
                             :limit => params[:limit])
  end
end

AFTER

1
2
3
4
5
6
7
8
9
10
11
12
class Post < ActiveRecord::Base
  named_scope :matching, lambda { |column, value|
    return {} if value.blank?
    { :conditions => ["#{column} like ?", "%#{value}%"] }
  }
  named_scope :order, lambda { |order|
  { :order => case order
      when "title" : "title desc"
      when "created_at" : "created_at"
    end }
  }
end
1
2
3
4
5
6
7
class PostController < ApplicationController
  def search
    @posts = Post.matching(:title, params[:title])
                 .matching(:content, params[:content])
                 .order(params[:order])
  end
end

More references :
http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality
http://railscasts.com/episodes/108-named-scope

Rails Best Practice Snippet: Model refactor.
Reference link to the PDF.Rails-best-practices.

Before:

1
2
3
4
5
6
class Invoice < ActiveRecord::Base
  belongs_to :user
end
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>

After:

1
2
3
4
5
6
7
class Invoice < ActiveRecord::Base
  belongs_to :user
  delegate :name, :address, :cellphone, :to => :user, :prefix => true
end
<%= @invoice.user_name %>
<%= @invoice.user_address %>
<%= @invoice.user_cellphone %>

See more details about Delegate in rails doc.

© 2011 Refactoring Thoughts Suffusion theme by Sayontan Sinha
普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress