Sha256: 598cb7f8ae51e1c68a1c3a1652b8524d3056d3e19fcfff22dde347d54acd2ee6

Contents?: true

Size: 1.36 KB

Versions: 2

Compression:

Stored size: 1.36 KB

Contents

require 'redcarpet'
require 'pygments.rb'

class << ActiveRecord::Base

  def converts_markdown(markdown = :markdown, html = :html)
    markdown = markdown.to_s
    html = html.to_s

    after_save :"convert_#{markdown}_to_#{html}"

    define_method "convert_#{markdown}_to_#{html}" do
      renderer = Redcarpet::Markdown.new(
        HTMLwithPygments.new(:hard_wrap => false, :with_toc_data => true),
        {
          :autolink => true,
          :fenced_code_blocks => true,
          :highlight => true,
          :space_after_headers => true,
          :strikethrough => true,
          :tables => true,
          :underline => true,
        }
      )

      update_columns(
        html.to_sym => renderer.render(self.send("clean_#{markdown}"))
      )
    end

    define_method "clean_#{markdown}" do
      md = self.send(markdown)
      return "" if md.blank?
      md.gsub(
        /(?:http[s]?:\/\/)?(?:www\.)?(?:youtu\.be)\/(?:watch\?v=)?(.+)/,
        '<iframe width="420" height="345" src="http://www.youtube.com/embed/\1" frameborder="0" allowfullscreen></iframe>'
      ).gsub(
        /[”“]/,
        '"'
      ).gsub(
        /\[file\:(.*)\]/,
        '<p class="file"><code>\1</code></p>'
      )
    end
  end

  class HTMLwithPygments < Redcarpet::Render::HTML
    def block_code(code, language)
      Pygments.highlight(code, lexer: language)
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mark_it_zero-0.1.1 lib/mark_it_zero/converts_markdown.rb
mark_it_zero-0.1.0 lib/mark_it_zero/converts_markdown.rb