Where To Put User-defined Classes in Rails

☆樱花仙子☆ 提交于 2019-12-06 19:16:41

问题


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



来源:https://stackoverflow.com/questions/2660933/where-to-put-user-defined-classes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!