Embedding a ruby script in AppleScript
Solution 1:
A Ruby script can be placed into an AppleScript string for use with do shell script
, but note that special characters in the string such as backslash and double quotes will need to be escaped with a backslash. There are a couple of different arrangements you can use, my preference is a here document, for example:
on run -- Script Editor or application double-clicked
doStuff for (choose file with multiple selections allowed)
end run
on open theFiles -- items dropped onto the application
doStuff for theFiles
end open
on adding folder items to this_folder after receiving these_items -- folder action
doStuff for these_items
end adding folder items to
to doStuff for someFiles
set argString to "" -- create an argument string from the item list
repeat with anItem in someFiles -- quote and separate
set anItem to POSIX path of anItem
set argString to argString & quoted form of anItem & space
end repeat
set heredoc to "<<-SCRIPT
# place your (escaped for AppleScript strings) code here, for example:
ARGV.each_with_index do |arg, index|
puts \"Argument #{index}: #{arg}\"
end
SCRIPT"
set scriptResult to (do shell script "/usr/bin/env ruby - " & argString & heredoc) -- run it
return paragraphs of scriptResult -- or whatever
end doStuff
The -e
option can also be used instead of the here document (see the Ruby man page), for example:
set rubyScript to "# place your (escaped for AppleScript strings) code here, for example:
ARGV.each_with_index do |arg, index|
puts \"Argument #{index}: #{arg}\"
end"
set scriptResult to (do shell script "/usr/bin/env ruby -e " & (quoted form of rubyScript) & space & argString) -- run it