Module: Legion::Notebook::Renderer
- Defined in:
- lib/legion/notebook/renderer.rb
Constant Summary collapse
- RESET =
"\e[0m"- BOLD =
"\e[1m"- DIM =
"\e[2m"- YELLOW =
"\e[33m"- CYAN =
"\e[36m"- GREEN =
"\e[32m"- RED =
"\e[31m"- RULE =
"\e[2m#{'─' * 60}\e[0m".freeze
Class Method Summary collapse
- .highlight(code, language, color) ⇒ Object
- .render_cell_header(index, type, color) ⇒ Object
- .render_cell_outputs(outputs, color) ⇒ Object
- .render_cell_source(cell, language, color) ⇒ Object
- .render_notebook(notebook, color: true) ⇒ Object
- .rule(color) ⇒ Object
Class Method Details
.highlight(code, language, color) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/legion/notebook/renderer.rb', line 55 def self.highlight(code, language, color) return code unless color begin require 'rouge' lexer = Rouge::Lexer.find(language.to_s) || Rouge::Lexers::PlainText.new formatter = Rouge::Formatters::Terminal256.new(Rouge::Themes::Monokai.new) formatter.format(lexer.lex(code)) rescue LoadError => e Legion::Logging.debug "Notebook::Renderer#highlight rouge not available: #{e.}" if defined?(Legion::Logging) code end end |
.render_cell_header(index, type, color) ⇒ Object
30 31 32 33 |
# File 'lib/legion/notebook/renderer.rb', line 30 def self.render_cell_header(index, type, color) label = "[#{type}] Cell #{index}" color ? "#{BOLD}#{YELLOW}#{label}#{RESET}" : label end |
.render_cell_outputs(outputs, color) ⇒ Object
45 46 47 48 49 50 51 52 53 |
# File 'lib/legion/notebook/renderer.rb', line 45 def self.render_cell_outputs(outputs, color) outputs.filter_map do |output| next if output[:text].to_s.strip.empty? prefix = color ? "#{DIM} => " : ' => ' suffix = color ? RESET : '' "#{prefix}#{output[:text].strip}#{suffix}" end end |
.render_cell_source(cell, language, color) ⇒ Object
35 36 37 38 39 40 41 42 43 |
# File 'lib/legion/notebook/renderer.rb', line 35 def self.render_cell_source(cell, language, color) return '' if cell[:source].empty? if cell[:type] == 'code' highlight(cell[:source], language, color) else color ? "#{DIM}#{cell[:source]}#{RESET}" : cell[:source] end end |
.render_notebook(notebook, color: true) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/legion/notebook/renderer.rb', line 15 def self.render_notebook(notebook, color: true) lines = [] kernel = notebook[:kernel] lines << (color ? "#{BOLD}#{CYAN}Kernel: #{kernel}#{RESET}" : "Kernel: #{kernel}") if kernel notebook[:cells].each_with_index do |cell, idx| lines << '' lines << render_cell_header(idx + 1, cell[:type], color) lines << render_cell_source(cell, notebook[:language], color) lines += render_cell_outputs(cell[:outputs], color) unless cell[:outputs].empty? end lines.join("\n") end |
.rule(color) ⇒ Object
69 70 71 |
# File 'lib/legion/notebook/renderer.rb', line 69 def self.rule(color) color ? RULE : ('-' * 60) end |