Best practices

Best practices

Below are a collection of best practices when developing your own triggers.

Code organization

Organize your code by use case. Group scripts for a specific use case into a descriptive folder, so that all behavior for that use case is in one place.

For example:

~/.tuple/triggers
├── README.md
├── do-not-disturb
│   ├── call-connected
│   └── call-ended
├── clean-desktop
│   ├── screen-share-started
│   └── screen-share-stop
├── hide-messages
│   ├── screen-share-started
│   └── screen-share-stop
├── pause-spotify
│   ├── call-connected

As two of these triggers respond to the same two events, they could technically be in one script and live in the root directory. However, we don’t recommend that approach.

Keeping triggers in separate subdirectories simplifies each file, and makes it easier to remove a set of behaviors when you don’t want it anymore.

Logging

Log generously. The last thing you want is to notice that one of your scripts is broken, and realize that you have no logs to go look through. All stdout and stderr from your scripts are collected in the triggers.log, so print anything and everything that you think might be helpful when debugging a future problem.

State persistence

Persist state sparingly. If you do need to persist state between triggers, we recommend using a local file in an easily parsable format like JSON. If you’ve broken your scripts up by use case, then you can keep this state file in the same directory as the script without worrying about overwriting it in another script.

For example:

#!/usr/bin/env ruby

require "json"

# Load previous state
state = File.exists?("state.json") ? JSON.parse(File.read("state.json")) : {}

# your script logic here

# Write out current state for next run
File.open("state.json", "w") { |f| f.write(state.to_json) }