Last active
April 13, 2023 02:31
-
-
Save straydogstudio/323139591f2cc5d48fbc to your computer and use it in GitHub Desktop.
Render template inside a Rails runner script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
view_assigns = {widgets: Widget.all} | |
av = ActionView::Base.new(ActionController::Base.view_paths, view_assigns) | |
av.class_eval do | |
# include any needed helpers (for the view) | |
include ApplicationHelper | |
end | |
# normal render statement | |
content = av.render template: 'widgets/index.xlsx.axlsx' | |
# do something with content, such as: | |
File.open("/tmp/with_runner.xlsx","w+b") {|f| f.puts content } |
If you’re writing a view spec or similar, and your template contains instance variables, you can add/change locals
to assigns
in the above snippet from @delbetu
# if your .xlsx.aslsx file needs access to a `@posts`
# instance variable rather than local variable, use this:
content = ApplicationController.render(
template: "exports/demo/index",
assigns: { posts: Post.all.limit(3) },
handlers: [:axlsx],
formats: [:xlsx]
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This didn't work for me.
I had to do this: