使用Ruby或Rails或Gems从MySQL表中提供RSS

时间:2009-12-12 10:33:23

标签: ruby-on-rails ruby rubygems

我有一个MySQL表,我想从中选择某些列来创建RSS Feed。如何使用Ruby或Rails或Gems做到这一点?

2 个答案:

答案 0 :(得分:3)

根据我的目的,我可能会选择一个简单的Ruby脚本。我会使用ActiveRecord所以我不必编写任何SQL。然后我会使用BuilderRubyRSS来生成Feed。

直接将ActiveRecord连接到MySQL服务器就像:

require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "myusername",
:password => "mypassword",
:database  => "mydb"
)

然后您可以像在常规Rails应用程序中一样定义ActiveRecord模型。

RubyRSS website上有RSS生成器示例,Railscasts website上有一个Builder生成器。

答案 1 :(得分:2)

Hernan是对的......这是从数据库中获取数据所需的全部步骤(我将代码移到了步骤下方以便于格式化:

  1. 安装ActiveRecord: sudo gem install activerecord
  2. 根据hernan43的建议建立连接(最好在单独的文件中,我们称之为“connection.rb”
  3. 通过继承ActiveRecord
  4. 创建一个使用该连接的类
  5. 从表中检索记录,并使用它/它们来填充RSS生成器
  6. 您不必将所有内容分成文件...您可以将下面的所有内容放在一个文件中,并删除文件2和3中的“要求”,但这是一个将您的问题分开的常规。方式类似于我所做的。

    #1:file connection.rb

    require 'rubygems'
    require 'active_record'
    
    ActiveRecord::Base.establish_connection(
      :adapter => "mysql",
      :host => "localhost",
      :database => "appdb",
      :username => "appuser",
      :password => "secret"
    )
    

    #2 filename:singural_rss_table_name.rb     需要'连接'

    class SingularRSSTableName < ActiveRecord::Base
      set_table_name 'real_database_table_name' #if the table name is the lowercase, underscore plural of the class name, then you don't need this line.
    end
    

    #3 filename:rss_creator_file.rb

    require 'singular_rss_table_name'
    
    # Here you retrieve the rows from your database table, 
    # based on the condition that the column 'title' is exactly the text 'article_title'
    # there are a lot more options for 
    # conditions in ActiveRecord, and you'll probably want to look them up.
    records_for_rss_entries = SingularRssTableName.find(:all, :conditions => {:title => 'article_title'})
    
    
    rss_object = RSS::Maker.new(version) do |feed|
      feed.channel.title = "Example Ruby RSS feed"
    
      records_for_rss_entries.each do |entry_record|  # here we're iterating through
                                                      # each of the rows we found.
        entry = feed.items.new_item
        entry.title = entry_record.title # at this point, each 'entry_record' is a row in your db table
                                         # use the dot (.) operator to access columns in the table.
    
        ...
      end  
    
    end
    

    这个答案的内容部分答案来自:

    http://rubyrss.com/
    

    http://www.agileadvisor.com/2008/01/using-activerecord-outside-rails.html