参考
- Simple Markdown Powered Rails Blog | shubox.io
- How can I automatically render partials using markdown in Rails 3_ - Stack Overflow
やりたいこと
- そこそこ文章量のあるほぼ静的なページで、個別にController作るのだるいし、DBに入れるまでもないようなページ作りたい
- ルーティング書くのもだるいのでURLから判別してレンダリングして欲しい
- md内でhelperは使いたい
やり方
下準備
gem 'high_voltage'
gem 'rdiscount'
config/initializers/high_voltage.rb
HighVoltage.configure do |config|
config.content_path = 'stashes/'
end
config/initializers/markdown_handler.rb
require 'rdiscount'
module MarkdownHandler
def self.erb
@erb ||= ActionView::Template.registered_template_handler(:erb)
end
def self.call(template)
compiled_source = erb.call(template)
"RDiscount.new(begin;#{compiled_source};end).to_html"
end
end
ActionView::Template.register_template_handler :md, MarkdownHandler
/blog/:post の場合
routes.rb
get 'blog/:post', to: 'high_voltage/pages#show', id: 'blog'
app/views/stashes/blog.html.erb
<% post = "#{params[:post].gsub('-', '_')}" %>
<%= render("stashes/blog/#{post}").html_safe %>
app/views/stashes/blog/_test.md
# TEST
<%= Time.current %>
<%= link_to 'root', root_path %>
これで http://localhost:3000/blog/test
を開くと
現在時刻とルートへのリンクのあるページが表示できる。
違うページは同様に app/views/stashes/blog/_xxx.md
を追加していけばよい。