require 'dispatcher' class SitePackager # Base path for exporting static pages. @@base_path = "static" cattr_accessor :base_path # Location of configuration script @@configuration = "config/static_paths" cattr_accessor :configuration # Default extension to append to URIs @@static_extention = ".html" cattr_accessor :static_extention @@paths = Array.new cattr_accessor :paths def initialize(options = {}) rm_rf self.base_path mkdir_p self.base_path if options.has_key?(:with_public) ? options[:with_public] : true # Copy all files from 'public', excluding Rails' dispatch scripts public_files = Dir['public/*'].delete_if { |f| /dispatch\.(cgi|fcgi|rb)/.match f } FileUtils.cp_r public_files, self.base_path $stdout.puts "Copied entire 'public' folder to '#{self.base_path}'." end @paths = Array.new end def process require self.configuration self.paths.each { |path| get path } end private # Fakes a GET request to a given path and saves the response body to the base_path. def get(path) cgi = FakeCGI.new 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => path Dispatcher.dispatch cgi, false, cgi.stdoutput @result = cgi.stdoutput.string headers, body = @result.split(/\r\n\r\n/, 2) FileUtils.makedirs(File.dirname(self.base_path + path)) File.open(self.base_path + path + self.static_extention, "wb+") { |f| f.write(body) } end class FakeCGI < CGI attr_accessor :stdoutput, :env_table def initialize(env) self.env_table = env self.stdoutput = StringIO.new super() end end end # Some extensions, modifying view helpers to meet our needs. module ActionView module Helpers module UrlHelper # Redefine this method to include SitePackager::static_extention on the urls # this isn't entirely appropriate, what if linked content is not html? def url_for(options = {}, *parameters_for_method_reference) if options.kind_of? Hash options = { :only_path => true }.update(options.symbolize_keys) escape = options.key?(:escape) ? options.delete(:escape) : true else escape = true end url = @controller.send(:url_for, options, *parameters_for_method_reference) escape ? html_escape(url + SitePackager.static_extention) : url end end end end