I am combining multiple items into one RSS file iterating them like so:
# create RSS
atom = RSS::Maker.make('atom') do |f|
f.channel.updated = Date.today.to_s
# iterate through Ideas
ideas[0,50].each do |r|
f.items.new_item do |e|
e.updated = DateTime.parse(r[:date].to_s).to_s
e.title = r[:title]
e.content.type = 'html'
end
end
# iterate through Articles
articles[0,50].each do |r|
f.items.new_item do |e|
e.updated = DateTime.parse(r[:date].to_s).to_s
e.title = r[:title]
e.content.type = 'html'
end
end
end
But the order of the items in the file is not sorted by date (because I loop through the first batch “Ideas” then ”Articles”)
I tried after iterating to sort by date
/ updated
value, with the following combos:
# f.items.sort {|a,b| a.updated <=> b.updated}
# atom.items.sort! {|a,b| a.date <=> b.date}
# f.items.reverse!
# f.items.sort_by(&:date)
# f.sort_by(&:date)
But without success.
Do I need to loop again through each item in the RSS to sort them?
CodePudding user response:
I would combine both arrays into one items
array and then sort that one before iterating over it:
atom = RSS::Maker.make('atom') do |f|
f.channel.updated = Date.today.to_s
items = ideas.first(50) articles.first(50)
items = items.sort_by { |item| item[:date] }
# iterate through all items
items.each do |r|
f.items.new_item do |e|
e.updated = DateTime.parse(r[:date].to_s).to_s
e.title = r[:title]
e.content.type = 'html'
end
end
end
Note that this works because both types (articles
and ideas
) have the same properties and are rendered into RSS in the same way.