class Foxy::FileCache

Attributes

nocache[RW]

Public Class Methods

html(*path, &block) click to toggle source
# File lib/foxy/file_cache.rb, line 14
def html(*path, &block)
  cache path, "html", &block
end
html!(*path, &block) click to toggle source
# File lib/foxy/file_cache.rb, line 30
def html!(*path, &block)
  cache! path, "html", &block
end
json(*path) click to toggle source
# File lib/foxy/file_cache.rb, line 22
def json(*path)
  JSON[cache(path, "json") { JSON[yield] }]
end
json!(*path) click to toggle source
# File lib/foxy/file_cache.rb, line 38
def json!(*path)
  JSON[cache!(path, "json") { JSON[yield] }]
end
new(*path) click to toggle source
# File lib/foxy/file_cache.rb, line 75
def initialize(*path)
  @path = path
end
nocache!(reason = nil) click to toggle source
# File lib/foxy/file_cache.rb, line 8
def nocache!(reason = nil)
  self.nocache = true
  puts "NO CACHE: #{reason}"
  binding.pry
end
raw(*path, &block) click to toggle source
# File lib/foxy/file_cache.rb, line 18
def raw(*path, &block)
  cache path, "txt", &block
end
raw!(*path, &block) click to toggle source
# File lib/foxy/file_cache.rb, line 34
def raw!(*path, &block)
  cache! path, "txt", &block
end
yaml(*path) { || ... } click to toggle source
# File lib/foxy/file_cache.rb, line 26
def yaml(*path)
  YAML.load(cache(path, "yaml") { YAML.dump(yield) })
end
yaml!(*path) { || ... } click to toggle source
# File lib/foxy/file_cache.rb, line 42
def yaml!(*path)
  YAML.load(cache!(path, "yaml") { YAML.dump(yield) })
end

Private Class Methods

cache(path, format, force = false) { || ... } click to toggle source
# File lib/foxy/file_cache.rb, line 48
def cache(path, format, force = false)
  self.nocache = false
  path_tokens = path.map { |slice| slice.to_s.gsub(/[^a-z0-9\-]+/i, "_") }
                .unshift("cache")
  filepath = path_tokens.join("/") + ".#{format}"

  return File.read(filepath) if File.exist?(filepath) && !force

  makedir_p(path_tokens[0...-1])
  res = yield.to_s
  File.write(filepath, res) unless nocache

  res
end
cache!(path, format, &block) click to toggle source
# File lib/foxy/file_cache.rb, line 63
def cache!(path, format, &block)
  cache(path, format, true, &block)
end
makedir_p(tokens) click to toggle source
# File lib/foxy/file_cache.rb, line 67
def makedir_p(tokens)
  1.upto(tokens.size) do |n|
    dir = tokens[0...n].join("/")
    Dir.mkdir(dir) unless Dir.exist?(dir)
  end
end