繁体   English   中英

来自MySQL表的RSS提要,使用Ruby或Rails或Gems

[英]RSS feed from MySQL table using either Ruby or Rails or Gems

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

根据我要尝试执行的操作,我可能只想使用一个简单的Ruby脚本。 我将使用ActiveRecord,因此不必编写任何SQL。 然后,我将使用BuilderRubyRSS生成提要。

将ActiveRecord直接连接到MySQL服务器非常简单:

require 'active_record'

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

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

RubyRSS网站上有RSS生成器示例,在Railscasts网站上有一个生成器示例。

Hernan是正确的...这里是从数据库获取数据所需的全部步骤(为了简化格式化,我将代码移至了以下步骤:

  1. 安装ActiveRecord: sudo gem install activerecord
  2. 根据hernan43的建议建立连接(最好在一个单独的文件中,将其称为“ connection.rb”
  3. 通过从ActiveRecord继承来创建使用该连接的类
  4. 从表中检索记录,并使用它来填充您的RSS生成器

您不必将所有内容都分离到一个文件中……您可以将所有内容都放在一个文件中,然后删除文件2和3中的“ requires”,但这是一种约定,以类似于我做了什么

#1:文件connection.rb

require 'rubygems'
require 'active_record'

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

#2文件名: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文件名: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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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