2 ms·
As you can see from the example, we use Ruby's standard find, find_all, sort, and map array methods. Chaining together Ruby blocks in this manner can be a reall
by js2 15y ago
As you can see from the example, we use Ruby's standard find, find_all, sort, and map array methods. Chaining together Ruby blocks in this manner can be a really convenient and syntactically expressive way to dig into the contents of Scripting Bridge data structures
I think that doing it that way sends many more apple events (and is thus much slower) than needed. Here's two examples in Python. The first is similar to the example ruby code in the article:
from ScriptingBridge import SBApplication, NSPredicate
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
library = [s for s in iTunes.sources() if s.name() == "Library"][0]
playlist = [p for p in library.playlists() if p.name() == "Top 25 Most Played"][0]
tracks = [t for t in playlist.tracks() if t.rating() > 3]
favsongs = ["<li>%s - %s (%s)<li>" % (t.artist(), t.name(), t.playedCount())
for t in sorted(tracks, key=lambda t:t.playedCount())]
print '\n'.join(favsongs)
The problem with this code is that we first ask iTunes for all its sources, then filter those in Python. Next we ask the library source for all its playlists, and again filter in Python. Etc.
Instead, we can rely on so-called lazy evaluation and send a single apple event like so:
library = iTunes.sources().objectWithName_("Library")
playlist = library.playlists().objectWithName_("Top 25 Most Played")
tracks = playlist.tracks().filteredArrayUsingPredicate_(
NSPredicate.predicateWithFormat_("rating > 3"))
See the Apple Scripting Bridge documentation for more info.