Class: Pupprb::Pdf

Inherits:
Object
  • Object
show all
Defined in:
lib/pupprb/pdf.rb

Defined Under Namespace

Classes: Unsecure

Constant Summary collapse

BASE58_ALPHABET =
("0".."9").to_a + ("A".."Z").to_a + ("a".."z").to_a - ["0", "O", "I", "l"]

Class Method Summary collapse

Class Method Details

.base58(n = 16) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/pupprb/pdf.rb', line 8

def base58(n = 16)
  SecureRandom.random_bytes(n).unpack("C*").map do |byte|
    idx = byte % 64
    idx = SecureRandom.random_number(58) if idx >= 58
    BASE58_ALPHABET[idx]
  end.join
end

.debug(message) ⇒ Object



24
25
26
# File 'lib/pupprb/pdf.rb', line 24

def debug message
  rails? ? Rails.logger.debug(message) : puts(message)
end

.gem_rootObject



20
21
22
# File 'lib/pupprb/pdf.rb', line 20

def gem_root
  File.join(File.expand_path(File.dirname(__FILE__)), "../..")
end

.rails?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/pupprb/pdf.rb', line 16

def rails?
  defined?(Rails) && Rails.class.is_a?(Module) && Rails.methods.include?(:root)
end

.write(url, options = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pupprb/pdf.rb', line 28

def write(url, options = {})
  filename = rails? ? Rails.root.join("tmp/#{base58(32)}.pdf").to_s : "/tmp/#{base58(32)}.pdf"

  resource = clean_resource(url.to_s)

  command = [File.join(gem_root, "bin", "puppeteer"), resource, filename]
  command << "--pageOptions=#{options[:page].to_json}" if options[:page]

  env = {}
  env["CHROME_DEVEL_SANDBOX"] = "/usr/local/sbin/chrome-devel-sandbox" if File.exist?("/usr/local/sbin/chrome-devel-sandbox")
  env["CHROME_DEVEL_SANDBOX"] ||= "/usr/local/sbin/chrome_sandbox" if File.exist?("/usr/local/sbin/chrome_sandbox")
  env["NODE_PATH"] = Rails.root.join("node_modules").to_s if rails?


  if !node_present?
    raise "Node not found. Required."
  end

  debug("Start creating a pdf using puppeteer, command: #{env.map{|k,v| "#{k}=>#{v}"}} #{command.join(' ')}")
  system(env, *command, exception: true)

  return filename
end