Module: Sinatra::FragmentCache

Defined in:
lib/sinatra_fragment_cache/fragment_cache.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cache_pathObject

Returns the value of attribute cache_path.



3
4
5
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 3

def cache_path
  @cache_path
end

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 3

def options
  @options
end

#pathObject

Returns the value of attribute path.



3
4
5
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 3

def path
  @path
end

Class Method Details

.registered(app) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 43

def self.registered(app)
  app.extend Sinatra
  app.helpers FragmentCache

  app.set :fragment_cache_enabled, true
  app.set :fragment_cache_output_dir, lambda { "#{ app.root }/tmp/cache" }
end

Instance Method Details

#fragment_cache(path, options = {}, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 5

def fragment_cache(path, options = {}, &block)
  @path = path
  @options = options
  file_name = options[:file_name] || 'index.cache'
  @cache_path = "#{ settings.fragment_cache_output_dir }/#{ path }/#{ file_name }"

  return block.call unless settings.fragment_cache_enabled

  @_out_buf = []
  if cache = read_fragment
    @_out_buf << cache
  else
    pos = @_out_buf.length
    tmp = block.call
    write_fragment tmp[pos..-1]
  end
end

#read_fragmentObject



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 23

def read_fragment
  now = Time.now
  if File.file?(cache_path)
    if options[:expires_in]
      (current_age = (now - File.mtime(cache_path)).to_i / 60)
      return false if (current_age > options[:expires_in])
    end
    return File.read(cache_path)
  end
  false
end

#write_fragment(buffer) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 35

def write_fragment(buffer)
  FileUtils.mkdir_p "#{ settings.fragment_cache_output_dir }/#{ path }"
  file = File.new(cache_path, 'w+')
  file.write(buffer)
  file.close
  buffer
end