Last active
April 19, 2017 00:21
-
-
Save TeknoFiend/20f335aa6f5fb826e2772dec093b4bc1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%# Making sure a Rails partial's dependencies are represented in the cache keys is a common source %> | |
<%# of bugs that are hard to debug & often "bad" (revealing priviledged info). %> | |
<%# One strategy I've used is to cache outside a partial and try to pass the parts of the cache %> | |
<%# key to the partial as locals. This setup is beneficial because the proximity of the key to %> | |
<%# the locals makes it easier to realize/remember to update them at the same time. But they can %> | |
<%# still fall out of sync (also the partial can access `@post` or whatever behind your back). %> | |
<% cache [ @post, @user.can_edit?, @user.can_delete? ] do %> | |
<%= render partial: 'post', locals: { post: @post, user_can_edit: @user.can_edit?, user_can_delete: user.can_delete? } %> | |
<% end %> | |
<%# One possible improvement would be to wrap the context needed by the partial in an object with %> | |
<%# a pair of methods for the cache key & the locals. In the object you would need to keep the %> | |
<%# key & data in sync but you should be able to do that automatically with some meta programming. %> | |
<% cacheable_post = CacheablePost.new( @post, @user ) %> | |
<% cache cacheable_post.cache_key do %> | |
<%= render partial: 'post', locals: cacheable_post.locals_for_partial %> | |
<% end %> | |
<%# A solution like this (esp. w/ the meta programming) seems like it would work well as a gem so %> | |
<%# I'm wondering if this already exists and I just can't find it or if I'm going about this all "wrong". %> | |
<%# This still has the problem that the partial can technically access any controller variables %> | |
<%# (i.e. `@post`) that it wants to. AFAIK there's no way to restrict partials to just `locals`. %> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment