I was making a RSS feed the other day and wanted to limit the number of characters in my description. Here is how I did it.
First lets take a look at the code for my whole feed (views>RSS_feed.rxml file):
xml.instruct! :xml, :version=>"1.0"
xml.rss "version" => "2.0" do
xml.channel do
xml.title "Title goes here"
xml.link url_for :only_path => false, :controller => 'posts'
xml.description "Description goes here"
@posts.each do |post|
xml.item do
xml.title post.title
xml.link url_for :only_path => false, :controller => 'posts', :action => 'show', :id => post.id
xml.guid url_for :only_path => false, :controller => 'posts', :action => 'show', :id => post.id
xml.description post.description
xml.pubDate post.date
end
end
end
end
Now what we need to do is truncate the description to a set character length, I chose 300. So, replace this line:
xml.description post.description
with this:
xml.description truncate(post.description, 300, "...")
The “300″ is the number of characters and the “…” is whatever characters you want at the end of your description.
That’s it, you should be good to go.
5 Responses to “How to set a character limit for a Ruby on Rails RSS feeds”