Accessing URL Helpers when Rendering Partials from Rails Models

Viewed 1682

I have to render some templates and send the HTML block to SendGrid for email substitution. So, unfortunately, I am doing some rendering in model like this:

    view = ActionView::Base.new(Rails.configuration.paths["app/views"].first)
    view.render(:partial => template_name)

Even if I added:

    view.extend Rails.application.routes.url_helpers
    view.extend ActionView::Helpers::UrlHelper
    view.extend ApplicationHelper

The partial don't have access to URL Helpers like url_for unless I explicit define the module like in the following:

    Rails.application.routes.url_helpers.edit_user_url(user, :host => Rails.application.config.action_mailer.default_url_options[:host])

Is there a cleaner way to use URL Helper in templates called from models?

4 Answers

this is my solution

options = Rails.configuration.action_mailer.default_url_options
view = ApplicationController.renderer.new(http_host: "#{options[:host]}:#{options[:port]}")
view.class_eval do       
  include Rails.application.routes.url_helpers
  include ApplicationHelper

  def protect_against_forgery?
    false
  end
end
view.render partial: "mailers/#{name.to_s}", layout:false
Related