14 December 2023
Freek
Automatically starting Ray on MacOS
When using Ray to debug your project, you're not using a function like dump($variable)
to display the value of a variable, but ray($variable)
. This will send the value of your variable to the Ray desktop app. Of course, Ray can do a whole lot more than just displaying the content of a variable.
Behind the scenes, when you execute ray()
an HTTP call will be made to a port the Ray desktop app listens to. But what happens if the Ray desktop app is not open? Well, nothing ... your call will be lost in the void. Would it be nice if we could automatically start up Ray whenever ray()
is executed?
Since its inception, MacOS has had support for automating various tasks through AppleScript. Using a bit of AppleScript, we can launch the Ray application whenever it is not running.
set appBundleID to "be.spatie.ray"
tell application "System Events"
if not (exists (processes whose bundle identifier is appBundleID)) then
tell application "Ray" to activate
delay 1
end if
end tell
The above script should be executed whenever a ray()
call is made. You can do that using Ray::beforeSendRequest()
, which accepts a closure.
// somewhere where your app is booting
Ray::beforeSendRequest(function () {
$script = '
set appBundleID to "be.spatie.ray"
tell application "System Events"
if not (exists (processes whose bundle identifier is appBundleID)) then
tell application "Ray" to activate
delay 1
end if
end tell
';
$escapedScript = escapeshellarg($script);
$command = "osascript -e $escapedScript";
$output = shell_exec($command);
});
You should put this code somewhere where your app is booting. In a Laravel app, you could put this code in a service provider.
With this in place, the Ray desktop app will automatically boot up where you call ray()
in your PHP code.
A big thank you to Sebastian Kloos for coming up with this neat technique!
We're currently considering adding this code to the Ray PHP itself, but we wanted to already share this cool bit of knowledge with you.
Understand and fix bugs faster
Ray is a desktop application that serves as the dedicated home for debugging output. Send, format and filter debug information from both local projects and remote servers.