What's the best way to use SOAP with Ruby?

后端 未结 10 1541
别那么骄傲
别那么骄傲 2020-11-27 10:15

A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of RE

10条回答
  •  不知归路
    2020-11-27 10:40

    I have used SOAP in Ruby when i've had to make a fake SOAP server for my acceptance tests. I don't know if this was the best way to approach the problem, but it worked for me.

    I have used Sinatra gem (I wrote about creating mocking endpoints with Sinatra here) for server and also Nokogiri for XML stuff (SOAP is working with XML).

    So, for the beginning I have create two files (e.g. config.rb and responses.rb) in which I have put the predefined answers that SOAP server will return. In config.rb I have put the WSDL file, but as a string.

    @@wsdl = '
             .......
          '
    

    In responses.rb I have put samples for responses that SOAP server will return for different scenarios.

    @@login_failure = "
        
            
                
                    Invalid username and password
                    
                    false
                
            
        
    "
    

    So now let me show you how I have actually created the server.

    require 'sinatra'
    require 'json'
    require 'nokogiri'
    require_relative 'config/config.rb'
    require_relative 'config/responses.rb'
    
    after do
    # cors
    headers({
        "Access-Control-Allow-Origin" => "*",
        "Access-Control-Allow-Methods" => "POST",
        "Access-Control-Allow-Headers" => "content-type",
    })
    
    # json
    content_type :json
    end
    
    #when accessing the /HaWebMethods route the server will return either the WSDL file, either and XSD (I don't know exactly how to explain this but it is a WSDL dependency)
    get "/HAWebMethods/" do
      case request.query_string
        when 'xsd=xsd0'
            status 200
            body = @@xsd0
        when 'wsdl'
            status 200
            body = @@wsdl
      end
    end
    
    post '/HAWebMethods/soap' do
    request_payload = request.body.read
    request_payload = Nokogiri::XML request_payload
    request_payload.remove_namespaces!
    
    if request_payload.css('Body').text != ''
        if request_payload.css('Login').text != ''
            if request_payload.css('email').text == some username && request_payload.css('password').text == some password
                status 200
                body = @@login_success
            else
                status 200
                body = @@login_failure
            end
        end
    end
    end
    

    I hope you'll find this helpful!

提交回复
热议问题