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 3 years have passed since last update.

初学者のプログラミング フックで処理を差し込む

Posted at

フック

コールバック処理のようにコントローラーが実行するアクションの前後に処理を差し込むこと

フック一覧

| フック名|処理が実行されるタイミング|
| - + -|
|before_action|Actionの実行前
|after_action|Actionの実行後(正常にActionが実行された場合のみ呼び出す)
|around_action|Actionの前後

フックの記述例

class BooksController < ApplicationController
  protect_from_forgery except: [destroy]
  before_action :set_book, only: [:show, :destroy]
  around_action :action_logger, only [:destroy]

  #略#

  private

  def set_book
    @book = Book.find(params[:id])
  end

  def action_logger
    logger.info "around-before"
    yeild
    logger.info "around-after"
  end
end

beforeフックでset_bookメソッドを、aroundフックでaction_loggerメソッドを呼び出している。またaroundフックではメソッド側でフックによる処理のタイミングを考慮する必要があり、around-beforeの際はyeildによってアクション側に処理を戻す必要がある。

まとめ

アクションの前に実行したい処理にはbeforeで、後に実行したい処理の場合はafterで記述し、前後の両方で実行したい処理の場合はaroundで記述する。

さいごに

プログラミングの初学者です。その日に学んだことを学習の一環としてアウトプットしています。より深く学習していきたいと考えておりますので、ご指摘等いただけますと幸いです。

参考図書:パーフェクト Ruby on Rails【増補改訂版】すがわらまさのり/前島真一/橋立友宏/後藤優一/五十嵐邦明

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?