First let's make sure we are talking about the same acronym D.R.Y. when it comes to coding and that is Don't Repeat Yourself. It's been awhile since I've blogged about something AppleScript but I've taken a strive to make sure everything I write is implementing D.R.Y. When writing applications or scripts that do something which could get passed to someone I find it a good practice to inform the user executing the code what the process is doing with an AppleScript notification or dialog. Calling a simple notification isn't hard:
tell application "Finder"
display notification "Hello Monkey" with title "programmingmonkeys.com"
end tell
There is also a simplified alternative to calling this three liner with a one line:
tell application "Finder" to display notification "Hello Monkey" with title "programmingmonkeys.com"
To use dialog the same can be applied as above but with the only change being the call of dialog
apposed to notification
:
tell application "Finder"
display dialog "Hello Monkey" with title "programmingmonkeys.com"
end tell
and now the one liner:
tell application "Finder" to display dialog "Hello Monkey" with title "programmingmonkeys.com"
After awhile I became tired of repeatedly calling the same tell application "Finder" to foo
and with title "bar"
I decided to implement a handler. Handlers in AppleScript are just like coding a function in PHP:
on scriptMessager(foo, bar)
## some code
end scriptMessager
but make sure if calling a custom handler you use my
before the handler:
on scriptMessager(foo, bar)
## some code
end scriptMessager
my scriptMessager()
With the base of the handler written I decided instead of coding out notification
or dialog
all the time because I'm lazy I would indicate which one to use by setting them to an integer using 1 for notifications and 2 for dialogs:
on scriptMessager(call)
if call is equal to 1 then
tell application "Finder" to display notification
else if call is equal to 2 then
tell application "Finder" to display dialog
end if
end scriptMessager
We are on a good start but we still aren't passing a string to the handler:
on scriptMessager(call, theText)
if call is equal to 1 then
tell application "Finder" to display notification theText
else if call is equal to 2 then
tell application "Finder" to display dialog theText
end if
return
end scriptMessager
Another good practice is to give the display the title of the app or script running:
on scriptMessager(call, theText)
set theTitle to "Mr. Monkey"
if call is equal to 1 then
tell application "Finder" to display notification theText with title theTitle
else if call is equal to 2 then
tell application "Finder" to display dialog theText with title theTitle
end if
return
end scriptMessager
To be able to use the handler we just pass it the string with the integer 1 or 2 to tell it to call the notification or dialog:
## notification
my scriptMessager(1, "What are you coding next?")
## dialog
my scriptMessager(2, "Have any plans this weekend?")