WagnerMatosUK WagnerMatosUK - 28 days ago 8
Ruby Question

Why ERB doesn't not render this line

I'm rendering a erb template outside Rails. The template is to be saved as an html file and sent elsewhere, so in my code I have this:

erb_file = "templates/banners/#{template}.html.erb"

erb_str = File.read(erb_file)

@city = options[:city]
@address = "#{@campaign.open_house_day} #{@case.open_house_from.strftime('%d/%m')} kl. #{@case.open_house_from.strftime('%H.%M')}-#{@case.open_house_to.strftime('%H.%M')}"
...

renderer = ERB.new(erb_str)
result = renderer.result(binding)

FileUtils.mkdir_p('temp') unless File.directory?('temp')

File.open('temp/index.html', 'w') do |f|
f.write(result)
end


All content is rendered fine, but erb simply ignore
@address
variable. Any ideas of why? While in my code, if I do
puts @address
the output is a string as expected. If I do
puts @address.class
the output is a String. Wha am I missing?

Please note that the above does not use Rails

EDIT

Here's the line in my template that I use to render the html:

<span class="wday"><%= @address %></span>

Answer

The main thing I can think of is you're not setting the instance variable in the same scope as the ERB rendering.

You can also try this to define address in the ERB:

# make sure address is set first
# if it's not, you have a scoping problem
raise(ArgumentError) if @address.nil?

binding.local_variable_set :address, @address

puts ERB.new("<%= address %>").result binding