Class: Gitlab::Highlight

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/highlight.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(blob_name, blob_content, nowrap: true) ⇒ Highlight

Returns a new instance of Highlight


16
17
18
19
# File 'lib/gitlab/highlight.rb', line 16

def initialize(blob_name, blob_content, nowrap: true)
  @formatter = rouge_formatter(nowrap: nowrap)
  @lexer = Rouge::Lexer.guess(filename: blob_name, source: blob_content).new rescue Rouge::Lexers::PlainText
end

Class Method Details

.highlight(blob_name, blob_content, nowrap: true, plain: false) ⇒ Object


3
4
5
6
# File 'lib/gitlab/highlight.rb', line 3

def self.highlight(blob_name, blob_content, nowrap: true, plain: false)
  new(blob_name, blob_content, nowrap: nowrap).
    highlight(blob_content, continue: false, plain: plain)
end

.highlight_lines(repository, ref, file_name) ⇒ Object


8
9
10
11
12
13
14
# File 'lib/gitlab/highlight.rb', line 8

def self.highlight_lines(repository, ref, file_name)
  blob = repository.blob_at(ref, file_name)
  return [] unless blob

  blob.load_all_data!(repository)
  highlight(file_name, blob.data).lines.map!(&:html_safe)
end

Instance Method Details

#highlight(text, continue: true, plain: false) ⇒ Object


21
22
23
24
25
26
27
28
29
# File 'lib/gitlab/highlight.rb', line 21

def highlight(text, continue: true, plain: false)
  if plain
    @formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
  else
    @formatter.format(@lexer.lex(text, continue: continue)).html_safe
  end
rescue
  @formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
end