Generating multiple files with one ERB template

I’m trying to generate html files based on an ERB template with data
pulled from yaml files.

My code looks like this:

listing_data = Dir[’…/data/*’]

listings = []
listing_data.each do |file|
listing = File.open(file) { |data| YAML::load(data) }
listings << Listing.new(listing)
end

listing_template = ERB.new(File.read(‘listing.rhtml’))

listings.each do |listing|
File.open("…/homes/#{listing.file_name}.html", ‘w’) { |file|
file.write(listing_template.result(binding)) }
end

The problem that I am having is only the first listing is generated
along with an error: “no such file or directory” for the second one.

I have spent a couple of hours looking into it and trying different
things, but I’m just not able to figure it out. I know everything is in
place because the first listing gets generated just fine, but why
doesn’t it loop through the rest? If anybody can help me out that would
be amazing.

The problem that I am having is only the first listing is generated
along with an error: “no such file or directory” for the second one.

That couldn’t be more vague. Which lines of code are you talking about?

The following works fine for me:

require ‘erb’
require ‘yaml’

class Listing
attr_reader :file_name, :data

def initialize(arr)
@file_name = arr[0]
@data = arr[1]
end
end

data = [‘listingA’, 3]
File.open("…/data/data1.yaml", “w”) {|f| YAML::dump(data, f)}
data = [‘listingB’, 2]
File.open("…/data/data2.yaml", “w”) {|f| YAML::dump(data, f)}

data_fnames = Dir["…/data/*"]
p data_fnames

listings = []

data_fnames.each do |fname|
yaml_data = File.open(fname) {|f| YAML::load(f)}
listings << Listing.new(yaml_data)
end

p listings

listing_template = ERB.new(File.read(‘listing.rhtml’))

=begin
#listing.rhtml:

<% count.times do |i| %>
info <%= i %>
<% end %> =end

listings.each do |listing|
fname = listing.file_name
count = listing.data
File.open("…/homes/#{listing.file_name}.html", “w”) do |f|
f.write(listing_template.result(binding))
end
end

–output:–
["…/data/data1.yaml", “…/data/data2.yaml”]

[#<Listing:0x5d4080 @file_name=“listingA”, @data=3>,
#<Listing:0x5d3edc @file_name=“listingB”, @data=2>]

I have spent a couple of hours looking into it and trying different
things

Depending on what’s in your template, I think you could have problems
with this part:

listings.each do |listing|
File.open("…/homes/#{listing.file_name}.html", ‘w’) { |file|
file.write(listing_template.result(binding)) }
end

In the future, copy and paste the exact error message–not your
characterization of the error–as well a comment in your code where the
error occurred, e.g.

#<-------ERRROR HERE*****

thanks for the response and sorry to be so vague!

I was using Dir.chdir in one of my methods in my listing class, which
was the problem.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs