Option associates a menu description with a command and optional input-preparation behavior. It keeps the CLI menu focused on presentation while commands handle business logic. section 6.3.3
An Option coordinates a menu choice in four steps:
- Stores the displayed name, command object, and optional preparation callback. section 6.3.3
- Runs the preparation callback when user input is needed, such as bookmark data or an identifier. section 6.3.3
- Passes prepared data to command.execute(), or executes the command without data. section 6.3.3
- Prints the command’s returned message and represents itself with its menu name. section 6.3.3
Bookmark menu options
A menu can map A to Option('Add a bookmark', AddBookmarkCommand(), prep_call=get_new_bookmark_data), B to a date-ordered listing command, and T to the same command configured for title order. The menu prints each Option’s name, then calls choose() for the selected item. section 6.3.3
Listing 6.11. Connecting menu text to business logic commands
class Option:
def __init__(self, name, command, prep_call=None):
self.name = name #1
self.command = command #2
self.prep_call = prep_call #3
def choose(self): #4
data = self.prep_call() if self.prep_call else None #5
message = self.command.execute(data) if data
else self.command.execute() #6
print(message)
def __str__(self): #7
return self.name
Inspect the compact implementation showing stored configuration, optional preparation, command dispatch, output, and string conversion. section 6.3.3
