<DAY104>アプリ制作続き redcarpetとrougeの導入
学習状況
●学習日数 104日
●学習時間(本日)10時間
●累計学習時間 478.0時間
●一日あたりの平均学習時間 4.59時間
ドリルの復習(記載方法の違いについて)
2種類の記載があります。どちらも同じ表示をしますが、片方の表記
が好まれます。どちらが良いか、またその理由を述べよ。
#Aパターン @users = User.all @users.each do |user| = renser 'user', user: user #Bパターン @user = User.all =render 'user', users: @users
結論はBパターンが望ましい。
理由は、renderで情報を渡す前にeachをかけてしまうと、
renderで情報を渡す際に、eachの情報分繰り返し実行されサーバーに不可がかかる為。
railsのMarkdown記載内容をhtmlに出力する
gemを使用する。でもはまった。原理を理解するのに務める。
まだよくわかっていないが、欲しい機能の実装はできたので、メモ。
隙間時間に何をしていたのかを理解していく。
参考文献
これめっちゃわかりやすい
https://www.tmp1024.com/programming/rails-use-markdown-of-redcarpet/
redcarpet
GitHub - vmg/redcarpet: The safe Markdown parser, reloaded.
rouge
https://github.com/rouge-ruby/rouge
gemの導入
#htmlを解析してmarkdownに変換してくれる優れもの gem 'redcarpet' #言語を判別して色付けしてくれる(シンタックスハイライト) gem 'rouge'
導入後bundle install
markdown記載用のhelper.rbを作成
app/helper/markdown_helper.rbを作成し、コードを記述する
module MarkdownHelper def markdown(text) #rougeのオブジェクトにまず渡すオプション render_options = { filter_html: true, hard_wrap: true } # マークダウンオブジェクトに渡すオプション。この渡し方でハマった extensions = { autolink: true, fenced_code_blocks: true, lax_spacing: true, no_intra_emphasis: true, strikethrough: true, superscript: true, tables: true } renderer = RougeConfig::RougeRender.new(render_options) Redcarpet::Markdown.new(renderer, extensions).render(text) end end
libファイルを作成する
lib/rouge_config/rouge_render.rbを作成。クラスを記述
require 'redcarpet' require 'rouge' require 'rouge/plugins/redcarpet' module RougeConfig class RougeRender < Redcarpet::Render::HTML include Rouge::Plugins::Redcarpet end end
libファイルの内容を読みこます
このファイルを読みこます為にconfig/application.rbのクラス内の記述を変更
module (作成したアプリ名) class Application < Rails::Application #クラス内省略 #以下を追加! config.autoload_paths += %W(#{config.root}/lib/) end end
railsの変更をしたので、サーバーは再起動させる。
シンタックハイライトを適用させる
capp/assets/stylesheets/rouge.css.erbを作成
<%= Rouge::Themes::Monokai.render(:scope => '.highlight') %>
ビューにマークダウン記載反映されたのを表示
<%= sanitize markdown(tweet.content) %>