Feeds on Rails

View Feed Rss on your site

 

Install the plugin from my svn repository.

script/plugin install http://svn.maugustyniak.com/plugins/rails/feed

Create public/feeds folder and make it writable

Add column to your table

def self.up
  add_column :table :feed_url,  :string
end

Next in model add has_feed, this association has default options, but :as is required. The line below means associate my feed by :feed_url column as feed object ..

has_feed    :feed_url, :as => :feed

Display the feed like in example below:

<%= model.feed.to_html %>

to_html method will output your feed with default options, no need to loop through all the items. However if you want to loop through the feed's items and do some extra actions, use the code below:

<%
model.feed.items.each do |item| item.title item.content etc... end
%>

How that works? When you first time browse the page it will cache the entire feed to the file stored in public/feeds directory.

To reload the cache programatically you can use reload method, example:

<%= model.feed.reload.to_html %>

or

<%
model.feed.reload.items.each do |item|
..

I know what you think now, how to re-cache the feed for some period of time, well this can be done by your system cron job which will remove the cached files in public/feeds directory, this is only way so far.

 

additional has_feed options:

:length - the length of the item to display, Example:

:length => 3

:item - defines html tags to wrap the element Example:

:item => {:title => 'h2', :date => 'div', :description => 'p'}

:order - defines the order of the element. Example:

:order => [:title, :description, :date]

:path = path to store cached feeds. Change the path if you wish

:path         => "#{RAILS_ROOT}/public/feeds"

 

that's all, let me know if you notice wrong behavior or just does not work

Good luck

Add Comment