6
1

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.

Rails で render の後に書かれた処理は実行されるけどレスポンスを返すのは全処理が終わった後

Posted at

背景

環境

➜ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]
➜ rails -v
Rails 6.0.2.2

調べた結果

  • 普通にタイムアウトした :sob:
  • render head などのレスポンス系のメソッドの後に書かれた処理も実行される
  • ただ、アクションの中で書かれたすべての処理が実行された後に response を返すっぽい
  • 処理の順番が逆になるわけではないので最後に render するのが自然
class HelloController < ApplicationController
  def hello
    render status: 200

    sleep 3.0

    slack_client = Slack::Web::Client.new(
      token: ENV['SLACK_TOKEN']
    )
    res = slack_client.chat_postMessage(
      channel: params[:channel_id],
      text: 'hello world'
    )
  end
end
  • after_action 系を使っても同じ挙動
class HelloController < ApplicationController
  after_action :slack_post

  def hello
    render status: 200
  end

  def slack_post
    sleep 3.0

    slack_client = Slack::Web::Client.new(
      token: ENV['SLACK_TOKEN']
    )
    res = slack_client.chat_postMessage(
      channel: params[:channel_id],
      text: 'hello world'
    )
  end
end
  • ただ before_action で render すると処理がそこで終わる
class HelloController < ApplicationController
  before_action :before_render

  def before_render
    render status: 200
  end

  def hello
    # ここは実行されない
    sleep 3.0

    slack_client = Slack::Web::Client.new(
      token: ENV['SLACK_TOKEN']
    )
    res = slack_client.chat_postMessage(
      channel: params[:channel_id],
      text: 'hello world'
    )
  end
end
6
1
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
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?