Back to overview

Automatically starting Ray on MacOS

14 December 2023

Image of Freek

Freek

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.

Stay in the loop with updates & promotions for Ray

We only send a few emails a year.

Debug without breaking your flow

Ray keeps all your debug output neatly organized in a dedicated desktop app.

Licenses are valid for 1 year and managed through Spatie. Licenses purchased before Ray 3 remain valid. VAT is calculated at checkout.