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



33
34
35
36
37
38
39
40
41
# File 'lib/bibsync/utils.rb', line 33

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_xml(url, params = nil, headers = nil) ⇒ Object



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

def fetch_xml(url, params = nil, headers = nil)
  REXML::Document.new(fetch(url, params, headers)).root
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