Class: TP::Slide::Code

Inherits:
TP::Slide show all
Defined in:
lib/tp/slide/code.rb

Constant Summary collapse

LANGUAGE_MAPPINGS =
{
  [nil] => 'text',
  %w[clj] => 'clojure',
  %w[ex exs elixir] => 'ruby',
  %w[objc] => 'cpp',
  %w[rb] => 'ruby'
}

Instance Attribute Summary

Attributes inherited from TP::Slide

#markdown

Instance Method Summary collapse

Methods inherited from TP::Slide

#centered_header, #content, #frames, #hard_width?, #header, #initialize, #lines, #pdf_content_height, #pdf_content_top_left, #pdf_header_height

Constructor Details

This class inherits a constructor from TP::Slide

Instance Method Details

#character_ratio(pdf) ⇒ Object



27
28
29
# File 'lib/tp/slide/code.rb', line 27

def character_ratio(pdf)
  pdf.font_size / pdf.width_of("#")
end

#codeObject



53
54
55
# File 'lib/tp/slide/code.rb', line 53

def code
  content.lines.to_a.reject { |line| line.start_with? "```" }.join
end

#heightObject



45
46
47
# File 'lib/tp/slide/code.rb', line 45

def height
  code.lines.count + 2
end

#highlighted_codeObject



57
58
59
# File 'lib/tp/slide/code.rb', line 57

def highlighted_code
  CodeRay.encode(code, language, :terminal)
end

#languageObject



67
68
69
70
71
72
73
# File 'lib/tp/slide/code.rb', line 67

def language
  LANGUAGE_MAPPINGS.each do |keys, value|
    return value if keys.include? raw_language
  end

  raw_language
end

#maximum_line_lengthObject



31
32
33
# File 'lib/tp/slide/code.rb', line 31

def maximum_line_length
  [code.lines.to_a.map { |line| line.rstrip.length }.max, 80].min
end

#prawn_codeObject



35
36
37
# File 'lib/tp/slide/code.rb', line 35

def prawn_code
  CodeRay.scan(code.gsub(' ', Prawn::Text::NBSP), language).to_prawn
end

#raw_languageObject



61
62
63
64
65
# File 'lib/tp/slide/code.rb', line 61

def raw_language
  match = lines[2].match(/^\`{3}(\w+)/)

  match[1] if match
end

#render_pdf(pdf) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/tp/slide/code.rb', line 10

def render_pdf(pdf)
  pdf.text_box header,
    align: :center,
    overflow: :shrink_to_fit,
    single_line: true,
    height: pdf_header_height,
    size: pdf_header_height

  pdf.font 'Courier' do
    pdf.formatted_text_box prawn_code,
      at: pdf_content_top_left(pdf),
      height: pdf_content_height(pdf),
      size: (pdf.bounds.width / maximum_line_length) * character_ratio(pdf),
      valign: :center
  end
end

#render_terminalObject



39
40
41
42
43
# File 'lib/tp/slide/code.rb', line 39

def render_terminal
  centered_header +
    "\n\n" +
    highlighted_code
end

#widthObject



49
50
51
# File 'lib/tp/slide/code.rb', line 49

def width
  lines.collect { |line| line.rstrip.length }.max
end