Class: Diffux::Snapshotter

Inherits:
Object
  • Object
show all
Defined in:
lib/diffux_core/snapshotter.rb

Overview

Snapshotter is responsible for delegating to PhantomJS to take the snapshot for a given URL and viewoprt, and then saving that snapshot to a file and storing any metadata on the Snapshot object.

Constant Summary collapse

SCRIPT_PATH =
File.join(File.dirname(__FILE__), 'script/take-snapshot.js').to_s

Instance Method Summary collapse

Constructor Details

#initialize(url: raise, viewport_width: raise, outfile: raise, user_agent: nil) ⇒ Snapshotter

Returns a new instance of Snapshotter.

Parameters:

  • url (String) (defaults to: raise)

    the URL to snapshot

  • viewport_width (Integer) (defaults to: raise)

    the width of the screen used when snapshotting

  • outfile (File) (defaults to: raise)

    where to store the snapshot PNG.

  • user_agent (String) (defaults to: nil)

    an optional useragent string to used when requesting the page.



19
20
21
22
23
24
25
# File 'lib/diffux_core/snapshotter.rb', line 19

def initialize(url:     raise, viewport_width: raise,
               outfile: raise, user_agent: nil)
  @viewport_width = viewport_width
  @user_agent     = user_agent
  @outfile        = outfile
  @url            = url
end

Instance Method Details

#take_snapshot!Hash

Takes a snapshot of the URL and saves it in the out_file as a PNG image.

Returns:

  • (Hash)

    a hash containing the following keys: title [String] the <title> of the page being snapshotted log [String] a log of events happened during the snapshotting process



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/diffux_core/snapshotter.rb', line 32

def take_snapshot!
  result = {}
  opts = {
    address: @url,
    outfile: @outfile,
    viewportSize: {
      width:  @viewport_width,
      height: @viewport_width,
    },
  }
  opts[:userAgent] = @user_agent if @user_agent

  run_phantomjs(opts) do |line|
    begin
      result = JSON.parse line, symbolize_names: true
    rescue JSON::ParserError
      # We only expect a single line of JSON to be output by our snapshot
      # script. If something else is happening, it is likely a JavaScript
      # error on the page and we should just forget about it and move on
      # with our lives.
    end
  end
  result
end