Class: OpenapiFirst::DefaultOperationResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_first/default_operation_resolver.rb

Instance Method Summary collapse

Constructor Details

#initialize(namespace) ⇒ DefaultOperationResolver

Returns a new instance of DefaultOperationResolver.



7
8
9
10
# File 'lib/openapi_first/default_operation_resolver.rb', line 7

def initialize(namespace)
  @namespace = namespace
  @handlers = {}
end

Instance Method Details

#call(operation) ⇒ Object



12
13
14
15
16
17
# File 'lib/openapi_first/default_operation_resolver.rb', line 12

def call(operation)
  @handlers[operation.name] ||= begin
    id = handler_id(operation)
    find_handler(id) if id
  end
end

#find_class_method_handler(name) ⇒ Object



43
44
45
46
47
# File 'lib/openapi_first/default_operation_resolver.rb', line 43

def find_class_method_handler(name)
  module_name, method_name = name.split('.')
  klass = find_const(@namespace, module_name)
  klass.method(Utils.underscore(method_name))
end

#find_const(parent, name) ⇒ Object



56
57
58
59
60
61
# File 'lib/openapi_first/default_operation_resolver.rb', line 56

def find_const(parent, name)
  name = Utils.classify(name)
  throw :halt unless parent.const_defined?(name, false)

  parent.const_get(name, false)
end

#find_handler(id) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/openapi_first/default_operation_resolver.rb', line 19

def find_handler(id)
  name = id.match(/:*(.*)/)&.to_a&.at(1)
  return if name.nil?

  catch :halt do
    return find_class_method_handler(name) if name.include?('.')
    return find_instance_method_handler(name) if name.include?('#')
  end
  method_name = Utils.underscore(name)
  return unless @namespace.respond_to?(method_name)

  @namespace.method(method_name)
end

#find_instance_method_handler(name) ⇒ Object



49
50
51
52
53
54
# File 'lib/openapi_first/default_operation_resolver.rb', line 49

def find_instance_method_handler(name)
  module_name, klass_name = name.split('#')
  const = find_const(@namespace, module_name)
  klass = find_const(const, klass_name)
  klass.new
end

#handler_id(operation) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/openapi_first/default_operation_resolver.rb', line 33

def handler_id(operation)
  id = operation['x-handler'] || operation['operationId']
  if id.nil?
    raise HandlerNotFoundError,
          "operationId or x-handler is missing in '#{operation.method} #{operation.path}' so I cannot find a handler for this operation." # rubocop:disable Layout/LineLength
  end

  id
end