Module: CacheReplace

Defined in:
lib/cache_replace.rb,
lib/cache_replace/version.rb

Constant Summary collapse

ERROR_MISSING_KEY_OR_BLOCK =
"You must either pass a `replace` key or a block to render_cached."
CACHE_REPLACE_KEY_OPEN =
'<cr '
VERSION =
"0.1.3"

Instance Method Summary collapse

Instance Method Details

#cache_replace_key(key) ⇒ Object

string key containing the partial file name or placeholder key. It is a tag that should never be returned to be rendered by the client, but if so, it will be hidden since CR is not a valid html tag.



52
53
54
# File 'lib/cache_replace.rb', line 52

def cache_replace_key(key)
  raw "#{CACHE_REPLACE_KEY_OPEN}#{key.to_s}>"
end

#render_cached(partial, options = {}) ⇒ Object

Supports 4 options:

  1. Single partial to replace. “inner” is the key name and “_inner.*” is the partial file name.

render_cached "container", replace: "inner"
  1. Array of partials to replace

render_cached "container", replace: ["inner"]
  1. Map of keys to replace with values

render_cached "container", replace: {key_name: a_helper_method(object)}
  1. Yield to a hash of keys to replace with values

render_cached "container" do
  {key_name: a_helper_method(object)}
end


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/cache_replace.rb', line 27

def render_cached(partial, options={})
  replace = options.delete(:replace)
  fragment = render(partial, options)

  case replace
  when Hash
    replace_from_hash fragment, replace
  when NilClass
    raise ArgumentError.new(ERROR_MISSING_KEY_OR_BLOCK) unless block_given?
    replace_from_hash fragment, yield
  else
    replace = *replace
    replace.each do |key|
      fragment.gsub! cache_replace_key(key), render(key, options)
    end
  end

  raw fragment
end