Module: Sinatra::RPC::Helpers

Defined in:
lib/sinatra/rpc/helpers.rb

Overview

Some methods to include in the app class.

Instance Method Summary collapse

Instance Method Details

#call_rpc_method(method, arguments) ⇒ Object

Execute an RPC method with the given name and arguments.

Parameters:

  • method (String)

    the RPC method name, e.g. 'system.listMethods'

  • arguments (Array)

    the list of arguments

Returns:

  • (Object)

    the return value of the method call on the target handler

Raises:



18
19
20
21
22
# File 'lib/sinatra/rpc/helpers.rb', line 18

def call_rpc_method(method, arguments)
  m = settings.rpc_method_index[method]
  raise Sinatra::RPC::NotFound if m.nil?
  m[:handler].send m[:method], *arguments
end

#handle_rpc(request) ⇒ Object

Handle RPC requests. This method should be called inside a POST definition.

Examples:

class MyApp < Sinatra:Base
  register Sinatra::RPC
  add_rpc_handler MyHandlerClass

  post '/RPC2' do
    handle_rpc(request)
  end
end

Parameters:

  • request

    the incoming HTTP request object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sinatra/rpc/helpers.rb', line 35

def handle_rpc(request)
  # The request/response serializer can be XML-RPC (the default) 
  # or any serializer implemented as a subclass of Sinatra::RPC::Serializer::Base.
  # The serializer class is chosen by reading the 'Content-Type' header in the request.
  serializer = select_serializer(request.env['CONTENT_TYPE'])
  
  body = request.body.read

  # An empty request is not acceptable in RPC.
  if body.empty?
    halt 400
  end

  # Generate the response.
  resp = begin
    # Parse the contents of the request.
    method, arguments = serializer.parse body

    # Execute the method call.
    call_rpc_method(method, arguments)
  rescue Sinatra::RPC::NotFound
    halt 404
  rescue Sinatra::RPC::Fault => ex
    ex
  rescue ArgumentError => ex
    Sinatra::RPC::BadRequestFault.new(ex.message)
  rescue Exception => ex
    Sinatra::RPC::GenericFault.new("#{ex.class.name}: #{ex.message}")
  end
 
  content_type(serializer.content_type, serializer.content_type_options)
  serializer.dump(resp)
end

#select_serializer(content_type) ⇒ Object

Generate a serializer instance suitable for the incoming RPC request. (see Sinatra::RPC::Serializer.find)



9
10
11
# File 'lib/sinatra/rpc/helpers.rb', line 9

def select_serializer(content_type)
  Sinatra::RPC::Serializer.find(content_type).new
end