環境
- 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