Develop the right mindset for Rails security
Avoid shipping vulnerable code by learning how to prevent security issues in your Rails applications.
Get the course for $99The app itself is a typical kanban board where you can setup different stages for the tasks and they are in the column of the appropriate stage. I have a project where I have 4 stages: To-do, In progress, Waiting for review, Done. On this board I have 138 tasks in the moment. According to Rack Metrics this page takes between 1485 and 1678 ms to get ready on the server side. This is way too slow in my opinion so I will dig in a bit more. I randomly picked one of the request to this route and I saw there the following:
Duration: 1598.14ms
View runtime: 1485.152174ms
DB runtime: 78.776503ms
Render calls: 140First, I need to make sure caching is enabled and set to `mem_cache_store` by putting this line into config/production.rb:
config.action_controller.perform_caching = true
config.cache_store = :mem_cache_store<% status.tasks.each do |task| %>
<%= render task %>
<% end %><% status.tasks.each do |task| %>
<% cache(task) do %>
<%= render task %>
<% end %>
<% end %>class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true, touch: true
endI already made my app perform better but there is one more thing I can do to make it even faster. I could cache the whole view in a fragment and bust the cache when any of the tasks has changed. To make this work I created a helper method to generate a cache_key based on the number of tasks and the updated task:
module ProjectsHelper
def cache_key_for_tasks
count = Task.count
max_updated_at = Task.maximum(:updated_at).try(:utc).try(:to_s, :number)
"tasks/all-#{count}-#{max_updated_at}"
end
end<% cache(cache_key_for_tasks) do %>
...
# rest of the file
<% end %>As you see with clever caching your Rails app can be a lot faster and use less resources.
I hope you enjoyed the article. UPDATE: A second part of this acrticle available at: https://greg.molnar.io/blog/rails-caching-again