Save file dialog boxes have always seemed magical to me because I have never done any client side applications. While working on a MacRuby client app I needed to save a file, obviously, and it was amazing how simple a save file dialog box really is.
What Does NSSavePanel Do?
This is very simple. It returns a path to the file you want to save. From there you hand off that path to what ever you needed to save a file. This really makes it simple to save files. I was impressed with NSSavePanel for 2 reasons. One: It gave me a way to have users save files with a consistent look and feel. And two: Once you figure it out, its dead simple to use and understand.
You can configure the NSSavePanel a lot more than what I am showing here. I recommend you take a look at the NSSavePanel Class Reference to see what all you can do, then just play with it a bit.
dialog = NSSavePanel.new dialog.allowedFileTypes = ["xyz"] if dialog.runModal == NSOKButton puts dialog.filename end
Above is mostly the bare minimum. Lets look at what it does.
Line 1: creates a new instance of NSSavePanel so we can use it. NSSavePanel is a cocoa object that you are using.
Line 3: This sets the array allowedFileTypes 0 index to “xyz”. If you only have 1 file type in the array it defaults the path returned to have that file type. So you could set it to txt and the path returned would be /some/path/to/file.txt.
Line 5: This is the magic. The runModal method is what opens the NSSavePanel. Once you do your thing and hit the OK button it checks that you clicked the OK button and runs line 6.
Line 6: This outputs to console the filename of where and what you just wanted to save. This is where you would put your actual save file code using dialog.filename for the path to write to. You can use the ruby File object here.
Saving files is easy enough. Using the built in cocoa ability to save files makes life all that much easier. This is why I really like using MacRuby because it makes writing cocoa apps so much simpler. The code used in this example is the bare minimum of what you need, and will work in a lot of cases. Have fun with MacRuby.