module VueCK class FileManager def initialize(filename) @filename = filename @js_cache = "#{DIRS[:cache]}#{FILES[:javascript]}" @css_cache = "#{DIRS[:cache]}#{FILES[:style]}" end def serve return render unless cache_valid? read_file end private def cache_valid? cachedir_exists? and cachefiles_exist? and cachefiles_fresh? end def render renders = BatchRenderer.new.render File.write(@js_cache, renders[:components]) File.write(@css_cache, renders[:style]) read_file end def read_file cache_file = @js_cache if @filename == FILES[:javascript] cache_file = @css_cache if @filename == FILES[:style] File.read(cache_file) end def cachedir_exists? return true if File.exists? DIRS[:cache] Dir.mkdir DIRS[:cache] false end def cachefiles_exist? return File.exists?(@js_cache) && File.exists?(@css_cache) end def cachefiles_fresh? cache_mtime = newest_file_in_dir(DIRS[:cache]) source_mtime = newest_file_in_dir(DIRS[:components]) return cache_mtime > source_mtime end def newest_file_in_dir(path) Dir.glob(File.join(path, '*.*')).max { |a,b| File.mtime(a) <=> File.mtime(b) } end end end