Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Rails helper methods available when calling render_to_string to render a template

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

like image 773
user1883793 Avatar asked Jan 06 '14 21:01

user1883793


1 Answers

ApplicationController.new.render_to_string works for me


like image 165
user1883793 Avatar answered Sep 24 '22 04:09

user1883793