Class: HtmlTo::HtmlHeadless

Inherits:
Object
  • Object
show all
Includes:
ChromiumControll
Defined in:
lib/html_to/html_headless.rb

Instance Method Summary collapse

Methods included from ChromiumControll

#chrome

Instance Method Details

#html_file_pathObject



35
36
37
# File 'lib/html_to/html_headless.rb', line 35

def html_file_path
  @path ||= Rails.public_path.join(SecureRandom.urlsafe_base64.downcase + ".html")
end

#screenshot_file_pathObject



38
39
40
# File 'lib/html_to/html_headless.rb', line 38

def screenshot_file_path
  @screenshot_file_path ||= Rails.public_path.join(SecureRandom.urlsafe_base64.downcase + ".png")
end

#to_image(obj, width = 1200, height = 630) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/html_to/html_headless.rb', line 6

def to_image(obj, width=1200, height=630)

  width = obj.class.class_variable_get(:@@html_to_width) if obj.class.class_variable_defined?(:@@html_to_width)
  height = obj.class.class_variable_get(:@@html_to_height) if obj.class.class_variable_defined?(:@@html_to_height)

  @template = File.read(Rails.root.join('app/views').join(obj.class.class_variable_get(:@@share_template)+".html.erb"))
  html = ERB.new(@template.html_safe).result(binding)
  File.open(html_file_path, 'w+') {|f| f.write(html) }
  begin
    cmd = "'#{chrome}'
      --headless
      --screenshot=#{screenshot_file_path}
      --window-size=#{width},#{height}
      --disable-gpu
      --disable-features=NetworkService #{html_file_path}".gsub("\n",' ')
    `#{cmd}`
    if $?.success?
      obj.skip_share_image_generate = true
      obj.send("#{obj.class.class_variable_get(:@@share_uploader)}=", File.open(screenshot_file_path))
      obj.save
    else
      raise "result = #{$?}; command = #{cmd}"
    end
  ensure
     FileUtils.rm(html_file_path)
     FileUtils.rm(screenshot_file_path)
  end
end