Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby on Rails initializer to log Savon SOAP XML as pretty JSON instead. Also show what line of code called it.
--------------------------------------------------
lib/foo.rb:22:in `save'
# foo.book
>> REQUEST:
{
"CashBook_Book": {
"cashBookHandle": {
"Number": "14"
}
}
}
<< RESPONSE:
{
"CashBook_BookResponse": {
"xmlns": "http://e-conomic.com",
"CashBook_BookResult": {
"Number": "14"
}
}
}
--------------------------------------------------
# config/initializers/savon.rb
# Don't mention the adapter!
HTTPI.log = false
# Log pretty JSON instead of XML, and never mind URL and headers.
class Savon::SOAP::Request
def log_request(url, headers, body)
Savon.log ""
log_calling_line
Savon.log ""
Savon.log ">> REQUEST:"
log_soap_prettily body
end
def log_response(code, body)
Savon.log ""
Savon.log "<< RESPONSE:"
log_soap_prettily body
Savon.log ""
Savon.log "-"*50
end
def log_calling_line
calling_line = caller[1..-1].find { |line| line.include?(Rails.root.to_s) }
calling_line.sub!(Rails.root.to_s + "/", "")
file, line, _ = calling_line.split(":")
code_line = File.readlines(file)[line.to_i - 1].strip
Savon.log calling_line
Savon.log "# #{code_line}"
end
def log_soap_prettily(soap)
# depends on json gem
hash = Hash.from_xml(soap)
body = hash["Envelope"]["Body"]
json = JSON.pretty_generate(body)
Savon.log json
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.