Sitemap

Member-only story

Enabling Cache for Development Mode in Ruby on Rails

2 min readFeb 17, 2024
Rails Logo

I finally took the ‘pain’ to build my first Ruby on Rails application — it’s nothing serious at all — It’s a single endpoint to fetch crypto rates using Quidax API and in order to prevent abuse of the API — I wanted to be sure I wasn’t making request to the API everytime someone hits the endpoint. Thankfully Rails ships with a low-level caching mechanism which is in fact perfect for this scenario, the code looks something roughly like this

def index
Rails.cache.fetch('daily_crypto_rates', expires_in: 1.hour) do
# fetch your resource
render :json your_data
end
end

Upon implementation, I open my terminal and I run curl http://localhost:3000 , and I get some data back — expected behavior, upon running curl again on the endpoint, I still get back data from the endpoint — unexpected behavior. The simple reason is because cache is disabled by default in development mode, to resolve this issue, all I had to do was run the following in the terminal

./bin/rails dev:cache

I run curl again and I get some data — expected behavior, then again, and no content is returned and it’s execution is also superfast. Your frontend should have some strategy to store the data locally as subsequent calls to the endpoint will return nothing until the cache expires. The status code with also be 204

--

--

Aremu Oluwagbamila (SMOG)
Aremu Oluwagbamila (SMOG)

Written by Aremu Oluwagbamila (SMOG)

full time overthinker doing frontend things.

Responses (1)