Building an API with Rails and I wanted to respond back with a certain error message just using a hash. Easypeasy with JSON, however with XML it wasn't as straight forward.
Using this error_hash as our example response:
error_hash = {'LOGINFAILBOAT' => 'Yo Your Login/Password Failed'}
With JSON, you can pass that to your response block and works just fine; try to respond with XML and no bueno. However Nokogiri let's you make it work, by passing the key of your hash as the xml element name.
When I hit my conditions to throw an error, I have it call the following method with the type and message, which is mostly a generic respond_to; with the exception of the XML response.
def return_error_response(error_type, message)
error_response = { error_type => message }
respond_to do |format|
format.json { render json: error_response }
format.xml { render xml: build_xml_error_message(error_response) }
end
end
And if it's an XML it gets sent to this method.
def build_xml_error_message(error_hash)
error_attr = error_hash.keys.first
error_valu = error_hash[error_attr]
xml_error_message = Nokogiri::XML::Builder.new do |xml|
xml.send(error_attr.to_sym, error_valu)
end
return xml_error_message
end
Pretty simple, but pretty simple was all I needed.