Skip to content

Instantly share code, notes, and snippets.

@hlxwell
Last active December 20, 2015 20:59
Show Gist options
  • Save hlxwell/6194299 to your computer and use it in GitHub Desktop.
Save hlxwell/6194299 to your computer and use it in GitHub Desktop.
How to render text in model
# One thing I don't know is how to pass @var to template.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment