Class: Tenjin::FileBaseTemplateCache

Inherits:
TemplateCache show all
Defined in:
lib/tenjin.rb

Overview

file base template cache which saves template script into file

Instance Method Summary collapse

Instance Method Details

#load(cachepath, timestamp = nil) ⇒ Object



1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
# File 'lib/tenjin.rb', line 1025

def load(cachepath, timestamp=nil)
  # 'timestamp' argument has mtime of template file
  #: load template data from cache file.
  begin
    #: if template timestamp is specified and different from that of cache file, return nil
    mtime = File.mtime(cachepath)
    if timestamp && mtime != timestamp
      #File.unlink(cachepath)
      Tenjin.logger.debug("[tenjin.rb:#{__LINE__}] cache expired (cachefile=#{cachepath.inspect}).") if Tenjin.logger
      return nil
    end
    script = File.open(cachepath, 'rb') {|f| f.read }
  rescue Errno::ENOENT => ex
    #: if cache file is not found, return nil.
    Tenjin.logger.debug("[tenjin.rb:#{__LINE__}] cache not found (cachefile=#{cachepath.inspect}).") if Tenjin.logger
    return nil
  end
  #: get template args data from cached data.
  args = script.sub!(/\A\#@ARGS (.*)\r?\n/, '') ? $1.split(/,/) : []
  #: return script, template args, and mtime of cache file.
  Tenjin.logger.debug("[tenjin.rb:#{__LINE__}] cache found (cachefile=#{cachepath.inspect}).") if Tenjin.logger
  return [script, args, mtime]
end

#save(cachepath, template) ⇒ Object



1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/tenjin.rb', line 1013

def save(cachepath, template)
  #: save template script and args into cache file.
  t = template
  tmppath = "#{cachepath}#{rand().to_s[1,8]}"
  s = t.args ? "\#@ARGS #{t.args.join(',')}\n" : ''
  File.open(tmppath, 'wb') {|f| f.write(s); f.write(t.script) }
  #: set cache file's mtime to template timestamp.
  File.utime(t.timestamp, t.timestamp, tmppath) if t.timestamp
  File.rename(tmppath, cachepath)
  Tenjin.logger.debug("[tenjin.rb:#{__LINE__}] cache saved (cachefile=#{cachepath.inspect}).") if Tenjin.logger
end