Yours:
dir = File.dirname(model.path)
basename = File.basename(model.path, '.*')
return if model.path == ''
if Sketchup.platform == :platform_win
File.join(dir, 'AutoSave_' + basename + '.skp')
else
File.join(dir, basename + '~.skp')
end
Mine:
dir = File.dirname(File.expand_path(model.path))
basename = model.title
return if model.path.empty? || model.path == '.'
if Sketchup.platform == :platform_win rescue RUBY_PLATFORM !~ /darwin/i
File.join(dir, "AutoSave_#{basename}.skp")
else
File.join(dir, basename + '~.skp')
end
line 1: File.expand_path() converts backslashes to forward slashes
line 2: model.title is suffcient
line 3: It is more effcient to simply call the empty?() method upon a string,
than create a new empty string object and pass it to the ==() method.
(When you express a literal string even an empty one, the Ruby interpreter must take
that as an argument, and pass it to String::new() in order to create a string object.)
line 3: The current directory dot string can be returned for unsaved models.
line 4: Older versions of SketchUp do not have the platform method, so a NoMethodError
would be raised. Adding a rescue modifier can trap this and fallback to testing
the global Ruby constant.
… BUT you do not really need a platform conditional in this case (as John points out.)
line 5: As mentioned in “line 3” (above,) literals create string objects.
So, this: ‘AutoSave_’ + basename + ‘.skp’ creates two new objects.
Then each one of the calls to the +() method creates yet another 2 string objects.
Most effcient here is create one new string and use #{} interpolation to insert the
already existing basename string into it’s middle.
What I would do, is ask the user to create a default path for autosaves on unsaved models.
You could also save the last used autosave path to your plugin’s defaults (just be sure it has forward slashes!)
Say this fallback directory is loaded into a module var: @@fallback, then the code would look like:
Possible:
dir = File.dirname(File.expand_path(model.path))
basename = model.title
if basename.empty?
t = Time.now
basename = t.strftime("%Y-%m-%d_%s")
end
dir = @@fallback if dir.empty? || dir == '.'
@autopath = File.join( dir, "AutoSave_#{basename}.skp" )
# save it
Ref Ruby doc: Time#strftime()
Q: _Why did I use strftime("%Y-%m-%d_%s") instead of just splitting the string output of the Time instance and using the first element of the returned array ?
ie,
date = Time.now.to_s.split.first
A: Because date separators are locale dependent. I toyed with the idea of gsub’ing all the invalid filename characters to dashes, but it creates more code and work for Ruby, then just formatting an output string with strftime("%Y-%m-%d_%s").