lib/nuva.rb in nuva-0.4.0 vs lib/nuva.rb in nuva-0.4.1

- old
+ new

@@ -57,34 +57,46 @@ def inspect "#<Nuva::Nuva version=#{version.major}.#{version.minor}.#{version.patch} diseaseCount=#{repositories.diseases.all.count} vaccineCount=#{repositories.vaccines.all.count} valenceCount=#{repositories.valences.all.count}>" end - LATEST_VERSION_URI = - URI("https://cdnnuva.mesvaccins.net/versions/last.json") + class << self + CDN_URI = URI("https://cdnnuva.mesvaccins.net/") - def self.load(lang: "en", hash: nil) - ::Net::HTTP.start( - LATEST_VERSION_URI.host, - LATEST_VERSION_URI.port, - use_ssl: LATEST_VERSION_URI.scheme == "https" - ) do |http| - # Fetch version manifest if necessary - hash ||= fetch_latest_version_hash(http:) + def load(lang: "en", hash: nil) + init_http do |http| + # Fetch version manifest if necessary + hash ||= fetch_latest_version_hash(http:) - dump_uri = LATEST_VERSION_URI.dup - dump_uri.path = "/proto/#{hash}_en.db" - response = http.get(dump_uri) - ::Nuva::Nuva.new(::Nuva::NuvaDatabase.decode(response.body)) + response = http.get("/proto/#{hash}_en.db") + ::Nuva::Nuva.new(::Nuva::NuvaDatabase.decode(response.body)) + end end - end - def self.fetch_latest_version_hash(http: Net::HTTP) - response = http.get(LATEST_VERSION_URI) - JSON.parse(response.body)["dump_hash"] - end + def fetch_latest_version_hash(http: nil) + if http.nil? + http = init_http + passed_http = false + end + response = http.get("/versions/last.json") + hash = JSON.parse(response.body)["dump_hash"] + http.finish unless passed_http + hash + end - def self.load_from_file(path) - Nuva.new(NuvaDatabase.decode(File.read(path))) + def load_from_file(path) + Nuva.new(NuvaDatabase.decode(File.read(path))) + end + + private + + def init_http(&block) + Net::HTTP.start( + CDN_URI.host, + CDN_URI.port, + use_ssl: CDN_URI.scheme == "https", + &block + ) + end end end end