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 1 year has passed since last update.

Rails7でCacheを利用する(purgeも含む)

Last updated at Posted at 2023-08-25

環境

  • Ruby on Rails 7.0.5
  • Ruby 3.2.2

コード例

キャッシュを使う(ない場合は作る)

app/controllers/users_controller.rb
  def users_for_select
    @users = Rails.cache.fetch(User::CACHE_FOR_SELECT, expires_in: 5.minutes) do
      User.active.select(:id, :email, :name)
    end
  end

キャッシュのキー定義とデータ変更時に削除するコード

app/models/user.rb
  class User
    CACHE_FOR_SELECT = 'users_for_select'

    after_commit :purge_cache_for_select, on: %i[create update destroy]

    private

    def purge_cache_for_select
      Rails.cache.delete(CACHE_FOR_SELECT)
    end
  end

キャッシュストアの定義

config/application.rb

config/application.rb
  config.cache_store = :memory_store, { size: 64.megabytes }
  # デフォルトは32MB
  # 本番環境では、Redis等を利用する

config/environments/test.rb

config/environments/test.rb
  config.cache_store = :memory_store, { size: 64.megabytes }
  # これがないと、テストで ActiveSupport::Cache::NullStore error が出る

テストコード

spec/models/tenant_spec.rb
  describe '#purge_cache_for_select' do
    let!(:user) { create(:user) }

    before do
      allow(Rails.cache).to receive(:delete)
    end

    it 'purges cache on create' do
      create(:tenant)
      expect(Rails.cache).to have_received(:delete).with(User::CACHE_FOR_SELECT)
    end

    it 'purges cache on update' do
      tenant.update(name: 'new name')
      expect(Rails.cache).to have_received(:delete).with(User::CACHE_FOR_SELECT)
    end

    it 'purges cache on destroy' do
      tenant.destroy
      expect(Rails.cache).to have_received(:delete).with(User::CACHE_FOR_SELECT)
    end
  end
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?