Module: Relaton::Doi::Crossref

Extended by:
Crossref
Included in:
Crossref
Defined in:
lib/relaton/doi/crossref.rb

Constant Summary collapse

USER_AGENT =
"Relaton::Doi (https://www.relaton.org/guides/doi/; mailto:open.source@ribose.com)"

Instance Method Summary collapse

Instance Method Details

#agentObject



65
66
67
68
69
# File 'lib/relaton/doi/crossref.rb', line 65

def agent
  @agent ||= Mechanize.new do |a|
    a.user_agent = USER_AGENT
  end
end

#get(doi) ⇒ RelatonBib::BibliographicItem, ...

Get a document by DOI from the CrossRef API.

Parameters:

  • doi (String)

    The DOI.

Returns:

  • (RelatonBib::BibliographicItem, RelatonIetf::IetfBibliographicItem, RelatonBipm::BipmBibliographicItem, RelatonIeee::IeeeBibliographicItem, RelatonNist::NistBibliographicItem)

    The bibitem.



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/relaton/doi/crossref.rb', line 19

def get(doi)
  Util.info "Fetching from search.crossref.org ...", key: doi
  id = doi.sub(%r{^doi:}, "")
  message = get_by_id id
  if message
    Util.info "Found: `#{message['DOI']}`", key: doi
    Parser.parse message
  else
    Util.info "Not found.", key: doi
    nil
  end
end

#get_by_id(id) ⇒ Hash

Get a document by DOI from the CrossRef API.

Parameters:

  • id (String)

    The DOI.

Returns:

  • (Hash)

    The document.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/relaton/doi/crossref.rb', line 39

def get_by_id(id) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
  n = 0
  url = "https://api.crossref.org/works/#{CGI.escape(id)}"
  loop do
    resp = agent.get url
    work = JSON.parse resp.body
    return work["message"] if work["status"] == "ok"

    if n > 1
      raise Relaton::RequestError, "Crossref error: #{resp.body}"
    end

    n += 1
    sleep resp.response["x-rate-limit-interval"].to_i * n
  rescue Mechanize::ResponseCodeError => e
    return nil if e.response_code == "404"

    if n > 1
      raise Relaton::RequestError, "Crossref error: #{e.page.body}"
    end

    n += 1
    sleep e.page.response["x-rate-limit-interval"].to_i * n
  end
end