简体   繁体   中英

Where To Put User-defined Classes in Rails

I'm trying to to use this class

http://robbyonrails.com/articles/2005/05/11/parsing-a-rss-feed

but am not sure where to place the file so that it functions like a helper.

Where To Put User-defined Classes in Rails ? To lib directory


To your specific RssReader class question.

The best code written on that page is in comment from Veez (30.7.2008). Final code should look like this (not tested)

# lib/rss_reader.rb
require 'rss/2.0'
require 'open-uri'

class RssReader

  def self.posts_for(feed_url, length=2, perform_validation=false)
    posts = []
    open(feed_url) do |rss|
      posts = RSS::Parser.parse(rss, perform_validation).items
    end
    posts[0..length - 1] if posts.size > length
  end

In controller

# for last five messages
require 'rss_reader'
def some_action
  @posts = RssReader.posts_for(rss_url, 5, false)
end

In view (rewritten from comment in HAML to ERB)

<ul>
  <% @posts.each do |post| %>
    <li><%= post.title %> - <%= post.description %></li>
  <% end %>
</ul>

Watch RSS::Parser.parse parameters for details.


I think, rss feed reader should be Model in Rails. Very simple RSS feed reader is described by Travis on Rails (read comments, you don't need to use open method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM