Generating XML in a model

Hi all,

I have an application that produces an RSS feed of blog posts. To do
this, I have a file rss.rxml that contains code like this:

@blogs.each do |blog|
    xml.item do
       xml.title blog.subject
       xml.link blogs_path
       xml.description blog.body
       xml.guid blogs_path
       xml.pubDate blog.created_at
    end
end

I want to move this code into a to_rss method on my Blog model, so
that I can simply write:

@blogs.each do |blog|
    blog.to_rss
end

The idea here is that it should be really easy to add other items to
my rss feed, like photos or events - my view file can then generate
the feed for a collection of arbitrary objects, as long as the models
all have to_rss methods.

My question is, what do I need to include in the model in order to use
the xml builder? I want to write in blog.rb

def to_rss
    xml.item do
       xml.title self.subject
       xml.link blogs_path
       xml.description self.body
       xml.guid blogs_path
       xml.pubDate self.created_at
    end
end

This raises an error like "undefined variable xml". Does anyone know
how to solve this?

Many thanks,
Adam

My question is, what do I need to include in the model in order to use
the xml builder? I want to write in blog.rb

def to_rss
   xml.item do
      xml.title self.subject
      xml.link blogs_path
      xml.description self.body
      xml.guid blogs_path
      xml.pubDate self.created_at
   end
end

This raises an error like "undefined variable xml". Does anyone know
how to solve this?

In the context of an rxml view, an instance of Builder::XMLMarkup has
already been created for you and assigned to the local variable xml.
You just need to do the same. See also the examples at http://builder.rubyforge.org/

Fred

Thanks Fred - I just solved the problem by passing the xml variable to
the to_rss method, and now I feel a bit silly for asking! :slight_smile: