Class: Mumukit::Directives::Sections

Inherits:
Directive
  • Object
show all
Defined in:
lib/mumukit/directives/sections.rb

Overview

‘Sections` directive allows code to be splitted into zero or more parts, using markup-like delimiter.

The transformed result is a hash that replaces the key’s content with the included sections. For example, if the ‘extra` key has two sections `foo` and `bar`…

“‘ # Input { extra: ’foo /*<baz#/lalala/#baz>*/ ignored /*<bar#/lelele/#bar>*/‘ } “`

… the resultant hash will contain the ‘foo` and `bar` keys, and no `extra` key:

“‘ # Output { baz: ’lalala’, bar: ‘lelele’ } “‘

Alternatively, if the ‘nest_sections` option is enabled…

“‘ Mumukit::Directives::Sections.new nest_sections: true “`

…instead of replacing the original parent section, the new child sections are nested into it:

“‘ # Output { extra: { baz: ’lalala’, bar: ‘lelele’ } } “‘

Instance Attribute Summary

Attributes inherited from Directive

#comment_type

Instance Method Summary collapse

Methods inherited from Directive

#comment_regexp

Constructor Details

#initialize(options = {}) ⇒ Sections

Returns a new instance of Sections.



35
36
37
# File 'lib/mumukit/directives/sections.rb', line 35

def initialize(options={})
  @nest_sections = !!options[:nest_sections]
end

Instance Method Details

#build(section, content) ⇒ Object



66
67
68
# File 'lib/mumukit/directives/sections.rb', line 66

def build(section, content)
  "#{comment_type.comment "<#{section}#"}#{content}#{comment_type.comment "##{section}>"}"
end

#interpolate(section) ⇒ Object



70
71
72
# File 'lib/mumukit/directives/sections.rb', line 70

def interpolate(section)
  comment_type.comment("...#{section}...")
end

#join(sections) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/mumukit/directives/sections.rb', line 58

def join(sections)
  file_declarations, _file_references = sections.map do |section, content|
    [build(section, content), interpolate(section)]
  end.transpose

  file_declarations.join "\n"
end

#regexpObject



39
40
41
# File 'lib/mumukit/directives/sections.rb', line 39

def regexp
  /<(.+?)##{comment_type.close_comment}(.*?)#{comment_type.open_comment}#(.+?)>/m
end

#split_sections(code) ⇒ Object



43
44
45
46
47
48
# File 'lib/mumukit/directives/sections.rb', line 43

def split_sections(code)
  sections = code.captures(comment_regexp).map do
    [$1, $2]
  end
  Hash[sections]
end

#transform(sections) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/mumukit/directives/sections.rb', line 50

def transform(sections)
  result = {}
  sections.each do |key, code|
    merge_sections! result, key, code, split_sections(code)
  end
  result
end