LoginSignup
2
1

More than 5 years have passed since last update.

304 Not Modifiedで返してブラウザキャッシュを使ってもらう

Last updated at Posted at 2018-06-01

ざっくり

  • CarrierWave で AWS S3 に画像をアップ
  • その画像を認証通った人だけ表示する

こんな風になっていたのを

class UsersController < ApplicationController
  authorize_resource

  # 権限チェックした人だけ画像を返す
  def avatar
    uploader = @user.avatar

    send_data(
      uploader.read,
      type: uploader.content_type,
      disposition: 'inline',
    )
  end

次のように改修して

class UsersController < ApplicationController
  authorize_resource

  def avatar
    # avatar 以外の更新があった場合でも ETag が変わってしまうので
    # ファイル名などを使ってもいいかも?
    # stale?(@user, etag: Digest::MD5.hexdigest(filename), template: false)
    return unless stale?(@user, template: false)

    # 明示しておかないとsend_data が `Cache-Control: private` にしてしまう
    # ファイルの更新頻度がわかっているのであれば有効期間を伸ばしてあげればよい
    expires_in 0, public: false, must_revalidate: true

    uploader = @user.avatar

    send_data(
      uploader.read,
      type: uploader.content_type,
      disposition: 'inline',
    )
  end

S3へのアクセス (uploader.read の部分) を減らしました

2
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
2
1