Module: Ask::Tools

Defined in:
lib/ask/tools.rb

Overview

Tool registry and discovery.

Provides a central registry for tool classes and auto-discovery of Ask::Tool subclasses via ObjectSpace. Thread-safe.

Ask::Tools.register(MyTool)
Ask::Tools.all        # => [MyTool.new, ...]
Ask::Tools["my_tool"] # => instance of MyTool
Ask::Tools.discover   # auto-register all loaded Ask::Tool subclasses

Class Method Summary collapse

Class Method Details

.[](name) ⇒ Ask::Tool?

Find a registered tool by its derived name.

Parameters:

  • name (String, Symbol)

    the tool name to look up

Returns:

  • (Ask::Tool, nil)

    an instance of the matching tool, or nil



51
52
53
54
55
56
57
58
59
60
# File 'lib/ask/tools.rb', line 51

def [](name)
  name_str = name.to_s
  monitor.synchronize do
    registry.each_value do |klass|
      instance = klass.new
      return instance if instance.name == name_str
    end
    nil
  end
end

.allArray<Ask::Tool>

Return an array of instantiated registered tools.

Returns:



29
30
31
# File 'lib/ask/tools.rb', line 29

def all
  monitor.synchronize { registry.values.map(&:new) }
end

.clearvoid

This method returns an undefined value.

Remove all registered tools.



65
66
67
# File 'lib/ask/tools.rb', line 65

def clear
  monitor.synchronize { registry.clear }
end

.countInteger

Number of registered tool classes.

Returns:

  • (Integer)


72
73
74
# File 'lib/ask/tools.rb', line 72

def count
  monitor.synchronize { registry.size }
end

.discoverArray<Class>

Auto-discover loaded Ask::Tool subclasses via ObjectSpace and register any that aren’t already registered.

Returns:

  • (Array<Class>)

    the newly discovered classes



37
38
39
40
41
42
43
44
45
# File 'lib/ask/tools.rb', line 37

def discover
  monitor.synchronize do
    discovered = ObjectSpace.each_object(Class).select do |klass|
      klass < Ask::Tool && !registry.value?(klass) && klass.name
    end
    discovered.each { |klass| register(klass) }
    discovered
  end
end

.register(tool_class) ⇒ void

This method returns an undefined value.

Register a tool class manually.

Parameters:

  • tool_class (Class < Ask::Tool])

    ool_class [Class < Ask::Tool]



22
23
24
# File 'lib/ask/tools.rb', line 22

def register(tool_class)
  monitor.synchronize { registry[tool_class.name] = tool_class }
end