Class: Gorgyrella::Composer

Inherits:
Object
  • Object
show all
Defined in:
lib/gorgyrella/composer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(formatter = 'Coderay') ⇒ Composer

Returns a new instance of Composer.



5
6
7
8
9
10
11
# File 'lib/gorgyrella/composer.rb', line 5

def initialize(formatter = 'Coderay')
  @formatter = formatter
  
  # Caches
  @includes = {}
  @loads = {}
end

Instance Attribute Details

#formatterObject



65
66
67
# File 'lib/gorgyrella/composer.rb', line 65

def formatter
  Formatters.const_get(@formatter)
end

Instance Method Details

#format(lines, lexer = nil, format = nil) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/gorgyrella/composer.rb', line 69

def format(lines, lexer = nil, format = nil)
  text = lines.collect {|lne| lne[1]}.join("\n")
  
  if (format && lexer)
    formatter.highlight(text, lexer, format)
  else
    text
  end
end

#load(filename) ⇒ Object



13
14
15
16
17
18
# File 'lib/gorgyrella/composer.rb', line 13

def load(filename)
  with_cache(@loads, filename) do
    content = File.read(filename)
    Parser.run_machine(content)
  end
end

#process(filename) ⇒ Object

Process a template file.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/gorgyrella/composer.rb', line 25

def process(filename)
  builder = load(filename)
  results = []

  builder.sections.each do |s|
    case s[:command]
    when 'export'
      results << format(s[:lines])
    when 'include'
      results << render_include(s[:file], s[:section], s[:format], s[:language], filename)
    else
      raise "unknown command" + s[:command].to_s
    end
  end

  results.join("\n")
end

#render_include(file, section = "1", format = nil, language = nil, parent_filename = nil) ⇒ Object

Render an included section from another document. Called by process() and can also be called directly.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/gorgyrella/composer.rb', line 45

def render_include(file, section = "1", format = nil, language = nil, parent_filename = nil)
  key = [parent_filename, file, section, format || 'auto'].join("::")
  
  with_cache(@includes, key) do
    builder = load(file)
    raise unless builder
    
    # Get the lines we will actually render for this section.
    lines = builder.lines_for(section)
    
    # Fetch the first few lines of sample text for auto-detecting the lexer.
    firsts = format(builder.lines_for(builder.sections.first[:section]))

    lexer = formatter.resolve_lexer(file, language, firsts)
    format = formatter.resolve_format(format, parent_filename, lines[0][0])
    
    format(lines, lexer, format)
  end
end

#with_cache(cache, key) ⇒ Object



20
21
22
# File 'lib/gorgyrella/composer.rb', line 20

def with_cache(cache, key)
  cache[key] ||= yield
end