Commit b262f50c authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Method parameter auto-detection.

parent d815bae8
Loading
Loading
Loading
Loading
+12 −4
Original line number Diff line number Diff line
@@ -22,13 +22,13 @@ module JsDuck
      elsif function?(ast) && class_name?(ast["id"])
        {:type => :class}
      elsif function?(ast)
        {:type => :method, :name => to_s(ast["id"])}
        make_method(ast["id"], ast)
      elsif exp && assignment?(exp) && function?(exp["right"])
        {:type => :method, :name => to_s(exp["left"])}
        make_method(exp["left"], exp["right"])
      elsif var && function?(var["init"])
        {:type => :method, :name => to_s(var["id"])}
        make_method(var["id"], var["init"])
      elsif property?(ast) && function?(ast["value"])
        {:type => :method, :name => to_s(ast["key"])}
        make_method(ast["key"], ast["value"])
      else
        {:type => :property}
      end
@@ -73,6 +73,14 @@ module JsDuck
      return to_s(ast).split(/\./).last =~ /\A[A-Z]/
    end

    def make_method(name_ast, ast=nil)
      return {
        :type => :method,
        :name => to_s(name_ast),
        :params => (ast && !empty_fn?(ast)) ? ast["params"].map {|p| to_s(p) } : []
      }
    end

    def to_s(ast)
      case ast["type"]
      when "MemberExpression"
+32 −1
Original line number Diff line number Diff line
require "jsduck/ast"
require "jsduck/esprima_parser"

describe "JsDuck::Ast detects method" do
describe "JsDuck::Ast detects method with" do
  def detect(string)
    node = JsDuck::EsprimaParser.new(string).parse[0]
    return JsDuck::Ast.new.detect(node[:code])
@@ -60,4 +60,35 @@ describe "JsDuck::Ast detects method" do
    end
  end

  describe "no params in" do
    it "function declaration without params" do
      detect("/** */ function foo() {}")[:params].length.should == 0
    end

    it "Ext.emptyFn assignment" do
      detect("/** */ foo = Ext.emptyFn")[:params].length.should == 0
    end
  end

  describe "one param in" do
    it "function declaration with one param" do
      detect("/** */ function foo(x) {}")[:params].length.should == 1
    end
  end

  describe "two params in" do
    it "function assignment with two params" do
      detect("/** */ foo = function(a,b){}")[:params].length.should == 2
    end
  end

  describe "param names" do
    it "function assignment with three params" do
      params = detect("/** */ foo = function(a, b, c){}")[:params]
      params[0].should == "a"
      params[1].should == "b"
      params[2].should == "c"
    end
  end

end