Class: Lookbook::CodeHighlighter

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

Defined Under Namespace

Classes: LookbookFormatter

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Service

call

Constructor Details

#initialize(source, opts = {}) ⇒ CodeHighlighter

Returns a new instance of CodeHighlighter.



8
9
10
11
# File 'lib/lookbook/services/code/code_highlighter.rb', line 8

def initialize(source, opts = {})
  @source = source.to_s
  @opts = opts
end

Instance Attribute Details

#sourceObject (readonly)



6
7
8
# File 'lib/lookbook/services/code/code_highlighter.rb', line 6

def source
  @source
end

Instance Method Details

#callObject



17
18
19
20
21
22
23
24
# File 'lib/lookbook/services/code/code_highlighter.rb', line 17

def call
  coder = HTMLEntities.new
  decoded_source = coder.decode(source)
  language = opts.fetch(:language, "ruby")
  formatter = LookbookFormatter.new(language: language, **opts)
  lexer = Rouge::Lexer.find(language.to_s) || Rouge::Lexer.find("plaintext")
  formatter.format(lexer.lex(decoded_source)).html_safe
end

#optsObject



13
14
15
# File 'lib/lookbook/services/code/code_highlighter.rb', line 13

def opts
  (@opts.is_a?(String) || @opts.is_a?(Symbol)) ? {language: @opts} : @opts.to_h
end