Class: CodeSlide::Snippet

Inherits:
Object
  • Object
show all
Defined in:
lib/code_slide/snippet.rb

Constant Summary collapse

EXTMAP =

rubocop:disable Style/MutableConstant

{ # rubocop:disable Style/MutableConstant
  '.rb'   => :ruby,
  '.py'   => :python,
  '.c'    => :c,
  '.java' => :java
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(snippet, options = {}) ⇒ Snippet

Returns a new instance of Snippet.



36
37
38
39
# File 'lib/code_slide/snippet.rb', line 36

def initialize(snippet, options = {})
  @analyzer = CodeSlide::Analyzer.new(snippet, options)
  use_font(nil)
end

Class Method Details

.detect_language_type(filename) ⇒ Object



32
33
34
# File 'lib/code_slide/snippet.rb', line 32

def self.detect_language_type(filename)
  EXTMAP[File.extname(filename).downcase]
end

.from_file(filename, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/code_slide/snippet.rb', line 7

def self.from_file(filename, options = {})
  options = options.dup

  start = options.delete(:start) || 1
  finish = options.delete(:finish) || -1

  line_start = options[:line_number_start] || start

  # assume people number their file lines starting at 1
  start -= 1 if start > 0
  finish -= 1 if finish > 0

  text = File.read(filename).lines[start..finish].join
  new(text,
      options.merge(lang: options[:lang] || detect_language_type(filename),
                    line_number_start: line_start))
end

Instance Method Details

#make_pdf(filename, options = {}) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/code_slide/snippet.rb', line 50

def make_pdf(filename, options = {})
  PDFFormatter.new(@analyzer).
    use_font(@font, bold: @bold,
                    italic: @italic,
                    bold_italic: @bold_italic).
    build_pdf(options).
    render_file(filename)
end

#make_png(filename, options = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/code_slide/snippet.rb', line 59

def make_png(filename, options = {})
  options = options.dup
  dpi = options.delete(:dpi)
  keep_pdf = options.delete(:keep_pdf)

  pdf_name = File.basename(filename, File.extname(filename)) + '.pdf'

  make_pdf(pdf_name, options)
  PNGFormatter.new(pdf_name).
    generate_png(filename, dpi: dpi)
  File.delete(pdf_name) unless keep_pdf
end

#use_font(path, bold: path, italic: path, bold_italic: path) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/code_slide/snippet.rb', line 41

def use_font(path, bold: path, italic: path, bold_italic: path)
  @font = path
  @bold = bold
  @italic = italic
  @bold_italic = bold_italic

  self
end