1require 'osx/cocoa' 2require 'kconv' 3 4class AppleScript 5 include OSX 6 7 def initialize (src, raise_err_p = true) 8 @script = NSAppleScript.alloc.initWithSource(src) 9 @errinfo = OCObject.new 10 @script.compileAndReturnError?(@errinfo) 11 @script = nil if handle_error(@errinfo, raise_err_p) 12 end 13 14 def execute (raise_err_p = false) 15 @errinfo = OCObject.new 16 result = @script.executeAndReturnError(@errinfo) 17 handle_error(@errinfo, raise_err_p) 18 return result 19 end 20 21 def source 22 @script.source.to_s 23 end 24 25 def error? 26 return nil if @errinfo.ocnil? 27 return (errmsg_of @errinfo) 28 end 29 30 private 31 32 def handle_error (errinfo, raise_err_p) 33 return false if errinfo.ocnil? 34 if raise_err_p then 35 raise "AppleScriptError: #{errmsg_of errinfo}" 36 else 37 $stderr.puts( errmsg_of(errinfo) ) 38 end 39 return true 40 end 41 42 def errmsg_of (errinfo) 43 errinfo.objectForKey('NSAppleScriptErrorMessage').to_s 44 end 45 46end 47 48class AEList 49 include Enumerable 50 51 def initialize (aedesc) 52 @aedesc = aedesc 53 end 54 55 def each 56 @aedesc.numberOfItems.times do |index| 57 yield @aedesc.descriptorAtIndex( index + 1 ) 58 end 59 return self 60 end 61 62end 63 64if __FILE__ == $0 then 65 66 $stderr.puts "executing applescript ..." 67 68 # AppleScript - all album names of iTunes playlist 1 69 script = AppleScript.new %{ 70 tell application "iTunes" 71 album of tracks of library playlist 1 72 end tell 73 } 74 75 # execute and get result as AEList 76 result = script.execute 77 albums = AEList.new(result) 78 79 # convert Ruby string and uniq 80 albums = albums.map {|i| i.stringValue.to_s.toeuc }.uniq 81 82 # print all alubum names 83 albums.each do |title| 84 puts title 85 end 86 87end 88