Module: BibSync::Utils

Instance Method Summary collapse

Instance Method Details

#arxiv_download(dir, id) ⇒ Object



23
24
25
26
27
# File 'lib/bibsync/utils.rb', line 23

def arxiv_download(dir, id)
  File.open(File.join(dir, "#{arxiv_id(id, version: true, prefix: false)}.pdf"), 'wb') do |o|
    o.write(fetch("http://arxiv.org/pdf/#{id}"))
  end
end

#arxiv_id(arxiv, opts = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/bibsync/utils.rb', line 39

def arxiv_id(arxiv, opts = {})
  raise unless opts.include?(:prefix) && opts.include?(:version)
  arxiv = arxiv[:arxiv] if Entry === arxiv
  if arxiv
    arxiv = arxiv.sub(/\A.*\//, '') unless opts[:prefix]
    arxiv = arxiv.sub(/v\d+\Z/, '') unless opts[:version]
  end
  arxiv
end

#fetch(url, params = nil, headers = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/bibsync/utils.rb', line 8

def fetch(url, params = nil, headers = nil)
  client = Faraday.new(url) do |c|
    c.use FaradayMiddleware::FollowRedirects, limit: 3
    c.use Faraday::Response::RaiseError
    c.use Faraday::Adapter::NetHttp
  end
  response = client.get(url, params, headers)
  raise "HTTP error #{response.status}" unless response.status == 200
  body = response.body
  encoding = body.encoding
  body.force_encoding(Encoding::UTF_8)
  body.force_encoding(encoding) unless body.valid_encoding?
  body
end

#fetch_html(url, params = nil, headers = nil) ⇒ Object



35
36
37
# File 'lib/bibsync/utils.rb', line 35

def fetch_html(url, params = nil, headers = nil)
  Nokogiri::HTML(fetch(url, params, headers))
end

#fetch_xml(url, params = nil, headers = nil) ⇒ Object



29
30
31
32
33
# File 'lib/bibsync/utils.rb', line 29

def fetch_xml(url, params = nil, headers = nil)
  xml = Nokogiri::XML(fetch(url, params, headers))
  xml.remove_namespaces!
  xml
end

#name_without_ext(file) ⇒ Object



3
4
5
6
# File 'lib/bibsync/utils.rb', line 3

def name_without_ext(file)
  file =~ /\A(.*?)\.\w+\Z/
  $1
end