Class: YARD::CodeObjects::Base Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/yard/code_objects/base.rb

Overview

This class is abstract.

This class should not be used directly. Instead, create a subclass that implements #path, #sep or #type.

Base is the superclass of all code objects recognized by YARD. A code object is any entity in the Ruby language (class, method, module). A DSL might subclass Base to create a new custom object representing a new entity type.

Registry Integration

Any created object associated with a namespace is immediately registered with the registry. This allows the Registry to act as an identity map to ensure that no object is represented by more than one Ruby object in memory. A unique #path is essential for this identity map to work correctly.

Custom Attributes

Code objects allow arbitrary custom attributes to be set using the #[]= assignment method.

Namespaces

There is a special type of object called a “namespace”. These are subclasses of the NamespaceObject and represent Ruby entities that can have objects defined within them. Classically these are modules and classes, though a DSL might create a custom NamespaceObject to describe a specific set of objects.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace, name, *args) {|self| ... } ⇒ Base

Creates a new code object

Examples:

Create a method in the root namespace

CodeObjects::Base.new(:root, '#method') # => #<yardoc method #method>

Create class Z inside namespace X::Y

CodeObjects::Base.new(P("X::Y"), :Z) # or
CodeObjects::Base.new(Registry.root, "X::Y")

Parameters:

  • namespace (NamespaceObject)

    the namespace the object belongs in, Registry.root or :root should be provided if it is associated with the top level namespace.

  • name (Symbol, String)

    the name (or complex path) of the object.

Yields:

  • (self)

    a block to perform any extra initialization on the object

Yield Parameters:

  • self (Base)

    the newly initialized code object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/yard/code_objects/base.rb', line 209

def initialize(namespace, name, *args, &block)
  if namespace && namespace != :root &&
      !namespace.is_a?(NamespaceObject) && !namespace.is_a?(Proxy)
    raise ArgumentError, "Invalid namespace object: #{namespace}"
  end

  @files = []
  @current_file_has_comments = false
  @name = name.to_sym
  @source_type = :ruby
  @visibility = :public
  @tags = []
  @docstring = Docstring.new('', self)
  @docstring_extra = nil
  @docstring_extra_tags = nil
  @namespace = nil
  self.namespace = namespace
  yield(self) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#dynamic_attr_nameObject #dynamic_attr_name=(value) ⇒ Object

Overloads:

  • #dynamic_attr_nameObject

    Returns the value of attribute named by the method attribute name.

    Returns:

    • the value of attribute named by the method attribute name

    Raises:

    • (NoMethodError)

      if no method or custom attribute exists by the attribute name

    See Also:

  • #dynamic_attr_name=(value) ⇒ Object

    Returns value.

    Parameters:

    • value

      a value to set

    Returns:

    • value

    See Also:



344
345
346
347
348
349
350
351
352
# File 'lib/yard/code_objects/base.rb', line 344

def method_missing(meth, *args, &block)
  if meth.to_s =~ /=$/
    self[meth.to_s[0..-2]] = args.first
  elsif instance_variable_get("@#{meth}")
    self[meth]
  else
    super
  end
end

Instance Attribute Details

#docstringDocstring

The documentation string associated with the object

Returns:



141
142
143
# File 'lib/yard/code_objects/base.rb', line 141

def docstring
  @docstring
end

#dynamicBoolean

Marks whether or not the method is conditionally defined at runtime

Returns:

  • (Boolean)

    true if the method is conditionally defined at runtime



145
146
147
# File 'lib/yard/code_objects/base.rb', line 145

def dynamic
  @dynamic
end

#filesArray<String> (readonly)

The files the object was defined in. To add a file, use #add_file.

Returns:

See Also:



115
116
117
# File 'lib/yard/code_objects/base.rb', line 115

def files
  @files
end

#groupString

Returns the group this object is associated with.

Returns:

  • (String)

    the group this object is associated with

Since:

  • 0.6.0



149
150
151
# File 'lib/yard/code_objects/base.rb', line 149

def group
  @group
end

#namespaceNamespaceObject Also known as: parent

The namespace the object is defined in. If the object is in the top level namespace, this is Registry.root

Returns:



120
121
122
# File 'lib/yard/code_objects/base.rb', line 120

def namespace
  @namespace
end

#signatureString

The one line signature representing an object. For a method, this will be of the form “def meth(arguments…)”. This is usually the first source line.

Returns:

  • (String)

    a line of source



137
138
139
# File 'lib/yard/code_objects/base.rb', line 137

def signature
  @signature
end

#sourceString?

The source code associated with the object

Returns:

  • (String, nil)

    source, if present, or nil



124
125
126
# File 'lib/yard/code_objects/base.rb', line 124

def source
  @source
end

#source_typeSymbol

Language of the source code associated with the object. Defaults to :ruby.

Returns:

  • (Symbol)

    the language type



130
131
132
# File 'lib/yard/code_objects/base.rb', line 130

def source_type
  @source_type
end

#visibilitySymbol

Returns the visibility of an object (:public, :private, :protected).

Returns:

  • (Symbol)

    the visibility of an object (:public, :private, :protected)



156
157
158
# File 'lib/yard/code_objects/base.rb', line 156

def visibility
  @visibility
end

Class Method Details

.===(other) ⇒ Boolean

Compares the class with subclasses

Parameters:

  • other (Object)

    the other object to compare classes with

Returns:

  • (Boolean)

    true if other is a subclass of self



190
191
192
# File 'lib/yard/code_objects/base.rb', line 190

def ===(other)
  other.is_a?(self)
end

.new(namespace, name, *args) {|obj| ... } ⇒ Base

Allocates a new code object

Yields:

  • (obj)

Returns:

Raises:

  • (ArgumentError)

See Also:



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/yard/code_objects/base.rb', line 164

def new(namespace, name, *args, &block)
  raise ArgumentError, "invalid empty object name" if name.to_s.empty?
  if namespace.is_a?(ConstantObject)
    namespace = Proxy.new(namespace.namespace, namespace.value)
  end

  if name.to_s[0,2] == NSEP
    name = name.to_s[2..-1]
    namespace = Registry.root
  end

  if name =~ /(?:#{NSEPQ})([^:]+)$/
    return new(Proxy.new(namespace, $`), $1, *args, &block)
  end

  obj = super(namespace, name, *args)
  existing_obj = Registry.at(obj.path)
  obj = existing_obj if existing_obj && existing_obj.class == self
  yield(obj) if block_given?
  obj
end

Instance Method Details

#[](key) ⇒ Object?

Accesses a custom attribute on the object

Parameters:

  • key (#to_s)

    the name of the custom attribute

Returns:

  • (Object, nil)

    the custom attribute or nil if not found.

See Also:



314
315
316
317
318
319
320
# File 'lib/yard/code_objects/base.rb', line 314

def [](key)
  if respond_to?(key)
    send(key)
  elsif instance_variable_defined?("@#{key}")
    instance_variable_get("@#{key}")
  end
end

#[]=(key, value) ⇒ void

This method returns an undefined value.

Sets a custom attribute on the object

Parameters:

  • key (#to_s)

    the name of the custom attribute

  • value (Object)

    the value to associate

See Also:



327
328
329
330
331
332
333
# File 'lib/yard/code_objects/base.rb', line 327

def []=(key, value)
  if respond_to?("#{key}=")
    send("#{key}=", value)
  else
    instance_variable_set("@#{key}", value)
  end
end

#add_file(file, line = nil, has_comments = false) ⇒ Object

Associates a file with a code object, optionally adding the line where it was defined. By convention, ‘<stdin>’ should be used to associate code that comes form standard input.

Parameters:

  • file (String)

    the filename (‘<stdin>’ for standard input)

  • line (Fixnum, nil) (defaults to: nil)

    the line number where the object lies in the file

  • has_comments (Boolean) (defaults to: false)

    whether or not the definition has comments associated. This will allow #file to return the definition where the comments were made instead of any empty definitions that might have been parsed before (module namespaces for instance).

Raises:

  • (ArgumentError)


262
263
264
265
266
267
268
269
270
271
272
# File 'lib/yard/code_objects/base.rb', line 262

def add_file(file, line = nil, has_comments = false)
  raise(ArgumentError, "file cannot be nil or empty") if file.nil? || file == ''
  obj = [file.to_s, line]
  return if files.include?(obj)
  if has_comments && !@current_file_has_comments
    @current_file_has_comments = true
    @files.unshift(obj)
  else
    @files << obj # back of the line
  end
end

#copy_to(other) ⇒ Base

Copies all data in this object to another code object, except for uniquely identifying information (path, namespace, name, scope).

Parameters:

  • other (Base)

    the object to copy data to

Returns:

  • (Base)

    the other object

Since:

  • 0.8.0



235
236
237
238
239
240
241
242
# File 'lib/yard/code_objects/base.rb', line 235

def copy_to(other)
  copyable_attributes.each do |ivar|
    ivar = "@#{ivar}"
    other.instance_variable_set(ivar, instance_variable_get(ivar))
  end
  other.docstring = docstring.to_raw
  other
end

#copyable_attributesArray<String> (protected)

Override this method if your code object subclass does not allow copying of certain attributes.

Returns:

  • (Array<String>)

    the list of instance variable names (without “@” prefix) that should be copied when #copy_to is called

See Also:

Since:

  • 0.8.0



533
534
535
536
537
# File 'lib/yard/code_objects/base.rb', line 533

def copyable_attributes
  vars = instance_variables.map {|ivar| ivar.to_s[1..-1] }
  vars -= %w(docstring namespace name path)
  vars
end

#dynamic?Boolean

Is the object defined conditionally at runtime?

Returns:

  • (Boolean)

See Also:



153
# File 'lib/yard/code_objects/base.rb', line 153

def dynamic?; @dynamic end

#equal?(other) ⇒ Boolean Also known as: ==, eql?

Tests if another object is equal to this, including a proxy

Parameters:

  • other (Base, Proxy)

    if other is a Proxy, tests if the paths are equal

Returns:

  • (Boolean)

    whether or not the objects are considered the same



294
295
296
297
298
299
300
# File 'lib/yard/code_objects/base.rb', line 294

def equal?(other)
  if other.is_a?(Base) || other.is_a?(Proxy)
    path == other.path
  else
    super
  end
end

#fileString

Returns the filename the object was first parsed at, taking definitions with docstrings first.

Returns:



278
279
280
# File 'lib/yard/code_objects/base.rb', line 278

def file
  @files.first ? @files.first[0] : nil
end

#format(options = {}) ⇒ String

Renders the object using the templating system.

Examples:

Formats a class in plaintext

puts P('MyClass').format

Formats a method in html with rdoc markup

puts P('MyClass#meth').format(:format => :html, :markup => :rdoc)

Parameters:

  • options (Hash) (defaults to: {})

    a set of options to pass to the template

Options Hash (options):

  • :format (Symbol) — default: :text

    :html, :text or another output format

  • :template (Symbol) — default: :default

    a specific template to use

  • :markup (Symbol) — default: nil

    the markup type (:rdoc, :markdown, :textile)

  • :serializer (Serializers::Base) — default: nil

    see Serializers

Returns:

  • (String)

    the rendered template

See Also:

  • Templates::Engine#render


465
466
467
468
# File 'lib/yard/code_objects/base.rb', line 465

def format(options = {})
  options = options.merge(:object => self)
  Templates::Engine.render(options)
end

#has_tag?(name) ⇒ Boolean

Tests if the #docstring has a tag

Returns:

  • (Boolean)

See Also:



510
# File 'lib/yard/code_objects/base.rb', line 510

def has_tag?(name); docstring.has_tag?(name) end

#hashInteger

Returns the object’s hash value (for equality checking).

Returns:

  • (Integer)

    the object’s hash value (for equality checking)



305
# File 'lib/yard/code_objects/base.rb', line 305

def hash; path.hash end

#inspectString

Inspects the object, returning the type and path

Returns:

  • (String)

    a string describing the object



472
473
474
# File 'lib/yard/code_objects/base.rb', line 472

def inspect
  "#<yardoc #{type} #{path}>"
end

#lineFixnum?

Returns the line the object was first parsed at (or nil)

Returns:

  • (Fixnum)

    the line where the object was first defined.

  • (nil)

    if there is no line associated with the object



286
287
288
# File 'lib/yard/code_objects/base.rb', line 286

def line
  @files.first ? @files.first[1] : nil
end

#name(prefix = false) ⇒ Symbol, String

The name of the object

Parameters:

  • prefix (Boolean) (defaults to: false)

    whether to show a prefix. Implement this in a subclass to define how the prefix is showed.

Returns:

  • (Symbol)

    if prefix is false, the symbolized name

  • (String)

    if prefix is true, prefix + the name as a String. This must be implemented by the subclass.



250
251
252
# File 'lib/yard/code_objects/base.rb', line 250

def name(prefix = false)
  prefix ? @name.to_s : @name
end

#pathString Also known as: to_s

Represents the unique path of the object. The default implementation joins the path of #namespace with #name via the value of #sep. Custom code objects should ensure that the path is unique to the code object by either overriding #sep or this method.

Examples:

The path of an instance method

MethodObject.new(P("A::B"), :c).path # => "A::B#c"

Returns:

  • (String)

    the unique path of the object

See Also:



420
421
422
423
424
425
426
# File 'lib/yard/code_objects/base.rb', line 420

def path
  @path ||= if parent && !parent.root?
    [parent.path, name.to_s].join(sep)
  else
    name.to_s
  end
end

#relative_path(other) ⇒ String

Returns the shortest relative path from this object to other.

Parameters:

  • other (Base, String)

    another code object (or object path)

Returns:

  • (String)

    the shortest relative path from this object to other

Since:

  • 0.5.3



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/yard/code_objects/base.rb', line 432

def relative_path(other)
  other = Registry.at(other) if String === other && Registry.at(other)
  same_parent = false
  if other.respond_to?(:path)
    same_parent = other.parent == parent
    other = other.path
  end
  return other unless namespace
  common = [path, other].join(" ").match(/^(\S*)\S*(?: \1\S*)*$/)[1]
  common = path unless common =~ /(\.|::|#)$/
  common = common.sub(/(\.|::|#)[^:#\.]*?$/, '') if same_parent
  if %w(. :).include?(common[-1,1]) || other[common.size,1] == '#'
    suffix = ''
  else
    suffix = '(::|\.)'
  end
  result = other.sub(/^#{Regexp.quote common}#{suffix}/, '')
  result.empty? ? other : result
end

#root?Boolean

Returns whether or not this object is a RootObject.

Returns:

  • (Boolean)

    whether or not this object is a RootObject



513
# File 'lib/yard/code_objects/base.rb', line 513

def root?; false end

#sepString

Override this method with a custom component separator. For instance, MethodObject implements sep as ‘#’ or ‘.’ (depending on if the method is instance or class respectively). #path depends on this value to generate the full path in the form: namespace.path + sep + name

Returns:

  • (String)

    the component that separates the namespace path and the name (default is NSEP)



522
# File 'lib/yard/code_objects/base.rb', line 522

def sep; NSEP end

#tag(name) ⇒ Object

Gets a tag from the #docstring

See Also:



502
# File 'lib/yard/code_objects/base.rb', line 502

def tag(name); docstring.tag(name) end

#tags(name = nil) ⇒ Object

Gets a list of tags from the #docstring

See Also:



506
# File 'lib/yard/code_objects/base.rb', line 506

def tags(name = nil); docstring.tags(name) end

#to_arynil

Returns this object does not turn into an array.

Returns:

  • (nil)

    this object does not turn into an array



308
# File 'lib/yard/code_objects/base.rb', line 308

def to_ary; nil end

#typeSymbol

Default type is the lowercase class name without the “Object” suffix. Override this method to provide a custom object type

Returns:

  • (Symbol)

    the type of code object this represents



407
408
409
# File 'lib/yard/code_objects/base.rb', line 407

def type
  self.class.name.split(/#{NSEPQ}/).last.gsub(/Object$/, '').downcase.to_sym
end