Reputation: 683
I am using the axlsx gem to generate excel spreadsheets. I am trying to send the generated spreadsheet to the model for zipping. This method zips the excel file with some other files.
The method in my model looks like this:
def zipper
tempfile = Tempfile.new
children = self.children_with_forms
Zip::OutputStream.open(tempfile) do |stream|
children.each do |child|
directory = "#{child.wide_reference[0,3]}/"
if child.model_name == "Position"
stream.put_next_entry("#{child.volume} #{child.title} TOC.xlsx")
stream.print IO.read(Rails.application.routes.url_helpers.toc_path(format: :xlsx, position_id: child.id))
end
stream.put_next_entry("#{directory}#{child.wide_reference}-#{child.short_name}-#{child.title.truncate(15, omission:'')}.docx")
stream.print IO.read(child.download_form.path)
end
end
tempfile
end
The part I am having problems with is :
if child.model_name == "Position"
stream.put_next_entry("#{child.volume} #{child.title} TOC.xlsx")
stream.print IO.read(Rails.application.routes.url_helpers.toc_path(format: :xlsx, position_id: child.id))
end
How do I get the generated file to the model?
Upvotes: 0
Views: 1351
Reputation: 683
I ended up having to render the view from inside the model using: ActionView::Base.new(ActionController::Base.view_paths, {key: value})
, thanks to the help I received here.
Below is what ended up working.
def download
tempfile = Tempfile.new
children = self.children_with_forms
Zip::OutputStream.open(tempfile) do |stream|
children.each do |child|
directory = "#{child.wide_reference[0,3]}/"
if child.model_name == "Position"
av = ActionView::Base.new(ActionController::Base.view_paths, {position: child, model: child.model})
stream.put_next_entry("#{directory}#{child.volume} #{child.title} TOC.xlsx")
@position = child
@model = child.model
stream.print av.render template: 'pages/toc.xlsx.axlsx'
end
stream.put_next_entry("#{directory}#{child.wide_reference} #{child.title.truncate(15, omission:'')} (#{child.short_name}).docx")
stream.print IO.read(child.download_form.path)
end
stream.put_next_entry("Excel File.xlsx")
av = ActionView::Base.new(ActionController::Base.view_paths, {model: self})
stream.print av.render template: 'pages/excel_file.xlsx.axlsx'
end
tempfile
end
NOTE: "Model" is the name of the class that this method is in.
Upvotes: 0