|
| 1 | +require "active_support/all" |
| 2 | +require 'net/http' |
| 3 | +require 'json' |
| 4 | +require 'uri' |
| 5 | + |
| 6 | +module Helpers |
| 7 | + extend ActiveSupport::NumberHelper |
| 8 | +end |
| 9 | + |
| 10 | +module Jekyll |
| 11 | + class InspireHEPCitationsTag < Liquid::Tag |
| 12 | + Citations = { } |
| 13 | + |
| 14 | + def initialize(tag_name, params, tokens) |
| 15 | + super |
| 16 | + @recid = params.strip |
| 17 | + end |
| 18 | + |
| 19 | + def render(context) |
| 20 | + recid = context[@recid.strip] |
| 21 | + api_url = "https://inspirehep.net/api/literature/?fields=citation_count&q=recid:#{recid}" |
| 22 | + |
| 23 | + begin |
| 24 | + # If the citation count has already been fetched, return it |
| 25 | + if InspireHEPCitationsTag::Citations[recid] |
| 26 | + return InspireHEPCitationsTag::Citations[recid] |
| 27 | + end |
| 28 | + |
| 29 | + # Fetch the citation count from the API |
| 30 | + uri = URI(api_url) |
| 31 | + response = Net::HTTP.get(uri) |
| 32 | + data = JSON.parse(response) |
| 33 | + |
| 34 | + # # Log the response for debugging |
| 35 | + # puts "API Response: #{data.inspect}" |
| 36 | + |
| 37 | + # Extract citation count from the JSON data |
| 38 | + citation_count = data["hits"]["hits"][0]["metadata"]["citation_count"].to_i |
| 39 | + |
| 40 | + # Format the citation count for readability |
| 41 | + citation_count = Helpers.number_to_human(citation_count, format: '%n%u', precision: 2, units: { thousand: 'K', million: 'M', billion: 'B' }) |
| 42 | + |
| 43 | + rescue Exception => e |
| 44 | + # Handle any errors that may occur during fetching |
| 45 | + citation_count = "N/A" |
| 46 | + |
| 47 | + # Print the error message including the exception class and message |
| 48 | + puts "Error fetching citation count for #{recid}: #{e.class} - #{e.message}" |
| 49 | + end |
| 50 | + |
| 51 | + InspireHEPCitationsTag::Citations[recid] = citation_count |
| 52 | + return "#{citation_count}" |
| 53 | + end |
| 54 | + end |
| 55 | +end |
| 56 | + |
| 57 | +Liquid::Template.register_tag('inspirehep_citations', Jekyll::InspireHEPCitationsTag) |
0 commit comments