Bala Karthik Bala Karthik - 1 year ago 61
Ruby Question

Generate PDF by binding erb template that contains instance variable while sending email

While sending a mail, I need to convert the mail as a pdf document.

In order to do this i need to bind the erb template with the data, but the erb template contains instance variables

let the template be..,

<h1>Name: <%=@name%><h1>
<h2>Address: <%= @address %><h2>

I have followed this solution mention in the question, Using a namespace for binding the templates with data.

class Namespace
def initialize(hash)
hash.each do |key, value|
singleton_class.send(:define_method, key) { value }

def get_binding

ns = 'Joan', address: 'Chennai, India')

This works fine for the templates which doesn't contains instance variables.

I need to pass data to the instance variables in the template is there any possibility for doing this.

And I knew a way to solve this problem by assigning the instance variables with the data that we bind ie)

in the template

<% @name = name %>
<% @address = address %>
<h1>Name: <%=@name%><h1>
<h2>Address: <%= @address %><h2>

But I don't want this kind of implementation.

Answer Source

I hope you are rendering the HTML string to generate some PDF / kind of files. In those case, we need to declare the instance variable from where your are invoking those calls. So that it can be accessed through out the request. (Same mailer concepts)

I tried the below one for those cases. It works.

  def generate_attachment(your_variable)
    @your_instance_variable = your_variable

    attachments['attachment.pdf'] = => "filename.pdf",:template => '/_template.html.erb'))