[code] Renaming Materials by their filename in bulk by directory
EDIT3: version 3 is FIXED
UPDATED to also change the “title” element in "documentProperties.xml"
file. (Thanks to TIG)
The materials were invalidated in version 2 because the ruby was running faster than the file system and the Zip archive undpates. Basically both xml documents were the same as the second because Ruby was changing the one reference too fast.
In version 3 I created two separate update paths, strings etc., so that the xml data would not get “crossed”.
rename_my_matls_3.rb (1.8 KB)
@sustainablebuilders You’d fire it off via …
rename_my_matls("D:/Storage Documents/SketchUp")
The contents of the ruby file … FIXED ver 3
# Might need to do ...
# Gem::Install("rubyzip")
# ... then ...
require 'zip'
# This method will rename the SKM Material's
# display name to match that of the filename.
# Suggested this be done on a cloned folder of SKM
# files first, and then test the results !
#
# ver: 3
#
def rename_my_matls(
start_dir = ENV["HOME"]
)
path = UI.select_directory(
directory: start_dir,
title: 'Select Materials Folder'
)
return unless path
Dir::chdir(path) do |dir|
#
matls = Dir["*.skm"]
temp = Sketchup::temp_dir
path1 = File.join(temp,"document.xml")
path2 = File.join(temp,"documentProperties.xml")
#
matls.each do |skm|
#
matl_name = File.basename(skm,".*")
Zip::File.open(skm) do |zipfile|
#
modes = File::CREAT|File::TRUNC|File::RDWR
#
doc1 = zipfile.find_entry("document.xml")
next if doc1.nil?
xml_str1 = zipfile.read( doc1 )
xml_str1.gsub!(
/name="[\d\s\w]+"/,
%[name="#{matl_name}"]
)
File::open( path1, modes ) { |file| file.write(xml_str1) }
zipfile.replace( doc1, path1 )
#
doc2 = zipfile.find_entry("documentProperties.xml")
next if doc2.nil?
xml_str2 = zipfile.read( doc2 )
xml_str2.gsub!(
/<dp:title>[\d\s\w]+<\/dp:title>/,
%[<dp:title>#{matl_name}</dp:title>]
)
File::open( path2, modes ) { |file| file.write(xml_str2) }
zipfile.replace( doc2, path2 )
#
end # zipfile
#
end # each matls
#
File.delete(path1) if File.exist?(path1)
File.delete(path2) if File.exist?(path2)
#
end # change dir (old working dir is restored automatically)
#
end ### rename_my_matls()