Class: Opal::CliRunners::Applescript

Inherits:
Object
  • Object
show all
Defined in:
opal/lib/opal/cli_runners/applescript.rb

Defined Under Namespace

Classes: MissingAppleScript, MissingJavaScriptSupport

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Applescript

Returns a new instance of Applescript.



6
7
8
9
10
11
12
# File 'opal/lib/opal/cli_runners/applescript.rb', line 6

def initialize(options)
  unless system('which osalang > /dev/null')
    raise MissingJavaScriptSupport, 'JavaScript Automation is only supported by OS X Yosemite and above.'
  end

  @output = options.fetch(:output, $stdout)
end

Instance Attribute Details

#exit_statusObject (readonly)

Returns the value of attribute exit_status.



13
14
15
# File 'opal/lib/opal/cli_runners/applescript.rb', line 13

def exit_status
  @exit_status
end

#outputObject (readonly)

Returns the value of attribute output.



13
14
15
# File 'opal/lib/opal/cli_runners/applescript.rb', line 13

def output
  @output
end

Instance Method Details

#puts(*args) ⇒ Object



15
16
17
# File 'opal/lib/opal/cli_runners/applescript.rb', line 15

def puts(*args)
  output.puts(*args)
end

#run(code, argv) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'opal/lib/opal/cli_runners/applescript.rb', line 19

def run(code, argv)
  require 'tempfile'
  tempfile = Tempfile.new('opal-applescript-runner-')
  # tempfile = File.new('opal-applescript-runner.js', 'w') # for debugging
  tempfile.puts code
  tempfile.puts "'';" # OSAScript will output the last thing
  tempfile.close
  _successful = system_with_output('osascript', '-l', 'JavaScript', tempfile.path, *argv)
rescue Errno::ENOENT
  raise MissingAppleScript, 'AppleScript is only available on Mac OS X.'
end

#system_with_output(env, *cmd) ⇒ Object

Let's support fake IO objects like StringIO



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
# File 'opal/lib/opal/cli_runners/applescript.rb', line 32

def system_with_output(env, *cmd)
  if (_io_output = IO.try_convert(output))
    system(env, *cmd)
    @exit_status = $?.exitstatus
    return
  end

  if RUBY_PLATFORM == 'java'
    # JRuby has issues in dealing with subprocesses (at least up to 1.7.15)
    # @headius told me it's mostly fixed on master, but while we wait for it
    # to ship here's a tempfile workaround.
    require 'tempfile'
    require 'shellwords'
    tempfile = Tempfile.new('opal-applescript-output')
    system(env, cmd.shelljoin + " > #{tempfile.path}")
    @exit_status = $?.exitstatus
    captured_output = File.read tempfile.path
    tempfile.close
  else
    require 'open3'
    captured_output, status = Open3.capture2(env, *cmd)
    @exit_status = status.exitstatus
  end
  output.write captured_output
end