举例:当创建了一篇文章后,希望把这篇文章的 show 页面 html 给存到指定目录。
需求是,当你创建文章以后,我要把整个页面的 css 和 html 全部打包成 zip。
解决篇
# 这个方法就能生成HTML了。当然我还不知道怎么吧@var传到view里去。
def to_html
request = ActionDispatch::Request.new Hash.new
# I am using Gon also.
Gon.clear
Gon::Request.instance_variable_set(:@request_id, request.object_id)
Gon::Request.env = {}
# Assign gon variables
Gon.some_variables = self.some_variables
view = ActionView::Base.new(views_path)
view.controller = ArticlesController.new
view.request = request
text = view.render(
:formats => ['json'],
:template => 'articles/index',
:layout => 'layouts/application',
:locals => { :articles => @articles }
)
end
private
def views_path
@views_path ||= Rails.configuration.paths["app/views"]
end
def helpers
@helpers ||= Rails.application.routes.url_helpers
end
def default_host
@default_host ||= Rails.configuration.action_mailer.default_url_options[:host]
end
应要求,分享打包的代码
require 'zip/zip'
# Please run the method in background
def generate_offline_zip
# ensure the folder was there.
FileUtils.mkdir_p File.join(Rails.root, "tmp", "offline_zips")
zip_path = File.join(Rails.root, "tmp", "offline_zips", "#{self.id.to_s}.zip")
# Remove previous generated zip
FileUtils.rm_rf zip_path
Zip::ZipFile.open zip_path, Zip::ZipFile::CREATE do |zipfile|
# Store js css
zipfile.add "application.js", File.join(Rails.public_path, "assets", "application.js")
zipfile.add "application.css", File.join(Rails.public_path, "assets", "application.css")
zipfile.add "your_javascript.js", File.join(Rails.public_path, "assets", "your_javascript.js")
# Store audio and images
zipfile.add "audio.mp3", File.join(Rails.public_path, self.audio_path)
zipfile.add "image.png", File.join(Rails.public_path, "assets", "image.png")
# Store index.html
zipfile.get_output_stream("index.html") { |f| f.puts self.to_html }
end
# move zip to public folder
FileUtils.mkdir_p File.join(Rails.public_path, "zips") # make sure folder was there.
FileUtils.mv zip_path, File.join(Rails.public_path, "zips", "#{self.id}.zip")
true
rescue => e
# error processing
false
end