Class: Selenium::Phantomjs::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/selenium/phantomjs/instance.rb

Direct Known Subclasses

WebDriver

Constant Summary collapse

PHANTOMJS_BIN =
%x{which phantomjs}.strip.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pid_file) ⇒ Instance

Returns a new instance of Instance.



8
9
10
11
12
13
14
15
# File 'lib/selenium/phantomjs/instance.rb', line 8

def initialize(pid_file)
  raise "Please install phantomjs first and make sure that phantomjs is in your PATH" if PHANTOMJS_BIN == ''
  
  pid_dir = File.dirname(pid_file)
  FileUtils.mkpath(pid_dir) unless File.directory? pid_dir

  @pid_file = pid_file
end

Instance Attribute Details

#pid_fileObject (readonly)

Returns the value of attribute pid_file.



6
7
8
# File 'lib/selenium/phantomjs/instance.rb', line 6

def pid_file
  @pid_file
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
# File 'lib/selenium/phantomjs/instance.rb', line 45

def alive?
  !! pid && begin
    !! Process.kill(0, pid)
  rescue Errno::ESRCH, RangeError
    false
  end
end

#die!Object



53
54
55
56
57
# File 'lib/selenium/phantomjs/instance.rb', line 53

def die!
  Process.kill('TERM', pid) if alive?
  File.delete(pid_file) if File.exists? pid_file
  @pid = nil
end

#pidObject



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/selenium/phantomjs/instance.rb', line 59

def pid
  @pid ||= if File.exists? pid_file
    File.open(pid_file, 'r') do |f|
      begin
        f.readline.to_s.strip.to_i
      rescue EOFError
        nil
      end
    end
  end
end

#run(args, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


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
# File 'lib/selenium/phantomjs/instance.rb', line 17

def run(args, options = {})
  die!

  arguments = if args.is_a? Hash
    args.map do |k, v| 
      if v
        %Q{--#{k}=#{v}}
      else
        "--#{k}"
      end
    end
  else
    Array(args)
  end

  raise ArgumentError.new("PhantomJS: interactive shell is not supported.") if arguments.empty?

  command = [PHANTOMJS_BIN] + arguments
  @pid = Process.spawn(*command, options)
  Process.detach(@pid)

  sleep 1
  raise "PhantomJS: failed to start" unless alive?
  File.open(pid_file, 'w') { |f| f.write @pid }

  @pid
end