Reputation: 395
I have a hash I have created with Nokogiri, and I am trying to produce a JSON file out of it. I found
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(tempHash.to_json)
end
Problem is I keep getting the error
test.rb:43:in `initialize': No such file or directory - public/temp.json (Errno::ENOENT)
My code looks like
def summary
listing_data = @nodes
listings = listing_data.css('div.unsponsored div.item.compact.listing')
listing_hashes = listings.map do |x|
type = "#{@type}"
address = x.css('div.body h3 a').text
unit = x.css('div.body h3 a').text.gsub!(/.*?(?=#)/im, "")
url = x.css('div.item_inner div.body h3 a').text
price = x.css('h3 span').text
{
:type => type,
:address => address,
:unit => unit,
:url => url,
:price => price,
}
end
File.open("public/temp.json","w") do |f|
f.write(JSON.pretty_generate(listing_hashes))
end
end
Thanks!
Upvotes: 0
Views: 412
Reputation: 7566
The error is pretty self-explanatory: "No such file or directory - public/temp.json"
In this case, it's probably the directory that doesn't exist, since you specified 'w'
for the mode argument. Specifying 'w'
will create the file if it doesn't exist, but it won't create the directory.
Try creating the public
directory yourself and then running your code again.
Upvotes: 0
Reputation: 16730
You probably don't have the folder created. File.open
with the option w
will create a file if it does not exists, but it can't create missing directories.
You can create the folder with this code if you can't create it manually
Dir.mkdir('public') unless File.exists?('public')
File.open("public/temp.json","w") do |f|
f.write(JSON.pretty_generate(listing_hashes))
end
Upvotes: 1