I am trying to create an html file from ERB, as I want to save a copy of invoice of a very complicated calculation. My ERB template is using many different calculation and using heavily number_to_currency
and image_tag
Following is my action method
def save_invoice
erb_file = 'app/views/orders/invoice.html.erb'
html_file = File.basename(erb_file, '.erb')
erb_str = File.read(erb_file)
renderer = ERB.new(erb_str)
@order = Order.find(params[:id]).to_i
result = renderer.result(binding)
File.open(html_file, 'w') do |f|
f.write(result)
end
end
My invoice.html.erb
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Invoice</title>
</head>
<body>
<header>
<%= image_tag 'logo_new.png', width: '110',height: '100' %>
</header>
<h1>Invoice # <%= @order.id %></h1>
<p>Client : <%= @order.user.first_name %>, <%= @order.user.last_name %></p>
<p>Amount : <%= number_to_currency(@order.totals) %></p>
It is making html file but if I remove all image_tag (viewer helper) and number_to_currency function. So how can I use those function in my ERB. I understand it is because I am creating ERB string I really don't understand this code much than a reference which is working when I remove all those functions. Please suggest me what should I include in method. I put here very condense codes, actually codes are a lot mess with thousands lines.
I just realised that I have used bindings, so why not call view helper as an object and use its function inside my view. that way it will automatically send helper to ERB
file. I added following line on top after def save_invoice
in my save_invoice method
@views_helper = ActionView::Base.new
Now in my erb file I have replace my image_tag
with adding this object like following
<%= @views_helper.image_tag 'logo_new.png', width: '110',height: '100' %>
and for my number_to_currency I did same thing
<p>Amount : <%= @views_helper.number_to_currency(@order.totals) %></p>
And it resolve my issue, currently working fine, I am sure I am making full object and then forwarding it to view may have consequences of heavy request but that is working fine for me.
As for explanation I create object and binding will show all local variables in my ERB file so this object will be also accessible and do job.