Prettifying Builder::XmlMarkup.new

76 views
Skip to first unread message

Paul

unread,
Jun 15, 2011, 11:38:45 AM6/15/11
to rubyonrails-talk
I've got a web service which outputs XML. I'm generating it very
conveniently by creating a file in the view named index.xml.builder.
That all works great, almost.

I can write that file very simply and cleanly like this:

xml.instruct!
xml.search do
xml.total @results[:total]
end

That's really maintainable, but the output contains lots of extra
spaces and newlines that muck it up. I can get rid of all the spaces
by adding this line to the top of each xml.builder file:

xml = Builder::XmlMarkup.new

But that takes out ALL the spaces and newlines, so the entire output
is on one line. What I want is something in the middle. Through
experimentation, I've explicitly added newlines and spaces where I
want them, but suddenly the file is no longer as easily maintainable:

xml = Builder::XmlMarkup.new
xml.instruct!
xml.text!("\n")
xml.search do
xml.text!("\n ")
xml.total @results[:total]
end

Does anyone know of a cleaner approach where I get the maintainability
of the top example with the output of the bottom example?

Thanks!

Walter Lee Davis

unread,
Jun 15, 2011, 12:02:38 PM6/15/11
to rubyonra...@googlegroups.com

Couldn't you run the output through pp?

Walter

>
> Thanks!
>
> --
> You received this message because you are subscribed to the Google
> Groups "Ruby on Rails: Talk" group.
> To post to this group, send email to rubyonrails-
> ta...@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com
> .
> For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
> .
>

Paul

unread,
Jun 15, 2011, 12:35:49 PM6/15/11
to rubyonra...@googlegroups.com

Maybe if I knew how. I'm not sure how to insert pp after the view template.

My controllers look like this:

respond_to do |format|
format.html
format.xml
end

And I don't understand the magic enough to know how to put pp in there.

Also, I was looking at the documentation for pp and it's not clear
what it will do with a string in xml format. If I could solve the
first problem I'll experiment with it.

Allan

unread,
Jun 16, 2011, 4:53:55 PM6/16/11
to rubyonra...@googlegroups.com
Try xml = Builder::XmlMarkup.new(:indent=>2)

Paul

unread,
Jun 16, 2011, 5:05:06 PM6/16/11
to rubyonra...@googlegroups.com
Thanks. That's where I started. That does two things: it indents the
markup just like I want, but it does a second thing, too. It leaves
all the white space that exists in the xml.builder file also, so that
the resultant XML document is really ugly and contains extra newlines
and extra spaces.
Reply all
Reply to author
Forward
0 new messages