Module: CacheRocket

Includes:
Key
Defined in:
lib/cache_rocket.rb,
lib/cache_rocket/key.rb,
lib/cache_rocket/version.rb,
lib/cache_rocket/fragment.rb

Defined Under Namespace

Modules: Key Classes: Fragment

Constant Summary collapse

ERROR_MISSING_KEY_OR_BLOCK =
"You must either pass a `replace` key or a block to render_cached."
VERSION =
"0.2.1"

Constants included from Key

Key::CACHE_REPLACE_KEY_OPEN

Instance Method Summary collapse

Methods included from Key

#cache_replace_key

Instance Method Details

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

Supports 5 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
  1. Render a collection with Procs for replace values.

render_cached "partial", collection: objects, replace: { key_name: ->(object){a_method(object)} }


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cache_rocket.rb', line 36

def render_cached(partial, options={})
  replace_hash = options.delete(:replace)
  collection = options.delete(:collection)

  fragment = Fragment.new(render(partial, options))

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

  fragment.to_s.html_safe
end