Skip to content

Commit

Permalink
Applied patch by Marek Janukowicz to stop race condition
Browse files Browse the repository at this point in the history
git-svn-id: http://svn.livsey.org/plugins/timed_fragment_cache@45 179e805f-c116-0410-8f81-92903350386d
  • Loading branch information
rlivsey committed Aug 13, 2007
1 parent e4eafd6 commit 682f7b9
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions lib/timed_fragment_cache.rb
Expand Up @@ -46,33 +46,39 @@ module Caching
# in the template, as 'when_fragment_expired' will expire the fragment for you.
module TimedFragment

def self.included(base) # :nodoc:
base.class_eval do
alias_method :cache_erb_fragment_without_expiry, :cache_erb_fragment
alias_method :cache_erb_fragment, :cache_erb_fragment_with_expiry
end
end

def cache_erb_fragment_with_expiry(block, name = {}, options = nil, expiry = nil)
def cache_erb_fragment(block, name = {}, options = nil, expiry = nil)
unless perform_caching then block.call; return end

if expiry && fragment_expired?(name)
fragment = get_fragment(name)
if expiry && !fragment
expire_and_write_meta(name, expiry)
end

cache_erb_fragment_without_expiry(block, name, options)

buffer = eval("_erbout", block.binding)

if fragment
buffer.concat(fragment)
else
pos = buffer.length
block.call
write_fragment(name, buffer[pos..-1], options)
end

end

def expiry_time(name)
read_meta_fragment(name)
end

def fragment_expired?(name)
return true unless read_fragment(name)
def get_fragment(name)
return fragments[name] if fragments[name]
fragment = read_fragment(name)
return nil unless fragment
fragments[name] = fragment
expires = expiry_time(name)
expires.nil? || expires < Time.now
return expires && expires > Time.now ? fragment : nil
end

def read_meta_fragment(name)
YAML.load(read_fragment(meta_fragment_key(name))) rescue nil
end
Expand All @@ -86,8 +92,7 @@ def meta_fragment_key(name)
end

def when_fragment_expired(name, expiry=nil)
return unless fragment_expired? name

return if get_fragment( name )
yield
expire_and_write_meta(name, expiry)
end
Expand All @@ -97,6 +102,9 @@ def expire_and_write_meta(name, expiry)
write_meta_fragment(name, expiry) if expiry
end

def fragments
@fragments ||= {}
end
end
end
end
Expand All @@ -120,4 +128,4 @@ def cache_with_expiry(name = {}, expires = nil, &block)
end

ActionController::Base.send :include, ActionController::Caching::TimedFragment
ActionView::Base.send(:include, ActionView::Helpers::TimedFragmentCacheHelper)
ActionView::Base.send(:include, ActionView::Helpers::TimedFragmentCacheHelper)

0 comments on commit 682f7b9

Please sign in to comment.