Skip to content

Commit

Permalink
fixup! If there's a local copy of the MapIt Area data, use that
Browse files Browse the repository at this point in the history
  • Loading branch information
mhl committed Mar 3, 2017
1 parent 9827871 commit 9aeac8f
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions lib/mapit/wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,26 +45,34 @@ def mapit_area_cache_filename(area_type)
File.join('mapit', "#{URI.parse(mapit_url).host}-#{area_type}.json")
end

def fetch_and_save(url, filename)
FileUtils.mkdir_p(File.dirname(filename))
def download_to_file(url, filename)
ensure_containing_directory_exists(filename)
open(filename, 'wb') do |f|
data = Net::HTTP.get(url)
f.write(data)
data
end
end

def mapit_area_url(area_type)
URI(mapit_url + area_type)
end

def ensure_containing_directory_exists(filename)
FileUtils.mkdir_p(File.dirname(filename))
end

def ensure_downloaded(url, filename)
download_to_file(url, filename) unless File.file?(filename)
end

def parse_json_file(filename)
JSON.parse(open(filename, &:read))
end

def areas_data(area_type)
# If the MapIt data is already cached in the filesystem, use
# that - otherwise fetch it from the server and save it.
cache_filename = mapit_area_cache_filename(area_type)
if File.file?(cache_filename)
json_data = open(cache_filename, &:read)
else
url = URI(mapit_url + area_type)
json_data = fetch_and_save(url, cache_filename)
end
JSON.parse(json_data).values
ensure_downloaded(mapit_area_url(area_type), cache_filename)
parse_json_file(cache_filename).values
end

def cache_mapit_data
Expand Down

0 comments on commit 9aeac8f

Please sign in to comment.