Class: SharedTools::Tools::Notification::MacDriver

Inherits:
BaseDriver
  • Object
show all
Defined in:
lib/shared_tools/tools/notification/mac_driver.rb

Overview

macOS notification driver using osascript and the say command.

Instance Method Summary collapse

Instance Method Details

#alert(message:, title: nil, buttons: ['OK'], default_button: nil) ⇒ Hash

Returns includes :button with label of clicked button.

Parameters:

  • message (String)
  • title (String, nil) (defaults to: nil)
  • buttons (Array<String>) (defaults to: ['OK'])
  • default_button (String, nil) (defaults to: nil)

Returns:

  • (Hash)

    includes :button with label of clicked button



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/shared_tools/tools/notification/mac_driver.rb', line 29

def alert(message:, title: nil, buttons: ['OK'], default_button: nil)
  btn_list  = buttons.map(&:inspect).join(', ')
  script    = "display dialog #{message.inspect}"
  script   += " with title #{title.inspect}" if title
  script   += " buttons {#{btn_list}}"
  script   += " default button #{default_button.inspect}" if default_button

  stdout, stderr, status = Open3.capture3('osascript', '-e', script)
  if status.success?
    button = stdout.match(/button returned:(.+)/i)&.captures&.first&.strip
    { success: true, button: button }
  else
    { success: false, error: stderr.strip }
  end
end

#notify(message:, title: nil, subtitle: nil, sound: nil) ⇒ Hash

Parameters:

  • message (String)
  • title (String, nil) (defaults to: nil)
  • subtitle (String, nil) (defaults to: nil)
  • sound (String, nil) (defaults to: nil)

    e.g. ‘Glass’, ‘Ping’

Returns:

  • (Hash)


15
16
17
18
19
20
21
22
# File 'lib/shared_tools/tools/notification/mac_driver.rb', line 15

def notify(message:, title: nil, subtitle: nil, sound: nil)
  parts = ["display notification #{message.inspect}"]
  parts << "with title #{title.inspect}" if title
  parts << "subtitle #{subtitle.inspect}"  if subtitle
  parts << "sound name #{sound.inspect}"   if sound
  run_osascript(parts.join(' '))
    .then { |r| r[:success] ? r.merge(action: 'notify') : r }
end

#speak(text:, voice: nil, rate: nil) ⇒ Hash

Parameters:

  • text (String)
  • voice (String, nil) (defaults to: nil)

    e.g. ‘Samantha’

  • rate (Integer, nil) (defaults to: nil)

    words per minute

Returns:

  • (Hash)


49
50
51
52
53
54
55
# File 'lib/shared_tools/tools/notification/mac_driver.rb', line 49

def speak(text:, voice: nil, rate: nil)
  cmd  = ['say', text]
  cmd += ['-v', voice]    if voice
  cmd += ['-r', rate.to_s] if rate
  _, stderr, status = Open3.capture3(*cmd)
  status.success? ? { success: true, action: 'speak' } : { success: false, error: stderr.strip }
end