Module: Sinatra::FragmentCache
- Defined in:
- lib/sinatra_fragment_cache/fragment_cache.rb
Instance Attribute Summary collapse
-
#cache_path ⇒ Object
Returns the value of attribute cache_path.
-
#options ⇒ Object
Returns the value of attribute options.
-
#path ⇒ Object
Returns the value of attribute path.
Class Method Summary collapse
Instance Method Summary collapse
- #fragment_cache(path, options = {}, &block) ⇒ Object
- #read_fragment ⇒ Object
- #write_fragment(buffer) ⇒ Object
Instance Attribute Details
#cache_path ⇒ Object
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 |
#options ⇒ Object
Returns the value of attribute options.
3 4 5 |
# File 'lib/sinatra_fragment_cache/fragment_cache.rb', line 3 def @options end |
#path ⇒ Object
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, = {}, &block) @path = path @options = file_name = [: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_fragment ⇒ Object
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 [:expires_in] (current_age = (now - File.mtime(cache_path)).to_i / 60) return false if (current_age > [: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 |