From: pjb@... (Pascal J. Bourguignon) Date: 2009-03-11T19:08:07+09:00 Subject: Re: Shell scripting & Windows/Linux Paths Michael Malone writes: > Juan Zanos wrote: >> Yes, I'm mostly concerned with paths. I'd like to write everything >> in Unix style and just have it automatically converted somehow so >> everything stays relatively legible. >> >> > One good pattern for dealing with this I have seen is simply to have a > shell_command method somewhere, so you can do different things if you're > on different OSs. And to figure out dynamically which OS you're working > with, use this: > > require 'rbconfig' > if Config::CONFIG["target_os"] == 'linux' > OS = 'linux' > else > OS = 'windows' #presumably > end > > Yes, I am aware that that code is specific to linux/windows but it was > enough for me. You're a puts call away from getting the required > options. That sort of thing can make life easier if you want to > redirect to /dev/null or NUL and only want to change your command in one > place. It would be much better to have subclasses for each OS. This way, you could generate commands for one OS, from another OS, and send it remotely thru ssh or some other way. (class OS (def genGetRootDirectory (subclassResponsibility) end) (def genGetListOfDirectoriesInDirectory(directory) (subclassResponsibility) end) (def genGetListOfFilesInDirectory(directory) (subclassResponsibility) end) (def genRemoteExecute(command) (subclassResponsibility) end) (def execute(command) (subclassResponsibility) end) end) (class Linux < OS (def genGetRootDirectory (Directory . new "/") end) (def genGetListOfDirectoriesInDirectory(directory) (Command . new "find #{(quoteShellArgument (directory . path))}/* -prune -type d -print") end) (def genGetListOfFilesInDirectory(directory) (Command . new "find #{(quoteShellArgument (directory . path))}/* -prune \\( \\! -type d \\) -print") end) (def genRemoteExecute(command,host,user=nil) (Command . new "ssh #{(user ? user+"@" : "")}#{host} #{(command . text)}") end) (def execute(command) (system (command . text)) end) end) and similarly for MSWindows. So you can write: (localHost = ((Config::CONFIG["target_os"] == 'linux') ? (Linux . new) : (MSWindows . new))) (remoteDoze = (MSWindows . new)) (remoteLinux = (Linux . new)) (localHost . execute (localHost . genRemoteExecute (remoteDoze . genGetListOfFiles (remoteDoze . genGetRootDirectory)))) (localHost . execute (localHost . genRemoteExecute (remoteLinux . genGetListOfFiles (remoteLinux . genGetRootDirectory)))) (localHost . execute (localHost . genGetListOfFiles (localHost . genGetRootDirectory))) -- __Pascal Bourguignon__