Inside PRESSBLOG

PRESSBLOG / Instagram / SNS マーケティングとか

Railsではてなブログみたいにユーザー毎のRSS実装した

PRESSブログ内でRSSフィードを実装しました。

↓RSSフィード例

https://pressblog.me/users/pressblog/rss

↓RSSフィードドキュメント

更新フィード | PRESS

仕様

  1. ユーザー毎にRSSフィードを作成する
  2. 新規投稿 or 記事更新をしたら、RSSフィードを生成しなおす
  3. xmlは1時間キャッシュする

使用したライブラリ

RailsのAction Viewは .builder 拡張子をつけると、 Builder::XmlMarkup のインスタンスを使用できます。

↓公式の説明はこちら↓

railsguides.jp

def show
  @posts = Post.order(published_at: :desc)
  @latest_post = Post.order(updated_at: :desc).first
end
cache "rss-last-updated_at_#{@latest_post.updated_at.to_i}", expires_in: 1.hours do
  xml.instruct! :xml, version: 1.0
  xml.rss(version: '2.0') do
    xml.channel do
      xml.title "#{current_user.name}#{' 公式ブログ' if current_user.is_official}"
      xml.description current_user.desc
      xml.link current_user.page_path(full_path: true)
      xml.language 'ja'
      xml.lastBuildDate Time.current.rfc822
      xml.generator 'PRESSブログ'
      if current_user.is_official && current_user.category.present?
        xml.category current_user.category.name
      end
      xml.images do
        xml.url current_user.thumb_url
        xml.title current_user.name
        xml.link current_user.page_path(full_path: true)
      end

      @posts.each do |bp|
        xml.item do
          xml.title bp.title
          xml.link bp.page_path(full_path: true)
          xml.description bp.desc
          xml.pubDate bp.published_at.rfc822
          xml.enclosure bp.thumb_url
        end
      end
    end
  end
end

Action Viewでxmlを生成できるので、余計なライブラリをいれず動的生成をさくっと出来て便利です。

おまけ

Builder::XmlMarkup ライブラリは rails c で実行できます。

$ rails c
>xml = Builder::XmlMarkup.new(target: STDOUT, indent: 2)
>xml.channel do
*xml.title 'test'
*end

targetSTDOUT を指定しておくと、生成されるxmlを標準出力してくれるので、コンソールでのデバッグのときはこれを指定しておくと便利です。

© DESSART & Co.