How to make a local variable an instance variable for an ERB template with Binding?

Asked

Viewed 74 times

1

Below I exemplify my need in a code where I need to redefine variables such as @dispute = dispute so that they are instance variables and the template loaded by ERB can access them through the binding:

class Remittance::ExportService
  def initialize(remittance)
    @remittance = remittance
    @template = 'app/views/remittances/letter.text.erb'
  end

  def letters
    tempfile = Tempfile.new(['post', '.txt'])

    @remittance.disputes.each_with_index do |dispute, index|
      @dispute = dispute
      @index = index

      dispute.users.each do |user|
        @user = user

        tempfile.write ERB.new(File.read(@template)).result binding
      end
    end

    tempfile.rewind

    @remittance.post = tempfile
    @remittance.save
  end
end

Is there any way to automatically turn local variables into instance variables using each or some magic method?

  • This code works without any problem, my questioning focuses on improvements and the possibility of learning. Perhaps there is no possibility of doing what I wish is to delete the three extra statements that this code has.

  • 1

    Studying on Binding seems to me that you would have access to all local variables within your template, without creating instance variables. Just access them without the @in front.

  • Yes, I do! But I use this same template in other places where the variable access is per instance. That would be a valid response to your observation as well. I’ll wait and see if I can get another answer. If there is such a possibility as well, from what I’m seeing, there may not be.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.