Skip to content

Instantly share code, notes, and snippets.

@straydogstudio
Last active April 13, 2023 02:31
Show Gist options
  • Save straydogstudio/323139591f2cc5d48fbc to your computer and use it in GitHub Desktop.
Save straydogstudio/323139591f2cc5d48fbc to your computer and use it in GitHub Desktop.
Render template inside a Rails runner script
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 }
@bjgaynor
Copy link

@straydogstudio, any word on this?

@wilfrank84, did you get it working? I'll likely have a very similar setup soon and it would be great to have an example to work with if there is one.

@straydogstudio
Copy link
Author

@wilfrank84 @bjgaynor I apologize I have not gotten to this. I will get to it this weekend.

@straydogstudio
Copy link
Author

@willfrank84 Did you have any specific errors? Your stuff is too specific for me to run it on some rails project. I notice, however, that you are using the rails runner version of the script. When you run it outside of Docker, is it by command or within sidekiq? In docker are you using Sidekiq? It's been a long while since I worked with Sidekiq. The jobs I remember had to have extra work to have what they needed. But I am not sure.

@straydogstudio
Copy link
Author

@willfrank Would you post your Gemfile?

@delbetu
Copy link

delbetu commented Aug 23, 2022

This didn't work for me.

I had to do this:

content = ApplicationController.render(
  template: "exports/demo/index",
  locals: {posts: Post.all.limit(3)},
  handlers: [:axlsx],
  formats: [:xlsx]
)

@mculp
Copy link

mculp commented Apr 13, 2023

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