July 14, 2006

Populating Windows Registry from Ruby hash

require 'win32/registry.rb'

#
# Populates registry keys with values given in a hash
#   h = { ".c" => { nil => "source_code_file",       # default
#                   "Content Type" => "text/plain" },
#         '.txt\shell\edit\command'=> { nil, 'editor.exe "%1"' } }
# 
#   populate_registry HKCR, h
#
#   # From an open key:
#   Win32::Registry::HKEY_CLASSES_ROOT.create(".c", KEY_ALL_ACCESS) do |reg|
#       populate_registry reg, {nil => "source_code_file", "Content Type" => "text/plain" }
#   end
#
def populate_registry( root, registry_hash )
    registry_hash.each{|k,v|

        # Make a copy of a String because hash keys are frozen and ...
        key = k.frozen?  ?  k[0..-1] : k    # ... Registry tries to modify them
        
        if v.kind_of? Hash
            root.create(key, KEY_ALL_ACCESS){|reg|
                populate_registry reg, v
            }
        else
            root[key] = v
        end
    }
end


Posted by laza at July 14, 2006 01:30 PM | TrackBack