Class: LoyalCore::TextUtil

Inherits:
Object
  • Object
show all
Defined in:
lib/loyal_core/utils/text_util.rb

Class Method Summary collapse

Class Method Details

.markdown(text) ⇒ Object



5
6
7
8
9
10
# File 'lib/loyal_core/utils/text_util.rb', line 5

def markdown(text)
  # options = [:hard_wrap, :filter_html, :autolink, :no_intraemphasis, :fenced_code, :gh_blockcode]

  options = [:hard_wrap, :autolink, :no_intraemphasis, :fenced_code, :gh_blockcode]
  self.syntax_highlighter(::RedcarpetCompat.new(text, *options).to_html).html_safe
end

.syntax_highlighter(html) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/loyal_core/utils/text_util.rb', line 12

def syntax_highlighter(html)
  doc = ::Nokogiri::HTML(html)

  doc.search("//pre").each do |pre|
    lang = pre.attr('lang')

    if lang.blank?
      _lang_class = pre.attr('class').to_s.split(' ').select {|_itm| _itm.include?('lang-') }.first

      if _lang_class
        lang = _lang_class.gsub('lang-', '')
      end
    end

    # debugger
    if (pre_code=pre.css('code')).any?
      lang = pre_code.attr('class').to_s
    end

    if lang.blank?
      lang = :text
    end

    text = pre.text.rstrip

    begin
      pre.replace ::CodeRay.scan(text, lang).div.to_s
    rescue Exception => error
      Rails.logger.debug "#{__FILE__} syntax_highlighter error: \ntext => #{text} \nlang => #{lang}\n origin error:#{error}"
    end
  end

  doc.css('body').try(:inner_html).to_s
end