Class: AttributeHandler

Inherits:
YARD::Handlers::Ruby::AttributeHandler
  • Object
show all
Defined in:
lib/yard/attribute_handler.rb

Instance Method Summary collapse

Instance Method Details

#node_exists?(ast_node, jumps) ⇒ <Type>

Checks whether a node exists at the given jumps

Parameters:

  • ast_node (<AstNode>)

    A YARD::Parser::Ruby::AstNode

  • jumps ([<Symbol>])

    array of AST node types that should match

Returns:

  • (<Type>)


62
63
64
65
# File 'lib/yard/attribute_handler.rb', line 62

def node_exists?(ast_node, jumps)
  jumped = walk(ast_node, jumps)
  !!jumped
end

#processObject



5
6
7
8
9
10
11
12
13
14
15
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
49
50
51
52
# File 'lib/yard/attribute_handler.rb', line 5

def process
  params = statement.parameters(false).dup
  options = params.pop if params.last.type == :list

  validated_attribute_names(params).each do |name|
    namespace.attributes[scope][name] ||= SymbolHash[:read => nil, :write => nil]

    object = MethodObject.new(namespace, name, scope)
    object.file = statement.file
    object.source = statement.source
    register(object)

    if options.first.jump(:label).source == "type:"
      return_type = options.first.jump(:const).source
    end

    return_type = "String"
    desc = ""

    options.each do |option|
      if option.jump(:label).source == "desc:"
        desc = option.jump(:string_content).source
      end

      if option.jump(:label).source == "type:"
        if node_exists?(option, [:var_ref, :const])
          return_type = option.source.sub(/^type: /, "")
        elsif node_exists?(option, [:assoc, :symbol_literal])
          return_type = walk(option, [:assoc, :symbol_literal, :ident]).source.capitalize
        end

        if node_exists?(option, [:arg_paren])
          return_type = "[#{return_type.sub(/\AArray\(/,"").sub(/\)\z/, "")}]"
        end
      end
    end

    object.docstring = desc.gsub(/\n/, " ") if desc

    # tags must be added after the docstring
    object.add_tag(
      YARD::Tags::Tag.new(:return, nil, return_type)
    )

    # Register the object explicitly
    namespace.attributes[scope][name][:read] = object
  end
end

#walk(ast_node, jumps) ⇒ <AstNode, nil>

Recusively jumps the AstNode node to find a node that matches all provided jumps. Returns nil if node is not found.

In constast jump will return any node that matches any of the provided jumps and return the original node if there are no matches.

Parameters:

  • ast_node (<AstNode>)

    A YARD::Parser::Ruby::AstNode

  • jumps ([<Symbol>])

    through array of AST node types to walk

Returns:

  • (<AstNode, nil>)

    the requested node or nil



81
82
83
84
85
86
# File 'lib/yard/attribute_handler.rb', line 81

def walk(ast_node, jumps)
  jumps = Array(jumps)
  node = jumps.inject(ast_node) { |o, j| o.jump(j) }

  return node if node != ast_node
end