tristanm
tristanm

Reputation: 3357

Is there a way to cache a string fragment within a helper method?

I have a helper that generates complex HTML for common components in an engine.

Helper (very simplified):

def component(name)
  component = Component.find_by_name!(name)
  # a whole lot of complex stuff that uses component to build some HTML
end

View:

<%= component(:my_component) %>

I want to implement fragment caching on these components but I want to do it within #component itself to keep things DRY, e.g.

def component(name)
  ...

  cache some_unique_fragment_name do
    html
  end

  # or, more succinctly:
  cache(some_unique_fragment_name, html)
end

The problem is that Rails' cache helper expects it's going to wrap a block of HTML in Erb and therefore won't work as I've described above.

Is there a way to use #cache for a string fragment in a helper method?

Upvotes: 3

Views: 435

Answers (1)

Gavin Miller
Gavin Miller

Reputation: 43875

I'm a big fan of the fetch block, you can read more in the Rails docs:

def component(name)
  # ...

  cache.fetch('some_unique_fragment_name') do
    html
  end
end

What this does is it will return the value of some_unique_fragment_name if it's available, otherwise it will generate it inside the block. It's a readable, clean way of showing that caching is occurring.

Upvotes: 3

Related Questions