Class: Hash

Inherits:
Object show all
Defined in:
lib/savon/core_ext/hash.rb

Instance Method Summary collapse

Instance Method Details

#find_soap_bodyObject

Returns the values from the soap:Body element or an empty Hash in case the soap:Body tag could not be found.



5
6
7
8
9
# File 'lib/savon/core_ext/hash.rb', line 5

def find_soap_body
  envelope = self[keys.first] || {}
  body_key = envelope.keys.find { |key| /.+:Body/ =~ key } rescue nil
  body_key ? envelope[body_key].map_soap_response : {}
end

#map_soap_responseObject

Maps keys and values of a Hash created from SOAP response XML to more convenient Ruby Objects.



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/savon/core_ext/hash.rb', line 53

def map_soap_response
  inject({}) do |hash, (key, value)|
    value = case value
      when Hash   then value["xsi:nil"] ? nil : value.map_soap_response
      when Array  then value.map { |a_value| a_value.map_soap_response rescue a_value }
      when String then value.map_soap_response
    end

    hash.merge key.strip_namespace.snakecase.to_sym => value
  end
end

#to_soap_xmlObject

Translates the Hash into SOAP request compatible XML.

Example:

{ :find_user => { :id => 123, "wsdl:Key" => "api" } }.to_soap_xml
# => "<findUser><id>123</id><wsdl:Key>api</wsdl:Key></findUser>"

Comes with a way to control the order of XML tags in case you’re foced to do so (parameterOrder). Specify an optional Array under the :order! key reflecting the order of your keys. An ArgumentError is raised unless the Array contains the exact same/all keys of your Hash.

Example:

{ :find_user => { :name => "Eve", :id => 123, :order! => [:id, :name] } }.to_soap_xml
# => "<findUser><id>123</id><name>Eve</name></findUser>"

You can also specify attributes for XML tags by via an optional Hash under the :attributes! key.

Example:

{ :find_user => { :person => "Eve", :attributes! => { :person => { :id => 123 } } } }
# => "<findUser><person id="123">Eve</person></findUser>"


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/savon/core_ext/hash.rb', line 33

def to_soap_xml
  xml = Builder::XmlMarkup.new
  attributes = delete(:attributes!) || {}

  order.each do |key|
    attrs = attributes[key] || {}
    value = self[key]
    key = key.to_soap_key

    case value
      when Array then xml << value.to_soap_xml(key)
      when Hash  then xml.tag!(key, attrs) { xml << value.to_soap_xml }
      else            xml.tag!(key, attrs) { xml << value.to_soap_value }
    end
  end

  xml.target!
end