Class: OpenapiFirst::FindHandler

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

Instance Method Summary collapse

Constructor Details

#initialize(spec, namespace) ⇒ FindHandler

Returns a new instance of FindHandler.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/openapi_first/find_handler.rb', line 7

def initialize(spec, namespace)
  @namespace = namespace
  @handlers = spec.operations.each_with_object({}) do |operation, hash|
    operation_id = operation.operation_id
    handler = find_handler(operation_id)
    if handler.nil?
      warn "#{self.class.name} cannot not find handler for '#{operation.operation_id}' (#{operation.method} #{operation.path}). This operation will be ignored." # rubocop:disable Layout/LineLength
      next
    end
    hash[operation_id] = handler
  end
end

Instance Method Details

#[](operation_id) ⇒ Object



20
21
22
# File 'lib/openapi_first/find_handler.rb', line 20

def [](operation_id)
  @handlers[operation_id]
end

#find_class_method_handler(name) ⇒ Object



38
39
40
41
42
# File 'lib/openapi_first/find_handler.rb', line 38

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



53
54
55
56
57
58
# File 'lib/openapi_first/find_handler.rb', line 53

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(operation_id) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/openapi_first/find_handler.rb', line 24

def find_handler(operation_id)
  name = operation_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



44
45
46
47
48
49
50
51
# File 'lib/openapi_first/find_handler.rb', line 44

def find_instance_method_handler(name)
  module_name, klass_name = name.split('#')
  const = find_const(@namespace, module_name)
  klass = find_const(const, klass_name)
  return ->(params, res) { klass.new.call(params, res) } if klass.instance_method(:initialize).arity.zero?

  ->(params, res) { klass.new(params.env).call(params, res) }
end