Where To Put User-defined Classes in Rails

2019-04-20 20:17发布

问题:

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.

回答1:

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).