neighborland/cache_rocket

Key not getting replaced inside quotes

Closed this issue · 4 comments

When passing in:

<%= render_cached 'post',
  collection: @posts,
  replace: {
    post_id: -> (post) { post.id.to_s },
    ...
%>

and trying to use it as part of a css class name:

<%= content_tag(:li, class: "js-post-#{cache_replace_key :post_id}", .... do %>

it fails to replace the key and leaves <li class="js-post-&lt;cr post_id&gt;"....> in the html.

Is it because rails is converting the angle brackets to &lt; and &gt; before cache_digest can do a replace on them?

Is there a way around this or should I just pass the class string in as a key into the view?

<%= content_tag(:li, class: (cache_replace_key :list_item_class), ... do %>

I suspect Rails is escaping this string: "js-post-#{cache_replace_key :post_id}". You should call .html_safe on it.

Yep, that sorted it, thanks @teeparham.

@teeparham I was just wondering if it would be better if key.rb used double curly braces {{ }} for the key to replace rather than angle brackets < > to remove this issue in future.

Curly braces seem to be a standard in templating systems as well for sections of content to replace so hopefully should make sense.

What do you think?

Feel free to re-close the issue again if you don't think it's the right solution or even necessary.

I haven't run into any problems with <crk xyz> as the cache replace key format.

If this is a problem, you should be able to override CacheRocket::Key#cache_replace_key:

module CacheRocket
  module Key
    def cache_replace_key(key)
      "{{#{key}}}"
    end
  end
end