當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。