Class: Repubmark::Highlight

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

Constant Summary collapse

NO_SYNTAX =
'txt'
NO_LINE_NUMBERS =
%i[sh_hist].freeze
SYNTAXES =
{
  certbot: 'ini',
  css: 'css',
  hjson: nil,
  html: 'html',
  ini: 'ini',
  knockd: nil,
  nginx: 'nginx',
  openssh: nil,
  ruby: 'ruby',
  sh_hist: nil,
  sysctl: nil,
  torrc: nil,
  wireguard: 'ini',
  yggdrasil: nil, # Hjson
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(syntax, str) ⇒ Highlight

Returns a new instance of Highlight.



32
33
34
35
# File 'lib/repubmark/highlight.rb', line 32

def initialize(syntax, str)
  self.syntax = syntax
  self.str = str
end

Instance Attribute Details

#strObject

Returns the value of attribute str.



30
31
32
# File 'lib/repubmark/highlight.rb', line 30

def str
  @str
end

#syntaxObject

Returns the value of attribute syntax.



30
31
32
# File 'lib/repubmark/highlight.rb', line 30

def syntax
  @syntax
end

Class Method Details

.callObject



28
# File 'lib/repubmark/highlight.rb', line 28

def self.call(...) = new(...).call

Instance Method Details

#callObject



37
38
39
40
41
42
43
44
45
46
# File 'lib/repubmark/highlight.rb', line 37

def call
  Open3.popen2(*cmdline) do |stdin, stdout, wait_thr|
    stdin.write str
    stdin.close
    result = stdout.read.freeze
    raise 'Highlight error' unless wait_thr.value.success?

    "<pre><code>#{result}</code></pre>\n".freeze
  end
end

#cmdlineObject (private)



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/repubmark/highlight.rb', line 69

def cmdline
  @cmdline ||= [
    'highlight',
    '--stdout',
    '--fragment',
    '--out-format',
    'html',
    '--syntax',
    SYNTAXES[syntax] || NO_SYNTAX,
  ].tap do |cmdline|
    unless syntax.nil? || NO_LINE_NUMBERS.include?(syntax)
      cmdline << '--line-numbers'
    end
  end.freeze
end