From fd69f9e04dfd5fcf19abbce43f052f91d98d52c3 Mon Sep 17 00:00:00 2001 From: Dan Milne Date: Wed, 22 Apr 2020 17:29:07 +1000 Subject: [PATCH] Get the data from the array just once --- Gemfile.lock | 2 +- lib/openlib/book.rb | 11 +++++++++-- lib/openlib/client.rb | 6 +++++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index 29ae474..376a5ed 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - openlib (0.1.0) + openlib (0.1.1) GEM remote: https://rubygems.org/ diff --git a/lib/openlib/book.rb b/lib/openlib/book.rb index 7c4571a..6820f2b 100644 --- a/lib/openlib/book.rb +++ b/lib/openlib/book.rb @@ -27,15 +27,19 @@ module Openlib @data ||= @client.get(id: @id, id_kind: @id_kind, format: 'data') end + def web + @web ||= @client.get(id: @id, id_kind: @id_kind, format: 'data') + end + def view_data(req:) view.first.last.dig(req.to_s) end def data_data(req:) case req - when :authors, :publishers, :subjects then data.first.last.dig(req.to_s).map { |p| p.dig('name') } + when :authors, :publishers, :subjects then data.dig(req.to_s).map { |p| p.dig('name') } else - data.first.last.dig(req.to_s) + data.dig(req.to_s) end end @@ -44,11 +48,14 @@ module Openlib end def to_h + return {} if data.empty? + %i[url authors identifiers classifications subjects subject_places subject_people subject_times publishers publish_places publish_date excerpts links cover ebooks number_of_pages weight title].each_with_object({}) do |obj, memo| memo[obj] = send(obj) unless send(obj).nil? + memo end end diff --git a/lib/openlib/client.rb b/lib/openlib/client.rb index 8e5d1e5..73c7a33 100644 --- a/lib/openlib/client.rb +++ b/lib/openlib/client.rb @@ -20,7 +20,11 @@ module Openlib puts resp.status.first.to_s unless resp.status.first == '200' - JSON.parse(resp.read) + data = JSON.parse(resp.read) + + return data if data.empty? + + data.find { |k, _v| k.include?(id) }&.last end end end