Class: RailsTwirp::RouteSet::ServiceRouteSet

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_twirp/route_set.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(service_class) ⇒ ServiceRouteSet

Returns a new instance of ServiceRouteSet.



32
33
34
35
36
37
# File 'lib/rails_twirp/route_set.rb', line 32

def initialize(service_class)
  @service_class = service_class
  @service_class.raise_exceptions = true

  @rpcs = {}
end

Instance Attribute Details

#rpcsObject (readonly)

Returns the value of attribute rpcs.



30
31
32
# File 'lib/rails_twirp/route_set.rb', line 30

def rpcs
  @rpcs
end

Instance Method Details

#add_route(name, mapping) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/rails_twirp/route_set.rb', line 39

def add_route(name, mapping)
  if @rpcs[name]
    raise ArgumentError, "Invalid RPC, route already defined: #{name}"
  end

  @rpcs[name] = mapping
end

#to_serviceObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rails_twirp/route_set.rb', line 47

def to_service
  # Synthesize a handler that will process the requests
  #
  handler = Class.new
  @rpcs.each do |name, mapping|
    rpc_info = @service_class.rpcs[name]
    raise UnknownRpcError, "Unknown RPC #{name} on #{@service_class.service_name} service" unless rpc_info
    method_name = rpc_info[:ruby_method]

    # Stolen from Rails in ActionDispatch::Request#controller_class_for
    action_name = mapping.action
    response_class = rpc_info[:output_class]

    handler.define_method(method_name) do |req, env|
      controller_name = mapping.controller.underscore
      const_name = controller_name.camelize << "Controller"
      controller_class = const_name.constantize
      controller_class.dispatch(action_name, req, response_class, name, env)
    end
  end

  service = @service_class.new(handler.new)
  service.before do |rack_env, env|
    env[:rack_env] = rack_env
  end
  service
end