71 lines
1.4 KiB
Ruby
71 lines
1.4 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
module Repubmark
|
|
module Elems
|
|
class CodeBlock < Base
|
|
parents :Canvas
|
|
|
|
attr_reader :syntax, :str, :indent
|
|
|
|
def initialize(parent, syntax, str, indent: 0)
|
|
super parent
|
|
|
|
self.syntax = syntax
|
|
self.str = str
|
|
self.indent = indent
|
|
end
|
|
|
|
#################
|
|
# Basic methods #
|
|
#################
|
|
|
|
def to_html = highlighted_str
|
|
|
|
def to_gemtext
|
|
[
|
|
"```\n",
|
|
"#{str.strip}\n",
|
|
"```\n",
|
|
].join.freeze
|
|
end
|
|
|
|
private
|
|
|
|
def syntax=(syntax)
|
|
return @syntax = nil if syntax.nil?
|
|
|
|
unless syntax.instance_of? Symbol
|
|
raise TypeError, "Expected #{Symbol}, got #{syntax.class}"
|
|
end
|
|
|
|
@syntax = syntax
|
|
end
|
|
|
|
def str=(str)
|
|
str = String(str).freeze
|
|
raise 'Expected non-blank string' if str.strip.empty?
|
|
|
|
@str = str
|
|
end
|
|
|
|
def indent=(indent)
|
|
@indent = Integer indent
|
|
raise 'Expected non-negative number' if @indent.negative?
|
|
end
|
|
|
|
def highlighted_str
|
|
@highlighted_str ||= Highlight.call syntax, transformed_str
|
|
end
|
|
|
|
def transformed_str
|
|
@transformed_str ||=
|
|
str.lines.map { |line| "#{indentation}#{line}" }.join.freeze
|
|
end
|
|
|
|
def indentation
|
|
@indentation ||= (' ' * indent).freeze
|
|
end
|
|
end
|
|
end
|
|
end
|