Skip to content

Commit

Permalink
Add method for registering a method and returning a JSONRPCAction
Browse files Browse the repository at this point in the history
  • Loading branch information
Garulf committed Jan 25, 2024
1 parent 02439d4 commit 95b9f1b
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
6 changes: 4 additions & 2 deletions pyflowlauncher/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ def __init__(self):
def _get_callable_name(self, method: Callable[..., Any]):
return getattr(method, '__name__', method.__class__.__name__).lower()

def add_method(self, method: Callable[..., Any], *, name=None):
self._methods[name or self._get_callable_name(method)] = method
def add_method(self, method: Callable[..., Any], *, name=None) -> str:
key = name or self._get_callable_name(method)
self._methods[key] = method
return key

def add_methods(self, methods: Iterable[Callable[..., Any]]):
for method in methods:
Expand Down
11 changes: 8 additions & 3 deletions pyflowlauncher/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sys
from functools import wraps
from typing import Any, Callable, Iterable, Union
from typing import Any, Callable, Iterable, Optional, Union
from pathlib import Path
import json

Expand All @@ -26,9 +26,9 @@ def __init__(self, methods: list[Method] | None = None) -> None:
if methods:
self.add_methods(methods)

def add_method(self, method: Method) -> None:
def add_method(self, method: Method) -> str:
"""Add a method to the event handler."""
self._event_handler.add_method(method)
return self._event_handler.add_method(method)

def add_methods(self, methods: Iterable[Method]) -> None:
self._event_handler.add_methods(methods)
Expand All @@ -48,6 +48,11 @@ def add_exception_handler(self, exception: Exception, handler: Callable[..., Any
"""Add exception handler to be called when an exception is raised in a method."""
self._event_handler.add_exception_handler(exception, handler)

def action(self, method: Method, parameters: Optional[Iterable] = None) -> JsonRPCAction:
"""Register a method and return a JsonRPCAction that calls it."""
method_name = self.add_method(method)
return {"method": method_name, "parameters": parameters or []}

@property
def settings(self) -> dict:
if self._settings is None:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,9 @@ def test_root_dir_not_found(tmp_path, monkeypatch):
plugin = Plugin()
with pytest.raises(FileNotFoundError):
assert plugin.root_dir() == tmp_path


def test_action():
plugin = Plugin()
action = plugin.action(query)
assert action == {'method': 'query', 'parameters': []}

0 comments on commit 95b9f1b

Please sign in to comment.