12

I have a ActiveMailer class, and inside I am sending emails with attached PDF template using the render_to_string method like this:

 def send_sales_order(email_service)
    @email_service = email_service
    @sales_order = SalesOrder.find_by_cid(email_service.order[:id])
    mail(:subject => I18n.t("custom_mailer.sales_order.subject", company_name: "test"), :to => @email_service.recipients) do |format|
      format.html
      format.pdf do
        attachments['purchase_order.pdf'] = WickedPdf.new.pdf_from_string(
          render_to_string('sales_orders/show.pdf.erb', locals: {current_company: @sales_order.company})
        )
      end
    end
  end

Inside the show.pdf.erb template, I called my helper methods defined elsewhere such as the current_company method defined in ApplicationController like follow:

    class ApplicationController < ActionController::Base
      helper_method :current_company, :current_role

      def current_company
        return if current_user.nil?
        if session[:current_company_id].blank?
          session[:current_company_id] = current_user.companies.first.id.to_s
        end
        @current_company ||= Company.find(session[:current_company_id])
      end

But these helper methods are not available when I use the render_to_string method to render the template, is there a way around this?

Thanks

user1883793
  • 4,011
  • 11
  • 36
  • 65

3 Answers3

7

ApplicationController.new.render_to_string works for me


Halo
  • 1,730
  • 1
  • 8
  • 31
user1883793
  • 4,011
  • 11
  • 36
  • 65
0

Starting with Rails 5 you can use:

rendered_string = ApplicationController.render(
  template: 'invoice/show',
  assigns: { invoice: invoice }
)

This create a request-like object in a controller like env, assign a @invoice instance variable accessible in the template.

See documentation here for more options: http://api.rubyonrails.org/classes/ActionController/Renderer.html#method-i-render

tal
  • 3,423
  • 1
  • 25
  • 21
-1

Just beat my head on the wall for a couple hours on this one. Finally found the add_template_helper method which did the trick.

class ApplicationController < ActionController::Base
  add_template_helper ApplicationHelper
  ...
  def foo
    @foo = render_to_string(partial: 'some_file.rb')
  end
end

This will make all methods from ApplicationHelper available, even when using render_to_string with a partial.

ErvalhouS
  • 4,178
  • 1
  • 22
  • 38
Paulissimo
  • 19
  • 1