Module: TwirpRails::Routes::Helper

Defined in:
lib/twirp_rails/routes.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.constantize_first(*variants) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/twirp_rails/routes.rb', line 41

def self.constantize_first(*variants)
  variants.each do |name|
    clazz = name.to_s.camelize.safe_constantize

    return clazz if clazz
  end

  nil
end

.installObject



51
52
53
# File 'lib/twirp_rails/routes.rb', line 51

def self.install
  ActionDispatch::Routing::Mapper.include TwirpRails::Routes::Helper
end

.on_create_service(&block) ⇒ Object



57
58
59
60
# File 'lib/twirp_rails/routes.rb', line 57

def self.on_create_service(&block)
  Helper.create_service_hooks ||= []
  Helper.create_service_hooks << block
end

.run_create_hooks(service) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/twirp_rails/routes.rb', line 62

def self.run_create_hooks(service)
  return unless Helper.create_service_hooks

  Helper.create_service_hooks.each do |hook|
    hook.call service
  end
end

Instance Method Details

#mount_twirp(name, handler: nil, scope: 'twirp') ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/twirp_rails/routes.rb', line 6

def mount_twirp(name, handler: nil, scope: 'twirp')
  TwirpRails.handle_dev_error "mount twirp route #{name}" do
    case name
    when Class
      raise 'handler param required when name is a class' unless handler&.is_a?(Class)

      service_class = name

    when String, Symbol
      service_class = Helper.constantize_first "#{name}_service", name

      unless service_class
        msg = "mount_twirp of #{name} error. #{name.camelize}Service or #{name.camelize} class is not found"

        raise TwirpRails::Error, msg
      end

      handler ||= "#{name}_handler".camelize.constantize
    else
      raise 'twirp service name required'
    end

    service = service_class.new(ErrorHandlingFactory.wrap_handler(handler.new))
    Helper.run_create_hooks service

    if scope
      scope scope do
        mount service, at: service.full_name
      end
    else
      mount service, at: service.full_name
    end
  end
end