Reputation: 328
I am currently using the cities gem to populate a list of cities in the database for creation of addresses. I have been asked to remove this gem and to read in all the json files from the cities folder that comes with the cities gem.
I have looked at several SO posts regarding how to do implement this, including: Iterate through every file in one directory
Upon implementation wit the Dir.glob
, my app just completely crashes on that specific page and quits/exits the server.
Otherwise, with Dir.foreach
, I get
Errno::ENOENT in StuffsController
No such file or directory @ dir_initialize
For this error, I tried this SO post but realized that I really can't be updating my Gemfile as it causes more problems for me.
Here is my code that produces Errno::ENOENT
:
@okay = Array.new
Dir.foreach("#{Rails.root}/cities/*.json") do |json_file|
@okay << JSON.parse(File.read(json_file))
end
I have also tried the below code from this SO post but received a
NameError in StuffsController
undefined local variable or method `id' for # <StuffsController>
@okay = Array.new
Dir.foreach("#{Rails.root}/cities/#{id}.json") do |json_file|
@okay << JSON.parse(File.read(json_file))
end
I can get it to work for reading a single file from that folder just fine, 100% no problems:
@cities = Array.new
@json = JSON.parse(File.read('cities/AD.json'))
@json.each do |j|
if j.second.has_key?("accentcity")
@cities << j.second.select {|k,v| k == "accentcity"}
name = j.second.select {|k,v| k == "accentcity"}
City.first_or_create(name: name)
end
end
(Please note that the @cities
array was primarily used for testing whether or not my method produced what I wanted)
I am using Ruby on Rails version 4.2.6.
Upvotes: 3
Views: 4291
Reputation: 54223
Dir.foreach
isn't the correct method here. Its parameter should be a directory, not a glob pattern. In your case, it looks for a directory literally called "cities/*.json"
in your Rails project, which obviously doesn't exist.
If there only are .json
files in cities/
, you could use Dir.foreach("#{Rails.root}/cities/")
Dir.glob
should be the correct method. Could you please show us the error message you get when your server crashes?
This code should work, provided all the json files in "cities"
are valid :
@okay = Dir.glob("#{Rails.root}/cities/*.json").map do |json_file|
JSON.parse(File.read(json_file))
end
Upvotes: 6