2
votes

In Ruby on Windows 7, how do you open a program's source file from the command line?

Example:

def dev_mode
  if ARGV[0] == '--dev-mode'
    system('open test.rb')
  end
end

Is it possible to open a program using the default editor of the user's computer? Such as opening it in notepad (if the user doesn't have an editor) or the editor the user uses for source files?

2
Which operating system are you asking about? Calling open is a Mac convention, but Notepad is a standard windows application - on Mac, the equivalent application is TextEdit.app.Michael Gaskill
@MichaelGaskill I totally thought I added the OS, I apologize, it's Windows 7, and has been added to the question13aal
@Jordan Wow, that's a good one, but that completely changes my question lol. Thank you though!13aal

2 Answers

2
votes

On a Mac, you're already halfway there; open opens a file in the default application. By default it opens a reasonable editor for text files and XCode for Ruby files; I don't edit Ruby in XCode, but I could change the association if I wanted.

The name of the file that started a Ruby program is in $PROGRAM_NAME, so you can do

def dev_mode
  if ARGV[0] == '--dev-mode'
    system("open #{$PROGRAM_NAME}")
  end
end

On Unix-like systems, including OS X, you might want to use the value of ENV['EDITOR'] (the EDITOR environment variable) if it's set. That's a convention used by many programs.

I'll let others give answers for other operating systems.

2
votes

The canonical way to open a file with the associated program is different from one operating system (or shell) to another. Here are 4 examples that will work on the specified OSes:

Opening the File

Windows

Use the standard command shell start, available beginning with Windows 95:

system %{cmd /c "start #{file_to_open}"}

Mac OS X

Use the standard open command:

system %{open "#{file_to_open}"}

Linux/Unix Gnome

Use the Gnome utility gnome-open:

system %{gnome-open "#{file_to_open}"}

Linux/Unix

Use the xdg-open utility:

system %{xdg-open "#{file_to_open}"}

Associated Programs

Detecting the associated program for a file type can be a fairly tall order on any one system. For instance, with Windows, you have to inspect the registry, whereas with Mac OS X you have to read the right plist values; Linux is a whole other world, altogether.

You're likely better off simply requiring the user to have a program associated to make things easy enough to get started. Once you have the other logic working in your application, you might be able to add interesting features like fallback to a default application in the absence of an existing file association.