勉強がてら自分のブログをrailsで運用しています。
RSSくらい対応したいなと思いRSS対応をしました。
railsはRSSフォーマットに対応しているので、gemなどを使わずにrailsのデフォルトの機能で実装していきます。
実装の流れはCRUDを作成するのようなイメージで、ルーティング、コントローラー、ビューを追加していきます。
以下のコミットでRSS対応をしているので、コミットを見ながらやりたい方は参考にしてください。
リポジトリにスターもつけていただけると狂喜乱舞します。
https://github.com/tackeyy/blog/commit/079ceca788130d238fd59d95b6e71583d715da5b
ルーティングを設定
config/routes.rb
resources 'feed', only: %i(index)
コントローラーを作成してRSSフォーマットを返す
app/controllers/feed_controller.rb
class FeedController < ApplicationController
def index
@posts = Post.shipped.order(created_at: :desc).page(params[:page]).decorate
respond_to do |format|
format.rss { render layout: false }
end
end
end
index.rss.builderを作成してXMLを記載する
app/views/feed/index.rss.builder
# encoding: UTF-8
xml.instruct! :xml, :version => "1.0"
xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
xml.channel do
xml.title Settings.title
xml.description Settings.description
xml.link Settings.url
@posts.each do |post|
xml.item do
xml.title post.title
xml.description do
xml.cdata! HTML_Truncator.truncate(post.to_html, 1).html_safe
end
xml.pubDate post.created_at
xml.guid blog_path(post.friendly_id || post.id)
xml.link blog_path(post.friendly_id || post.id)
end
end
end
end
-
slug を簡単に付けれる
friendly_id
を使っているので*_path(post.friendly_id 〜
となっています
https://github.com/norman/friendly_id -
title, descriptionは
config
というGemを使っています
https://github.com/railsconfig/config
以下にアクセスしてXMLが表示されればOKです。
feedlyのボタンを設置する
ここからfeedlyのボタンをhtmlを生成します。
あとは任意の場所にリンクを貼るだけです。
私の場合はフッターを以下のようにしました。
app/views/layouts/_footer.html.haml
%footer
.container
.row
.col-lg-8.col-lg-offset-2.col-md-10.col-md-offset-1
%ul.list-inline.text-center
%li
%a{href: "https://github.com/tackeyy", target: "blank"}
%span.fa-stack.fa-lg
%i.fa.fa-circle.fa-stack-2x
%i.fa.fa-github.fa-stack-1x.fa-inverse
%li
%a{:href => 'https://twitter.com/3chhe', :target => '_blank'}
%span.fa-stack.fa-lg
%i.fa.fa-circle.fa-stack-2x
%i.fa.fa-twitter.fa-stack-1x.fa-inverse
%li
%a{href: "http://cloud.feedly.com/#subscription%2Ffeed%2Fhttp%3A%2F%2Ftackeyy.com%2Ffeed", target: "blank"}
%span.fa-stack.fa-lg
%i.fa.fa-circle.fa-stack-2x
%i.fa.fa-rss.fa-stack-1x.fa-inverse
%p.copyright.text-muted Copyright © #{Settings.title} 2017
こんな感じで簡単にRSS対応できました。
参考