Class: Pagelapse::Screenshot

Inherits:
Object
  • Object
show all
Includes:
Capybara::DSL
Defined in:
lib/pagelapse/screenshot.rb

Overview

Instance Method Summary collapse

Instance Method Details

#capture(url, output_path, width: 1024, height: 768, full: false, timeout: false, capture_if: nil, save_if: nil) ⇒ Object

Captures a screenshot of url saving it to output_path.



11
12
13
14
15
16
17
18
19
20
21
22
23
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
# File 'lib/pagelapse/screenshot.rb', line 11

def capture(url, output_path, width: 1024, height: 768, full: false, timeout: false, capture_if: nil, save_if: nil)
  # Browser settings
  page.driver.resize(width, height)
  page.driver.headers = {
    "User-Agent" => "Pagelapse #{Pagelapse::VERSION}",
  }

  unless capture_if
    capture_if = Proc.new do
      page.driver.status_code == 200
    end
  end

  unless save_if
    save_if = Proc.new do |old_file, new_file|
      Digest::MD5.file(old_file).hexdigest != Digest::MD5.file(new_file).hexdigest
    end
  end

  # Open page
  visit url

  # Timeout
  sleep timeout if timeout

  if instance_eval(&capture_if)
    old_file = last_file_next_to(output_path)

    # Save screenshot
    page.driver.save_screenshot(output_path, :full => full)

    # If no old file, than always save
    return true unless old_file

    if save_if.call(old_file, output_path)
      true
    else
      File.delete output_path
      false
    end
  else
    false
  end
end

#start_session(&block) ⇒ Object



56
57
58
59
60
# File 'lib/pagelapse/screenshot.rb', line 56

def start_session(&block)
  Capybara.reset_sessions!
  Capybara.current_session.instance_eval(&block) if block_given?
  self
end