I\'ve got a pure, working, Rails application.
I now need it to start communicating with another application (sympa). This application exposes that exposes a SOAP interfa
EDIT: this is an outdated answer dating of rails 2.x. For a more present answer, I recommend you to watch railscast #290 . I'm leaving this answer here in case someone is still using rails 2.x for some reason, and can't apply what Ryan Bates says there.
I've been fighting with this for some days now and I think I found a solution myself.
The simplest, most active gem that I could find for SOAP interaction is called Savon.
It's supposed to work with Ruby itself. Here's a quick tour on how you use it with Rails:
Install the gem. Easiest way is to edit config/environment and add
config.gem "savon"
And then run
rake gems:install
This should install savon along with a couple more gems.
Next, create a class on your app/models/
directory (it doesn't have to be a subclass of ActiveRecord, just a regular class on your models directory)
If you are like me, you will want to stay as far away from XML as possible. You can do so by creating a class like this one:
class MyWebservice
WSDL = "http://www.theWebSiteWithAService.com/wsdl"
def self.client
@@client ||= Savon::Client.new(WSDL)
end
def self.soap_actions
return client.wsdl.soap_actions
end
def self.invoke(action, parameters)
response = client.send(action) { |soap| soap.body = parameters }
return response.to_hash
end
end
You will be mostly using it for invoking methods. The kind of methods you will be able to invoke depends on the services that "the other site" provides. Let's imagine that 3 actions are available - :create_monkey
, :destroy_monkey
& :list_monkeys
. You can confirm that the list is correct by doing this on the rails console:
MyWebservice.soap_actions
=> [:create_monkey, :destroy_monkey, :list_monkeys]
Now imagine that you want to invoke :create_monkey. First you need to know which parameters are needed for that call. The best place to look at this is the wsdl file itself. You should see something like this:
<message name="create_monkey_request">
<part name="name" type="xsd:string"/>
<part name="hair_color" type="xsd:string"/>
</message>
<message name="create_monkey_response">
<part name="status" type="xsd:string"/>
</message>
So it takes two parameters: name
and hair_color
. On the ruby console, you can invoke it like this:
MyWebService.invoke :create_monkey, {:name => 'frank', :hair_color => 'red' }
=> {:status => 'ok'}
You will get a hash as a response. In this case I got an 'ok' status, but it could be far more complex.
Later on, you can create (for example) a tableless model called Monkey
, and define methods like new
, create
, etc that use the webservice.
I'm leaving out lots of interesting things, such as security. But this should get you started if you have the same problem I had.
Regards!