I have a Rails app that acts as a pass-through for an XML services API.
The main use cases goes like this:
- User POSTs parameters to Rails via http://example.com/model/report. For brevity, let’s say the form just submits
zip_code=90010. - Rails takes
zip_codeand uses RestClient to query an external XML services API via a GET request: http://xmlservice.example.com/report?report_id=1&zip_code=90010 - The report response is returned via XML. I want to parse the XML via Nokogiri and output a normal HTML view via report.html.erb.
I’m struggling to figure out where to put my XML (Nokogiri) code. Should I process the XML in my model or do all the parsing in the controller?
I know both methods will work, but I want to know what the best practice would be. This also is not a background XML feed grab, so it’s not suited to be a delayed job that runs nightly. It has to answer dynamic requests 24/7.
Keep in mind, I’ve removed ActiveRecord from my app for optimization. This app doesn’t touch any databases. It’s basically a pass-through to the XML API that will render HTML output for the client.
I’ve read it’s best to go with “skinny controllers” and “fat models”, but most of the Nokogiri examples I see out there have doc = Nokogiri::XML(RestClient.get(myurl, myparams)) type code inside the controller.
So… model or controller?
Thanks!
I would place the code in a class which would fetch the xml and parse the xml for you.
This way its easier to Unit Test the class for parsing or any other operations you want to do on the returned XML.
The class can be placed in the lib folder or if its sort of like a Pseudo Model ( with a XML Database ) it can be placed in Models as well. Thats mostly upto what the class is and how you would like structure your codebase.
Update: a Plus of this approach, you code base can remain the same even if you swap out the service for something else, because you code base interacts with this class, the changes will have to be made only to this class. Interface advantages 🙂