Ruby on Rails - fragment caching in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
Fragment caching
- Rails cache, provided by ActiveSupport, can be used to cache any serializable Ruby object across requests.
- To fetch a value from the cache for a given key, use cache.read:
Rails.cache.read('city')
# => nil
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
- Use cache.write to write a value to the cache:
Rails.cache.write('city', 'Duckburgh')
Rails.cache.read('city')
# => 'Duckburgh'
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
Alternatively, use cache.fetch to read a value from the cache and optionally write a default if there is no value:
Rails.cache.fetch('user') do
User.where(:is_awesome => true)
end
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
- The return value of the passed block will be assigned to the cache under the given key, and then returned.
- We can also specify a cache expiry:
Rails.cache.fetch('user', :expires_in => 30.minutes) do
User.where(:is_awesome => true)
end