Rails XML generation like Active Model Serializer - ruby-on-rails

Is there a way to generate XML from the configuration/programming used by the Rails AciveModelSerializer gem? AMS seems to only generate customized JSON. XML comes out in a default format.
I've seen references to AciveModelSerialization and that it supports JSON and XML, but the configuration, while similar, is different. What is the story with the difference between them? Is one going away? How do they compare in real use (other than format capability)?

As you can see here, there (and at other spots), XML is slowly disappearing from the web. There are a couple of reasons for that. 1 - JSON objects are smaller. 2 - JSON is the de-facto format for most client-side javascript libraries. 3 - Fashion, people like it.
You can still use ActiveModel to serialize Xml if you wish so:
http://api.rubyonrails.org/classes/ActiveModel/Serializers/Xml.html
Hope it helps.

Related

XSS in Rails' JSON

I'm rendering content using Backbone in Rails. Some of the json properties i'm getting from the models will be html attributes, some of them might be used inside the javascript and others will be inserted between html elements. All of these require different escaping mechanisms, how do people deal with this?
In our project we are using doT templates which (as most other) allow for interpolation with encoding ({{! ... }}). You could also try to encode all data and strip any possible javascripts server side when data is saved to be 100% sure you won't get anything malicious
Additionally if you are using jquery methods remember to use text method to insert data rather then html as text will automatically encode it.
And I really recommend the doT! It's super fast and we've managed to make it play really nicely with requirejs

Time Cost Comparison: Haml render_to_string vs. string addition

I'm working on something that will render a small bit of xml (10 lines) every second.
I like the ease of constructing Xml with Haml, but I was wondering if anyone knew any details about the server cost of using render_to_string with haml versus building a string with String addition.
Haml is meant to be used when
you want to generate pretty XML,
the structure of the XML is hand-edited.
If you are generating small XML documents for machine consumption use faster libraries like Nokogiri or Builder.
Please do not use string interpolation, most of the time you will end up creating malformed documents because the input data will be slightly different from the data you used to test your app. This is true whenever you handle user-generated data. String interpolation is also a nice way to introduce security bugs. Just don't do it.

ActiveRecord: Produce multi-line human-friendly json

Using ActiveRecord::Base.to_json I do:
user = User.find_by_name 'Mika'
{"created_at":"2011-07-10T11:30:49+03:00","id":5,"is_deleted":null,"name":"Mika"}
Now, what I would like to have is:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
}
Is there an option to do this?
It would be great to have a global option, so that the behaviour be set depending on dev/live environment.
I'll go out on a limb and say "no, there is no such option".
AFAIK, the JSON encoding is actually handled by ActiveSupport rather than ActiveRecord. If you look at lib/active_support/json/encoding.rb for your ActiveSupport gem, you'll see a lot of monkey patching going on to add as_json and encode_json methods to some core classes; the as_json methods are just used to flatten things like Time, Regexp, etc. to simpler types such as String. The interesting monkey patches are the encode_json ones, those methods are doing the real work of producing JSON and there's nothing in them for controlling the final output format; the Hash version, for example, is just this:
# comments removed for clarity
def encode_json(encoder)
"{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
end
The encoder just handles things like Unicode and quote escaping. As you can see, the encode_json is just mashing it all together in one compact string with no options for enabling prettiness.
All the complex classes appear to boil down to Hash or Array during JSONification so you could, in theory, add your own monkey patches to Hash and Array to make them produce something pretty. However, you might have some trouble keeping track of how deep in the structure you are so producing this:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
"nested":{
"not":"so pretty now",
"is":"it"
}
}
Would be pretty straight forward but this:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
"nested": {
"not":"so pretty now",
"is":"it"
}
}
would be harder and, presumably, you'd want the latter and especially so with deeply nested JSON where eyeballing the structure is difficult. You might be able to hang a bit of state on the encoder that gets passed around but that would be getting a little ugly and brittle.
A more feasible option would be an output filter to parse and reformat the JSON before sending it off to the browser. You'd have to borrow or build the pretty printer but that shouldn't be that difficult. You should be able to conditionally attach said filter only for your development environment without too much ugliness as well.
If you're just looking to debug your JSON based interactions then maybe the JSONovich extension for Firefox would be less hassle. JSONovich has a few nice features (such as expanding and collapsing nested structures) that go beyond simple pretty printing too.
BTW, I reviewed Rails 3.0 and 3.1 for this, you can check Rails 2 if you're interested.
Have you considered the JSON gem? I believe it does exactly what you're looking for.
e.g.
JSON.pretty_generate(user)
Have a look at the detail here...
http://apidock.com/ruby/JSON/pretty_generate

Testing "HTML fixtures" with RSpec and rails

I have a web scraper built to parse html from a website and I'm trying to write tests for it.
The class I'm trying to test receives a Nokogiri HTML object and extracts the required data from it. Now as usual the html can vary, sometimes elements will be missing or whatnot. I need to test these different situations.
So what I'd like to do is make a bunch of html files, each one representing a case with a particular element missing etc. For each html file, I wish to also construct an associated hash of the data I would expect the scraper to extract, assuming it is working correctly.
So I would like to write a test which will iterate over these html files and compare the data extracted by the class being tested against the expected data and report whether or not it is correct.
Any suggestions as to how to do this?
Have a look at the Artifice, fakeweb or webmock gems, which override net/http in order to supply testable results.

How to pass parameters between rails applications?

I have to pass parameters between two rails apps. In one side (sender) I have an array of hashes. I have a code like the following to send the data:
http = Net::HTTP.new('localhost', '3030')
result = http.post('/processar_lotes', my_array_of_hashes)
Some questions
Is there any (kind of) serialize or something like this that I can pass to the other app?
At the other side, how can I de-serialize the information?
Is there a limit to the size of what I pass as a parameter?
To answer your questions:
There are many ways to 'serialize' the data. You can use your own custom format, or use a standard one. For example, you can try to use the Rails to_xml method, or the to_json method. You can also use Ruby's Marshal object.
Depending on your choice, this might be from_json, from_xml, Marshal.load, or your own custom reader.
Normally, this is unlimited for HTTP posts, but depending on your server configuration, it could be less.
Probably not the answer you're looking for, but I'd use XML. This would make your application much more flexible than using language-specific serialization.
It shouldn't be too hard to convert the array to XML and back.
EDIT: You might wanna check out ROXML and XML::Mapping.

Resources