0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Ruby】同じコードを書かないためだけにbefore_filterを使っていませんか?

0
Last updated at Posted at 2016-10-22

結論

「同じコードを書かない」のは目的でなく、
品質を上げる1つの手段。

本題

例えば以下のようなプログラムがあるとする。

class TestsController < ApplicationController

  def index
    @tests = Test.all
  end

  def show
    @test = Test.find(params[:id])
  end

  def edit
    @test = Test.find(params[:id])
  end

  # 略
end

「同じコードを2回(以上)書いている!
DRY(Don't Repeat Yourself)に反している!」

と思い、いままで以下の様に書き換えていました。

class TestsController < ApplicationController
  before_filter :set_test, only: [:show, :edit]

  def index
    @tests = Test.all
  end

  def show
  end

  def edit
  end

  # 略

  private
  
  def set_test
    @test = Test.find(params[:id])
  end
end

しかし、こう書くことでバグのリスクが少し高まります。
例えば、新しいactionを追加したとき、
before_filterにactionの追加を忘れる、ということも起きうる。

上記の例ぐらい文量が少なければ問題ないと思います。
が、ソースコードが増える、複数の人がコードを書くようになると、
抜け漏れが起きる可能性も高まります。

だから敢えて品質向上を目的に、
各actionに同じコードを書く。
これによって、ソースを見る人は各actionの中だけを見て
プログラムを書くことができます。

class TestsController < ApplicationController

  def index
    @tests = Test.all
  end

  def show
    @test = Test.find(params[:id])
  end

  def edit
    @test = Test.find(params[:id])
  end

  # 略
end

before_filterを使う方が良い時

actionに関わらず、コントローラーに必要な処理はbefore_filterで書く。
※ ログイン認証など

なぜならbefore_filterを使わない場合、
各actionに記入漏れをする可能性があるからです。

改めて結論

規則は規則ですが、
バグの起きにくいように書きましょう。

関連記事

Railsのフィルターオプション only と except の使い分け
DRY (Don't Repeat Yoursel) の意味を勘違いしてたかも

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?