Class: Vangrail::Tools

Inherits:
Object
  • Object
show all
Defined in:
lib/vangrail/tools.rb

Overview

Named callables a Conversation may invoke, and only after Admission says so. The handler never sees a request that was not granted.

tools = Tools.new
tools.register(:cite) { |args, convo| ... }
convo = Conversation.new(engine, allow: { cite: %i[data] }, tools: tools)
convo.ask('Cite the partition table.')
convo.invoke(:cite, arguments: page)

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(handlers = {}) ⇒ Tools

Returns a new instance of Tools.



17
18
19
20
# File 'lib/vangrail/tools.rb', line 17

def initialize(handlers = {})
  @handlers = {}
  handlers.each { |name, fn| register(name, fn) }
end

Instance Method Details

#call(_name, _arguments, _conversation) ⇒ Object

Raises:



42
43
44
# File 'lib/vangrail/tools.rb', line 42

def call(_name, _arguments, _conversation)
  raise PrivilegeError, 'use Conversation#invoke'
end

#dupObject



52
53
54
55
56
# File 'lib/vangrail/tools.rb', line 52

def dup
  copy = self.class.new
  @handlers.each { |name, entry| copy.register(name, entry.handler, readonly: entry.readonly) }
  copy
end

#fire(name, arguments, conversation) ⇒ Object

Raises:

  • (ArgumentError)


46
47
48
49
50
# File 'lib/vangrail/tools.rb', line 46

def fire(name, arguments, conversation)
  raise ArgumentError, "unknown tool #{name}" unless key?(name)

  @handlers[name.to_sym].handler.call(arguments, conversation)
end

#key?(name) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/vangrail/tools.rb', line 30

def key?(name)
  @handlers.key?(name.to_sym)
end

#namesObject



38
39
40
# File 'lib/vangrail/tools.rb', line 38

def names
  @handlers.keys
end

#readonly?(name) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/vangrail/tools.rb', line 34

def readonly?(name)
  !!@handlers[name.to_sym]&.readonly
end

#register(name, callable = nil, readonly: false, &block) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
# File 'lib/vangrail/tools.rb', line 22

def register(name, callable = nil, readonly: false, &block)
  fn = callable || block
  raise ArgumentError, "tool #{name} needs a callable" unless fn.respond_to?(:call)

  @handlers[name.to_sym] = Entry.new(handler: fn, readonly: readonly)
  self
end

#to_hObject



58
59
60
# File 'lib/vangrail/tools.rb', line 58

def to_h
  @handlers.transform_values(&:handler)
end