LoginSignup
0
0

More than 3 years have passed since last update.

controller内のdry(Don't repeat yourself)「メソッドによるコード省略」

Posted at

今日はDRYです。
さて、今回学習したのはcontroller内のprivateメソッドとbefore_actionです.

メソッドによるコード省略

同じコードをメソッドにまとめよう
続いて、tweets_controller.rbを見てみましょう。
tweets_controller.rbの中身を見ると、@tweet = Tweet.find(params[:id])が繰り返し記述されています。

app/controllers/tweets_controller.rb
class TweetsController < ApplicationController

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end

  def create
    Tweet.create(tweet_params)
  end

  def destroy
    tweet = Tweet.find(params[:id])
    tweet.destroy
  end

  def edit
    @tweet = Tweet.find(params[:id])
  end

  def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params)
  end

  def show
    @tweet = Tweet.find(params[:id])
  end

  private

  def tweet_params
    params.require(:tweet).permit(:name, :image, :text)
  end
end

before_actionを利用して、メソッドとしてまとめる

before_actionを使用すると、コントローラで定義されたアクションが実行される前に、共通の処理を行うことができます。

メソッド名 オプション
before_action :処理させたいメソッド名 only/except

*resourcesと同様にonlyやexceptなどのオプションを使用することによって、どのアクションの実行前に、処理を実行させるかなど制限が可能です。

tweets_controller.rb を編集しましょう

app/controllers/tweets_controller.rb
 class TweetsController < ApplicationController
  before_action :set_tweet, only: [:edit, :show]

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end

  def create
    Tweet.create(tweet_params)
  end

  def destroy
    tweet = Tweet.find(params[:id])
    tweet.destroy
  end

  def edit
  end

  def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params)
  end

  def show
  end

  private

  def tweet_params
    params.require(:tweet).permit(:name, :image, :text)
  end

  def set_tweet
    @tweet = Tweet.find(params[:id])
  end
end

今回のように、before_action :set_tweet, only: [:edit, :show]と記述することで、editアクションとshowアクションが実行される前に、set_tweetに定義されている処理が実行されるようになります。つまり、editアクションとshowアクションが実行される前に、@tweet = Tweet.find(params[:id])が実行されるということです。

before_actionを用いることで、重複した記述を1つのメソッドにまとめることができます。

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