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.