Class: Lookbook::CodeHighlighter::LookbookFormatter

Inherits:
Rouge::Formatters::HTML
  • Object
show all
Defined in:
lib/lookbook/services/code/code_highlighter.rb

Instance Method Summary collapse

Constructor Details

#initialize(**opts) ⇒ LookbookFormatter

Returns a new instance of LookbookFormatter.



27
28
29
30
31
32
# File 'lib/lookbook/services/code/code_highlighter.rb', line 27

def initialize(**opts)
  @opts = opts
  @highlight_lines = opts[:highlight_lines].to_a || []
  @start_line = opts[:start_line] || 1
  @language = opts[:language]
end

Instance Method Details

#highlighted?(i) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/lookbook/services/code/code_highlighter.rb', line 60

def highlighted?(i)
  @highlight_lines.include?(i + 1)
end

#line_number(i) ⇒ Object



64
65
66
# File 'lib/lookbook/services/code/code_highlighter.rb', line 64

def line_number(i)
  @start_line + i
end

#stream(tokens) {|"<div class='wrapper'>"| ... } ⇒ Object

Yields:

  • ("<div class='wrapper'>")


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/lookbook/services/code/code_highlighter.rb', line 34

def stream(tokens, &block)
  lines = token_lines(tokens)

  yield "<div class='wrapper'>"

  if @opts[:line_numbers]
    yield "<div class='line-numbers'>"
    lines.each.with_index do |line, i|
      yield "<div class='line #{"highlighted" if highlighted?(i)}'><span class='line-number'>#{line_number(i)}</span></div>"
    end
    yield "</div>"
  end

  yield "<pre class='code highlight' data-lang='#{@language}'><code>"
  lines.each.with_index do |line_tokens, i|
    yield "<div class='line#{" highlighted" if highlighted?(i)}'>"
    line_tokens.each do |token, value|
      yield span(token, value)
    end
    yield "</div>"
  end
  yield "</code></pre>"

  yield "</div>"
end