Class: JsDuck::Js::Method

Inherits:
Object
  • Object
show all
Includes:
Util::Singleton
Defined in:
lib/jsduck/js/method.rb

Overview

Auto-detection of methods.

Instance Method Summary collapse

Methods included from Util::Singleton

included

Instance Method Details

#detect(ast) ⇒ Object

Checks if AST node is a method, and if so, returns doc-hash with method name and various auto-detected properties. When not a method returns nil.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jsduck/js/method.rb', line 16

def detect(ast)
  exp = ast.expression_statement? ? ast["expression"] : nil
  var = ast.variable_declaration? ? ast["declarations"][0] : nil

  # function foo() {}
  if ast.function?
    make(ast["id"].to_s || "", ast)

    # foo = function() {}
  elsif exp && exp.assignment_expression? && exp["right"].function?
    make(exp["left"].to_s, exp["right"])

    # var foo = function() {}
  elsif var && var["init"] && var["init"].function?
    make(var["id"].to_s, var["init"])

    # (function() {})
  elsif exp && exp.function?
    make(exp["id"].to_s || "", exp)

    # foo: function() {}
  elsif ast.property? && ast.raw["kind"] == "init" && ast["value"].function?
    make(ast["key"].key_value, ast["value"])

    # Object.defineProperty(obj, "prop", {value: function() {} })
  elsif exp && (value = exp.object_descriptor("value")) && detect(value)
    name = exp["arguments"][1].to_value
    make(name, value)

  else
    nil
  end
end

#make(name, ast) ⇒ Object

Performs the auto-detection on function AST node and produces a doc-hash.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/jsduck/js/method.rb', line 52

def make(name, ast)
  if proper_function?(ast)
    return {
      :tagname => :method,
      :name => name,
      :params => arr_to_nil(params(ast)),
      :chainable => chainable?(ast) && name != "constructor",
      :fires => arr_to_nil(fires(ast)),
      :method_calls => arr_to_nil(method_calls(ast)),
    }
  else
    return {
      :tagname => :method,
      :name => name,
    }
  end
end