Commit 72bb0b13 authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Created DocLinks class for replacing {@link} tags.

parent f508eef6
Loading
Loading
Loading
Loading
+47 −0
Original line number Diff line number Diff line
module JsDuck

  # Detects {@link ...} tags in text and replaces them with HTML links
  # pointing to documentation.  In addition to the href attribute
  # links will also contain ext:cls and ext:member attributes.
  class DocLinks
    # Initializes instance to work in context of particular class, so
    # that when {@link #blah} is encountered it knows that
    # Context#blah is meant.
    def initialize(context)
      @context = context
    end

    # Replaces {@link Class#member link text} in given string with
    # HTML links.
    def replace(input)
      input.gsub(/\{@link +(\S*?)(?: +(.+?))?\}/) do
        target = $1
        text = $2
        if target =~ /^(.*)#(.*)$/
          cls = $1.empty? ? @context : $1
          member = $2
        else
          cls = target
          member = false
        end

        # Construct link attributes
        href = " href=\"output/#{cls}.html" + (member ? "#" + cls + "-" + member : "") + '"'
        ext_cls = ' ext:cls="' + cls + '"'
        ext_member = member ? ' ext:member="' + member + '"' : ""

        # Construct link text
        if text
          text = text
        elsif member
          text = (cls == @context) ? member : (cls + "." + member)
        else
          text = cls
        end

        "<a" + href + ext_cls + ext_member + ">" + text + "</a>"
      end
    end
  end

end

spec/doc_links_spec.rb

0 → 100644
+38 −0
Original line number Diff line number Diff line
require "jsduck/doc_links"

describe JsDuck::DocLinks, "#parse" do

  before do
    @links = JsDuck::DocLinks.new("Context")
  end

  it "replaces {@link Ext.Msg} with link to class" do
    @links.replace("Look at {@link Ext.Msg}").should ==
      'Look at <a href="output/Ext.Msg.html" ext:cls="Ext.Msg">Ext.Msg</a>'
  end

  it "replaces {@link Foo#bar} with link to class member" do
    @links.replace("Look at {@link Foo#bar}").should ==
      'Look at <a href="output/Foo.html#Foo-bar" ext:cls="Foo" ext:member="bar">Foo.bar</a>'
  end

  it "uses context to replace {@link #bar} with link to class member" do
    @links.replace("Look at {@link #bar}").should ==
      'Look at <a href="output/Context.html#Context-bar" ext:cls="Context" ext:member="bar">bar</a>'
  end

  it "allows use of custom link text" do
    @links.replace("Look at {@link Foo link text}").should ==
      'Look at <a href="output/Foo.html" ext:cls="Foo">link text</a>'
  end

  it "leaves text without {@link...} untouched" do
    @links.replace("Look at {@me here} too").should ==
      'Look at {@me here} too'
  end

  it "ignores unfinished {@link tag" do
    @links.replace("unfinished {@link tag here").should ==
      'unfinished {@link tag here'
  end
end