Enabling Cache for Development Mode in Ruby on Rails

Aremu Oluwagbamila (SMOG)
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

Edit: If you want your backend to continue to return data (which of cours is going to be stale), store the caching block in a variable and return that variable that way you don’t get a 204 with no content returned and you may not necessarily have to implement a strategy to store data locally — this would be still great though in case of network issues or if the backend goes down. Shout out to Yomionisade for pointing this out in the comments.

PS: When I tried searching for a solution online, nothing made sense. Apparently, the Rails Docs/Guides still remains the most reliable resource to answer all your question.

--

--

Aremu Oluwagbamila (SMOG)
Aremu Oluwagbamila (SMOG)

Written by Aremu Oluwagbamila (SMOG)

full time overthinker doing frontend things.

Responses (1)