I was just making some updates to the Ruby client I wrote for the Splunk REST API and wanted to point out one of the most wonderful facets of the language: The ability to dynamically generate methods to support a more natural interface.
Take this standard XML response from Splunk’s REST interface for search results:
Normally, using Nokogiri or another XML parsing library, you would need to do this to access the list of hosts (and any other Splunk field):
@doc = Nokogiri.parse(xmlResponse)
@doc.results.result.each do |result|
Yuck! Especially when the response format is standard and predictable. Enter Ruby’s awesome overrides and the method_missing method. Using the method_missing method, we can intercept what would normally be an exception and dynamically respond to method calls for Splunk fields without actually having to write those methods.
Now I can access those XML fields with a simple method call, in this case .host:
job.parsedResults.each do |result|
puts result.host #Or any other field!
Cool, huh? Can’t do that in Java. Check-out the library on Github.