Mark Szymanski
Mark Szymanski

Reputation: 58060

Open file in GUI with Ruby on Mac OS X, preferably without system()

Is there any way (an installed gem would be fine) to open a file in the GUI on Mac OS X, much like what can be done with the open shell command? I know that I could use the system() function to run the open shell command, but I would like to avoid doing that. If all else fails, of course, I could always fall back to using system().

Upvotes: 2

Views: 897

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

open, by itself uses the Mac's list of what files an app says it can open. That can be messy, or completely wrong, so I think it's safer to give it some hints using the -a flag or you could end up opening source with a word-processor, which seldom works well.

If you want to open a source file into something like MacVim, TextMate, BBEdit, you can use their command-line tools, mvim, mate or bbedit respectively. From IRB these all open my ~/.bashrc file and return immediately with no result, because they detach from the terminal. Using Ruby's back-ticks, or it's equivalent %x{}:

>> `mate ~/.bashrc` #=> ""
>> `mvim ~/.bashrc` #=> ""
>> `bbedit ~/.bashrc` #=> ""

You could look into using one of the Open3 methods to open apps too, though you will have to find the right binary to call unless the app supplies a shortcut like MacVim, TextMate or BBEdit.

The Mac's open -a application file_to_be_opened command can be called using back-ticks or %r{}. The corollaries to using the above commands look like:

`open -a TextMate ~/.bashrc`

MacVim is based on the Vim codebase, which comes from the *nix world. It has a -f flag which keeps it from detaching from the terminal so your code would pause waiting for the editor to finish and exit, before it could continue. That's useful on my Linux boxes when I am diffing files or writing a commit message before sending revisions to SVN. This works to do that in IRB:

`mvim -f ~/.bashrc`

Upvotes: 0

Mark Szymanski
Mark Szymanski

Reputation: 58060

I've found out that the only plausible solution would be to use the system() method to call the open command-line utility.

Upvotes: 3

Related Questions