Class: JsDuck::InlineExamples

Inherits:
Object
  • Object
show all
Defined in:
lib/jsduck/inline_examples.rb

Overview

Extracts inline examples from formatted docs and writes to file

Instance Method Summary collapse

Constructor Details

#initializeInlineExamples

Returns a new instance of InlineExamples.



8
9
10
11
12
# File 'lib/jsduck/inline_examples.rb', line 8

def initialize
  @begin_example_re = /<pre class='inline-example ([^']*)'><code>/
  @end_example_re = /<\/code><\/pre>/
  @examples = []
end

Instance Method Details

#add_classes(relations) ⇒ Object

Extracts inline examples from classes



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/jsduck/inline_examples.rb', line 15

def add_classes(relations)
  relations.each do |cls|
    extract(cls[:doc]).each_with_index do |ex, i|
      @examples << {
        :id => cls[:name] + "-" + i.to_s,
        :name => cls[:name] + " example #" + (i+1).to_s,
        :href => '#!/api/' + cls[:name],
        :code => ex[:code],
        :options => ex[:options],
      }
    end
  end

  self
end

#add_guides(guides) ⇒ Object

Extracts inline examples from guides



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/jsduck/inline_examples.rb', line 32

def add_guides(guides)
  guides.each_item do |guide|
    extract(guide[:html]).each_with_index do |ex, i|
      @examples << {
        :id => guide["name"] + "-" + i.to_s,
        :name => guide["title"] + " example #" + (i+1).to_s,
        :href => '#!/guide/' + guide["name"],
        :code => ex[:code],
        :options => ex[:options],
      }
    end
  end

  self
end

#extract(html) ⇒ Object

Extracts inline examples from HTML



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/jsduck/inline_examples.rb', line 54

def extract(html)
  examples = []

  s = StringScanner.new(html)
  while !s.eos? do
    if s.check(/</)
      if s.check(@begin_example_re)

        s.scan(@begin_example_re) =~ @begin_example_re
        options = build_options_hash($1)

        ex = s.scan_until(@end_example_re).sub(@end_example_re, '')

        examples << {
          :code => Util::HTML.unescape(Util::HTML.strip_tags(ex)),
          :options => options,
        }
      else
        s.skip(/</)
      end
    else
      s.skip(/[^<]+/)
    end
  end

  examples
end

#write(filename) ⇒ Object

Writes all found examples to .js file



49
50
51
# File 'lib/jsduck/inline_examples.rb', line 49

def write(filename)
  Util::Json.write_jsonp(filename, "__inline_examples__", @examples)
end