1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RailsでRSSを生成した時の備忘録(RSS2.0準拠)

Posted at

これなに

RailsでRSSを生成した時にちょっと困ったりして調べたのでまとめておく。
RSS::MakerとかBuilder::XmlMarkupとかあるけど、slimで書けばいいじゃない!と思ったけど結局builderでも書きました。
たぶんSmartNewsの[SmartFormat仕様書](url: https://publishers.smartnews.com/hc/ja/articles/360010977813-SmartFormat%E4%BB%95%E6%A7%98%E6%9B%B8-RSS2-0%E6%BA%96%E6%8B%A0-)の必須項目は埋めてあるはず。

サンプルコード

postsテーブルの構造はわりと一般的だと思うので割愛します。

slim

rss.xml.slim
doctype xml
rss version='2.0' xmlns:content='http://purl.org/rss/1.0/modules/content/' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:media='http://search.yahoo.com/mrss/'

  channel
    title タイトル
    link = Settings.url
    description ディスクリプション
    language ja
    pubDate = Time.zone.now.rfc822
    copyright Copyright My Blog, Inc. All Right Reserved.

    - @posts.each do |post|
      item
        title = post.title
        link = post_url(post.permalink)
        guid = post.permalink
        description = post.description
        pubDate = post.published_at.rfc822
        category = post.category.name
        content:encoded
          = cdata_section(render partial: 'posts', formats: :html, locals: { post: post })
        media:thumbnail url=post.eyecatch_url
        dc:creator = post.author.name

builder

rss.xml.builder
xml.instruct! :xml, version: 1.0
xml.rss(version: 2.0, 'xmlns:content': 'http://purl.org/rss/1.0/modules/content/', 'xmlns:dc': 'http://purl.org/dc/elements/1.1/', 'xmlns:media': 'http://search.yahoo.com/mrss/') do
  xml.channel do
    xml.title 'タイトル'
    xml.link Settings.url
    xml.description 'ディスクリプション'
    xml.language 'ja'
    xml.pubDate Time.zone.now.rfc822
    xml.copyright 'Copyright My Blog, Inc. All Right Reserved.'

    @posts.each do |post|
      xml.item do
        xml.title post.title
        xml.link post_url(post.permalink)
        xml.guid post.permalink
        xml.description post.description
        xml.pubDate post.published_at.rfc822
        xml.category post.category.name
        xml.tag!('content:encoded') do
          xml.cdata! render partial: 'posts', formats: :html, locals: { post: post }
        end
        xml.tag!('media:thumbnail', url: post.eyecatch_url)
        xml.tag!('dc:creator', post.author.name)
      end
    end
  end
end

メモ

  • xmlでコロン付きのタグを扱いたい時はxml.tag!を使う
  • cdataにしたい場合、slimではcdata_sectionヘルパー、xmlではxml.cdata!を使う
  • slimはもちろんbuilderでもpartialを呼べる
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?