Skip to content

Instantly share code, notes, and snippets.

@remino
Created January 9, 2014 18:01
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save remino/8338854 to your computer and use it in GitHub Desktop.
Save remino/8338854 to your computer and use it in GitHub Desktop.
kramdown-rails: Use Kramdown (Markdown) in Rails 4
# app/helpers/application_helper.rb
module ApplicationHelper
def markdown(source)
Kramdown::Document.new(source).to_html.html_safe
end
end
# Gemfile
gem 'kramdown'
# config/initializers/kramdown.rb
module Kramdown
module Converter
class Html
include ActionView::Helpers::AssetTagHelper
def convert_img(el, indent)
attrs = el.attr.dup
link = attrs.delete 'src'
image_tag ActionController::Base.helpers.asset_path(link), attrs
end
end
end
end
# config/initializers/markdown_handler.rb
module MarkdownHandler
def self.erb
@erb ||= ActionView::Template.registered_template_handler(:erb)
end
def self.call(template)
compiled_source = erb.call(template)
"Kramdown::Document.new(begin;#{compiled_source};end, auto_ids: false).to_html.html_safe"
end
end
ActionView::Template.register_template_handler :md, MarkdownHandler
ActionView::Template.register_template_handler :markdown, MarkdownHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment