Bfec5f7d1a4aaafc5a2451be8c42d26a

Ever noticed how all CRUD methods on each controller starts with the same line: @item = Model.find(params[:id]) ?

Hey! why not use filter so we don’t repeat ourselves ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class PostsController < ApplicationController
  before_filter :find_post, :only => [:show, :edit, :update, :destroy]

  def index
    @posts = Post.find(:all)
  end

  def show
  end

  def new
    @post = Post.new
  end

  def edit
  end

  def create
    @post = Post.new(params[:post])

    if @post.save
      flash[:notice] = ‘Post was successfully created.‘
      redirect_to post_url(@post)
    else
      render :action => "new"
    end
  end

  def update
    if @post.update_attributes(params[:post])
      flash[:notice] = ‘Post was successfully updated.‘
      redirect_to post_url(@post)
    else
      render :action => "edit"
    end
  end

  def destroy
    @post.destroy

    redirect_to posts_url
  end

  private
    def find_post
      @post = Post.find(params[:id])
    end
end

Refactorings

No refactoring yet !

Bfec5f7d1a4aaafc5a2451be8c42d26a

macournoyer

September 11, 2007, September 11, 2007 12:44, permalink

No rating. Login to rate!

Wow nice code ...

1
puts "Cool"
F6eddf2f983d23c2d031e407852625e9

jamesgolick

September 19, 2007, September 19, 2007 13:32, permalink

No rating. Login to rate!

Why not use make_resourceful

1
2
3
4
5
6
7
class PostsController < ApplicationController

  make_resourceful do
    actions :all
  end

end

Your refactoring





Format Copy from initial code

or Cancel