当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Ruby C类用法及代码示例

本文简要介绍ruby语言中 RDoc::Parser::C类 的用法。

RDoc::Parser::C 尝试解析 C 扩展文件。它查找您在扩展中找到的标准模式:rb_define_classrb_define_method 等等。它会尝试为方法找到相应的 C 源并提取注释,但如果我们失败了,我们不必太担心。

与 Ruby 方法关联的注释是从与 implements 该方法的例程关联的 C 注释块中提取的,也就是说,该方法的名称在 rb_define_method 调用中给出。例如,你可以写:

/*
 * Returns a new array that is a one-dimensional flattening of this
 * array (recursively). That is, for every element that is an array,
 * extract its elements into the new array.
 *
 *    s = [ 1, 2, 3 ]           #=> [1, 2, 3]
 *    t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
 *    a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
 *    a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 */
 static VALUE
 rb_ary_flatten(VALUE ary)
 {
     ary = rb_obj_dup(ary);
     rb_ary_flatten_bang(ary);
     return ary;
 }

 ...

 void
 Init_Array(void)
 {
   ...
   rb_define_method(rb_cArray, "flatten", rb_ary_flatten, 0);

这里 RDoc 将从 rb_define_method 行确定类 Array 中有一个名为 “flatten” 的方法,并将在方法 rb_ary_flatten 中查找实现。然后它将在 HTML 输出中使用该方法的注释。此方法必须与 rb_define_method 位于同一源文件中。

注释块可能包含特殊指令:

Document-class:name

命名类的文档。

Document-module:name

命名模块的文档。

Document-const:name

名为 rb_define_const 的文档。

可以在注释的第一行提供常量值,如下所示:

/* 300: The highest possible score in bowling */
rb_define_const(cFoo, "PERFECT", INT2FIX(300));

该值可以包含内部冒号,只要它们用 \ 转义即可

Document-global:name

命名为 rb_define_global_const 的文档

Document-variable:name

命名为 rb_define_variable 的文档

Document-method:method_name

命名方法的文档。当方法名称明确时使用此选项。

Document-method:ClassName::method_name

给定类中单例方法的文档。当单独的方法名称不明确时使用它。

Document-method:ClassName#method_name

给定类中实例方法的文档。当单独的方法名称不明确时使用它。

Document-attr:name

命名属性的文档。

call-seq:text up to an empty line

因为 C source 没有为Ruby-level 参数提供说明性名称,所以您需要明确记录调用顺序

此外, RDoc 假定默认情况下实现 Ruby 函数的 C 方法与 rb_define_method 调用位于同一源文件中。如果不是这种情况,请添加评论:

rb_define_method(....);  // in filename

例如,我们可能有一个扩展,它在其Init_xxx 方法中定义了多个类。我们可以使用

/*
 * Document-class:  MyClass
 *
 * Encapsulate the writing and reading of the configuration
 * file. ...
 */

/*
 * Document-method: read_value
 *
 * call-seq:
 *   cfg.read_value(key)            -> value
 *   cfg.read_value(key} { |key| }  -> value
 *
 * Return the value corresponding to +key+ from the configuration.
 * In the second form, if the key isn't found, invoke the
 * block and return its value.
 */

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 C类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。