Class: MagLove::PhantomScript

Inherits:
Object
  • Object
show all
Defined in:
lib/maglove/phantom_script.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script, options = {}) ⇒ PhantomScript

Returns a new instance of PhantomScript.



7
8
9
10
11
12
13
14
15
16
# File 'lib/maglove/phantom_script.rb', line 7

def initialize(script, options = {})
  @running = false
  @script = script
  @options = options.merge({
    script_path: Gem.datadir("maglove")
  })
  @path = File.absolute_path(File.join(@options[:script_path], "#{@script}.js"))
  throw "Script #{script} not found at #{@path}" unless File.exist?(@path)
  @log_file = Tempfile.new('pslog')
end

Instance Attribute Details

#log_fileObject

Returns the value of attribute log_file.



5
6
7
# File 'lib/maglove/phantom_script.rb', line 5

def log_file
  @log_file
end

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/maglove/phantom_script.rb', line 5

def options
  @options
end

#pathObject

Returns the value of attribute path.



5
6
7
# File 'lib/maglove/phantom_script.rb', line 5

def path
  @path
end

#runningObject

Returns the value of attribute running.



5
6
7
# File 'lib/maglove/phantom_script.rb', line 5

def running
  @running
end

#scriptObject

Returns the value of attribute script.



5
6
7
# File 'lib/maglove/phantom_script.rb', line 5

def script
  @script
end

Instance Method Details

#run(*args) ⇒ Object



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
# File 'lib/maglove/phantom_script.rb', line 18

def run(*args)
  start = Time.now
  @running = true
  cmd = "phantomjs #{@path} #{@log_file.path} #{args.join(' ')}"

  # log phantomjs info
  @log_thread = Thread.new do
    f = File.open(@log_file.path, "r")
    f.seek(0, IO::SEEK_END)
    puts "phantom@0ms ▸ (start)"
    while @running
      select([f])
      line = f.gets
      puts "phantom@#{((Time.now - start) * 1000.0).to_i}ms ▸ #{line}" if line
    end
  end

  # run command and return result
  result = `#{cmd}`
  @running = false
  result == "ERROR" ? false : result
ensure
  @log_file.close
  @log_file.unlink
end