Module: Mangdown::Tools

Included in:
CBZ
Defined in:
lib/mangdown/support/tools.rb

Overview

Common helpers

Constant Summary collapse

TYPHOEUS_OPTIONS =

rubocop:disable Metrics/LineLength

{
  headers: {
    'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36'
  }
}.freeze

Class Method Summary collapse

Class Method Details

.file_join(safe_path, *unsafe_parts) ⇒ Object



42
43
44
45
46
# File 'lib/mangdown/support/tools.rb', line 42

def file_join(safe_path, *unsafe_parts)
  now_safe_parts = unsafe_parts.map { |part| part.tr('/', '') }

  File.join(safe_path, *now_safe_parts)
end

.get(uri) ⇒ Object

Raises:



25
26
27
28
29
30
31
# File 'lib/mangdown/support/tools.rb', line 25

def get(uri)
  response = Typhoeus.get(uri)

  return response.body if response.success?

  raise Mangdown::Error, "Failed to GET: #{uri}"
end

.get_doc(uri) ⇒ Object

rubocop:enable Metrics/LineLength



20
21
22
23
# File 'lib/mangdown/support/tools.rb', line 20

def get_doc(uri)
  data = get(uri)
  @doc = Nokogiri::HTML(data)
end

.get_root(uri) ⇒ Object



33
34
35
36
# File 'lib/mangdown/support/tools.rb', line 33

def get_root(uri)
  uri = Addressable::URI.parse(uri)
  @root = "#{uri.scheme}://#{uri.host}"
end

.hydra_streaming(objects, hydra_opts = {}) ⇒ Object

rubocop:disable Metrics/MethodLength



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/mangdown/support/tools.rb', line 65

def hydra_streaming(objects, hydra_opts = {})
  hydra = Typhoeus::Hydra.new(hydra_opts)

  requests = objects.map do |obj|
    next unless yield(:before, obj)

    request = typhoeus(obj.uri)
    request.on_headers do |response|
      status = response.success? ? :succeeded : :failed
      yield(status, obj, response)
    end
    request.on_body do |chunk|
      yield(:body, obj, chunk)
    end
    request.on_complete do |_response|
      yield(:complete, obj)
    end

    hydra.queue(request)
    request
  end.compact

  hydra.run
  requests
end

.image_extension(path) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/mangdown/support/tools.rb', line 55

def image_extension(path)
  path = path.to_s

  return unless File.exist?(path)

  mime = MimeMagic.by_magic(File.open(path, 'r'))
  mime_to_extension(mime)
end

.relative_or_absolute_path(*sub_paths) ⇒ Object



38
39
40
# File 'lib/mangdown/support/tools.rb', line 38

def relative_or_absolute_path(*sub_paths)
  Pathname.new(Dir.pwd).join(*sub_paths)
end

.typhoeus(uri) ⇒ Object

rubocop:enable Metrics/MethodLength



92
93
94
# File 'lib/mangdown/support/tools.rb', line 92

def typhoeus(uri)
  Typhoeus::Request.new(uri, TYPHOEUS_OPTIONS)
end

.valid_path_name(name) ⇒ Object



48
49
50
51
52
53
# File 'lib/mangdown/support/tools.rb', line 48

def valid_path_name(name)
  name.to_s.sub(/(\d+)(\.\w+)*\Z/) do
    digits, ext = Regexp.last_match[1..2]
    digits.to_i.to_s.rjust(5, '0') + ext.to_s
  end
end