Skip to content
Rene Saarsoo edited this page May 28, 2013 · 5 revisions

JSDuck features some great auto-detection capabilities for its built-in members. Your custom members should not be worse - they too can have various attributes automatically detected from source code.

Built-in auto-detection

In fact, even without any additions, the @hook tag implemented in introductory chapter already has some auto detection in it.

When we try with the following code:

/**
 * @hook
 * Runs after the component is initialized.
 */
function after(self, cfg) {
}

We get the following output:

Screenshot of partly auto-detected hook

The name of the hook has been auto-detected from the function name. That's great, but the parameters are missing.

Improved auto-detection

We need to enhance the built-in auto-detection to include :params field. For this we override the process_code method:

def process_code(code)
  h = super(code)
  h[:params] = code[:params]
  h
end

This method is called with a hash of data that JSDuck itself auto-detected from code. In the case of our example the code parameter will have the value:

{
  :tagname => :method,
  :name => "after",
  :params => [{:name=>"self"}, {:name=>"cfg"}],
  :fires => nil,
  :chainable => false,
  :method_calls => nil,
}

First we pass this data to the superclass method, allowing it detect the name and a few other things. Then we augment the returned data to also include the auto-detected parameters.

The result now looks like expected:

Screenshot of fully auto-detected hook

Here's the full code for our improved @hook tag implementation:

require "jsduck/tag/member_tag"

class Hook < JsDuck::Tag::MemberTag
  def initialize
    @tagname = :hook
    @pattern = "hook"
    @member_type = {
      :title => "Hooks",
      :position => MEMBER_POS_CFG - 0.1,
      :icon => File.dirname(__FILE__) + "/hook.png",
    }
  end

  def parse_doc(scanner, position)
    return {
      :tagname => :hook,
      :name => scanner.ident,
    }
  end

  def process_doc(context, hook_tags, position)
    context[:name] = hook_tags[0][:name]
  end

  def process_code(code)
    h = super(code)
    h[:params] = code[:params]
    h
  end

  def to_html(hook, cls)
    member_link(hook) + member_params(hook[:params])
  end
end
Clone this wiki locally