Reputation: 1674
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?
Upvotes: 2
Views: 435
Reputation: 8042
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:
Use the standard command shell start
, available beginning with Windows 95:
system %{cmd /c "start #{file_to_open}"}
Use the standard open
command:
system %{open "#{file_to_open}"}
Use the Gnome utility gnome-open
:
system %{gnome-open "#{file_to_open}"}
Use the xdg-open
utility:
system %{xdg-open "#{file_to_open}"}
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.
Upvotes: 2
Reputation: 37607
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.
Upvotes: 2