Class: Webshot::Screenshot
- Inherits:
-
Object
- Object
- Webshot::Screenshot
- Includes:
- Capybara::DSL, Singleton
- Defined in:
- lib/webshot/screenshot.rb
Instance Method Summary collapse
-
#capture(url, path, opts = {}) ⇒ Object
Captures a screenshot of
urlsaving it topath. -
#initialize(opts = {}) ⇒ Screenshot
constructor
A new instance of Screenshot.
- #start_session(&block) ⇒ Object
Constructor Details
#initialize(opts = {}) ⇒ Screenshot
Returns a new instance of Screenshot.
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/webshot/screenshot.rb', line 8 def initialize(opts = {}) Webshot. width = opts.fetch(:width, Webshot.width) height = opts.fetch(:height, Webshot.height) user_agent = opts.fetch(:user_agent, Webshot.user_agent) # Browser settings page.driver.resize(width, height) page.driver.headers = { "User-Agent" => user_agent, } end |
Instance Method Details
#capture(url, path, opts = {}) ⇒ Object
Captures a screenshot of url saving it to path.
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/webshot/screenshot.rb', line 29 def capture(url, path, opts = {}) begin # Default settings width = opts.fetch(:width, 120) height = opts.fetch(:height, 90) gravity = opts.fetch(:gravity, "north") quality = opts.fetch(:quality, 85) # Reset session before visiting url .reset_sessions! unless @session_started @session_started = false # Open page visit url # Timeout sleep opts[:timeout] if opts[:timeout] # Check response code if page.driver.status_code.to_i == 200 || page.driver.status_code.to_i / 100 == 3 tmp = Tempfile.new(["webshot", ".png"]) tmp.close begin # Save screenshot to file page.driver.save_screenshot(tmp.path, :full => true) # Resize screenshot thumb = MiniMagick::Image.open(tmp.path) if block_given? # Customize MiniMagick options yield thumb else thumb. do |c| c.thumbnail "#{width}x" c.background "white" c.extent "#{width}x#{height}" c.gravity gravity c.quality quality end end # Save thumbnail thumb.write path thumb ensure tmp.unlink end else raise WebshotError.new("Could not fetch page: #{url.inspect}, error code: #{page.driver.status_code}") end rescue ::Poltergeist::BrowserError, ::Poltergeist::DeadClient, ::Poltergeist::TimeoutError, Errno::EPIPE => e # TODO: Handle Errno::EPIPE and Errno::ECONNRESET raise WebshotError.new("Capybara error: #{e.message.inspect}") end end |
#start_session(&block) ⇒ Object
21 22 23 24 25 26 |
# File 'lib/webshot/screenshot.rb', line 21 def start_session(&block) .reset_sessions! .current_session.instance_eval(&block) if block_given? @session_started = true self end |