From b88a66dd306c24c07da1efd7ab0232ed51afbf21 Mon Sep 17 00:00:00 2001 From: evazion Date: Sat, 7 Apr 2018 09:19:32 -0500 Subject: [PATCH] Iqdb::Download.find_similar: simplify error handling. Raise errors immediately to avoid deeply nested if-else statements. --- app/logical/iqdb/download.rb | 46 ++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/app/logical/iqdb/download.rb b/app/logical/iqdb/download.rb index b9c52e66a..081187ebb 100644 --- a/app/logical/iqdb/download.rb +++ b/app/logical/iqdb/download.rb @@ -16,35 +16,31 @@ module Iqdb end def self.find_similar(source) - if Danbooru.config.iqdbs_server - url, ref = get_referer(source) - params = { - "key" => Danbooru.config.iqdbs_auth_key, - "url" => url, - "ref" => ref - } - uri = URI.parse("#{Danbooru.config.iqdbs_server}/similar") - uri.query = URI.encode_www_form(params) + raise NotImplementedError, "the IQDBs service isn't configured. Similarity searches are not available." unless enabled? - resp = HTTParty.get(uri, Danbooru.config.httparty_options) - if resp.success? - json = JSON.parse(resp.body) - if json.is_a?(Array) - post_ids = json.map { |match| match["post_id"] } - posts = Post.find(post_ids) + url, ref = get_referer(source) + params = { + "key" => Danbooru.config.iqdbs_auth_key, + "url" => url, + "ref" => ref + } + uri = URI.parse("#{Danbooru.config.iqdbs_server}/similar") + uri.query = URI.encode_www_form(params) - json.map do |match| - post = posts.find { |post| post.id == match["post_id"] } - match.with_indifferent_access.merge({ post: post }) - end - else - [] - end - else - raise "HTTP error code: #{resp.code} #{resp.message}" + resp = HTTParty.get(uri, Danbooru.config.httparty_options) + raise "HTTP error code: #{resp.code} #{resp.message}" unless resp.success? + + json = JSON.parse(resp.body) + if json.is_a?(Array) + post_ids = json.map { |match| match["post_id"] } + posts = Post.find(post_ids) + + json.map do |match| + post = posts.find { |post| post.id == match["post_id"] } + match.with_indifferent_access.merge({ post: post }) end else - raise NotImplementedError, "the IQDBs service isn't configured. Similarity searches are not available." unless enabled? + [] end end end