Class: IronWorkerNG::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/iron_worker_ng/fetcher.rb

Class Method Summary collapse

Class Method Details

.fetch(url, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/iron_worker_ng/fetcher.rb', line 24

def self.fetch(url, &block)
  if IronWorkerNG::Fetcher.remote?(url)
    url = IronWorkerNG::Fetcher.fix_github_url(url)

    uri = URI.parse(url)

    http = Net::HTTP.new(uri.host, uri.port)

    if uri.scheme == 'https'
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    response = http.request(Net::HTTP::Get.new(uri.request_uri))

    if response.kind_of?(Net::HTTPRedirection)
      IronWorkerNG::Fetcher.fetch(response['location'], &block)

      return
    end

    block.call(response.body) unless block.nil?
  else
    unless File.exists?(url)
      block.call(nil) unless block.nil?

      return
    end

    block.call(File.read(url)) unless block.nil?
  end
end

.fetch_to_file(url, &block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/iron_worker_ng/fetcher.rb', line 57

def self.fetch_to_file(url, &block)
  if IronWorkerNG::Fetcher.remote?(url)
    IronWorkerNG::Fetcher.fetch(url) do |data|
      unless data.nil?
        tmp_dir_name = ::Dir.tmpdir + '/' + ::Dir::Tmpname.make_tmpname('iron-worker-ng-', 'http')

        ::Dir.mkdir(tmp_dir_name)

        File.open(tmp_dir_name + '/' + File.basename(url), 'wb') do |f|
          f.write(data)
        end

        block.call(tmp_dir_name + '/' + File.basename(url)) unless block.nil?

        FileUtils.rm_rf(tmp_dir_name)
      end
    end
  else
    unless File.exists?(url)
      block.call(nil) unless block.nil?

      return
    end

    block.call(url) unless block.nil?
  end
end

.fix_github_url(url) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/iron_worker_ng/fetcher.rb', line 12

def self.fix_github_url(url)
  if url.start_with?('http://github.com/') || url.start_with?('https://github.com/')
    fixed_url = url.sub('//github.com/', '//raw.github.com/').sub('/blob/', '/')

    IronCore::Logger.info 'IronWorkerNG', "Fixed github link with url='#{url}' to url='#{fixed_url}'"

    return fixed_url
  end

  url
end

.remote?(url) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/iron_worker_ng/fetcher.rb', line 8

def self.remote?(url)
  url.start_with?('http://') || url.start_with?('https://')
end