Skip to content

Instantly share code, notes, and snippets.

@kaichen
Created July 19, 2012 04:08
Show Gist options
  • Save kaichen/3140687 to your computer and use it in GitHub Desktop.
Save kaichen/3140687 to your computer and use it in GitHub Desktop.
Yet a cache generator for rubyonrails
# encoding: utf-8
require 'fileutils'
class MachineGun
class_attribute :page_cache_extension
self.page_cache_extension ||= '.html'
class_attribute :page_cache_directory
self.page_cache_directory ||= File.join(Rails.root, "public")
class << self
def touch klass, action, options = {}
path_info = url_for(klass.controller_path, action, options[:params] || {})
env = {
"rack.input" => StringIO.new(""),
"REQUEST_METHOD" => "GET",
"PATH_INFO" => path_info,
"QUERY_STRING" => ""
}
status, headers, body = klass.action(action).call env
if status == 200
write_cache_page body, path_info
else
raise "request error!"
end
status
end
def url_for controller, action, params = {}
options = {
:controller => controller,
:action => action,
:only_path => true
}.merge(params)
Rails.application.routes.url_for options
end
private
def write_cache_page(content, path, extension = nil, gzip = Zlib::BEST_COMPRESSION)
path = page_cache_path(path, extension)
FileUtils.makedirs(File.dirname(path))
File.open(path, "wb+") { |f| f.write(content) }
if gzip
Zlib::GzipWriter.open(path + '.gz', gzip) { |f| f.write(content) }
end
end
def page_cache_file(path, extension)
name = (path.empty? || path == "/") ? "/index" : URI.parser.unescape(path.chomp('/'))
unless (name.split('/').last || name).include? '.'
name << (extension || self.page_cache_extension)
end
return name
end
def page_cache_path(path, extension = nil)
page_cache_directory.to_s + page_cache_file(path, extension)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment