README

What's Ruby

Ruby is the interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks (as in Perl). It is simple, straight-forward, and extensible.

Features of Ruby

  • Simple Syntax
  • *Normal* Object-Oriented features(ex. class, method calls)
  • *Advanced* Object-Oriented features(ex. Mix-in, Singleton-method)
  • Operator Overloading
  • Exception Handling
  • Iterators and Closures
  • Garbage Collection
  • Dynamic Loading of Object files(on some architecture)
  • Highly Portable (works on many UNIX machines, and on DOS, Windows, Mac, BeOS etc.)

How to get Ruby

The Ruby distribution files can be found in the following FTP site:

ftp://ftp.ruby-lang.org/pub/ruby/
The latest source code of this version series can be checked out through SVN with the following command:
$ svn co http://svn.ruby-lang.org/repos/ruby/branches/ruby_1_8_6/
The trunk of the Ruby source tree can be checked out with the following command:
$ svn co http://svn.ruby-lang.org/repos/ruby/trunk/ ruby
There are some other branches under development. Try the following command and see the list of branches:
$ svn ls http://svn.ruby-lang.org/repos/ruby/branches/

Ruby home-page

The URL of the Ruby home-page is:

http://www.ruby-lang.org/

Mailing list

There is a mailing list to talk about Ruby. To subscribe this list, please send the following phrase

subscribe YourFirstName YourFamilyName
e.g.
subscribe Joseph Smith
in the mail body (not subject) to the address .

How to compile and install

This is what you need to do to compile and install Ruby:

  1. If ./configure does not exist or is older than configure.in,
     run autoconf to (re)generate configure.

  2. Run ./configure, which will generate config.h and Makefile.

  3. Edit defines.h if you need.  Usually this step will not be needed.

  4. Remove comment mark(#) before the module names from ext/Setup (or
     add module names if not present), if you want to link modules
     statically.

     If you don't want to compile non static extension modules
     (probably on architectures which does not allow dynamic loading),
     remove comment mark from the line "#option nodynamic" in
     ext/Setup.

  5. Run make.

  6. Optionally, run 'make test' to check whether the compiled Ruby
     interpreter works well.  If you see the message "test succeeded",
     your ruby works as it should (hopefully).

  7. Run 'make install'

     You may have to be a super user to install ruby.
If you fail to compile ruby, please send the detailed error report with the error log and machine/OS type, to help others.

Copying

See the file COPYING.

The Author

Feel free to send comments and bug reports to the author. Here is the author's latest mail address:

matz@netlab.jp


License

Please review the ReadMe and License below.

* You must install as administrator on Windows NT,
  2000, and XP in order for path and environment
  variable settings to take effect.

This distribution contains:

   The Ruby Interpreter, libraries, and extensions,
   all compiled with native Microsoft VC++ 6.0.
   See ReleaseNotes.txt for a list of extensions.

Ruby program files use the suffix ".rb"

If you don't want a console window to be created,
use the suffix ".rbw" instead.

Program files may be created using any plain text editor
such as emacs, notepad, or Notepad++.

Right-clicking on a Ruby file gives you the option of
editing or running the file.

This distribution packaged by:

           The RubyInstaller Team
           http://RubyInstaller.RubyForge.org/

No warranty expressed or implied, see below
for the full statement.

Sample Ruby code is in the "samples" directory and its
sub-directories.

The Ruby home page is
  www.ruby-lang.org

The Ruby FAQ may be found at
  www.rubycentral.com/faq

A very fine reference book on the Ruby language is
"Programming Ruby: The Pragmatic Programmer's Guide, Second Edition"
by Dave Thomas, with Chad Fowler and Andy Hunt
Pragmatic Bookshelf Oct 2004 ISBN: 0-9745140-5-5

Please report bugs in the installer (only) to
  http://rubyforge.org/tracker/?group_id=167

===================================================
Ruby License

The authoritative copy of the Ruby License can be found
at:  http://www.ruby-lang.org/en/LICENSE.txt

Below is a copy of that license made on 2004-07-30.
===================================================

Ruby is copyrighted free software by Yukihiro Matsumoto .
You can redistribute it and/or modify it under either the terms of the GPL
(see COPYING.txt file), or the conditions below:

  1. You may make and give away verbatim copies of the source form of the
     software without restriction, provided that you duplicate all of the
     original copyright notices and associated disclaimers.

  2. You may modify your copy of the software in any way, provided that
     you do at least ONE of the following:

       a) place your modifications in the Public Domain or otherwise
          make them Freely Available, such as by posting said
      modifications to Usenet or an equivalent medium, or by allowing
      the author to include your modifications in the software.

       b) use the modified software only within your corporation or
          organization.

       c) rename any non-standard executables so the names do not conflict
      with standard executables, which must also be provided.

       d) make other distribution arrangements with the author.

  3. You may distribute the software in object code or executable
     form, provided that you do at least ONE of the following:

       a) distribute the executables and library files of the software,
      together with instructions (in the manual page or equivalent)
      on where to get the original distribution.

       b) accompany the distribution with the machine-readable source of
      the software.

       c) give non-standard executables non-standard names, with
          instructions on where to get the original software distribution.

       d) make other distribution arrangements with the author.

  4. You may modify and include the part of the software into any other
     software (possibly commercial).  But some files in the distribution
     are not written by the author, so that they are not under this terms.

     They are gc.c(partly), utils.c(partly), regex.[ch], st.[ch] and some
     files under the ./missing directory.  See each file for the copying
     condition.

  5. The scripts and library files supplied as input to or produced as
     output from the software do not automatically fall under the
     copyright of the software, but belong to whomever generated them,
     and may be sold commercially, and may be aggregated with this
     software.

  6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
     IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
     WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     PURPOSE.


Class: Array

Class | Array
In: | array.c lib/abbrev.rb lib/mkmf.rb lib/pp.rb lib/rexml/xpath_parser.rb lib/yaml/rubytypes.rb
Parent: | Object

Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Methods

& * + - << <=> == [] [] []= abbrev assoc at clear collect collect! compact compact! concat dclone delete delete_at delete_if each each_index empty? eql? fetch fill first flatten flatten! frozen? hash include? index indexes indices initialize_copy insert inspect join last length map map! new nitems pack pop pretty_print pretty_print_cycle push quote rassoc reject reject! replace reverse reverse! reverse_each rindex select shift size slice slice! sort sort! to_a to_ary to_s to_yaml transpose uniq uniq! unshift values_at yaml_initialize zip |

Included Modules

Enumerable

Public Class methods

[](...)

Returns a new array populated with the given objects.

  Array.[]( 1, 'a', /^A/ )
  Array[ 1, 'a', /^A/ ]
  [ 1, 'a', /^A/ ]
Array.new(size=0, obj=nil)
Array.new(array)
Array.new(size) {|index| block }

Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element‘s index to the given block and storing the return value.

   Array.new
   Array.new(2)
   Array.new(5, "A")

   # only one copy of the object is created
   a = Array.new(2, Hash.new)
   a[0]['cat'] = 'feline'
   a
   a[1]['cat'] = 'Felix'
   a

   # here multiple copies are created
   a = Array.new(2) { Hash.new }
   a[0]['cat'] = 'feline'
   a

   squares = Array.new(5) {|i| i*i}
   squares

   copy = Array.new(squares)

Public Instance methods

array & other_array

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

   [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
array * int → an_array
array * str → a_string

Repetition—With a String argument, equivalent to self.join(str). Otherwise, returns a new array built by concatenating the int copies of self.

   [ 1, 2, 3 ] * 3    #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
   [ 1, 2, 3 ] * ","  #=> "1,2,3"
array + other_array → an_array

Concatenation—Returns a new array built by concatenating the two arrays together to produce a third array.

   [ 1, 2, 3 ] + [ 4, 5 ]    #=> [ 1, 2, 3, 4, 5 ]
array - other_array → an_array

Array Difference—Returns a new array that is a copy of the original array, removing any items that also appear in other_array. (If you need set-like behavior, see the library class Set.)

   [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]
array << obj → array

Append—Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together.

   [ 1, 2 ] << "c" << "d" << [ 3, 4 ]
           #=>  [ 1, 2, "c", "d", [ 3, 4 ] ]
array <=> other_array → -1, 0, +1

Comparison—Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array. Each object in each array is compared (using <=>). If any value isn‘t equal, then that inequality is the return value. If all the values found are equal, then the return is based on a comparison of the array lengths. Thus, two arrays are ``equal’’ according to Array#<=> if and only if they have the same length and the value of each element is equal to the value of the corresponding element in the other array.

   [ "a", "a", "c" ]    <=> [ "a", "b", "c" ]   #=> -1
   [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]            #=> +1
array == other_array → bool

Equality—Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object.==) the corresponding element in the other array.

   [ "a", "c" ]    == [ "a", "c", 7 ]     #=> false
   [ "a", "c", 7 ] == [ "a", "c", 7 ]     #=> true
   [ "a", "c", 7 ] == [ "a", "d", "f" ]   #=> false
array[index] → obj or nil
array[start, length] → an_array or nil
array[range] → an_array or nil
array.slice(index) → obj or nil
array.slice(start, length) → an_array or nil
array.slice(range) → an_array or nil

Element Reference—Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) are out of range.

   a = [ "a", "b", "c", "d", "e" ]
   a[2] +  a[0] + a[1]    #=> "cab"
   a[6]                   #=> nil
   a[1, 2]                #=> [ "b", "c" ]
   a[1..3]                #=> [ "b", "c", "d" ]
   a[4..7]                #=> [ "e" ]
   a[6..10]               #=> nil
   a[-3, 3]               #=> [ "c", "d", "e" ]
   # special cases
   a[5]                   #=> nil
   a[5, 1]                #=> []
   a[5..10]               #=> []
array[index] = obj → obj
array[start, length] = obj or an_array or nil → obj or an_array or nil
array[range] = obj or an_array or nil → obj or an_array or nil

Element Assignment—Sets the element at index, or replaces a subarray starting at start and continuing for length elements, or replaces a subarray specified by range. If indices are greater than the current capacity of the array, the array grows automatically. A negative indices will count backward from the end of the array. Inserts elements if length is zero. If nil is used in the second and third form, deletes elements from self. An IndexError is raised if a negative index points past the beginning of the array. See also Array#push, and Array#unshift.

   a = Array.new
   a[4] = "4";                 #=> [nil, nil, nil, nil, "4"]
   a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"]
   a[1..2] = [ 1, 2 ]          #=> ["a", 1, 2, nil, "4"]
   a[0, 2] = "?"               #=> ["?", 2, nil, "4"]
   a[0..2] = "A"               #=> ["A", "4"]
   a[-1]   = "Z"               #=> ["A", "Z"]
   a[1..-1] = nil              #=> ["A"]
abbrev(pattern = nil)

Calculates the set of unambiguous abbreviations for the strings in self. If passed a pattern or a string, only the strings matching the pattern or starting with the string are considered.

  %w{ car cone }.abbrev   #=> { "ca" => "car", "car" => "car",
                                "co" => "cone", "con" => cone",
                                "cone" => "cone" }
array.assoc(obj) → an_array or nil

Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches (that is, the first associated array), or nil if no match is found. See also Array#rassoc.

   s1 = [ "colors", "red", "blue", "green" ]
   s2 = [ "letters", "a", "b", "c" ]
   s3 = "foo"
   a  = [ s1, s2, s3 ]
   a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
   a.assoc("foo")      #=> nil
array.at(index) → obj or nil

Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range. See also Array#[]. (Array#at is slightly faster than Array#[], as it does not accept ranges and so on.)

   a = [ "a", "b", "c", "d", "e" ]
   a.at(0)     #=> "a"
   a.at(-1)    #=> "e"
array.clear → array

Removes all elements from self.

   a = [ "a", "b", "c", "d", "e" ]
   a.clear    #=> [ ]
array.collect {|item| block } → an_array
array.map {|item| block } → an_array

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.

   a = [ "a", "b", "c", "d" ]
   a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
   a                          #=> ["a", "b", "c", "d"]
array.collect! {|item| block } → array
array.map! {|item| block } → array

Invokes the block once for each element of self, replacing the element with the value returned by block. See also Enumerable#collect.

   a = [ "a", "b", "c", "d" ]
   a.collect! {|x| x + "!" }
   a             #=>  [ "a!", "b!", "c!", "d!" ]
array.compact → an_array

Returns a copy of self with all nil elements removed.

   [ "a", nil, "b", nil, "c", nil ].compact
                     #=> [ "a", "b", "c" ]
array.compact! → array or nil

Removes nil elements from array. Returns nil if no changes were made.

   [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
   [ "a", "b", "c" ].compact!           #=> nil
array.concat(other_array) → array

Appends the elements in other_array to self.

   [ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]
dclone()
array.delete(obj) → obj or nil
array.delete(obj) { block } → obj or nil

Deletes items from self that are equal to obj. If the item is not found, returns nil. If the optional code block is given, returns the result of block if the item is not found.

   a = [ "a", "b", "b", "b", "c" ]
   a.delete("b")                   #=> "b"
   a                               #=> ["a", "c"]
   a.delete("z")                   #=> nil
   a.delete("z") { "not found" }   #=> "not found"
array.delete_at(index) → obj or nil

Deletes the element at the specified index, returning that element, or nil if the index is out of range. See also Array#slice!.

   a = %w( ant bat cat dog )
   a.delete_at(2)    #=> "cat"
   a                 #=> ["ant", "bat", "dog"]
   a.delete_at(99)   #=> nil
array.delete_if {|item| block } → array

Deletes every element of self for which block evaluates to true.

   a = [ "a", "b", "c" ]
   a.delete_if {|x| x >= "b" }   #=> ["a"]
array.each {|item| block } → array

Calls block once for each element in self, passing that element as a parameter.

   a = [ "a", "b", "c" ]
   a.each {|x| print x, " -- " }

produces:

   a -- b -- c --
array.each_index {|index| block } → array

Same as Array#each, but passes the index of the element instead of the element itself.

   a = [ "a", "b", "c" ]
   a.each_index {|x| print x, " -- " }

produces:

   0 -- 1 -- 2 --
array.empty? → true or false

Returns true if self array contains no elements.

   [].empty?   #=> true
array.eql?(other) → true or false

Returns true if array and other are the same object, or are both arrays with the same content.

array.fetch(index) → obj
array.fetch(index, default ) → obj
array.fetch(index) {|index| block } → obj

Tries to return the element at position index. If the index lies outside the array, the first form throws an IndexError exception, the second form returns default, and the third form returns the value of invoking the block, passing in the index. Negative values of index count from the end of the array.

   a = [ 11, 22, 33, 44 ]
   a.fetch(1)               #=> 22
   a.fetch(-1)              #=> 44
   a.fetch(4, 'cat')        #=> "cat"
   a.fetch(4) { |i| i*i }   #=> 16
array.fill(obj) → array
array.fill(obj, start [, length]) → array
array.fill(obj, range ) → array
array.fill {|index| block } → array
array.fill(start [, length] ) {|index| block } → array
array.fill(range) {|index| block } → array

The first three forms set the selected elements of self (which may be the entire array) to obj. A start of nil is equivalent to zero. A length of nil is equivalent to self.length. The last three forms fill the array with the value of the block. The block is passed the absolute index of each element to be filled.

   a = [ "a", "b", "c", "d" ]
   a.fill("x")              #=> ["x", "x", "x", "x"]
   a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
   a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
   a.fill {|i| i*i}         #=> [0, 1, 4, 9]
   a.fill(-2) {|i| i*i*i}   #=> [0, 1, 8, 27]
array.first → obj or nil
array.first(n) → an_array

Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array.

   a = [ "q", "r", "s", "t" ]
   a.first    #=> "q"
   a.first(1) #=> ["q"]
   a.first(3) #=> ["q", "r", "s"]
array.flatten → an_array

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
array.flatten! → array or nil

Flattens self in place. Returns nil if no modifications were made (i.e., array contains no subarrays.)

   a = [ 1, 2, [3, [4, 5] ] ]
   a.flatten!   #=> [1, 2, 3, 4, 5]
   a.flatten!   #=> nil
   a            #=> [1, 2, 3, 4, 5]
array.frozen? → true or false

Return true if this array is frozen (or temporarily frozen while being sorted).

array.hash → fixnum

Compute a hash-code for this array. Two arrays with the same content will have the same hash code (and will compare using eql?).

array.include?(obj) → true or false

Returns true if the given object is present in self (that is, if any object == anObject), false otherwise.

   a = [ "a", "b", "c" ]
   a.include?("b")   #=> true
   a.include?("z")   #=> false
array.index(obj) → int or nil

Returns the index of the first object in self such that is == to obj. Returns nil if no match is found.

   a = [ "a", "b", "c" ]
   a.index("b")   #=> 1
   a.index("z")   #=> nil
array.indexes( i1, i2, ... iN ) → an_array
array.indices( i1, i2, ... iN ) → an_array

Deprecated; use Array#values_at.

array.indexes( i1, i2, ... iN ) → an_array
array.indices( i1, i2, ... iN ) → an_array

Deprecated; use Array#values_at.

array.replace(other_array) → array

Replaces the contents of self with the contents of other_array, truncating or expanding if necessary.

   a = [ "a", "b", "c", "d", "e" ]
   a.replace([ "x", "y", "z" ])   #=> ["x", "y", "z"]
   a                              #=> ["x", "y", "z"]
array.insert(index, obj...) → array

Inserts the given values before the element with the given index (which may be negative).

   a = %w{ a b c d }
   a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
   a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
array.inspect → string

Create a printable version of array.

array.join(sep=$,) → str

Returns a string created by converting each element of the array to a string, separated by sep.

   [ "a", "b", "c" ].join        #=> "abc"
   [ "a", "b", "c" ].join("-")   #=> "a-b-c"
array.last → obj or nil
array.last(n) → an_array

Returns the last element(s) of self. If the array is empty, the first form returns nil.

   [ "w", "x", "y", "z" ].last   #=> "z"
array.length → int

Returns the number of elements in self. May be zero.

   [ 1, 2, 3, 4, 5 ].length   #=> 5
array.collect {|item| block } → an_array
array.map {|item| block } → an_array

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.

   a = [ "a", "b", "c", "d" ]
   a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
   a                          #=> ["a", "b", "c", "d"]
array.collect! {|item| block } → array
array.map! {|item| block } → array

Invokes the block once for each element of self, replacing the element with the value returned by block. See also Enumerable#collect.

   a = [ "a", "b", "c", "d" ]
   a.collect! {|x| x + "!" }
   a             #=>  [ "a!", "b!", "c!", "d!" ]
array.nitems → int

Returns the number of non-nil elements in self. May be zero.

   [ 1, nil, 3, nil, 5 ].nitems   #=> 3
arr.pack ( aTemplateString ) → aBinaryString

Packs the contents of arr into a binary sequence according to the directives in aTemplateString (see the table below) Directives ``A,’’ ``a,’’ and ``Z’’ may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (``*’’), all remaining array elements will be converted. Any of the directives ``sSiIlL’’ may be followed by an underscore (``_’’) to use the underlying platform‘s native size for the specified type; otherwise, they use a platform-independent size. Spaces are ignored in the template string. See also String#unpack.

   a = [ "a", "b", "c" ]
   n = [ 65, 66, 67 ]
   a.pack("A3A3A3")   #=> "a  b  c  "
   a.pack("a3a3a3")   #=> "a\000\000b\000\000c\000\000"
   n.pack("ccc")      #=> "ABC"

Directives for pack.

 Directive    Meaning
 ---------------------------------------------------------------
     @     |  Moves to absolute position
     A     |  ASCII string (space padded, count is width)
     a     |  ASCII string (null padded, count is width)
     B     |  Bit string (descending bit order)
     b     |  Bit string (ascending bit order)
     C     |  Unsigned char
     c     |  Char
     D, d  |  Double-precision float, native format
     E     |  Double-precision float, little-endian byte order
     e     |  Single-precision float, little-endian byte order
     F, f  |  Single-precision float, native format
     G     |  Double-precision float, network (big-endian) byte order
     g     |  Single-precision float, network (big-endian) byte order
     H     |  Hex string (high nibble first)
     h     |  Hex string (low nibble first)
     I     |  Unsigned integer
     i     |  Integer
     L     |  Unsigned long
     l     |  Long
     M     |  Quoted printable, MIME encoding (see RFC2045)
     m     |  Base64 encoded string
     N     |  Long, network (big-endian) byte order
     n     |  Short, network (big-endian) byte-order
     P     |  Pointer to a structure (fixed-length string)
     p     |  Pointer to a null-terminated string
     Q, q  |  64-bit number
     S     |  Unsigned short
     s     |  Short
     U     |  UTF-8
     u     |  UU-encoded string
     V     |  Long, little-endian byte order
     v     |  Short, little-endian byte order
     w     |  BER-compressed integer\fnm
     X     |  Back up a byte
     x     |  Null byte
     Z     |  Same as ``a'', except that null is added with *
array.pop → obj or nil

Removes the last element from self and returns it, or nil if the array is empty.

   a = [ "a", "m", "z" ]
   a.pop   #=> "z"
   a       #=> ["a", "m"]
pretty_print(q)
pretty_print_cycle(q)
array.push(obj, ... ) → array

Append—Pushes the given object(s) on to the end of this array. This expression returns the array itself, so several appends may be chained together.

   a = [ "a", "b", "c" ]
   a.push("d", "e", "f")
           #=> ["a", "b", "c", "d", "e", "f"]
quote()
array.rassoc(key) → an_array or nil

Searches through the array whose elements are also arrays. Compares key with the second element of each contained array using ==. Returns the first contained array that matches. See also Array#assoc.

   a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
   a.rassoc("two")    #=> [2, "two"]
   a.rassoc("four")   #=> nil
array.reject {|item| block } → an_array

Returns a new array containing the items in self for which the block is not true.

array.reject! {|item| block } → array or nil

Equivalent to Array#delete_if, deleting elements from self for which the block evaluates to true, but returns nil if no changes were made. Also see Enumerable#reject.

array.replace(other_array) → array

Replaces the contents of self with the contents of other_array, truncating or expanding if necessary.

   a = [ "a", "b", "c", "d", "e" ]
   a.replace([ "x", "y", "z" ])   #=> ["x", "y", "z"]
   a                              #=> ["x", "y", "z"]
array.reverse → an_array

Returns a new array containing self‘s elements in reverse order.

   [ "a", "b", "c" ].reverse   #=> ["c", "b", "a"]
   [ 1 ].reverse               #=> [1]
array.reverse! → array

Reverses self in place.

   a = [ "a", "b", "c" ]
   a.reverse!       #=> ["c", "b", "a"]
   a                #=> ["c", "b", "a"]
array.reverse_each {|item| block }

Same as Array#each, but traverses self in reverse order.

   a = [ "a", "b", "c" ]
   a.reverse_each {|x| print x, " " }

produces:

   c b a
array.rindex(obj) → int or nil

Returns the index of the last object in array == to obj. Returns nil if no match is found.

   a = [ "a", "b", "b", "b", "c" ]
   a.rindex("b")   #=> 3
   a.rindex("z")   #=> nil
array.select {|item| block } → an_array

Invokes the block passing in successive elements from array, returning an array containing those elements for which the block returns a true value (equivalent to Enumerable#select).

   a = %w{ a b c d e f }
   a.select {|v| v =~ /[aeiou]/}   #=> ["a", "e"]
array.shift → obj or nil

Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty.

   args = [ "-m", "-q", "filename" ]
   args.shift   #=> "-m"
   args         #=> ["-q", "filename"]
size()

Alias for length

array[index] → obj or nil
array[start, length] → an_array or nil
array[range] → an_array or nil
array.slice(index) → obj or nil
array.slice(start, length) → an_array or nil
array.slice(range) → an_array or nil

Element Reference—Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) are out of range.

   a = [ "a", "b", "c", "d", "e" ]
   a[2] +  a[0] + a[1]    #=> "cab"
   a[6]                   #=> nil
   a[1, 2]                #=> [ "b", "c" ]
   a[1..3]                #=> [ "b", "c", "d" ]
   a[4..7]                #=> [ "e" ]
   a[6..10]               #=> nil
   a[-3, 3]               #=> [ "c", "d", "e" ]
   # special cases
   a[5]                   #=> nil
   a[5, 1]                #=> []
   a[5..10]               #=> []
array.slice!(index) → obj or nil
array.slice!(start, length) → sub_array or nil
array.slice!(range) → sub_array or nil

Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if the index is out of range. Equivalent to:

   def slice!(*args)
     result = self[*args]
     self[*args] = nil
     result
   end

   a = [ "a", "b", "c" ]
   a.slice!(1)     #=> "b"
   a               #=> ["a", "c"]
   a.slice!(-1)    #=> "c"
   a               #=> ["a"]
   a.slice!(100)   #=> nil
   a               #=> ["a"]
array.sort → an_array
array.sort {| a,b | block } → an_array

Returns a new array created by sorting self. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. See also Enumerable#sort_by.

   a = [ "d", "a", "e", "c", "b" ]
   a.sort                    #=> ["a", "b", "c", "d", "e"]
   a.sort {|x,y| y <=> x }   #=> ["e", "d", "c", "b", "a"]
array.sort! → array
array.sort! {| a,b | block } → array

Sorts self. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. See also Enumerable#sort_by.

   a = [ "d", "a", "e", "c", "b" ]
   a.sort                    #=> ["a", "b", "c", "d", "e"]
   a.sort {|x,y| y <=> x }   #=> ["e", "d", "c", "b", "a"]
array.to_a → array

Returns self. If called on a subclass of Array, converts the receiver to an Array object.

array.to_ary → array

Returns self.

array.to_s → string

Returns self.join.

   [ "a", "e", "i", "o" ].to_s   #=> "aeio"
to_yaml( opts = {} )
array.transpose → an_array

Assumes that self is an array of arrays and transposes the rows and columns.

   a = [[1,2], [3,4], [5,6]]
   a.transpose   #=> [[1, 3, 5], [2, 4, 6]]
array.uniq → an_array

Returns a new array by removing duplicate values in self.

   a = [ "a", "a", "b", "b", "c" ]
   a.uniq   #=> ["a", "b", "c"]
array.uniq! → array or nil

Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).

   a = [ "a", "a", "b", "b", "c" ]
   a.uniq!   #=> ["a", "b", "c"]
   b = [ "a", "b", "c" ]
   b.uniq!   #=> nil
array.unshift(obj, ...) → array

Prepends objects to the front of array. other elements up one.

   a = [ "b", "c", "d" ]
   a.unshift("a")   #=> ["a", "b", "c", "d"]
   a.unshift(1, 2)  #=> [ 1, 2, "a", "b", "c", "d"]
array.values_at(selector,... ) → an_array

Returns an array containing the elements in self corresponding to the given selector(s). The selectors may be either integer indices or ranges. See also Array#select.

   a = %w{ a b c d e f }
   a.values_at(1, 3, 5)
   a.values_at(1, 3, 5, 7)
   a.values_at(-1, -3, -5, -7)
   a.values_at(1..3, 2...5)
yaml_initialize( tag, val )
array.zip(arg, ...) → an_array
array.zip(arg, ...) {| arr | block } → nil

Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. This generates a sequence of self.size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than enumObj.size, nil values are supplied. If a block given, it is invoked for each output array, otherwise an array of arrays is returned.

   a = [ 4, 5, 6 ]
   b = [ 7, 8, 9 ]

   [1,2,3].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
   [1,2].zip(a,b)         #=> [[1, 4, 7], [2, 5, 8]]
   a.zip([1,2],[8])       #=> [[4,1,8], [5,2,nil], [6,nil,nil]]
array | other_array → an_array

Set Union—Returns a new array by joining this array with other_array, removing duplicates.

   [ "a", "b", "c" ] | [ "c", "d", "a" ]
          #=> [ "a", "b", "c", "d" ]


Class: Date

Class | Date
In: | lib/date/format.rb lib/date.rb lib/yaml/rubytypes.rb
Parent: | Object

Class representing a date.

See the documentation to the file date.rb for an overview.

Internally, the date is represented as an Astronomical Julian Day Number, ajd. The Day of Calendar Reform, sg, is also stored, for conversions to other date formats. (There is also an of field for a time zone offset, but this is only for the use of the DateTime subclass.)

A new Date object is created using one of the object creation class methods named after the corresponding date format, and the arguments appropriate to that date format; for instance, Date::civil() (aliased to Date::new()) with year, month, and day-of-month, or Date::ordinal() with year and day-of-year. All of these object creation class methods also take the Day of Calendar Reform as an optional argument.

Date objects are immutable once created.

Once a Date has been created, date values can be retrieved for the different date formats supported using instance methods. For instance, mon() gives the Civil month, cwday() gives the Commercial day of the week, and yday() gives the Ordinal day of the year. Date values can be retrieved in any format, regardless of what format was used to create the Date instance.

The Date class includes the Comparable module, allowing date objects to be compared and sorted, ranges of dates to be created, and so forth.

Methods

+ - << <=> === >> _dump _load _parse _strptime ajd ajd_to_amjd ajd_to_jd amjd amjd_to_ajd asctime civil civil_to_jd commercial commercial_to_jd ctime cwday cweek cwyear day day_fraction day_fraction_to_time downto england eql? gregorian gregorian? gregorian? gregorian_leap? hash inspect italy jd jd jd_to_ajd jd_to_civil jd_to_commercial jd_to_ld jd_to_mjd jd_to_ordinal jd_to_wday julian julian? julian? julian_leap? ld ld_to_jd leap? mday mjd mjd_to_jd mon month new new_start next ordinal ordinal_to_jd parse start step strftime strptime succ time_to_day_fraction to_s to_yaml today upto valid_civil? valid_commercial? valid_jd? valid_ordinal? valid_time? wday yday year

Included Modules

Comparable

Constants

MONTHNAMES | = | [nil] + %w(January February March April May June July August September October November December) | Full month names, in English. Months count from 1 to 12; a month‘s numerical representation indexed into this array gives the name of that month (hence the first element is nil).
DAYNAMES | = | %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday) | Full names of days of the week, in English. Days of the week count from 0 to 6 (except in the commercial week); a day‘s numerical representation indexed into this array gives the name of that day.
ABBR_MONTHNAMES | = | [nil] + %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) | Abbreviated month names, in English.
ABBR_DAYNAMES | = | %w(Sun Mon Tue Wed Thu Fri Sat) | Abbreviated day names, in English.
ITALY | = | 2299161 | The Julian Day Number of the Day of Calendar Reform for Italy and the Catholic countries.
ENGLAND | = | 2361222 | The Julian Day Number of the Day of Calendar Reform for England and her Colonies.
JULIAN | = | Infinity.new | A constant used to indicate that a Date should always use the Julian calendar.
GREGORIAN | = | -Infinity.new | A constant used to indicate that a Date should always use the Gregorian calendar.

External Aliases

gregorian_leap? | -> | leap?
new | -> | new!
valid_civil? | -> | valid_date?
civil | -> | new

Public Class methods

_load(str)

Load from Marshall format.

_parse(str, comp=false)
_strptime(str, fmt='%F')
ajd_to_amjd(ajd)

Convert an Astronomical Julian Day Number to an Astronomical Modified Julian Day Number.

ajd_to_jd(ajd, of=0)

Convert an Astronomical Julian Day Number to a (civil) Julian Day Number.

ajd is the Astronomical Julian Day Number to convert. of is the offset from UTC as a fraction of a day (defaults to 0).

Returns the (civil) Julian Day Number as [day_number, fraction] where fraction is always 1/2.

amjd_to_ajd(amjd)

Convert an Astronomical Modified Julian Day Number to an Astronomical Julian Day Number.

civil(y=-4712, m=1, d=1, sg=ITALY)

Create a new Date object for the Civil Date specified by year y, month m, and day-of-month d.

m and d can be negative, in which case they count backwards from the end of the year and the end of the month respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised. can be negative

y defaults to -4712, m to 1, and d to 1; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

civil_to_jd(y, m, d, sg=GREGORIAN)

Convert a Civil Date to a Julian Day Number. y, m, and d are the year, month, and day of the month. sg specifies the Day of Calendar Reform.

Returns the corresponding Julian Day Number.

commercial(y=1582, w=41, d=5, sg=ITALY)

Create a new Date object for the Commercial Date specified by year y, week-of-year w, and day-of-week d.

Monday is day-of-week 1; Sunday is day-of-week 7.

w and d can be negative, in which case they count backwards from the end of the year and the end of the week respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised.

y defaults to 1582, w to 41, and d to 5, the Day of Calendar Reform for Italy and the Catholic countries.

sg specifies the Day of Calendar Reform.

commercial_to_jd(y, w, d, ns=GREGORIAN)

Convert a Commercial Date to a Julian Day Number.

y, w, and d are the (commercial) year, week of the year, and day of the week of the Commercial Date to convert. sg specifies the Day of Calendar Reform.

day_fraction_to_time(fr)

Convert a fractional day fr to [hours, minutes, seconds, fraction_of_a_second]

gregorian?(jd, sg)

Does a given Julian Day Number fall inside the new-style (Gregorian) calendar?

The reverse of self.os? See the documentation for that method for more details.

gregorian_leap?(y)

Is a year a leap year in the Gregorian calendar?

All years divisible by 4 are leap years in the Gregorian calendar, except for years divisible by 100 and not by 400.

jd(jd=0, sg=ITALY)

Create a new Date object from a Julian Day Number.

jd is the Julian Day Number; if not specified, it defaults to 0. sg specifies the Day of Calendar Reform.

jd_to_ajd(jd, fr, of=0)

Convert a (civil) Julian Day Number to an Astronomical Julian Day Number.

jd is the Julian Day Number to convert, and fr is a fractional day. of is the offset from UTC as a fraction of a day (defaults to 0).

Returns the Astronomical Julian Day Number as a single numeric value.

jd_to_civil(jd, sg=GREGORIAN)

Convert a Julian Day Number to a Civil Date. jd is the Julian Day Number. sg specifies the Day of Calendar Reform.

Returns the corresponding [year, month, day_of_month] as a three-element array.

jd_to_commercial(jd, sg=GREGORIAN)

Convert a Julian Day Number to a Commercial Date

jd is the Julian Day Number to convert. sg specifies the Day of Calendar Reform.

Returns the corresponding Commercial Date as [commercial_year, week_of_year, day_of_week]

jd_to_ld(jd)

Convert a Julian Day Number to the number of days since the adoption of the Gregorian Calendar (in Italy).

jd_to_mjd(jd)

Convert a Julian Day Number to a Modified Julian Day Number.

jd_to_ordinal(jd, sg=GREGORIAN)

Convert a Julian Day Number to an Ordinal Date.

jd is the Julian Day Number to convert. sg specifies the Day of Calendar Reform.

Returns the corresponding Ordinal Date as [year, day_of_year]

jd_to_wday(jd)

Convert a Julian Day Number to the day of the week.

Sunday is day-of-week 0; Saturday is day-of-week 6.

julian?(jd, sg)

Does a given Julian Day Number fall inside the old-style (Julian) calendar?

jd is the Julian Day Number in question. sg may be Date::GREGORIAN, in which case the answer is false; it may be Date::JULIAN, in which case the answer is true; or it may a number representing the Day of Calendar Reform. Date::ENGLAND and Date::ITALY are two possible such days.

julian_leap?(y)

Is a year a leap year in the Julian calendar?

All years divisible by 4 are leap years in the Julian calendar.

ld_to_jd(ld)

Convert a count of the number of days since the adoption of the Gregorian Calendar (in Italy) to a Julian Day Number.

mjd_to_jd(mjd)

Convert a Modified Julian Day Number to a Julian Day Number.

new(ajd=0, of=0, sg=ITALY)

NOTE this is the documentation for the method new!(). If you are reading this as the documentation for new(), that is because rdoc doesn‘t fully support the aliasing of the initialize() method. new() is in fact an alias for civil(): read the documentation for that method instead.

Create a new Date object.

ajd is the Astronomical Julian Day Number. of is the offset from UTC as a fraction of a day. Both default to 0.

sg specifies the Day of Calendar Reform to use for this Date object.

Using one of the factory methods such as Date::civil is generally easier and safer.

ordinal(y=-4712, d=1, sg=ITALY)

Create a new Date object from an Ordinal Date, specified by year y and day-of-year d. d can be negative, in which it counts backwards from the end of the year. No year wraparound is performed, however. An invalid value for d results in an ArgumentError being raised.

y defaults to -4712, and d to 1; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

ordinal_to_jd(y, d, sg=GREGORIAN)

Convert an Ordinal Date to a Julian Day Number.

y and d are the year and day-of-year to convert. sg specifies the Day of Calendar Reform.

Returns the corresponding Julian Day Number.

parse(str='-4712-01-01', comp=false, sg=ITALY)

Create a new Date object by parsing from a String, without specifying the format.

str is a String holding a date representation. comp specifies whether to interpret 2-digit years as 19XX (>= 69) or 20XX (< 69); the default is not to. The method will attempt to parse a date from the String using various heuristics; see _parse in date/format.rb for more details. If parsing fails, an ArgumentError will be raised.

The default str is ’-4712-01-01’; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

strptime(str='-4712-01-01', fmt='%F', sg=ITALY)

Create a new Date object by parsing from a String according to a specified format.

str is a String holding a date representation. fmt is the format that the date is in. See date/format.rb for details on supported formats.

The default str is ’-4712-01-01’, and the default fmt is ’%F’, which means Year-Month-Day_of_Month. This gives Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

An ArgumentError will be raised if str cannot be parsed.

time_to_day_fraction(h, min, s)

Convert an h hour, min minutes, s seconds period to a fractional day.

today(sg=ITALY)

Create a new Date object representing today.

sg specifies the Day of Calendar Reform.

valid_civil?(y, m, d, sg=ITALY)

Do year y, month m, and day-of-month d make a valid Civil Date? Returns the corresponding Julian Day Number if they do, nil if they don‘t.

m and d can be negative, in which case they count backwards from the end of the year and the end of the month respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised. A date falling in the period skipped in the Day of Calendar Reform adjustment is not valid.

sg specifies the Day of Calendar Reform.

valid_commercial?(y, w, d, sg=ITALY)

Do year y, week-of-year w, and day-of-week d make a valid Commercial Date? Returns the corresponding Julian Day Number if they do, nil if they don‘t.

Monday is day-of-week 1; Sunday is day-of-week 7.

w and d can be negative, in which case they count backwards from the end of the year and the end of the week respectively. No wraparound is performed, however, and invalid values cause an ArgumentError to be raised. A date falling in the period skipped in the Day of Calendar Reform adjustment is not valid.

sg specifies the Day of Calendar Reform.

valid_jd?(jd, sg=ITALY)

Is jd a valid Julian Day Number?

If it is, returns it. In fact, any value is treated as a valid Julian Day Number.

valid_ordinal?(y, d, sg=ITALY)

Do the year y and day-of-year d make a valid Ordinal Date? Returns the corresponding Julian Day Number if they do, or nil if they don‘t.

d can be a negative number, in which case it counts backwards from the end of the year (-1 being the last day of the year). No year wraparound is performed, however, so valid values of d are -365 .. -1, 1 .. 365 on a non-leap-year, -366 .. -1, 1 .. 366 on a leap year. A date falling in the period skipped in the Day of Calendar Reform adjustment is not valid.

sg specifies the Day of Calendar Reform.

valid_time?(h, min, s)

Do hour h, minute min, and second s constitute a valid time?

If they do, returns their value as a fraction of a day. If not, returns nil.

The 24-hour clock is used. Negative values of h, min, and sec are treating as counting backwards from the end of the next larger unit (e.g. a min of -2 is treated as 58). No wraparound is performed.

Public Instance methods

+(n)

Return a new Date object that is n days later than the current one.

n may be a negative value, in which case the new Date is earlier than the current one; however, #-() might be more intuitive.

If n is not a Numeric, a TypeError will be thrown. In particular, two Dates cannot be added to each other.

-(x)

If x is a Numeric value, create a new Date object that is x days earlier than the current one.

If x is a Date, return the number of days between the two dates; or, more precisely, how many days later the current date is than x.

If x is neither Numeric nor a Date, a TypeError is raised.

<<(n)

Return a new Date object that is n months earlier than the current one.

If the day-of-the-month of the current Date is greater than the last day of the target month, the day-of-the-month of the returned Date will be the last day of the target month.

<=>(other)

Compare this date with another date.

other can also be a Numeric value, in which case it is interpreted as an Astronomical Julian Day Number.

Comparison is by Astronomical Julian Day Number, including fractional days. This means that both the time and the timezone offset are taken into account when comparing two DateTime instances. When comparing a DateTime instance with a Date instance, the time of the latter will be considered as falling on midnight UTC.

===(other)

The relationship operator for Date.

Compares dates by Julian Day Number. When comparing two DateTime instances, or a DateTime with a Date, the instances will be regarded as equivalent if they fall on the same date in local time.

>>(n)

Return a new Date object that is n months later than the current one.

If the day-of-the-month of the current Date is greater than the last day of the target month, the day-of-the-month of the returned Date will be the last day of the target month.

_dump(limit)

Dump to Marshal format.

ajd()

Get the date as an Astronomical Julian Day Number.

amjd()

Get the date as an Astronomical Modified Julian Day Number.

asctime()

alias_method :format, :strftime

ctime()

Alias for asctime

cwday()

Get the commercial day of the week of this date. Monday is commercial day-of-week 1; Sunday is commercial day-of-week 7.

cweek()

Get the commercial week of the year of this date.

cwyear()

Get the commercial year of this date. See Commercial Date in the introduction for how this differs from the normal year.

day()

Alias for mday

day_fraction()

Get any fractional day part of the date.

downto(min) {|date| ...}

Step backward one day at a time until we reach min (inclusive), yielding each date as we go.

england()

Create a copy of this Date object that uses the English/Colonial Day of Calendar Reform.

eql?(other)

Is this Date equal to other?

other must both be a Date object, and represent the same date.

gregorian()

Create a copy of this Date object that always uses the Gregorian Calendar.

gregorian?()

Is the current date new-style (Gregorian Calendar)?

hash()

Calculate a hash value for this date.

inspect()

Return internal object state as a programmer-readable string.

italy()

Create a copy of this Date object that uses the Italian/Catholic Day of Calendar Reform.

jd()

Get the date as a Julian Day Number.

julian()

Create a copy of this Date object that always uses the Julian Calendar.

julian?()

Is the current date old-style (Julian Calendar)?

ld()

Get the date as the number of days since the Day of Calendar Reform (in Italy and the Catholic countries).

leap?()

Is this a leap year?

mday()

Get the day-of-the-month of this date.

mjd()

Get the date as a Modified Julian Day Number.

mon()

Get the month of this date.

January is month 1.

month()

Alias for mon

new_start(sg=self.class::ITALY)

Create a copy of this Date object using a new Day of Calendar Reform.

next()

Return a new Date one day after this one.

start()

When is the Day of Calendar Reform for this Date object?

step(limit, step=1) {|date| ...}

Step the current date forward step days at a time (or backward, if step is negative) until we reach limit (inclusive), yielding the resultant date at each step.

strftime(fmt='%F')
succ()

Alias for next

to_s()

Return the date as a human-readable string.

The format used is YYYY-MM-DD.

to_yaml( opts = {} )
upto(max) {|date| ...}

Step forward one day at a time until we reach max (inclusive), yielding each date as we go.

wday()

Get the week day of this date. Sunday is day-of-week 0; Saturday is day-of-week 6.

yday()

Get the day-of-the-year of this date.

January 1 is day-of-the-year 1

year()

Get the year of this date.


Class: Dir

Class | Dir
In: | dir.c lib/tmpdir.rb
Parent: | Object

tmpdir - retrieve temporary directory path

$Id: tmpdir.rb 11708 2007-02-12 23:01:19Z shyouhei $

Methods

[] chdir chroot close delete each entries foreach getwd glob mkdir new open path pos pos= pwd read rewind rmdir seek tell tmpdir unlink

Included Modules

Enumerable

Public Class methods

Dir[ array ] => array
Dir[ string [, string ...] ] => array

Equivalent to calling Dir.glob(array,0) and href="Dir.html#M002347">Dir.glob(,0).

Dir.chdir( [ string] ) => 0
Dir.chdir( [ string] ) {| path | block } => anObject

Changes the current working directory of the process to the given string. When called without an argument, changes the directory to the value of the environment variable HOME, or LOGDIR. SystemCallError (probably Errno::ENOENT) if the target directory does not exist.

If a block is given, it is passed the name of the new current directory, and the block is executed with that as the current directory. The original working directory is restored when the block exits. The return value of chdir is the value of the block. chdir blocks can be nested, but in a multi-threaded program an error will be raised if a thread attempts to open a chdir block while another thread has one open.

   Dir.chdir("/var/spool/mail")
   puts Dir.pwd
   Dir.chdir("/tmp") do
     puts Dir.pwd
     Dir.chdir("/usr") do
       puts Dir.pwd
     end
     puts Dir.pwd
   end
   puts Dir.pwd

produces:

   /var/spool/mail
   /tmp
   /usr
   /tmp
   /var/spool/mail
Dir.chroot( string ) => 0

Changes this process‘s idea of the file system root. Only a privileged process may make this call. Not available on all platforms. On Unix systems, see chroot(2) for more information.

Dir.delete( string ) => 0
Dir.rmdir( string ) => 0
Dir.unlink( string ) => 0

Deletes the named directory. Raises a subclass of SystemCallError if the directory isn‘t empty.

Dir.entries( dirname ) => array

Returns an array containing all of the filenames in the given directory. Will raise a SystemCallError if the named directory doesn‘t exist.

   Dir.entries("testdir")   #=> [".", "..", "config.h", "main.rb"]
Dir.foreach( dirname ) {| filename | block } => nil

Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.

   Dir.foreach("testdir") {|x| puts "Got #{x}" }

produces:

   Got .
   Got ..
   Got config.h
   Got main.rb
Dir.getwd => string
Dir.pwd => string

Returns the path to the current working directory of this process as a string.

   Dir.chdir("/tmp")   #=> 0
   Dir.getwd           #=> "/tmp"
Dir.glob( pattern, [flags] ) => array
Dir.glob( pattern, [flags] ) {| filename | block } => nil

Returns the filenames found by expanding pattern which is an Array of the patterns or the pattern String, either as an array or as parameters to the block. Note that this pattern is not a regexp (it‘s closer to a shell glob). See File::fnmatch for the meaning of the flags parameter. Note that case sensitivity depends on your system (so File::FNM_CASEFOLD is ignored)

*: | Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp.
**: | Matches directories recursively.
?: | Matches any one character. Equivalent to /.{1}/ in regexp.
[set]: | Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).
{p,q}: | Matches either literal p or literal q. Matching literals may be more than one character in length. More than two literals may be specified. Equivalent to pattern alternation in regexp.
<code></code>: | Escapes the next metacharacter.
   Dir["config.?"]                     #=> ["config.h"]
   Dir.glob("config.?")                #=> ["config.h"]
   Dir.glob("*.[a-z][a-z]")            #=> ["main.rb"]
   Dir.glob("*.[^r]*")                 #=> ["config.h"]
   Dir.glob("*.{rb,h}")                #=> ["main.rb", "config.h"]
   Dir.glob("*")                       #=> ["config.h", "main.rb"]
   Dir.glob("*", File::FNM_DOTMATCH)   #=> [".", "..", "config.h", "main.rb"]

   rbfiles = File.join("**", "*.rb")
   Dir.glob(rbfiles)                   #=> ["main.rb",
                                            "lib/song.rb",
                                            "lib/song/karaoke.rb"]
   libdirs = File.join("**", "lib")
   Dir.glob(libdirs)                   #=> ["lib"]

   librbfiles = File.join("**", "lib", "**", "*.rb")
   Dir.glob(librbfiles)                #=> ["lib/song.rb",
                                            "lib/song/karaoke.rb"]

   librbfiles = File.join("**", "lib", "*.rb")
   Dir.glob(librbfiles)                #=> ["lib/song.rb"]
Dir.mkdir( string [, integer] ) => 0

Makes a new directory named by string, with permissions specified by the optional parameter anInteger. The permissions may be modified by the value of File::umask, and are ignored on NT. Raises a SystemCallError if the directory cannot be created. See also the discussion of permissions in the class documentation for File.

Dir.new( string ) → aDir

Returns a new directory object for the named directory.

Dir.open( string ) => aDir
Dir.open( string ) {| aDir | block } => anObject

With no block, open is a synonym for Dir::new. If a block is present, it is passed aDir as a parameter. The directory is closed at the end of the block, and Dir::open returns the value of the block.

Dir.getwd => string
Dir.pwd => string

Returns the path to the current working directory of this process as a string.

   Dir.chdir("/tmp")   #=> 0
   Dir.getwd           #=> "/tmp"
Dir.delete( string ) => 0
Dir.rmdir( string ) => 0
Dir.unlink( string ) => 0

Deletes the named directory. Raises a subclass of SystemCallError if the directory isn‘t empty.

tmpdir()

Returns the operating system‘s temporary file path.

Dir.delete( string ) => 0
Dir.rmdir( string ) => 0
Dir.unlink( string ) => 0

Deletes the named directory. Raises a subclass of SystemCallError if the directory isn‘t empty.

Public Instance methods

dir.close => nil

Closes the directory stream. Any further attempts to access dir will raise an IOError.

   d = Dir.new("testdir")
   d.close   #=> nil
dir.each { |filename| block } => dir

Calls the block once for each entry in this directory, passing the filename of each entry as a parameter to the block.

   d = Dir.new("testdir")
   d.each  {|x| puts "Got #{x}" }

produces:

   Got .
   Got ..
   Got config.h
   Got main.rb
dir.path => string or nil

Returns the path parameter passed to dir‘s constructor.

   d = Dir.new("..")
   d.path   #=> ".."
dir.pos => integer
dir.tell => integer

Returns the current position in dir. See also Dir#seek.

   d = Dir.new("testdir")
   d.tell   #=> 0
   d.read   #=> "."
   d.tell   #=> 12
dir.pos( integer ) => integer

Synonym for Dir#seek, but returns the position parameter.

   d = Dir.new("testdir")   #=> #<Dir:0x401b3c40>
   d.read                   #=> "."
   i = d.pos                #=> 12
   d.read                   #=> ".."
   d.pos = i                #=> 12
   d.read                   #=> ".."
dir.read => string or nil

Reads the next entry from dir and returns it as a string. Returns nil at the end of the stream.

   d = Dir.new("testdir")
   d.read   #=> "."
   d.read   #=> ".."
   d.read   #=> "config.h"
dir.rewind => dir

Repositions dir to the first entry.

   d = Dir.new("testdir")
   d.read     #=> "."
   d.rewind   #=> #<Dir:0x401b3fb0>
   d.read     #=> "."
dir.seek( integer ) => dir

Seeks to a particular location in dir. integer must be a value returned by Dir#tell.

   d = Dir.new("testdir")   #=> #<Dir:0x401b3c40>
   d.read                   #=> "."
   i = d.tell               #=> 12
   d.read                   #=> ".."
   d.seek(i)                #=> #<Dir:0x401b3c40>
   d.read                   #=> ".."
dir.pos => integer
dir.tell => integer

Returns the current position in dir. See also Dir#seek.

   d = Dir.new("testdir")
   d.tell   #=> 0
   d.read   #=> "."
   d.tell   #=> 12


Module: Enumerable

Module | Enumerable
In: | enum.c lib/set.rb lib/soap/property.rb ext/enumerator/enumerator.c

The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection. If Enumerable#max, min, or sort is used, the objects in the collection must also implement a meaningful <=> operator, as these methods rely on an ordering between members of the collection.

Methods

all? any? collect detect each_cons each_slice each_with_index entries enum_cons enum_slice enum_with_index find find_all grep include? inject inject map max member? min partition reject select sort sort_by to_a to_set zip

Classes and Modules

Class Enumerable::Enumerator

Public Instance methods

enum.all? [{|obj| block } ] => true or false

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is all? will return true only if none of the collection members are false or nil.)

   %w{ ant bear cat}.all? {|word| word.length >= 3}   #=> true
   %w{ ant bear cat}.all? {|word| word.length >= 4}   #=> false
   [ nil, true, 99 ].all?                             #=> false
enum.any? [{|obj| block } ] => true or false

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.

   %w{ ant bear cat}.any? {|word| word.length >= 3}   #=> true
   %w{ ant bear cat}.any? {|word| word.length >= 4}   #=> true
   [ nil, true, 99 ].any?                             #=> true
enum.collect {| obj | block } => array
enum.map {| obj | block } => array

Returns a new array with the results of running block once for every element in enum.

   (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
   (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
enum.detect(ifnone = nil) {| obj | block } => obj or nil
enum.find(ifnone = nil) {| obj | block } => obj or nil

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil

   (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
   (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
each_cons(n) {...}

Iterates the given block for each array of consecutive <n> elements.

e.g.:

    (1..10).each_cons(3) {|a| p a}
    # outputs below
    [1, 2, 3]
    [2, 3, 4]
    [3, 4, 5]
    [4, 5, 6]
    [5, 6, 7]
    [6, 7, 8]
    [7, 8, 9]
    [8, 9, 10]
e.each_slice(n) {...}

Iterates the given block for each slice of <n> elements.

e.g.:

    (1..10).each_slice(3) {|a| p a}
    # outputs below
    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    [10]
enum.each_with_index {|obj, i| block } → enum

Calls block with two arguments, the item and its index, for each item in enum.

   hash = Hash.new
   %w(cat dog wombat).each_with_index {|item, index|
     hash[item] = index
   }
   hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
enum.to_a => array
enum.entries => array

Returns an array containing the items in enum.

   (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
   { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]
e.enum_cons(n)

Returns Enumerable::Enumerator.new(self, :each_cons, n).

e.enum_slice(n)

Returns Enumerable::Enumerator.new(self, :each_slice, n).

enum_with_index

Returns Enumerable::Enumerator.new(self, :each_with_index).

enum.detect(ifnone = nil) {| obj | block } => obj or nil
enum.find(ifnone = nil) {| obj | block } => obj or nil

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil

   (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
   (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
enum.find_all {| obj | block } => array
enum.select {| obj | block } => array

Returns an array containing all elements of enum for which block is not false (see also Enumerable#reject).

   (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]
enum.grep(pattern) => array
enum.grep(pattern) {| obj | block } => array

Returns an array of every element in enum for which Pattern === element. If the optional block is supplied, each matching element is passed to it, and the block‘s result is stored in the output array.

   (1..100).grep 38..44   #=> [38, 39, 40, 41, 42, 43, 44]
   c = IO.constants
   c.grep(/SEEK/)         #=> ["SEEK_END", "SEEK_SET", "SEEK_CUR"]
   res = c.grep(/SEEK/) {|v| IO.const_get(v) }
   res                    #=> [2, 0, 1]
enum.include?(obj) => true or false
enum.member?(obj) => true or false

Returns true if any member of enum equals obj. Equality is tested using ==.

   IO.constants.include? "SEEK_SET"          #=> true
   IO.constants.include? "SEEK_NO_FURTHER"   #=> false
inject(init) {|result, item| ...}
enum.inject(initial) {| memo, obj | block } => obj
enum.inject {| memo, obj | block } => obj

Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn. At each step, memo is set to the value returned by the block. The first form lets you supply an initial value for memo. The second form uses the first element of the collection as a the initial value (and skips that element while iterating).

   # Sum some numbers
   (5..10).inject {|sum, n| sum + n }              #=> 45
   # Multiply some numbers
   (5..10).inject(1) {|product, n| product * n }   #=> 151200

   # find the longest word
   longest = %w{ cat sheep bear }.inject do |memo,word|
      memo.length > word.length ? memo : word
   end
   longest                                         #=> "sheep"

   # find the length of the longest word
   longest = %w{ cat sheep bear }.inject(0) do |memo,word|
      memo >= word.length ? memo : word.length
   end
   longest                                         #=> 5
enum.collect {| obj | block } => array
enum.map {| obj | block } => array

Returns a new array with the results of running block once for every element in enum.

   (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
   (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
enum.max => obj
enum.max {|a,b| block } => obj

Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

   a = %w(albatross dog horse)
   a.max                                  #=> "horse"
   a.max {|a,b| a.length <=> b.length }   #=> "albatross"
enum.include?(obj) => true or false
enum.member?(obj) => true or false

Returns true if any member of enum equals obj. Equality is tested using ==.

   IO.constants.include? "SEEK_SET"          #=> true
   IO.constants.include? "SEEK_NO_FURTHER"   #=> false
enum.min => obj
enum.min {| a,b | block } => obj

Returns the object in enum with the minimum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

   a = %w(albatross dog horse)
   a.min                                  #=> "albatross"
   a.min {|a,b| a.length <=> b.length }   #=> "dog"
enum.partition {| obj | block } => [ true_array, false_array ]

Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.

   (1..6).partition {|i| (i&1).zero?}   #=> [[2, 4, 6], [1, 3, 5]]
enum.reject {| obj | block } => array

Returns an array for all elements of enum for which block is false (see also Enumerable#find_all).

   (1..10).reject {|i|  i % 3 == 0 }   #=> [1, 2, 4, 5, 7, 8, 10]
enum.find_all {| obj | block } => array
enum.select {| obj | block } => array

Returns an array containing all elements of enum for which block is not false (see also Enumerable#reject).

   (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]
enum.sort => array
enum.sort {| a, b | block } => array

Returns an array containing the items in enum sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b. As of Ruby 1.8, the method Enumerable#sort_by implements a built-in Schwartzian Transform, useful when key computation or comparison is expensive..

   %w(rhea kea flea).sort         #=> ["flea", "kea", "rhea"]
   (1..10).sort {|a,b| b <=> a}   #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
enum.sort_by {| obj | block } => array

Sorts enum using a set of keys generated by mapping the values in enum through the given block.

   %w{ apple pear fig }.sort_by {|word| word.length}
                #=> ["fig", "pear", "apple"]

The current implementation of sort_by generates an array of tuples containing the original collection element and the mapped value. This makes sort_by fairly expensive when the keysets are simple

   require 'benchmark'
   include Benchmark

   a = (1..100000).map {rand(100000)}

   bm(10) do |b|
     b.report("Sort")    { a.sort }
     b.report("Sort by") { a.sort_by {|a| a} }
   end

produces:

   user     system      total        real
   Sort        0.180000   0.000000   0.180000 (  0.175469)
   Sort by     1.980000   0.040000   2.020000 (  2.013586)

However, consider the case where comparing the keys is a non-trivial operation. The following code sorts some files on modification time using the basic sort method.

   files = Dir["*"]
   sorted = files.sort {|a,b| File.new(a).mtime <=> File.new(b).mtime}
   sorted   #=> ["mon", "tues", "wed", "thurs"]

This sort is inefficient: it generates two new File objects during every comparison. A slightly better technique is to use the Kernel#test method to generate the modification times directly.

   files = Dir["*"]
   sorted = files.sort { |a,b|
     test(?M, a) <=> test(?M, b)
   }
   sorted   #=> ["mon", "tues", "wed", "thurs"]

This still generates many unnecessary Time objects. A more efficient technique is to cache the sort keys (modification times in this case) before the sort. Perl users often call this approach a Schwartzian Transform, after Randal Schwartz. We construct a temporary array, where each element is an array containing our sort key along with the filename. We sort this array, and then extract the filename from the result.

   sorted = Dir["*"].collect { |f|
      [test(?M, f), f]
   }.sort.collect { |f| f[1] }
   sorted   #=> ["mon", "tues", "wed", "thurs"]

This is exactly what sort_by does internally.

   sorted = Dir["*"].sort_by {|f| test(?M, f)}
   sorted   #=> ["mon", "tues", "wed", "thurs"]
enum.to_a => array
enum.entries => array

Returns an array containing the items in enum.

   (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
   { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]
to_set(klass = Set, *args, &block)

Makes a set from the enumerable object with given arguments. Needs to +require "set"+ to use this method.

enum.zip(arg, ...) => array
enum.zip(arg, ...) {|arr| block } => nil

Converts any arguments to arrays, then merges elements of enum with corresponding elements from each argument. This generates a sequence of enum#size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than enum#size, nil values are supplied. If a block given, it is invoked for each output array, otherwise an array of arrays is returned.

   a = [ 4, 5, 6 ]
   b = [ 7, 8, 9 ]

   (1..3).zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
   "cat\ndog".zip([1])   #=> [["cat\n", 1], ["dog", nil]]
   (1..3).zip            #=> [[1], [2], [3]]


Class: Enumerable::Enumerator

Class | Enumerable::Enumerator
In: | ext/enumerator/enumerator.c
Parent: | Object

A class which provides a method `each’ to be used as an Enumerable object.

Methods

each new

Included Modules

Enumerable

Public Class methods

Enumerable::Enumerator.new(obj, method = :each, *args)

Creates a new Enumerable::Enumerator object, which is to be used as an Enumerable object using the given object‘s given method with the given arguments.

e.g.:

    str = "xyz"

    enum = Enumerable::Enumerator.new(str, :each_byte)
    a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]

Public Instance methods

enum.each {...}

Iterates the given block using the object and the method specified in the first place.


Class: Exception

Class | Exception
In: | error.c lib/yaml/rubytypes.rb
Parent: | Object

Descendents of class Exception are used to communicate between raise methods and rescue statements in begin/end blocks. Exception objects carry information about the exception—its type (the exception‘s class name), an optional descriptive string, and optional traceback information. Programs may subclass Exception to add additional information.

Methods

backtrace exception exception inspect message new set_backtrace to_s to_str to_yaml yaml_new

Public Class methods

exc.exception(string) → an_exception or exc

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

Exception.new(msg = nil) => exception

Construct a new Exception object, optionally passing in a message.

yaml_new( klass, tag, val )

Public Instance methods

exception.backtrace => array

Returns any backtrace associated with the exception. The backtrace is an array of strings, each containing either ``filename:lineNo: in `method’’’ or ``filename:lineNo.’‘

   def a
     raise "boom"
   end

   def b
     a()
   end

   begin
     b()
   rescue => detail
     print detail.backtrace.join("\n")
   end

produces:

   prog.rb:2:in `a'
   prog.rb:6:in `b'
   prog.rb:10
exc.exception(string) → an_exception or exc

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

exception.inspect => string

Return this exception‘s class name an message

exception.message => string
exception.to_str => string

Returns the result of invoking exception.to_s. Normally this returns the exception‘s message or name. By supplying a to_str method, exceptions are agreeing to be used where Strings are expected.

exc.set_backtrace(array) => array

Sets the backtrace information associated with exc. The argument must be an array of String objects in the format described in Exception#backtrace.

exception.to_s => string

Returns exception‘s message (or the name of the exception if no message is set).

exception.message => string
exception.to_str => string

Returns the result of invoking exception.to_s. Normally this returns the exception‘s message or name. By supplying a to_str method, exceptions are agreeing to be used where Strings are expected.

to_yaml( opts = {} )


Class: File

Class | File
In: | file.c lib/ftools.rb lib/pp.rb
Parent: | IO

ftools.rb: Extra tools for the File class

Author: | WATANABE, Hirofumi
Documentation: | Zachary Landau

This library can be distributed under the terms of the Ruby license. You can freely distribute/modify this library.

It is included in the Ruby standard library.

Description

ftools adds several (class, not instance) methods to the File class, for copying, moving, deleting, installing, and comparing files, as well as creating a directory path. See the File class for details.

FileUtils contains all or nearly all the same functionality and more, and is a recommended option over ftools

When you

  require 'ftools'

then the File class aquires some utility methods for copying, moving, and deleting files, and more.

See the method descriptions below, and consider using FileUtils as it is more comprehensive.

Methods

atime atime basename blockdev? catname chardev? chmod chmod chmod chown chown compare copy ctime ctime delete directory? dirname executable? executable_real? exist? exists? expand_path extname file? flock fnmatch fnmatch? ftype grpowned? identical? install join lchmod lchown link lstat lstat makedirs move mtime mtime new o_chmod owned? path pipe? readable? readable_real? readlink rename safe_unlink setgid? setuid? size size? socket? split stat sticky? symlink symlink? syscopy truncate truncate umask unlink utime writable? writable_real? zero?

Classes and Modules

Module File::Constants
Class File::Stat

Constants

Separator | = | separator
SEPARATOR | = | separator
ALT_SEPARATOR | = | rb_obj_freeze(rb_str_new2("\\"))
ALT_SEPARATOR | = | Qnil
PATH_SEPARATOR | = | rb_obj_freeze(rb_str_new2(PATH_SEP))
BUFSIZE | = | 8 * 1024

External Aliases

copy | -> | cp
move | -> | mv
compare | -> | cmp
safe_unlink | -> | rm_f
makedirs | -> | mkpath

Public Class methods

File.atime(file_name) => time

Returns the last access time for the named file as a Time object).

   File.atime("testfile")   #=> Wed Apr 09 08:51:48 CDT 2003
File.basename(file_name [, suffix] ) → base_name

Returns the last component of the filename given in file_name, which must be formed using forward slashes (``/’’) regardless of the separator used on the local file system. If suffix is given and present at the end of file_name, it is removed.

   File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
   File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"
File.blockdev?(file_name) => true or false

Returns true if the named file is a block device.

catname(from, to)

If to is a valid directory, from will be appended to to, adding and escaping backslashes as necessary. Otherwise, to will be returned. Useful for appending from to to only if the filename was not specified in to.

File.chardev?(file_name) => true or false

Returns true if the named file is a character device.

chmod(mode, *files)

Changes permission bits on files to the bit pattern represented by mode. If the last parameter isn‘t a String, verbose mode will be enabled.

  File.chmod 0755, 'somecommand'
  File.chmod 0644, 'my.rb', 'your.rb', true
File.chmod(mode_int, file_name, ... ) → integer

Changes permission bits on the named file(s) to the bit pattern represented by mode_int. Actual effects are operating system dependent (see the beginning of this section). On Unix systems, see chmod(2) for details. Returns the number of files processed.

   File.chmod(0644, "testfile", "out")   #=> 2
File.chown(owner_int, group_int, file_name,... ) → integer

Changes the owner and group of the named file(s) to the given numeric owner and group id‘s. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file‘s group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Returns the number of files processed.

   File.chown(nil, 100, "testfile")
compare(from, to, verbose = false)

Returns true if and only if the contents of files from and to are identical. If verbose is true, from <=> to is printed.

copy(from, to, verbose = false)

Copies a file from to to using syscopy. If to is a directory, copies from to to/from. If verbose is true, from -> to is printed.

File.ctime(file_name) => time

Returns the change time for the named file (the time at which directory information about the file was changed, not the file itself).

   File.ctime("testfile")   #=> Wed Apr 09 08:53:13 CDT 2003
File.delete(file_name, ...) => integer
File.unlink(file_name, ...) => integer

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir.

File.directory?(file_name) => true or false

Returns true if the named file is a directory, false otherwise.

   File.directory?(".")
File.dirname(file_name ) → dir_name

Returns all components of the filename given in file_name except the last one. The filename must be formed using forward slashes (``/’’) regardless of the separator used on the local file system.

   File.dirname("/home/gumby/work/ruby.rb")   #=> "/home/gumby/work"
File.executable?(file_name) => true or false

Returns true if the named file is executable by the effective user id of this process.

File.executable_real?(file_name) => true or false

Returns true if the named file is executable by the real user id of this process.

File.exist?(file_name) => true or false
File.exists?(file_name) => true or false (obsolete)

Return true if the named file exists.

File.exist?(file_name) => true or false
File.exists?(file_name) => true or false (obsolete)

Return true if the named file exists.

File.expand_path(file_name [, dir_string] ) → abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a ``~’’, which expands to the process owner‘s home directory (the environment variable HOME must be set correctly). ``~user’’ expands to the named user‘s home directory.

   File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"
   File.expand_path("../../bin", "/tmp/x")   #=> "/bin"
File.extname(path) → string

Returns the extension (the portion of file name in path after the period).

   File.extname("test.rb")         #=> ".rb"
   File.extname("a/b/d/test.rb")   #=> ".rb"
   File.extname("test")            #=> ""
   File.extname(".profile")        #=> ""
File.file?(file_name) => true or false

Returns true if the named file exists and is a regular file.

File.fnmatch( pattern, path, [flags] ) => (true or false)
File.fnmatch?( pattern, path, [flags] ) => (true or false)

Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:

*: | Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp.
**: | Matches directories recursively or files expansively.
?: | Matches any one character. Equivalent to /.{1}/ in regexp.
[set]: | Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).
<code></code>: | Escapes the next metacharacter.

flags is a bitwise OR of the FNM_xxx parameters. The same glob pattern and flags are used by Dir::glob.

   File.fnmatch('cat',       'cat')        #=> true  : match entire string
   File.fnmatch('cat',       'category')   #=> false : only match partial string
   File.fnmatch('c{at,ub}s', 'cats')       #=> false : { } isn't supported

   File.fnmatch('c?t',     'cat')          #=> true  : '?' match only 1 character
   File.fnmatch('c??t',    'cat')          #=> false : ditto
   File.fnmatch('c*',      'cats')         #=> true  : '*' match 0 or more characters
   File.fnmatch('c*t',     'c/a/b/t')      #=> true  : ditto
   File.fnmatch('ca[a-z]', 'cat')          #=> true  : inclusive bracket expression
   File.fnmatch('ca[^t]',  'cat')          #=> false : exclusive bracket expression ('^' or '!')

   File.fnmatch('cat', 'CAT')                     #=> false : case sensitive
   File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true  : case insensitive

   File.fnmatch('?',   '/', File::FNM_PATHNAME)  #=> false : wildcard doesn't match '/' on FNM_PATHNAME
   File.fnmatch('*',   '/', File::FNM_PATHNAME)  #=> false : ditto
   File.fnmatch('[/]', '/', File::FNM_PATHNAME)  #=> false : ditto

   File.fnmatch('\?',   '?')                       #=> true  : escaped wildcard becomes ordinary
   File.fnmatch('\a',   'a')                       #=> true  : escaped ordinary remains ordinary
   File.fnmatch('\a',   '\a', File::FNM_NOESCAPE)  #=> true  : FNM_NOESACPE makes '\' ordinary
   File.fnmatch('[\?]', '?')                       #=> true  : can escape inside bracket expression

   File.fnmatch('*',   '.profile')                      #=> false : wildcard doesn't match leading
   File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)  #=> true    period by default.
   File.fnmatch('.*',  '.profile')                      #=> true

   rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
   File.fnmatch(rbfiles, 'main.rb')                    #=> false
   File.fnmatch(rbfiles, './main.rb')                  #=> false
   File.fnmatch(rbfiles, 'lib/song.rb')                #=> true
   File.fnmatch('**.rb', 'main.rb')                    #=> true
   File.fnmatch('**.rb', './main.rb')                  #=> false
   File.fnmatch('**.rb', 'lib/song.rb')                #=> true
   File.fnmatch('*',           'dave/.profile')                      #=> true

   pattern = '*' '/' '*'
   File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME)  #=> false
   File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true

   pattern = '**' '/' 'foo'
   File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME)     #=> true
   File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME)    #=> true
   File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME)  #=> true
   File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME)    #=> false
   File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
File.fnmatch( pattern, path, [flags] ) => (true or false)
File.fnmatch?( pattern, path, [flags] ) => (true or false)

Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:

*: | Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp.
**: | Matches directories recursively or files expansively.
?: | Matches any one character. Equivalent to /.{1}/ in regexp.
[set]: | Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).
<code></code>: | Escapes the next metacharacter.

flags is a bitwise OR of the FNM_xxx parameters. The same glob pattern and flags are used by Dir::glob.

   File.fnmatch('cat',       'cat')        #=> true  : match entire string
   File.fnmatch('cat',       'category')   #=> false : only match partial string
   File.fnmatch('c{at,ub}s', 'cats')       #=> false : { } isn't supported

   File.fnmatch('c?t',     'cat')          #=> true  : '?' match only 1 character
   File.fnmatch('c??t',    'cat')          #=> false : ditto
   File.fnmatch('c*',      'cats')         #=> true  : '*' match 0 or more characters
   File.fnmatch('c*t',     'c/a/b/t')      #=> true  : ditto
   File.fnmatch('ca[a-z]', 'cat')          #=> true  : inclusive bracket expression
   File.fnmatch('ca[^t]',  'cat')          #=> false : exclusive bracket expression ('^' or '!')

   File.fnmatch('cat', 'CAT')                     #=> false : case sensitive
   File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true  : case insensitive

   File.fnmatch('?',   '/', File::FNM_PATHNAME)  #=> false : wildcard doesn't match '/' on FNM_PATHNAME
   File.fnmatch('*',   '/', File::FNM_PATHNAME)  #=> false : ditto
   File.fnmatch('[/]', '/', File::FNM_PATHNAME)  #=> false : ditto

   File.fnmatch('\?',   '?')                       #=> true  : escaped wildcard becomes ordinary
   File.fnmatch('\a',   'a')                       #=> true  : escaped ordinary remains ordinary
   File.fnmatch('\a',   '\a', File::FNM_NOESCAPE)  #=> true  : FNM_NOESACPE makes '\' ordinary
   File.fnmatch('[\?]', '?')                       #=> true  : can escape inside bracket expression

   File.fnmatch('*',   '.profile')                      #=> false : wildcard doesn't match leading
   File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)  #=> true    period by default.
   File.fnmatch('.*',  '.profile')                      #=> true

   rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
   File.fnmatch(rbfiles, 'main.rb')                    #=> false
   File.fnmatch(rbfiles, './main.rb')                  #=> false
   File.fnmatch(rbfiles, 'lib/song.rb')                #=> true
   File.fnmatch('**.rb', 'main.rb')                    #=> true
   File.fnmatch('**.rb', './main.rb')                  #=> false
   File.fnmatch('**.rb', 'lib/song.rb')                #=> true
   File.fnmatch('*',           'dave/.profile')                      #=> true

   pattern = '*' '/' '*'
   File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME)  #=> false
   File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true

   pattern = '**' '/' 'foo'
   File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME)     #=> true
   File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME)    #=> true
   File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME)  #=> true
   File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME)    #=> false
   File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
File.ftype(file_name) => string

Identifies the type of the named file; the return string is one of ``file’’, ``directory’’, ``characterSpecial’’, ``blockSpecial’’, ``fifo’’, ``link’’, ``socket’’, or ``unknown’’.

   File.ftype("testfile")            #=> "file"
   File.ftype("/dev/tty")            #=> "characterSpecial"
   File.ftype("/tmp/.X11-unix/X0")   #=> "socket"
File.grpowned?(file_name) => true or false

Returns true if the named file exists and the effective group id of the calling process is the owner of the file. Returns false on Windows.

File.identical?(file_1, file_2) => true or false

Returns true if the named files are identical.

    open("a", "w") {}
    p File.identical?("a", "a")      #=> true
    p File.identical?("a", "./a")    #=> true
    File.link("a", "b")
    p File.identical?("a", "b")      #=> true
    File.symlink("a", "c")
    p File.identical?("a", "c")      #=> true
    open("d", "w") {}
    p File.identical?("a", "d")      #=> false
install(from, to, mode = nil, verbose = false)

If src is not the same as dest, copies it and changes the permission mode to mode. If dest is a directory, destination is dest/src. If mode is not set, default is used. If verbose is set to true, the name of each file copied will be printed.

File.join(string, ...) → path

Returns a new string formed by joining the strings using File::SEPARATOR.

   File.join("usr", "mail", "gumby")   #=> "usr/mail/gumby"
File.lchmod(mode_int, file_name, ...) => integer

Equivalent to File::chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). Often not available.

file.lchown(owner_int, group_int, file_name,..) => integer

Equivalent to File::chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). Often not available. Returns number of files in the argument list.

File.link(old_name, new_name) => 0

Creates a new name for an existing file using a hard link. Will not overwrite new_name if it already exists (raising a subclass of SystemCallError). Not available on all platforms.

   File.link("testfile", ".testfile")   #=> 0
   IO.readlines(".testfile")[0]         #=> "This is line one\n"
File.lstat(file_name) => stat

Same as File::stat, but does not follow the last symbolic link. Instead, reports on the link itself.

   File.symlink("testfile", "link2test")   #=> 0
   File.stat("testfile").size              #=> 66
   File.lstat("link2test").size            #=> 8
   File.stat("link2test").size             #=> 66
makedirs(*dirs)

Creates a directory and all its parent directories. For example,

    File.makedirs '/usr/lib/ruby'

causes the following directories to be made, if they do not exist.

    * /usr
    * /usr/lib
    * /usr/lib/ruby

You can pass several directories, each as a parameter. If the last parameter isn‘t a String, verbose mode will be enabled.

move(from, to, verbose = false)

Moves a file from to to using syscopy. If to is a directory, copies from from to to/from. If verbose is true, from -> to is printed.

File.mtime(file_name) => time

Returns the modification time for the named file as a Time object.

   File.mtime("testfile")   #=> Tue Apr 08 12:58:04 CDT 2003
File.new(filename, mode="r") => file
File.new(filename [, mode [, perm]]) => file

Opens the file named by filename according to mode (default is ``r’’) and returns a new File object. See the description of class IO for a description of mode. The file mode may optionally be specified as a Fixnum by or-ing together the flags (O_RDONLY etc, again described under IO). Optional permission bits may be given in perm. These mode and permission bits are platform dependent; on Unix systems, see open(2) for details.

   f = File.new("testfile", "r")
   f = File.new("newfile",  "w+")
   f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
File.owned?(file_name) => true or false

Returns true if the named file exists and the effective used id of the calling process is the owner of the file.

File.pipe?(file_name) => true or false

Returns true if the named file is a pipe.

File.readable?(file_name) => true or false

Returns true if the named file is readable by the effective user id of this process.

File.readable_real?(file_name) => true or false

Returns true if the named file is readable by the real user id of this process.

File.readlink(link_name) → file_name

Returns the name of the file referenced by the given link. Not available on all platforms.

   File.symlink("testfile", "link2test")   #=> 0
   File.readlink("link2test")              #=> "testfile"
File.rename(old_name, new_name) => 0

Renames the given file to the new name. Raises a SystemCallError if the file cannot be renamed.

   File.rename("afile", "afile.bak")   #=> 0
safe_unlink(*files)

Removes a list of files. Each parameter should be the name of the file to delete. If the last parameter isn‘t a String, verbose mode will be enabled. Returns the number of files deleted.

File.setgid?(file_name) => true or false

Returns true if the named file has the setgid bit set.

File.setuid?(file_name) => true or false

Returns true if the named file has the setuid bit set.

File.size(file_name) => integer

Returns the size of file_name.

File.size?(file_name) => Integer or nil

Returns nil if file_name doesn‘t exist or has zero size, the size of the file otherwise.

File.socket?(file_name) => true or false

Returns true if the named file is a socket.

File.split(file_name) => array

Splits the given string into a directory and a file component and returns them in a two-element array. See also File::dirname and File::basename.

   File.split("/home/gumby/.profile")   #=> ["/home/gumby", ".profile"]
File.stat(file_name) => stat

Returns a File::Stat object for the named file (see File::Stat).

   File.stat("testfile").mtime   #=> Tue Apr 08 12:58:04 CDT 2003
File.sticky?(file_name) => true or false

Returns true if the named file has the sticky bit set.

File.symlink(old_name, new_name) => 0

Creates a symbolic link called new_name for the existing file old_name. Raises a NotImplemented exception on platforms that do not support symbolic links.

   File.symlink("testfile", "link2test")   #=> 0
File.symlink?(file_name) => true or false

Returns true if the named file is a symbolic link.

syscopy(from, to)

Copies a file from to to. If to is a directory, copies from to to/from.

File.truncate(file_name, integer) => 0

Truncates the file file_name to be at most integer bytes long. Not available on all platforms.

   f = File.new("out", "w")
   f.write("1234567890")     #=> 10
   f.close                   #=> nil
   File.truncate("out", 5)   #=> 0
   File.size("out")          #=> 5
File.umask() => integer
File.umask(integer) => integer

Returns the current umask value for this process. If the optional argument is given, set the umask to that value and return the previous value. Umask values are subtracted from the default permissions, so a umask of 0222 would make a file read-only for everyone.

   File.umask(0006)   #=> 18
   File.umask         #=> 6
File.delete(file_name, ...) => integer
File.unlink(file_name, ...) => integer

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir.

File.utime(atime, mtime, file_name,...) => integer

Sets the access and modification times of each named file to the first two arguments. Returns the number of file names in the argument list.

File.writable?(file_name) => true or false

Returns true if the named file is writable by the effective user id of this process.

File.writable_real?(file_name) => true or false

Returns true if the named file is writable by the real user id of this process.

File.zero?(file_name) => true or false

Returns true if the named file exists and has a zero size.

Public Instance methods

file.atime => time

Returns the last access time (a Time object)

 for <i>file</i>, or epoch if <i>file</i> has not been accessed.

   File.new("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969
file.chmod(mode_int) => 0

Changes permission bits on file to the bit pattern represented by mode_int. Actual effects are platform dependent; on Unix systems, see chmod(2) for details. Follows symbolic links. Also see File#lchmod.

   f = File.new("out", "w");
   f.chmod(0644)   #=> 0
file.chown(owner_int, group_int ) => 0

Changes the owner and group of file to the given numeric owner and group id‘s. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file‘s group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Follows symbolic links. See also File#lchown.

   File.new("testfile").chown(502, 1000)
file.ctime → time

Returns the change time for file (that is, the time directory information about the file was changed, not the file itself).

   File.new("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003
file.flock (locking_constant ) => 0 or false

Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms.

Locking constants (in class File):

   LOCK_EX   | Exclusive lock. Only one process may hold an
             | exclusive lock for a given file at a time.
   ----------+------------------------------------------------
   LOCK_NB   | Don't block when locking. May be combined
             | with other lock options using logical or.
   ----------+------------------------------------------------
   LOCK_SH   | Shared lock. Multiple processes may each hold a
             | shared lock for a given file at the same time.
   ----------+------------------------------------------------
   LOCK_UN   | Unlock.

Example:

   File.new("testfile").flock(File::LOCK_UN)   #=> 0
file.lstat => stat

Same as IO#stat, but does not follow the last symbolic link. Instead, reports on the link itself.

   File.symlink("testfile", "link2test")   #=> 0
   File.stat("testfile").size              #=> 66
   f = File.new("link2test")
   f.lstat.size                            #=> 8
   f.stat.size                             #=> 66
file.mtime → time

Returns the modification time for file.

   File.new("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003
o_chmod(p1)

Alias for chmod

file.path → filename

Returns the pathname used to create file as a string. Does not normalize the name.

   File.new("testfile").path               #=> "testfile"
   File.new("/tmp/../tmp/xxx", "w").path   #=> "/tmp/../tmp/xxx"
file.truncate(integer) => 0

Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.

   f = File.new("out", "w")
   f.syswrite("1234567890")   #=> 10
   f.truncate(5)              #=> 0
   f.close()                  #=> nil
   File.size("out")           #=> 5


Module: File::Constants

Module | File::Constants
In: | file.c


Class: File::Stat

Class | File::Stat
In: | file.c lib/pp.rb
Parent: | Object

Objects of class File::Stat encapsulate common status information for File objects. The information is recorded at the moment the File::Stat object is created; changes made to the file after that point will not be reflected. File::Stat objects are returned by IO#stat, File::stat, File#lstat, and File::lstat. Many of these methods return platform-specific values, and not all values are meaningful on all systems. See also Kernel#test.

Methods

<=> atime blksize blockdev? blocks chardev? ctime dev dev_major dev_minor directory? executable? executable_real? file? ftype gid grpowned? ino inspect mode mtime new nlink owned? pipe? pretty_print rdev rdev_major rdev_minor readable? readable_real? setgid? setuid? size size? socket? sticky? symlink? uid writable? writable_real? zero?

Included Modules

Comparable

Public Class methods

  File::Stat.new(file_name)  => stat

Create a File::Stat object for the given file name (raising an exception if the file doesn‘t exist).

Public Instance methods

stat <=> other_stat => -1, 0, 1

Compares File::Stat objects by comparing their respective modification times.

   f1 = File.new("f1", "w")
   sleep 1
   f2 = File.new("f2", "w")
   f1.stat <=> f2.stat   #=> -1
stat.atime => time

Returns the last access time for this file as an object of class Time.

   File.stat("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969
stat.blksize => integer or nil

Returns the native file system‘s block size. Will return nil on platforms that don‘t support this information.

   File.stat("testfile").blksize   #=> 4096
stat.blockdev? => true or false

Returns true if the file is a block device, false if it isn‘t or if the operating system doesn‘t support this feature.

   File.stat("testfile").blockdev?    #=> false
   File.stat("/dev/hda1").blockdev?   #=> true
stat.blocks => integer or nil

Returns the number of native file system blocks allocated for this file, or nil if the operating system doesn‘t support this feature.

   File.stat("testfile").blocks   #=> 2
stat.chardev? => true or false

Returns true if the file is a character device, false if it isn‘t or if the operating system doesn‘t support this feature.

   File.stat("/dev/tty").chardev?   #=> true
stat.ctime → aTime

Returns the change time for stat (that is, the time directory information about the file was changed, not the file itself).

   File.stat("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003
stat.dev => fixnum

Returns an integer representing the device on which stat resides.

   File.stat("testfile").dev   #=> 774
stat.dev_major => fixnum

Returns the major part of File_Stat#dev or nil.

   File.stat("/dev/fd1").dev_major   #=> 2
   File.stat("/dev/tty").dev_major   #=> 5
stat.dev_minor => fixnum

Returns the minor part of File_Stat#dev or nil.

   File.stat("/dev/fd1").dev_minor   #=> 1
   File.stat("/dev/tty").dev_minor   #=> 0
stat.directory? => true or false

Returns true if stat is a directory, false otherwise.

   File.stat("testfile").directory?   #=> false
   File.stat(".").directory?          #=> true
stat.executable? => true or false

Returns true if stat is executable or if the operating system doesn‘t distinguish executable files from nonexecutable files. The tests are made using the effective owner of the process.

   File.stat("testfile").executable?   #=> false
stat.executable_real? => true or false

Same as executable?, but tests using the real owner of the process.

stat.file? => true or false

Returns true if stat is a regular file (not a device file, pipe, socket, etc.).

   File.stat("testfile").file?   #=> true
stat.ftype => string

Identifies the type of stat. The return string is one of: ``file’’, ``directory’’, ``characterSpecial’’, ``blockSpecial’’, ``fifo’’, ``link’’, ``socket’’, or ``unknown’’.

   File.stat("/dev/tty").ftype   #=> "characterSpecial"
stat.gid => fixnum

Returns the numeric group id of the owner of stat.

   File.stat("testfile").gid   #=> 500
stat.grpowned? => true or false

Returns true if the effective group id of the process is the same as the group id of stat. On Windows NT, returns false.

   File.stat("testfile").grpowned?      #=> true
   File.stat("/etc/passwd").grpowned?   #=> false
stat.ino => fixnum

Returns the inode number for stat.

   File.stat("testfile").ino   #=> 1083669
stat.inspect => string

Produce a nicely formatted description of stat.

  File.stat("/etc/passwd").inspect
     #=> "#<File::Stat dev=0xe000005, ino=1078078, mode=0100644,
          nlink=1, uid=0, gid=0, rdev=0x0, size=1374, blksize=4096,
          blocks=8, atime=Wed Dec 10 10:16:12 CST 2003,
          mtime=Fri Sep 12 15:41:41 CDT 2003,
          ctime=Mon Oct 27 11:20:27 CST 2003>"
stat.mode => fixnum

Returns an integer representing the permission bits of stat. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

   File.chmod(0644, "testfile")   #=> 1
   s = File.stat("testfile")
   sprintf("%o", s.mode)          #=> "100644"
stat.mtime → aTime

Returns the modification time of stat.

   File.stat("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003
stat.nlink => fixnum

Returns the number of hard links to stat.

   File.stat("testfile").nlink             #=> 1
   File.link("testfile", "testfile.bak")   #=> 0
   File.stat("testfile").nlink             #=> 2
stat.owned? => true or false

Returns true if the effective user id of the process is the same as the owner of stat.

   File.stat("testfile").owned?      #=> true
   File.stat("/etc/passwd").owned?   #=> false
stat.pipe? => true or false

Returns true if the operating system supports pipes and stat is a pipe; false otherwise.

pretty_print(q)
stat.rdev => fixnum or nil

Returns an integer representing the device type on which stat resides. Returns nil if the operating system doesn‘t support this feature.

   File.stat("/dev/fd1").rdev   #=> 513
   File.stat("/dev/tty").rdev   #=> 1280
stat.rdev_major => fixnum

Returns the major part of File_Stat#rdev or nil.

   File.stat("/dev/fd1").rdev_major   #=> 2
   File.stat("/dev/tty").rdev_major   #=> 5
stat.rdev_minor => fixnum

Returns the minor part of File_Stat#rdev or nil.

   File.stat("/dev/fd1").rdev_minor   #=> 1
   File.stat("/dev/tty").rdev_minor   #=> 0
stat.readable? => true or false

Returns true if stat is readable by the effective user id of this process.

   File.stat("testfile").readable?   #=> true
stat.readable_real? → true or false

Returns true if stat is readable by the real user id of this process.

   File.stat("testfile").readable_real?   #=> true
stat.setgid? => true or false

Returns true if stat has the set-group-id permission bit set, false if it doesn‘t or if the operating system doesn‘t support this feature.

   File.stat("/usr/sbin/lpc").setgid?   #=> true
stat.setuid? => true or false

Returns true if stat has the set-user-id permission bit set, false if it doesn‘t or if the operating system doesn‘t support this feature.

   File.stat("/bin/su").setuid?   #=> true
stat.size => fixnum

Returns the size of stat in bytes.

   File.stat("testfile").size   #=> 66
state.size => integer

Returns the size of stat in bytes.

   File.stat("testfile").size   #=> 66
stat.socket? => true or false

Returns true if stat is a socket, false if it isn‘t or if the operating system doesn‘t support this feature.

   File.stat("testfile").socket?   #=> false
stat.sticky? => true or false

Returns true if stat has its sticky bit set, false if it doesn‘t or if the operating system doesn‘t support this feature.

   File.stat("testfile").sticky?   #=> false
stat.symlink? => true or false

Returns true if stat is a symbolic link, false if it isn‘t or if the operating system doesn‘t support this feature. As File::stat automatically follows symbolic links, symlink? will always be false for an object returned by File::stat.

   File.symlink("testfile", "alink")   #=> 0
   File.stat("alink").symlink?         #=> false
   File.lstat("alink").symlink?        #=> true
stat.uid => fixnum

Returns the numeric user id of the owner of stat.

   File.stat("testfile").uid   #=> 501
stat.writable? → true or false

Returns true if stat is writable by the effective user id of this process.

   File.stat("testfile").writable?   #=> true
stat.writable_real? → true or false

Returns true if stat is writable by the real user id of this process.

   File.stat("testfile").writable_real?   #=> true
stat.zero? => true or false

Returns true if stat is a zero-length file; false otherwise.

   File.stat("testfile").zero?   #=> false


Class: Float

Class | Float
In: | numeric.c lib/rexml/xpath_parser.rb lib/yaml/rubytypes.rb
Parent: | Numeric

Float objects represent real numbers using the native architecture‘s double-precision floating point representation.

Methods

% * ** + - -@ / < <= <=> == > >= abs ceil coerce dclone divmod eql? finite? floor hash induced_from infinite? modulo nan? round to_f to_i to_int to_s to_yaml truncate zero?

Included Modules

Precision

Constants

ROUNDS | = | INT2FIX(FLT_ROUNDS)
RADIX | = | INT2FIX(FLT_RADIX)
MANT_DIG | = | INT2FIX(DBL_MANT_DIG)
DIG | = | INT2FIX(DBL_DIG)
MIN_EXP | = | INT2FIX(DBL_MIN_EXP)
MAX_EXP | = | INT2FIX(DBL_MAX_EXP)
MIN_10_EXP | = | INT2FIX(DBL_MIN_10_EXP)
MAX_10_EXP | = | INT2FIX(DBL_MAX_10_EXP)
MIN | = | rb_float_new(DBL_MIN)
MAX | = | rb_float_new(DBL_MAX)
EPSILON | = | rb_float_new(DBL_EPSILON)

Public Class methods

Float.induced_from(obj) => float

Convert obj to a float.

Public Instance methods

flt % other => float
flt.modulo(other) => float

Return the modulo after division of flt by other.

   6543.21.modulo(137)      #=> 104.21
   6543.21.modulo(137.24)   #=> 92.9299999999996
float * other => float

Returns a new float which is the product of float and other.

 flt ** other   => float

Raises float the other power.

float + other => float

Returns a new float which is the sum of float and other.

float + other => float

Returns a new float which is the difference of float and other.

-float => float

Returns float, negated.

float / other => float

Returns a new float which is the result of dividing float by other.

flt < other => true or false

true if flt is less than other.

flt <= other => true or false

true if flt is less than or equal to other.

flt <=> numeric => -1, 0, +1

Returns -1, 0, or +1 depending on whether flt is less than, equal to, or greater than numeric. This is the basis for the tests in Comparable.

flt == obj => true or false

Returns true only if obj has the same value as flt. Contrast this with Float#eql?, which requires obj to be a Float.

   1.0 == 1   #=> true
flt > other => true or false

true if flt is greater than other.

flt >= other => true or false

true if flt is greater than or equal to other.

flt.abs => float

Returns the absolute value of flt.

   (-34.56).abs   #=> 34.56
   -34.56.abs     #=> 34.56
flt.ceil => integer

Returns the smallest Integer greater than or equal to flt.

   1.2.ceil      #=> 2
   2.0.ceil      #=> 2
   (-1.2).ceil   #=> -1
   (-2.0).ceil   #=> -2
coerce(p1)

MISSING: documentation

dclone()
flt.divmod(numeric) => array

See Numeric#divmod.

flt.eql?(obj) => true or false

Returns true only if obj is a Float with the same value as flt. Contrast this with Float#==, which performs type conversions.

   1.0.eql?(1)   #=> false
flt.finite? → true or false

Returns true if flt is a valid IEEE floating point number (it is not infinite, and nan? is false).

flt.floor => integer

Returns the largest integer less than or equal to flt.

   1.2.floor      #=> 1
   2.0.floor      #=> 2
   (-1.2).floor   #=> -2
   (-2.0).floor   #=> -2
flt.hash => integer

Returns a hash code for this float.

flt.infinite? → nil, -1, +1

Returns nil, -1, or +1 depending on whether flt is finite, -infinity, or +infinity.

   (0.0).infinite?        #=> nil
   (-1.0/0.0).infinite?   #=> -1
   (+1.0/0.0).infinite?   #=> 1
flt % other => float
flt.modulo(other) => float

Return the modulo after division of flt by other.

   6543.21.modulo(137)      #=> 104.21
   6543.21.modulo(137.24)   #=> 92.9299999999996
flt.nan? → true or false

Returns true if flt is an invalid IEEE floating point number.

   a = -1.0      #=> -1.0
   a.nan?        #=> false
   a = 0.0/0.0   #=> NaN
   a.nan?        #=> true
flt.round => integer

Rounds flt to the nearest integer. Equivalent to:

   def round
     return (self+0.5).floor if self > 0.0
     return (self-0.5).ceil  if self < 0.0
     return 0
   end

   1.5.round      #=> 2
   (-1.5).round   #=> -2
flt.to_f => flt

As flt is already a float, returns self.

flt.to_i => integer
flt.to_int => integer
flt.truncate => integer

Returns flt truncated to an Integer.

flt.to_i => integer
flt.to_int => integer
flt.truncate => integer

Returns flt truncated to an Integer.

flt.to_s => string

Returns a string containing a representation of self. As well as a fixed or exponential form of the number, the call may return ``NaN’’, ``Infinity’’, and ``-Infinity’’.

to_yaml( opts = {} )
flt.to_i => integer
flt.to_int => integer
flt.truncate => integer

Returns flt truncated to an Integer.

flt.zero? → true or false

Returns true if flt is 0.0.


Class: Hash

Class | Hash
In: | hash.c lib/pp.rb lib/yaml/rubytypes.rb
Parent: | Object

A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.

Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil.

Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

  class MyClass
    attr_reader :str
    def initialize(str)
      @str = str
    end
    def eql?(o)
      o.is_a?(MyClass) && str == o.str
    end
    def hash
      @str.hash
    end
  end

  a = MyClass.new("some string")
  b = MyClass.new("some string")
  a.eql? b  #=> true

  h = {}

  h[a] = 1
  h[a]      #=> 1
  h[b]      #=> 1

  h[b] = 2
  h[a]      #=> 2
  h[b]      #=> 2

Methods

== [] [] []= clear default default= default_proc delete delete_if each each_key each_pair each_value empty? fetch has_key? has_value? include? index indexes indices initialize_copy inspect invert key? keys length member? merge merge! new pretty_print pretty_print_cycle rehash reject reject! replace select shift size sort store to_a to_hash to_s to_yaml update value? values values_at yaml_initialize

Included Modules

Enumerable

Public Class methods

Hash[ [key =>|, value]* ] => hash

Creates a new hash populated with the given objects. Equivalent to the literal { key, value, … }. Keys and values occur in pairs, so there must be an even number of arguments.

   Hash["a", 100, "b", 200]       #=> {"a"=>100, "b"=>200}
   Hash["a" => 100, "b" => 200]   #=> {"a"=>100, "b"=>200}
   { "a" => 100, "b" => 200 }     #=> {"a"=>100, "b"=>200}
Hash.new => hash
Hash.new(obj) => aHash
Hash.new {|hash, key| block } => aHash

Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn‘t correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block‘s responsibility to store the value in the hash if required.

   h = Hash.new("Go Fish")
   h["a"] = 100
   h["b"] = 200
   h["a"]           #=> 100
   h["c"]           #=> "Go Fish"
   # The following alters the single default object
   h["c"].upcase!   #=> "GO FISH"
   h["d"]           #=> "GO FISH"
   h.keys           #=> ["a", "b"]

   # While this creates a new default object each time
   h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
   h["c"]           #=> "Go Fish: c"
   h["c"].upcase!   #=> "GO FISH: C"
   h["d"]           #=> "Go Fish: d"
   h.keys           #=> ["c", "d"]

Public Instance methods

hsh == other_hash => true or false

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#==) the corresponding elements in the other hash.

   h1 = { "a" => 1, "c" => 2 }
   h2 = { 7 => 35, "c" => 2, "a" => 1 }
   h3 = { "a" => 1, "c" => 2, 7 => 35 }
   h4 = { "a" => 1, "d" => 2, "f" => 35 }
   h1 == h2   #=> false
   h2 == h3   #=> true
   h3 == h4   #=> false
hsh[key] => value

Element Reference—Retrieves the value object corresponding to the key object. If not found, returns the a default value (see Hash::new for details).

   h = { "a" => 100, "b" => 200 }
   h["a"]   #=> 100
   h["c"]   #=> nil
hsh[key] = value => value
hsh.store(key, value) => value

Element Assignment—Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).

   h = { "a" => 100, "b" => 200 }
   h["a"] = 9
   h["c"] = 4
   h   #=> {"a"=>9, "b"=>200, "c"=>4}
hsh.clear → hsh

Removes all key-value pairs from hsh.

   h = { "a" => 100, "b" => 200 }   #=> {"a"=>100, "b"=>200}
   h.clear                          #=> {}
hsh.default(key=nil) => obj

Returns the default value, the value that would be returned by hsh[key] if key did not exist in hsh. See also Hash::new and Hash#default=.

   h = Hash.new                            #=> {}
   h.default                               #=> nil
   h.default(2)                            #=> nil

   h = Hash.new("cat")                     #=> {}
   h.default                               #=> "cat"
   h.default(2)                            #=> "cat"

   h = Hash.new {|h,k| h[k] = k.to_i*10}   #=> {}
   h.default                               #=> 0
   h.default(2)                            #=> 20
hsh.default = obj => hsh

Sets the default value, the value returned for a key that does not exist in the hash. It is not possible to set the a default to a Proc that will be executed on each key lookup.

   h = { "a" => 100, "b" => 200 }
   h.default = "Go fish"
   h["a"]     #=> 100
   h["z"]     #=> "Go fish"
   # This doesn't do what you might hope...
   h.default = proc do |hash, key|
     hash[key] = key + key
   end
   h[2]       #=> #<Proc:0x401b3948@-:6>
   h["cat"]   #=> #<Proc:0x401b3948@-:6>
hsh.default_proc → anObject

If Hash::new was invoked with a block, return that block, otherwise return nil.

   h = Hash.new {|h,k| h[k] = k*k }   #=> {}
   p = h.default_proc                 #=> #<Proc:0x401b3d08@-:1>
   a = []                             #=> []
   p.call(a, 2)
   a                                  #=> [nil, nil, 4]
hsh.delete(key) => value
hsh.delete(key) {| key | block } => value

Deletes and returns a key-value pair from hsh whose key is equal to key. If the key is not found, returns the default value. If the optional code block is given and the key is not found, pass in the key and return the result of block.

   h = { "a" => 100, "b" => 200 }
   h.delete("a")                              #=> 100
   h.delete("z")                              #=> nil
   h.delete("z") { |el| "#{el} not found" }   #=> "z not found"
hsh.delete_if {| key, value | block } → hsh

Deletes every key-value pair from hsh for which block evaluates to true.

   h = { "a" => 100, "b" => 200, "c" => 300 }
   h.delete_if {|key, value| key >= "b" }   #=> {"a"=>100}
hsh.each {| key, value | block } → hsh

Calls block once for each key in hsh, passing the key and value to the block as a two-element array. Because of the assignment semantics of block parameters, these elements will be split out if the block has two formal parameters. Also see Hash.each_pair, which will be marginally more efficient for blocks with two parameters.

   h = { "a" => 100, "b" => 200 }
   h.each {|key, value| puts "#{key} is #{value}" }

produces:

   a is 100
   b is 200
hsh.each_key {| key | block } → hsh

Calls block once for each key in hsh, passing the key as a parameter.

   h = { "a" => 100, "b" => 200 }
   h.each_key {|key| puts key }

produces:

   a
   b
hsh.each_pair {| key_value_array | block } → hsh

Calls block once for each key in hsh, passing the key and value as parameters.

   h = { "a" => 100, "b" => 200 }
   h.each_pair {|key, value| puts "#{key} is #{value}" }

produces:

   a is 100
   b is 200
hsh.each_value {| value | block } → hsh

Calls block once for each key in hsh, passing the value as a parameter.

   h = { "a" => 100, "b" => 200 }
   h.each_value {|value| puts value }

produces:

   100
   200
hsh.empty? => true or false

Returns true if hsh contains no key-value pairs.

   {}.empty?   #=> true
hsh.fetch(key [, default] ) => obj
hsh.fetch(key) {| key | block } => obj

Returns a value from the hash for the given key. If the key can‘t be found, there are several options: With no other arguments, it will raise an IndexError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.

   h = { "a" => 100, "b" => 200 }
   h.fetch("a")                            #=> 100
   h.fetch("z", "go fish")                 #=> "go fish"
   h.fetch("z") { |el| "go fish, #{el}"}   #=> "go fish, z"

The following example shows that an exception is raised if the key is not found and a default value is not supplied.

   h = { "a" => 100, "b" => 200 }
   h.fetch("z")

produces:

   prog.rb:2:in `fetch': key not found (IndexError)
    from prog.rb:2
hsh.has_key?(key) => true or false
hsh.include?(key) => true or false
hsh.key?(key) => true or false
hsh.member?(key) => true or false

Returns true if the given key is present in hsh.

   h = { "a" => 100, "b" => 200 }
   h.has_key?("a")   #=> true
   h.has_key?("z")   #=> false
hsh.has_value?(value) => true or false
hsh.value?(value) => true or false

Returns true if the given value is present for some key in hsh.

   h = { "a" => 100, "b" => 200 }
   h.has_value?(100)   #=> true
   h.has_value?(999)   #=> false
hsh.has_key?(key) => true or false
hsh.include?(key) => true or false
hsh.key?(key) => true or false
hsh.member?(key) => true or false

Returns true if the given key is present in hsh.

   h = { "a" => 100, "b" => 200 }
   h.has_key?("a")   #=> true
   h.has_key?("z")   #=> false
hsh.index(value) => key

Returns the key for a given value. If not found, returns nil.

   h = { "a" => 100, "b" => 200 }
   h.index(200)   #=> "b"
   h.index(999)   #=> nil
hsh.indexes(key, ...) => array
hsh.indices(key, ...) => array

Deprecated in favor of Hash#select.

hsh.indexes(key, ...) => array
hsh.indices(key, ...) => array

Deprecated in favor of Hash#select.

hsh.replace(other_hash) → hsh

Replaces the contents of hsh with the contents of other_hash.

   h = { "a" => 100, "b" => 200 }
   h.replace({ "c" => 300, "d" => 400 })   #=> {"c"=>300, "d"=>400}
hsh.inspect => string

Return the contents of this hash as a string.

hsh.invert → aHash

Returns a new hash created by using hsh‘s values as keys, and the keys as values.

   h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
   h.invert   #=> {0=>"a", 100=>"n", 200=>"d", 300=>"y"}
hsh.has_key?(key) => true or false
hsh.include?(key) => true or false
hsh.key?(key) => true or false
hsh.member?(key) => true or false

Returns true if the given key is present in hsh.

   h = { "a" => 100, "b" => 200 }
   h.has_key?("a")   #=> true
   h.has_key?("z")   #=> false
hsh.keys => array

Returns a new array populated with the keys from this hash. See also Hash#values.

   h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
   h.keys   #=> ["a", "b", "c", "d"]
hsh.length => fixnum
hsh.size => fixnum

Returns the number of key-value pairs in the hash.

   h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
   h.length        #=> 4
   h.delete("a")   #=> 200
   h.length        #=> 3
hsh.has_key?(key) => true or false
hsh.include?(key) => true or false
hsh.key?(key) => true or false
hsh.member?(key) => true or false

Returns true if the given key is present in hsh.

   h = { "a" => 100, "b" => 200 }
   h.has_key?("a")   #=> true
   h.has_key?("z")   #=> false
hsh.merge(other_hash) → a_hash
hsh.merge(other_hash){|key, oldval, newval| block} → a_hash

Returns a new hash containing the contents of other_hash and the contents of hsh, overwriting entries in hsh with duplicate keys with those from other_hash.

   h1 = { "a" => 100, "b" => 200 }
   h2 = { "b" => 254, "c" => 300 }
   h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
   h1             #=> {"a"=>100, "b"=>200}
hsh.merge!(other_hash) => hsh
hsh.update(other_hash) => hsh
hsh.merge!(other_hash){|key, oldval, newval| block} => hsh
hsh.update(other_hash){|key, oldval, newval| block} => hsh

Adds the contents of other_hash to hsh, overwriting entries with duplicate keys with those from other_hash.

   h1 = { "a" => 100, "b" => 200 }
   h2 = { "b" => 254, "c" => 300 }
   h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
pretty_print(q)
pretty_print_cycle(q)
hsh.rehash → hsh

Rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted, this method will reindex hsh. If Hash#rehash is called while an iterator is traversing the hash, an IndexError will be raised in the iterator.

   a = [ "a", "b" ]
   c = [ "c", "d" ]
   h = { a => 100, c => 300 }
   h[a]       #=> 100
   a[0] = "z"
   h[a]       #=> nil
   h.rehash   #=> {["z", "b"]=>100, ["c", "d"]=>300}
   h[a]       #=> 100
hsh.reject {| key, value | block } → a_hash

Same as Hash#delete_if, but works on (and returns) a copy of the hsh. Equivalent to hsh.dup.delete_if.

hsh.reject! {| key, value | block } → hsh or nil

Equivalent to Hash#delete_if, but returns nil if no changes were made.

hsh.replace(other_hash) → hsh

Replaces the contents of hsh with the contents of other_hash.

   h = { "a" => 100, "b" => 200 }
   h.replace({ "c" => 300, "d" => 400 })   #=> {"c"=>300, "d"=>400}
hsh.select {|key, value| block} => array

Returns a new array consisting of [key,value] pairs for which the block returns true. Also see Hash.values_at.

   h = { "a" => 100, "b" => 200, "c" => 300 }
   h.select {|k,v| k > "a"}  #=> [["b", 200], ["c", 300]]
   h.select {|k,v| v < 200}  #=> [["a", 100]]
hsh.shift → anArray or obj

Removes a key-value pair from hsh and returns it as the two-item array [ key, value ], or the hash‘s default value if the hash is empty.

   h = { 1 => "a", 2 => "b", 3 => "c" }
   h.shift   #=> [1, "a"]
   h         #=> {2=>"b", 3=>"c"}
hsh.length => fixnum
hsh.size => fixnum

Returns the number of key-value pairs in the hash.

   h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
   h.length        #=> 4
   h.delete("a")   #=> 200
   h.length        #=> 3
hsh.sort => array
hsh.sort {| a, b | block } => array

Converts hsh to a nested array of [ key, value ] arrays and sorts it, using Array#sort.

   h = { "a" => 20, "b" => 30, "c" => 10  }
   h.sort                       #=> [["a", 20], ["b", 30], ["c", 10]]
   h.sort {|a,b| a[1]<=>b[1]}   #=> [["c", 10], ["a", 20], ["b", 30]]
hsh[key] = value => value
hsh.store(key, value) => value

Element Assignment—Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).

   h = { "a" => 100, "b" => 200 }
   h["a"] = 9
   h["c"] = 4
   h   #=> {"a"=>9, "b"=>200, "c"=>4}
hsh.to_a → array

Converts hsh to a nested array of [ key, value ] arrays.

   h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
   h.to_a   #=> [["a", 100], ["c", 300], ["d", 400]]
hsh.to_hash => hsh

Returns self.

hsh.to_s => string

Converts hsh to a string by converting the hash to an array of [ key, value ] pairs and then converting that array to a string using Array#join with the default separator.

   h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
   h.to_s   #=> "a100c300d400"
to_yaml( opts = {} )
hsh.merge!(other_hash) => hsh
hsh.update(other_hash) => hsh
hsh.merge!(other_hash){|key, oldval, newval| block} => hsh
hsh.update(other_hash){|key, oldval, newval| block} => hsh

Adds the contents of other_hash to hsh, overwriting entries with duplicate keys with those from other_hash.

   h1 = { "a" => 100, "b" => 200 }
   h2 = { "b" => 254, "c" => 300 }
   h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
hsh.has_value?(value) => true or false
hsh.value?(value) => true or false

Returns true if the given value is present for some key in hsh.

   h = { "a" => 100, "b" => 200 }
   h.has_value?(100)   #=> true
   h.has_value?(999)   #=> false
hsh.values => array

Returns a new array populated with the values from hsh. See also Hash#keys.

   h = { "a" => 100, "b" => 200, "c" => 300 }
   h.values   #=> [100, 200, 300]
hsh.values_at(key, ...) => array

Return an array containing the values associated with the given keys. Also see Hash.select.

  h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
  h.values_at("cow", "cat")  #=> ["bovine", "feline"]
yaml_initialize( tag, val )


Class: IO

Class | IO
In: | io.c lib/readbytes.rb lib/scanf.rb

Class IO is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream.

Many of the examples in this section use class File, the only standard subclass of IO. The two classes are closely associated.

As used in this section, portname may take any of the following forms.

  • A plain string represents a filename suitable for the underlying operating system.
  • A string starting with ``|’’ indicates a subprocess. The remainder of the string following the ``|’’ is invoked as a process with appropriate input/output channels connected to it.
  • A string equal to ``|-’’ will create another Ruby instance as a subprocess.

Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename ``/gumby/ruby/test.rb’’ will be opened as ``\gumby\ruby\test.rb’’. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:

   "c:\\gumby\\ruby\\test.rb"

Our examples here will use the Unix-style forward slashes; File::SEPARATOR can be used to get the platform-specific separator character.

I/O ports may be opened in any one of several different modes, which are shown in this section as mode. The mode may either be a Fixnum or a String. If numeric, it should be one of the operating system specific constants (O_RDONLY, O_WRONLY, O_RDWR, O_APPEND and so on). See man open(2) for more information.

If the mode is given as a String, it must be one of the values listed in the following table.

  Mode |  Meaning
  -----+--------------------------------------------------------
  "r"  |  Read-only, starts at beginning of file  (default mode).
  -----+--------------------------------------------------------
  "r+" |  Read-write, starts at beginning of file.
  -----+--------------------------------------------------------
  "w"  |  Write-only, truncates existing file
       |  to zero length or creates a new file for writing.
  -----+--------------------------------------------------------
  "w+" |  Read-write, truncates existing file to zero length
       |  or creates a new file for reading and writing.
  -----+--------------------------------------------------------
  "a"  |  Write-only, starts at end of file if file exists,
       |  otherwise creates a new file for writing.
  -----+--------------------------------------------------------
  "a+" |  Read-write, starts at end of file if file exists,
       |  otherwise creates a new file for reading and
       |  writing.
  -----+--------------------------------------------------------
   "b" |  (DOS/Windows only) Binary file mode (may appear with
       |  any of the key letters listed above).

The global constant ARGF (also accessible as $<) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF provides the methods path and filename to access the name of the file currently being read.

Methods

<< binmode close close_read close_write closed? each each_byte each_line eof eof? fcntl fileno flush for_fd foreach fsync getc gets inspect ioctl isatty lineno lineno= new new open pid pipe popen pos pos= print printf putc puts read read read_nonblock readbytes readchar readline readlines readlines readpartial reopen rewind scanf seek select stat sync sync= sysopen sysread sysseek syswrite tell to_i to_io tty? ungetc write write_nonblock

Included Modules

File::Constants Enumerable

Constants

SEEK_SET | = | INT2FIX(SEEK_SET)
SEEK_CUR | = | INT2FIX(SEEK_CUR)
SEEK_END | = | INT2FIX(SEEK_END)

Public Class methods

IO.for_fd(fd, mode) => io

Synonym for IO::new.

IO.foreach(name, sep_string=$/) {|line| block } => nil

Executes the block for every line in the named I/O port, where lines are separated by sep_string.

   IO.foreach("testfile") {|x| print "GOT ", x }

produces:

   GOT This is line one
   GOT This is line two
   GOT This is line three
   GOT And so on...
IO.new(fd, mode_string) => io

Returns a new IO object (a stream) for the given integer file descriptor and mode string. See also IO#fileno and IO::for_fd.

   a = IO.new(2,"w")      # '2' is standard error
   $stderr.puts "Hello"
   a.puts "World"

produces:

   Hello
   World
IO.new(fd, mode) => io

Returns a new IO object (a stream) for the given integer file descriptor and mode string. See also IO#fileno and IO::for_fd.

   a = IO.new(2,"w")      # '2' is standard error
   $stderr.puts "Hello"
   a.puts "World"

produces:

   Hello
   World
IO.open(fd, mode_string="r" ) => io
IO.open(fd, mode_string="r" ) {|io| block } => obj

With no associated block, open is a synonym for IO::new. If the optional code block is given, it will be passed io as an argument, and the IO object will automatically be closed when the block terminates. In this instance, IO::open returns the value of the block.

IO.pipe → array

Creates a pair of pipe endpoints (connected to each other) and returns them as a two-element array of IO objects: [ read_file, write_file ]. Not available on all platforms.

In the example below, the two processes close the ends of the pipe that they are not using. This is not just a cosmetic nicety. The read end of a pipe will not generate an end of file condition if there are any writers with the pipe still open. In the case of the parent process, the rd.read will never return if it does not first issue a wr.close.

   rd, wr = IO.pipe

   if fork
     wr.close
     puts "Parent got: <#{rd.read}>"
     rd.close
     Process.wait
   else
     rd.close
     puts "Sending message to parent"
     wr.write "Hi Dad"
     wr.close
   end

produces:

   Sending message to parent
   Parent got: <Hi Dad>
IO.popen(cmd_string, mode="r" ) => io
IO.popen(cmd_string, mode="r" ) {|io| block } => obj

Runs the specified command string as a subprocess; the subprocess‘s standard input and output will be connected to the returned IO object. If cmd_string starts with a ``-’’, then a new instance of Ruby is started as the subprocess. The default mode for the new file object is ``r’’, but mode may be set to any of the modes listed in the description for class IO.

If a block is given, Ruby will run the command as a child connected to Ruby with a pipe. Ruby‘s end of the pipe will be passed as a parameter to the block. At the end of block, Ruby close the pipe and sets $?. In this case IO::popen returns the value of the block.

If a block is given with a cmd_string of ``-’’, the block will be run in two separate processes: once in the parent, and once in a child. The parent process will be passed the pipe object as a parameter to the block, the child version of the block will be passed nil, and the child‘s standard in and standard out will be connected to the parent through the pipe. Not available on all platforms.

   f = IO.popen("uname")
   p f.readlines
   puts "Parent is #{Process.pid}"
   IO.popen ("date") { |f| puts f.gets }
   IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}
   p $?

produces:

   ["Linux\n"]
   Parent is 26166
   Wed Apr  9 08:53:52 CDT 2003
   26169 is here, f is
   26166 is here, f is #<IO:0x401b3d44>
   #<Process::Status: pid=26166,exited(0)>
IO.read(name, [length [, offset]] ) => string

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

   IO.read("testfile")           #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
   IO.read("testfile", 20)       #=> "This is line one\nThi"
   IO.read("testfile", 20, 10)   #=> "ne one\nThis is line "
IO.readlines(name, sep_string=$/) => array

Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep_string.

   a = IO.readlines("testfile")
   a[0]   #=> "This is line one\n"
IO.select(read_array
[, write_array
[, error_array
[, timeout]]] ) => array or nil

See Kernel#select.

IO.sysopen(path, [mode, [perm]]) => fixnum

Opens the given path, returning the underlying file descriptor as a Fixnum.

   IO.sysopen("testfile")   #=> 3

Public Instance methods

ios << obj => ios

String Output—Writes obj to ios. obj will be converted to a string using to_s.

   $stdout << "Hello " << "world!\n"

produces:

   Hello world!
ios.binmode => ios

Puts ios into binary mode. This is useful only in MS-DOS/Windows environments. Once a stream is in binary mode, it cannot be reset to nonbinary mode.

ios.close => nil

Closes ios and flushes any pending writes to the operating system. The stream is unavailable for any further data operations; an IOError is raised if such an attempt is made. I/O streams are automatically closed when they are claimed by the garbage collector.

If ios is opened by IO.popen, close sets $?.

ios.close_read => nil

Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an IOError if the stream is not duplexed.

   f = IO.popen("/bin/sh","r+")
   f.close_read
   f.readlines

produces:

   prog.rb:3:in `readlines': not opened for reading (IOError)
    from prog.rb:3
ios.close_write => nil

Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an IOError if the stream is not duplexed.

   f = IO.popen("/bin/sh","r+")
   f.close_write
   f.print "nowhere"

produces:

   prog.rb:3:in `write': not opened for writing (IOError)
    from prog.rb:3:in `print'
    from prog.rb:3
ios.closed? => true or false

Returns true if ios is completely closed (for duplex streams, both reader and writer), false otherwise.

   f = File.new("testfile")
   f.close         #=> nil
   f.closed?       #=> true
   f = IO.popen("/bin/sh","r+")
   f.close_write   #=> nil
   f.closed?       #=> false
   f.close_read    #=> nil
   f.closed?       #=> true
ios.each(sep_string=$/) {|line| block } => ios
ios.each_line(sep_string=$/) {|line| block } => ios

Executes the block for every line in ios, where lines are separated by sep_string. ios must be opened for reading or an IOError will be raised.

   f = File.new("testfile")
   f.each {|line| puts "#{f.lineno}: #{line}" }

produces:

   1: This is line one
   2: This is line two
   3: This is line three
   4: And so on...
ios.each_byte {|byte| block } => nil

Calls the given block once for each byte (0..255) in ios, passing the byte as an argument. The stream must be opened for reading or an IOError will be raised.

   f = File.new("testfile")
   checksum = 0
   f.each_byte {|x| checksum ^= x }   #=> #<File:testfile>
   checksum                           #=> 12
ios.each(sep_string=$/) {|line| block } => ios
ios.each_line(sep_string=$/) {|line| block } => ios

Executes the block for every line in ios, where lines are separated by sep_string. ios must be opened for reading or an IOError will be raised.

   f = File.new("testfile")
   f.each {|line| puts "#{f.lineno}: #{line}" }

produces:

   1: This is line one
   2: This is line two
   3: This is line three
   4: And so on...
ios.eof => true or false
ios.eof? => true or false

Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised.

   f = File.new("testfile")
   dummy = f.readlines
   f.eof   #=> true

If ios is a stream such as pipe or socket, IO#eof? blocks until the other end sends some data or closes it.

   r, w = IO.pipe
   Thread.new { sleep 1; w.close }
   r.eof?  #=> true after 1 second blocking

   r, w = IO.pipe
   Thread.new { sleep 1; w.puts "a" }
   r.eof?  #=> false after 1 second blocking

   r, w = IO.pipe
   r.eof?  # blocks forever

Note that IO#eof? reads data to a input buffer. So IO#sysread doesn‘t work with IO#eof?.

ios.eof => true or false
ios.eof? => true or false

Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised.

   f = File.new("testfile")
   dummy = f.readlines
   f.eof   #=> true

If ios is a stream such as pipe or socket, IO#eof? blocks until the other end sends some data or closes it.

   r, w = IO.pipe
   Thread.new { sleep 1; w.close }
   r.eof?  #=> true after 1 second blocking

   r, w = IO.pipe
   Thread.new { sleep 1; w.puts "a" }
   r.eof?  #=> false after 1 second blocking

   r, w = IO.pipe
   r.eof?  # blocks forever

Note that IO#eof? reads data to a input buffer. So IO#sysread doesn‘t work with IO#eof?.

ios.fcntl(integer_cmd, arg) => integer

Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams. Arguments and results are platform dependent. If arg is a number, its value is passed directly. If it is a string, it is interpreted as a binary sequence of bytes (Array#pack might be a useful way to build this string). On Unix platforms, see fcntl(2) for details. Not implemented on all platforms.

ios.fileno => fixnum
ios.to_i => fixnum

Returns an integer representing the numeric file descriptor for ios.

   $stdin.fileno    #=> 0
   $stdout.fileno   #=> 1
ios.flush => ios

Flushes any buffered data within ios to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well).

   $stdout.print "no newline"
   $stdout.flush

produces:

   no newline
ios.fsync => 0 or nil

Immediately writes all buffered data in ios to disk. Returns nil if the underlying operating system does not support fsync(2). Note that fsync differs from using IO#sync=. The latter ensures that data is flushed from Ruby‘s buffers, but doesn‘t not guarantee that the underlying operating system actually writes it to disk.

ios.getc => fixnum or nil

Gets the next 8-bit byte (0..255) from ios. Returns nil if called at end of file.

   f = File.new("testfile")
   f.getc   #=> 84
   f.getc   #=> 104
ios.gets(sep_string=$/) => string or nil

Reads the next ``line’’ from the I/O stream; lines are separated by sep_string. A separator of nil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs). The stream must be opened for reading or an IOError will be raised. The line read in will be returned and also assigned to $_. Returns nil if called at end of file.

   File.new("testfile").gets   #=> "This is line one\n"
   $_                          #=> "This is line one\n"
ios.inspect => string

Return a string describing this IO object.

ios.ioctl(integer_cmd, arg) => integer

Provides a mechanism for issuing low-level commands to control or query I/O devices. Arguments and results are platform dependent. If arg is a number, its value is passed directly. If it is a string, it is interpreted as a binary sequence of bytes. On Unix platforms, see ioctl(2) for details. Not implemented on all platforms.

ios.isatty => true or false
ios.tty? => true or false

Returns true if ios is associated with a terminal device (tty), false otherwise.

   File.new("testfile").isatty   #=> false
   File.new("/dev/tty").isatty   #=> true
ios.lineno => integer

Returns the current line number in ios. The stream must be opened for reading. lineno counts the number of times gets is called, rather than the number of newlines encountered. The two values will differ if gets is called with a separator other than newline. See also the $. variable.

   f = File.new("testfile")
   f.lineno   #=> 0
   f.gets     #=> "This is line one\n"
   f.lineno   #=> 1
   f.gets     #=> "This is line two\n"
   f.lineno   #=> 2
ios.lineno = integer => integer

Manually sets the current line number to the given value. $. is updated only on the next read.

   f = File.new("testfile")
   f.gets                     #=> "This is line one\n"
   $.                         #=> 1
   f.lineno = 1000
   f.lineno                   #=> 1000
   $. # lineno of last read   #=> 1
   f.gets                     #=> "This is line two\n"
   $. # lineno of last read   #=> 1001
ios.pid => fixnum

Returns the process ID of a child process associated with ios. This will be set by IO::popen.

   pipe = IO.popen("-")
   if pipe
     $stderr.puts "In parent, child pid is #{pipe.pid}"
   else
     $stderr.puts "In child, pid is #{$$}"
   end

produces:

   In child, pid is 26209
   In parent, child pid is 26209
ios.pos => integer
ios.tell => integer

Returns the current offset (in bytes) of ios.

   f = File.new("testfile")
   f.pos    #=> 0
   f.gets   #=> "This is line one\n"
   f.pos    #=> 17
ios.pos = integer => integer

Seeks to the given position (in bytes) in ios.

   f = File.new("testfile")
   f.pos = 17
   f.gets   #=> "This is line two\n"
ios.print() => nil
ios.print(obj, ...) => nil

Writes the given object(s) to ios. The stream must be opened for writing. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren‘t strings will be converted by calling their to_s method. With no argument, prints the contents of the variable $_. Returns nil.

   $stdout.print("This is ", 100, " percent.\n")

produces:

   This is 100 percent.
ios.printf(format_string [, obj, ...] ) => nil

Formats and writes to ios, converting parameters under control of the format string. See Kernel#sprintf for details.

ios.putc(obj) => obj

If obj is Numeric, write the character whose code is obj, otherwise write the first character of the string representation of obj to ios.

   $stdout.putc "A"
   $stdout.putc 65

produces:

   AA
ios.puts(obj, ...) => nil

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

   $stdout.puts("this", "is", "a", "test")

produces:

   this
   is
   a
   test
ios.read([length [, buffer]]) => string, buffer, or nil

Reads at most length bytes from the I/O stream, or to the end of file if length is omitted or is nil. length must be a non-negative integer or nil. If the optional buffer argument is present, it must reference a String, which will receive the data.

At end of file, it returns nil or "" depend on
length. ios.read()
and ios.read(nil) returns
"". ios.read(positive-integer) returns
nil.

   f = File.new("testfile")
   f.read(16)   #=> "This is line one"
ios.read_nonblock(maxlen) => string
ios.read_nonblock(maxlen, outbuf) => outbuf

Reads at most maxlen bytes from ios using read(2) system call after O_NONBLOCK is set for the underlying file descriptor.

If the optional outbuf argument is present, it must reference a String, which will receive the data.

read_nonblock just calls read(2). It causes all errors read(2) causes: EAGAIN, EINTR, etc. The caller should care such errors.

read_nonblock causes EOFError on EOF.

If the read buffer is not empty, read_nonblock reads from the buffer like readpartial. In this case, read(2) is not called.

readbytes(n)

Reads exactly n bytes.

If the data read is nil an EOFError is raised.

If the data read is too short a TruncatedDataError is raised and the read data is obtainable via its data method.

ios.readchar => fixnum

Reads a character as with IO#getc, but raises an EOFError on end of file.

ios.readline(sep_string=$/) => string

Reads a line as with IO#gets, but raises an EOFError on end of file.

ios.readlines(sep_string=$/) => array

Reads all of the lines in ios, and returns them in anArray. Lines are separated by the optional sep_string. If sep_string is nil, the rest of the stream is returned as a single record. The stream must be opened for reading or an IOError will be raised.

   f = File.new("testfile")
   f.readlines[0]   #=> "This is line one\n"
ios.readpartial(maxlen) => string
ios.readpartial(maxlen, outbuf) => outbuf

Reads at most maxlen bytes from the I/O stream. It blocks only if ios has no data immediately available. It doesn‘t block if some data available. If the optional outbuf argument is present, it must reference a String, which will receive the data. It raises EOFError on end of file.

readpartial is designed for streams such as pipe, socket, tty, etc. It blocks only when no data immediately available. This means that it blocks only when following all conditions hold.

  • the buffer in the IO object is empty.
  • the content of the stream is empty.
  • the stream is not reached to EOF.

When readpartial blocks, it waits data or EOF on the stream. If some data is reached, readpartial returns with the data. If EOF is reached, readpartial raises EOFError.

When readpartial doesn‘t blocks, it returns or raises immediately. If the buffer is not empty, it returns the data in the buffer. Otherwise if the stream has some content, it returns the data in the stream. Otherwise if the stream is reached to EOF, it raises EOFError.

   r, w = IO.pipe           #               buffer          pipe content
   w << "abc"               #               ""              "abc".
   r.readpartial(4096)      #=> "abc"       ""              ""
   r.readpartial(4096)      # blocks because buffer and pipe is empty.

   r, w = IO.pipe           #               buffer          pipe content
   w << "abc"               #               ""              "abc"
   w.close                  #               ""              "abc" EOF
   r.readpartial(4096)      #=> "abc"       ""              EOF
   r.readpartial(4096)      # raises EOFError

   r, w = IO.pipe           #               buffer          pipe content
   w << "abc\ndef\n"        #               ""              "abc\ndef\n"
   r.gets                   #=> "abc\n"     "def\n"         ""
   w << "ghi\n"             #               "def\n"         "ghi\n"
   r.readpartial(4096)      #=> "def\n"     ""              "ghi\n"
   r.readpartial(4096)      #=> "ghi\n"     ""              ""

Note that readpartial behaves similar to sysread. The differences are:

  • If the buffer is not empty, read from the buffer instead of "sysread for buffered IO (IOError)".
  • It doesn‘t cause Errno::EAGAIN and Errno::EINTR. When readpartial meets EAGAIN and EINTR by read system call, readpartial retry the system call.

The later means that readpartial is nonblocking-flag insensitive. It blocks on the situation IO#sysread causes Errno::EAGAIN as if the fd is blocking mode.

ios.reopen(other_IO) => ios
ios.reopen(path, mode_str) => ios

Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path. This may dynamically change the actual class of this stream.

   f1 = File.new("testfile")
   f2 = File.new("testfile")
   f2.readlines[0]   #=> "This is line one\n"
   f2.reopen(f1)     #=> #<File:testfile>
   f2.readlines[0]   #=> "This is line one\n"
ios.rewind => 0

Positions ios to the beginning of input, resetting lineno to zero.

   f = File.new("testfile")
   f.readline   #=> "This is line one\n"
   f.rewind     #=> 0
   f.lineno     #=> 0
   f.readline   #=> "This is line one\n"
scanf(str,&b)

The trick here is doing a match where you grab one line of input at a time. The linebreak may or may not occur at the boundary where the string matches a format specifier. And if it does, some rule about whitespace may or may not be in effect…

That‘s why this is much more elaborate than the string version.

For each line: Match succeeds (non-emptily) and the last attempted spec/string sub-match succeeded:

  could the last spec keep matching?
    yes: save interim results and continue (next line)

The last attempted spec/string did not match:

are we on the next-to-last spec in the string?

  yes:
    is fmt_string.string_left all spaces?
      yes: does current spec care about input space?
        yes: fatal failure
        no: save interim results and continue
  no: continue  [this state could be analyzed further]
ios.seek(amount, whence=SEEK_SET) → 0

Seeks to a given offset anInteger in the stream according to the value of whence:

  IO::SEEK_CUR  | Seeks to _amount_ plus current position
  --------------+----------------------------------------------------
  IO::SEEK_END  | Seeks to _amount_ plus end of stream (you probably
                | want a negative value for _amount_)
  --------------+----------------------------------------------------
  IO::SEEK_SET  | Seeks to the absolute location given by _amount_

Example:

   f = File.new("testfile")
   f.seek(-13, IO::SEEK_END)   #=> 0
   f.readline                  #=> "And so on...\n"
ios.stat => stat

Returns status information for ios as an object of type File::Stat.

   f = File.new("testfile")
   s = f.stat
   "%o" % s.mode   #=> "100644"
   s.blksize       #=> 4096
   s.atime         #=> Wed Apr 09 08:53:54 CDT 2003
ios.sync => true or false

Returns the current ``sync mode’’ of ios. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered by Ruby internally. See also IO#fsync.

   f = File.new("testfile")
   f.sync   #=> false
ios.sync = boolean => boolean

Sets the ``sync mode’’ to true or false. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered internally. Returns the new state. See also IO#fsync.

   f = File.new("testfile")
   f.sync = true

(produces no output)

ios.sysread(integer ) => string

Reads integer bytes from ios using a low-level read and returns them as a string. Do not mix with other methods that read from ios or you may get unpredictable results. Raises SystemCallError on error and EOFError at end of file.

   f = File.new("testfile")
   f.sysread(16)   #=> "This is line one"
ios.sysseek(offset, whence=SEEK_SET) => integer

Seeks to a given offset in the stream according to the value of whence (see IO#seek for values of whence). Returns the new offset into the file.

   f = File.new("testfile")
   f.sysseek(-13, IO::SEEK_END)   #=> 53
   f.sysread(10)                  #=> "And so on."
ios.syswrite(string) => integer

Writes the given string to ios using a low-level write. Returns the number of bytes written. Do not mix with other methods that write to ios or you may get unpredictable results. Raises SystemCallError on error.

   f = File.new("out", "w")
   f.syswrite("ABCDEF")   #=> 6
ios.pos => integer
ios.tell => integer

Returns the current offset (in bytes) of ios.

   f = File.new("testfile")
   f.pos    #=> 0
   f.gets   #=> "This is line one\n"
   f.pos    #=> 17
to_i()

Alias for fileno

ios.to_io → ios

Returns ios.

ios.isatty => true or false
ios.tty? => true or false

Returns true if ios is associated with a terminal device (tty), false otherwise.

   File.new("testfile").isatty   #=> false
   File.new("/dev/tty").isatty   #=> true
ios.ungetc(integer) => nil

Pushes back one character (passed as a parameter) onto ios, such that a subsequent buffered read will return it. Only one character may be pushed back before a subsequent read operation (that is, you will be able to read only the last of several characters that have been pushed back). Has no effect with unbuffered reads (such as IO#sysread).

   f = File.new("testfile")   #=> #<File:testfile>
   c = f.getc                 #=> 84
   f.ungetc(c)                #=> nil
   f.getc                     #=> 84
ios.write(string) => integer

Writes the given string to ios. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written.

   count = $stdout.write( "This is a test\n" )
   puts "That was #{count} bytes of data"

produces:

   This is a test
   That was 15 bytes of data
ios.write_nonblock(string) => integer

Writes the given string to ios using write(2) system call after O_NONBLOCK is set for the underlying file descriptor.

write_nonblock just calls write(2). It causes all errors write(2) causes: EAGAIN, EINTR, etc. The result may also be smaller than string.length (partial write). The caller should care such errors and partial write.


Class: Integer

Class | Integer
In: | numeric.c lib/mathn.rb lib/rational.rb lib/yaml/rubytypes.rb
Parent: | Numeric

Integer is the basis for the two concrete classes that hold whole numbers, Bignum and Fixnum.

Methods

ceil chr denominator downto floor from_prime_division gcd gcd2 gcdlcm induced_from integer? lcm next numerator prime_division round succ times to_i to_int to_r to_yaml truncate upto

Included Modules

Precision

Public Class methods

from_prime_division(pd)
Integer.induced_from(obj) => fixnum, bignum

Convert obj to an Integer.

Public Instance methods

int.to_i => int
int.to_int => int
int.floor => int
int.ceil => int
int.round => int
int.truncate => int

As int is already an Integer, all these methods simply return the receiver.

int.chr => string

Returns a string containing the ASCII character represented by the receiver‘s value.

   65.chr    #=> "A"
   ?a.chr    #=> "a"
   230.chr   #=> "\346"
denominator()

In an integer, the denominator is 1. Therefore, this method returns 1.

int.downto(limit) {|i| block } => int

Iterates block, passing decreasing values from int down to and including limit.

   5.downto(1) { |n| print n, ".. " }
   print "  Liftoff!\n"

produces:

   5.. 4.. 3.. 2.. 1..   Liftoff!
int.to_i => int
int.to_int => int
int.floor => int
int.ceil => int
int.round => int
int.truncate => int

As int is already an Integer, all these methods simply return the receiver.

gcd(other)

Returns the greatest common denominator of the two numbers (self and n).

Examples:

  72.gcd 168           # -> 24
  19.gcd 36            # -> 1

The result is positive, no matter the sign of the arguments.

gcd2(int)
gcdlcm(other)

Returns the GCD and the LCM (see gcd and lcm) of the two arguments (self and other). This is more efficient than calculating them separately.

Example:

  6.gcdlcm 9     # -> [3, 18]
int.integer? → true

Always returns true.

lcm(other)

Returns the lowest common multiple (LCM) of the two arguments (self and other).

Examples:

  6.lcm 7        # -> 42
  6.lcm 9        # -> 18
int.next => integer
int.succ => integer

Returns the Integer equal to int + 1.

   1.next      #=> 2
   (-1).next   #=> 0
numerator()

In an integer, the value is the numerator of its rational equivalent. Therefore, this method returns self.

prime_division()
int.to_i => int
int.to_int => int
int.floor => int
int.ceil => int
int.round => int
int.truncate => int

As int is already an Integer, all these methods simply return the receiver.

int.next => integer
int.succ => integer

Returns the Integer equal to int + 1.

   1.next      #=> 2
   (-1).next   #=> 0
int.times {|i| block } => int

Iterates block int times, passing in values from zero to int - 1.

   5.times do |i|
     print i, " "
   end

produces:

   0 1 2 3 4
int.to_i => int
int.to_int => int
int.floor => int
int.ceil => int
int.round => int
int.truncate => int

As int is already an Integer, all these methods simply return the receiver.

int.to_i => int
int.to_int => int
int.floor => int
int.ceil => int
int.round => int
int.truncate => int

As int is already an Integer, all these methods simply return the receiver.

to_r()

Returns a Rational representation of this integer.

to_yaml( opts = {} )
int.to_i => int
int.to_int => int
int.floor => int
int.ceil => int
int.round => int
int.truncate => int

As int is already an Integer, all these methods simply return the receiver.

int.upto(limit) {|i| block } => int

Iterates block, passing in integer values from int up to and including limit.

   5.upto(10) { |i| print i, " " }

produces:

   5 6 7 8 9 10


Module: Kernel

Module | Kernel
In: | object.c lib/open-uri.rb lib/pathname.rb lib/pp.rb lib/scanf.rb lib/soap/soap.rb lib/uri/common.rb lib/yaml.rb

Methods

Array Float Integer Pathname String URI ` abort at_exit autoload autoload? binding block_given? callcc caller catch chomp chomp! chop chop! eval exec exit exit! fail fork format getc gets global_variables gsub gsub! iterator? lambda load local_variables loop method_missing open open p pp pretty_inspect print printf proc putc puts raise rand readline readlines require scan select set_trace_func sleep split sprintf srand sub sub! syscall system test throw trace_var trap untrace_var warn warn

Public Instance methods

Array(arg) => array

Returns arg as an Array. First tries to call arg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg (unless arg is nil).

   Array(1..5)   #=> [1, 2, 3, 4, 5]
Float(arg) => float

Returns arg converted to a float. Numeric types are converted directly, the rest are converted using arg.to_f. As of Ruby 1.8, converting nil generates a TypeError.

   Float(1)           #=> 1.0
   Float("123.456")   #=> 123.456
Integer(arg) => integer

Converts arg to a Fixnum or Bignum. Numeric types are converted directly (with floating point numbers being truncated). If arg is a String, leading radix indicators (0, 0b, and 0x) are honored. Others are converted using to_int and to_i. This behavior is different from that of String#to_i.

   Integer(123.999)    #=> 123
   Integer("0x1a")     #=> 26
   Integer(Time.new)   #=> 1049896590
String(arg) => string

Converts arg to a String by calling its to_s method.

   String(self)        #=> "main"
   String(self.class   #=> "Object"
   String(123456)      #=> "123456"
URI(uri_str)

alias for URI.parse.

This method is introduced at 1.8.2.

`cmd` => string

Returns the standard output of running cmd in a subshell. The built-in syntax %x{…} uses this method. Sets $? to the process status.

   `date`                   #=> "Wed Apr  9 08:56:30 CDT 2003\n"
   `ls testdir`.split[1]    #=> "main.rb"
   `echo oops && exit 99`   #=> "oops\n"
   $?.exitstatus            #=> 99
abort
Kernel::abort
Process::abort

Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.

at_exit { block } → proc

Converts block to a Proc object (and therefore binds it at the point of call) and registers it for execution when the program exits. If multiple handlers are registered, they are executed in reverse order of registration.

   def do_at_exit(str1)
     at_exit { print str1 }
   end
   at_exit { puts "cruel world" }
   do_at_exit("goodbye ")
   exit

produces:

   goodbye cruel world
autoload(module, filename) => nil

Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

   autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
autoload(module, filename) => nil

Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

   autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
binding → a_binding

Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. Also see the description of class Binding.

   def getBinding(param)
     return binding
   end
   b = getBinding("hello")
   eval("param", b)   #=> "hello"
block_given? => true or false
iterator? => true or false

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

   def try
     if block_given?
       yield
     else
       "no block"
     end
   end
   try                  #=> "no block"
   try { "hello" }      #=> "hello"
   try do "hello" end   #=> "hello"
callcc {|cont| block } => obj

Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. See class Continuation for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.

caller(start=1) => array

Returns the current execution stack—an array containing strings in the form ``file:line’’ or ``file:line: in `method‘’’. The optional start parameter determines the number of initial stack entries to omit from the result.

   def a(skip)
     caller(skip)
   end
   def b(skip)
     a(skip)
   end
   def c(skip)
     b(skip)
   end
   c(0)   #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
   c(1)   #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
   c(2)   #=> ["prog:8:in `c'", "prog:12"]
   c(3)   #=> ["prog:13"]
catch(symbol) {| | block } > obj

catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw‘s symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.

   def routine(n)
     puts n
     throw :done if n <= 0
     routine(n-1)
   end

   catch(:done) { routine(3) }

produces:

   3
   2
   1
   0
chomp => $_
chomp(string) => $_

Equivalent to $_ = $_.chomp(string). See String#chomp.

   $_ = "now\n"
   chomp         #=> "now"
   $_            #=> "now"
   chomp "ow"    #=> "n"
   $_            #=> "n"
   chomp "xxx"   #=> "n"
   $_            #=> "n"
chomp! => $_ or nil
chomp!(string) => $_ or nil

Equivalent to $_.chomp!(string). See String#chomp!

   $_ = "now\n"
   chomp!       #=> "now"
   $_           #=> "now"
   chomp! "x"   #=> nil
   $_           #=> "now"
chop => string

Equivalent to ($_.dup).chop!, except nil is never returned. See String#chop!.

   a  =  "now\r\n"
   $_ = a
   chop   #=> "now"
   $_     #=> "now"
   chop   #=> "no"
   chop   #=> "n"
   chop   #=> ""
   chop   #=> ""
   a      #=> "now\r\n"
chop! => $_ or nil

Equivalent to $_.chop!.

   a  = "now\r\n"
   $_ = a
   chop!   #=> "now"
   chop!   #=> "no"
   chop!   #=> "n"
   chop!   #=> ""
   chop!   #=> nil
   $_      #=> ""
   a       #=> ""
eval(string [, binding [, filename [,lineno]]]) => obj

Evaluates the Ruby expression(s) in string. If binding is given, the evaluation is performed in its context. The binding may be a Binding object or a Proc object. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.

   def getBinding(str)
     return binding
   end
   str = "hello"
   eval "str + ' Fred'"                      #=> "hello Fred"
   eval "str + ' Fred'", getBinding("bye")   #=> "bye Fred"
exec(command [, arg, ...])

Replaces the current process by running the given external command. If exec is given a single argument, that argument is taken as a line that is subject to shell expansion before being executed. If multiple arguments are given, the second and subsequent arguments are passed as parameters to command with no shell expansion. If the first argument is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).

   exec "echo *"       # echoes list of files in current directory
   # never get here

   exec "echo", "*"    # echoes an asterisk
   # never get here
exit(integer=0)
Kernel::exit(integer=0)
Process::exit(integer=0)

Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.

   begin
     exit
     puts "never get here"
   rescue SystemExit
     puts "rescued a SystemExit exception"
   end
   puts "after begin block"

produces:

   rescued a SystemExit exception
   after begin block

Just prior to termination, Ruby executes any at_exit functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer).

   at_exit { puts "at_exit function" }
   ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
   exit

produces:

   at_exit function
   in finalizer
Process.exit!(fixnum=-1)

Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.

   Process.exit!(0)
raise
raise(string)
raise(exception [, string [, array]])
fail
fail(string)
fail(exception [, string [, array]])

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

   raise "Failed to create socket"
   raise ArgumentError, "No parameters", caller
Kernel.fork [{ block }] => fixnum or nil
Process.fork [{ block }] => fixnum or nil

Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

The thread calling fork is the only thread in the created child process. fork doesn‘t copy other threads.

format(format_string [, arguments...] ) => string
sprintf(format_string [, arguments...] ) => string

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

  Flag     | Applies to   | Meaning
  ---------+--------------+-----------------------------------------
  space    | bdeEfgGiouxX | Leave a space at the start of
           |              | positive numbers.
  ---------+--------------+-----------------------------------------
  (digit)$ | all          | Specifies the absolute argument number
           |              | for this field. Absolute and relative
           |              | argument numbers cannot be mixed in a
           |              | sprintf string.
  ---------+--------------+-----------------------------------------
   #       | beEfgGoxX    | Use an alternative format. For the
           |              | conversions `o', `x', `X', and `b',
           |              | prefix the result with ``0'', ``0x'', ``0X'',
           |              |  and ``0b'', respectively. For `e',
           |              | `E', `f', `g', and 'G', force a decimal
           |              | point to be added, even if no digits follow.
           |              | For `g' and 'G', do not remove trailing zeros.
  ---------+--------------+-----------------------------------------
  +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
  ---------+--------------+-----------------------------------------
  -        | all          | Left-justify the result of this conversion.
  ---------+--------------+-----------------------------------------
  0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
  ---------+--------------+-----------------------------------------
  *        | all          | Use the next argument as the field width.
           |              | If negative, left-justify the result. If the
           |              | asterisk is followed by a number and a dollar
           |              | sign, use the indicated argument as the width.

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

The field types are:

    Field |  Conversion
    ------+--------------------------------------------------------------
      b   | Convert argument as a binary number.
      c   | Argument is the numeric code for a single character.
      d   | Convert argument as a decimal number.
      E   | Equivalent to `e', but uses an uppercase E to indicate
          | the exponent.
      e   | Convert floating point argument into exponential notation
          | with one digit before the decimal point. The precision
          | determines the number of fractional digits (defaulting to six).
      f   | Convert floating point argument as [-]ddd.ddd,
          |  where the precision determines the number of digits after
          | the decimal point.
      G   | Equivalent to `g', but use an uppercase `E' in exponent form.
      g   | Convert a floating point number using exponential form
          | if the exponent is less than -4 or greater than or
          | equal to the precision, or in d.dddd form otherwise.
      i   | Identical to `d'.
      o   | Convert argument as an octal number.
      p   | The valuing of argument.inspect.
      s   | Argument is a string to be substituted. If the format
          | sequence contains a precision, at most that many characters
          | will be copied.
      u   | Treat argument as an unsigned decimal number. Negative integers
          | are displayed as a 32 bit two's complement plus one for the
          | underlying architecture; that is, 2 ** 32 + n.  However, since
          | Ruby has no inherent limit on bits used to represent the
          | integer, this value is preceded by two dots (..) in order to
          | indicate a infinite number of leading sign bits.
      X   | Convert argument as a hexadecimal number using uppercase
          | letters. Negative numbers will be displayed with two
          | leading periods (representing an infinite string of
          | leading 'FF's.
      x   | Convert argument as a hexadecimal number.
          | Negative numbers will be displayed with two
          | leading periods (representing an infinite string of
          | leading 'ff's.

Examples:

   sprintf("%d %04x", 123, 123)               #=> "123 007b"
   sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
   sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
   sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
   sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
   sprintf("%u", -123)                        #=> "..4294967173"
getc()

obsolete

gets(separator=$/) => string or nil

Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If multiple filenames are present in ARGV, +gets(nil)+ will read the contents one file at a time.

   ARGV << "testfile"
   print while gets

produces:

   This is line one
   This is line two
   This is line three
   And so on...

The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.

global_variables => array

Returns an array of the names of global variables.

   global_variables.grep /std/   #=> ["$stderr", "$stdout", "$stdin"]
gsub(pattern, replacement) => string
gsub(pattern) {|...| block } => string

Equivalent to $_.gsub…, except that $_ receives the modified result.

   $_ = "quick brown fox"
   gsub /[aeiou]/, '*'   #=> "q**ck br*wn f*x"
   $_                    #=> "q**ck br*wn f*x"
gsub!(pattern, replacement) => string or nil
gsub!(pattern) {|...| block } => string or nil

Equivalent to Kernel::gsub, except nil is returned if $_ is not modified.

   $_ = "quick brown fox"
   gsub! /cat/, '*'   #=> nil
   $_                 #=> "quick brown fox"
block_given? => true or false
iterator? => true or false

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

   def try
     if block_given?
       yield
     else
       "no block"
     end
   end
   try                  #=> "no block"
   try { "hello" }      #=> "hello"
   try do "hello" end   #=> "hello"
proc { |...| block } => a_proc
lambda { |...| block } => a_proc

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

load(filename, wrap=false) => true

Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program‘s global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

local_variables => array

Returns the names of the current local variables.

   fred = 1
   for i in 1..10
      # ...
   end
   local_variables   #=> ["fred", "i"]
loop {|| block }

Repeatedly executes the block.

   loop do
     print "Input: "
     line = gets
     break if !line or line =~ /^qQ/
     # ...
   end
obj.method_missing(symbol [, *args] ) => result

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

   class Roman
     def romanToInt(str)
       # ...
     end
     def method_missing(methId)
       str = methId.id2name
       romanToInt(str)
     end
   end

   r = Roman.new
   r.iv      #=> 4
   r.xxiii   #=> 23
   r.mm      #=> 2000
open(path [, mode [, perm]] ) => io or nil
open(path [, mode [, perm]] ) {|io| block } => obj

Creates an IO object connected to the given stream, file, or subprocess.

If path does not start with a pipe character (``|’’), treat it as the name of a file to open using the specified mode (defaulting to ``r’’). (See the table of valid modes on page 331.) If a file is being created, its initial permissions may be set using the integer third parameter.

If a block is specified, it will be invoked with the File object as a parameter, and the file will be automatically closed when the block terminates. The call returns the value of the block.

If path starts with a pipe character, a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess. If the command following the ``|’’ is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not ``-’’, the subprocess runs the command. If a block is associated with an open("|-") call, that block will be run twice—once in the parent and once in the child. The block parameter will be an IO object in the parent and nil in the child. The parent‘s IO object will be connected to the child‘s $stdin and $stdout. The subprocess will be terminated at the end of the block.

   open("testfile") do |f|
     print f.gets
   end

produces:

   This is line one

Open a subprocess and read its output:

   cmd = open("|date")
   print cmd.gets
   cmd.close

produces:

   Wed Apr  9 08:56:31 CDT 2003

Open a subprocess running the same Ruby program:

   f = open("|-", "w+")
   if f == nil
     puts "in Child"
     exit
   else
     puts "Got: #{f.gets}"
   end

produces:

   Got: in Child

Open a subprocess using a block to receive the I/O object:

   open("|-") do |f|
     if f == nil
       puts "in Child"
     else
       puts "Got: #{f.gets}"
     end
   end

produces:

   Got: in Child
p(obj, ...) => nil

For each object, directly writes obj.inspect followed by the current output record separator to the program‘s standard output.

   S = Struct.new(:name, :state)
   s = S['dave', 'TX']
   p s

produces:

   #<S name="dave", state="TX">
pretty_inspect()

returns a pretty printed object as a string.

print(obj, ...) => nil

Prints each object in turn to $stdout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren‘t strings will be converted by calling their to_s method.

   print "cat", [1,2,3], 99, "\n"
   $, = ", "
   $\ = "\n"
   print "cat", [1,2,3], 99

produces:

   cat12399
   cat, 1, 2, 3, 99
printf(io, string [, obj ... ] ) => nil
printf(string [, obj ... ] ) => nil

Equivalent to:

   io.write(sprintf(string, obj, ...)

or

   $stdout.write(sprintf(string, obj, ...)
proc { |...| block } => a_proc
lambda { |...| block } => a_proc

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

putc(int) => int

Equivalent to:

  $stdout.putc(int)
puts(obj, ...) => nil

Equivalent to

    $stdout.puts(obj, ...)
raise
raise(string)
raise(exception [, string [, array]])
fail
fail(string)
fail(exception [, string [, array]])

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

   raise "Failed to create socket"
   raise ArgumentError, "No parameters", caller
rand(max=0) => number

Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.

   srand 1234                 #=> 0
   [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
   [ rand(10), rand(1000) ]   #=> [6, 817]
   srand 1234                 #=> 1234
   [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
readline(separator=$/) => string

Equivalent to Kernel::gets, except readline raises EOFError at end of file.

readlines(separator=$/) => array

Returns an array containing the lines returned by calling Kernel.gets(separator) until the end of file.

require(string) => true or false

Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ``.rb’’, it is loaded as a source file; if the extension is ``.so’’, ``.o’’, or ``.dll’’, or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ``.rb’’, ``.so’’, and so on to the name. The name of the loaded feature is added to the array in $". A feature will not be loaded if it‘s name already appears in $". However, the file name is not converted to an absolute path, so that ``require ‘a’;require ’./a‘’’ will load a.rb twice.

   require "my-library.rb"
   require "db-driver"
scan(pattern) => array
scan(pattern) {|///| block } => $_

Equivalent to calling $_.scan. See String#scan.

IO.select(read_array
[, write_array
[, error_array
[, timeout]]] ) => array or nil

See Kernel#select.

set_trace_func(proc) => proc
set_trace_func(nil) => nil

Establishes proc as the handler for tracing, or disables tracing if the parameter is nil. proc takes up to six parameters: an event name, a filename, a line number, an object id, a binding, and the name of a class. proc is invoked whenever an event occurs. Events are: c-call (call a C-language routine), c-return (return from a C-language routine), call (call a Ruby method), class (start a class or module definition), end (finish a class or module definition), line (execute code on a new line), raise (raise an exception), and return (return from a Ruby method). Tracing is disabled within the context of proc.

    class Test
    def test
      a = 1
      b = 2
    end
    end

    set_trace_func proc { |event, file, line, id, binding, classname|
       printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
    }
    t = Test.new
    t.test

      line prog.rb:11               false
    c-call prog.rb:11        new    Class
    c-call prog.rb:11 initialize   Object
  c-return prog.rb:11 initialize   Object
  c-return prog.rb:11        new    Class
      line prog.rb:12               false
      call prog.rb:2        test     Test
      line prog.rb:3        test     Test
      line prog.rb:4        test     Test
    return prog.rb:4        test     Test
sleep([duration]) => fixnum

Suspends the current thread for duration seconds (which may be any number, including a Float with fractional seconds). Returns the actual number of seconds slept (rounded), which may be less than that asked for if another thread calls Thread#run. Zero arguments causes sleep to sleep forever.

   Time.new    #=> Wed Apr 09 08:56:32 CDT 2003
   sleep 1.2   #=> 1
   Time.new    #=> Wed Apr 09 08:56:33 CDT 2003
   sleep 1.9   #=> 2
   Time.new    #=> Wed Apr 09 08:56:35 CDT 2003
split([pattern [, limit]]) => array

Equivalent to $_.split(pattern, limit). See String#split.

format(format_string [, arguments...] ) => string
sprintf(format_string [, arguments...] ) => string

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

  Flag     | Applies to   | Meaning
  ---------+--------------+-----------------------------------------
  space    | bdeEfgGiouxX | Leave a space at the start of
           |              | positive numbers.
  ---------+--------------+-----------------------------------------
  (digit)$ | all          | Specifies the absolute argument number
           |              | for this field. Absolute and relative
           |              | argument numbers cannot be mixed in a
           |              | sprintf string.
  ---------+--------------+-----------------------------------------
   #       | beEfgGoxX    | Use an alternative format. For the
           |              | conversions `o', `x', `X', and `b',
           |              | prefix the result with ``0'', ``0x'', ``0X'',
           |              |  and ``0b'', respectively. For `e',
           |              | `E', `f', `g', and 'G', force a decimal
           |              | point to be added, even if no digits follow.
           |              | For `g' and 'G', do not remove trailing zeros.
  ---------+--------------+-----------------------------------------
  +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
  ---------+--------------+-----------------------------------------
  -        | all          | Left-justify the result of this conversion.
  ---------+--------------+-----------------------------------------
  0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
  ---------+--------------+-----------------------------------------
  *        | all          | Use the next argument as the field width.
           |              | If negative, left-justify the result. If the
           |              | asterisk is followed by a number and a dollar
           |              | sign, use the indicated argument as the width.

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

The field types are:

    Field |  Conversion
    ------+--------------------------------------------------------------
      b   | Convert argument as a binary number.
      c   | Argument is the numeric code for a single character.
      d   | Convert argument as a decimal number.
      E   | Equivalent to `e', but uses an uppercase E to indicate
          | the exponent.
      e   | Convert floating point argument into exponential notation
          | with one digit before the decimal point. The precision
          | determines the number of fractional digits (defaulting to six).
      f   | Convert floating point argument as [-]ddd.ddd,
          |  where the precision determines the number of digits after
          | the decimal point.
      G   | Equivalent to `g', but use an uppercase `E' in exponent form.
      g   | Convert a floating point number using exponential form
          | if the exponent is less than -4 or greater than or
          | equal to the precision, or in d.dddd form otherwise.
      i   | Identical to `d'.
      o   | Convert argument as an octal number.
      p   | The valuing of argument.inspect.
      s   | Argument is a string to be substituted. If the format
          | sequence contains a precision, at most that many characters
          | will be copied.
      u   | Treat argument as an unsigned decimal number. Negative integers
          | are displayed as a 32 bit two's complement plus one for the
          | underlying architecture; that is, 2 ** 32 + n.  However, since
          | Ruby has no inherent limit on bits used to represent the
          | integer, this value is preceded by two dots (..) in order to
          | indicate a infinite number of leading sign bits.
      X   | Convert argument as a hexadecimal number using uppercase
          | letters. Negative numbers will be displayed with two
          | leading periods (representing an infinite string of
          | leading 'FF's.
      x   | Convert argument as a hexadecimal number.
          | Negative numbers will be displayed with two
          | leading periods (representing an infinite string of
          | leading 'ff's.

Examples:

   sprintf("%d %04x", 123, 123)               #=> "123 007b"
   sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
   sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
   sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
   sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
   sprintf("%u", -123)                        #=> "..4294967173"
srand(number=0) => old_seed

Seeds the pseudorandom number generator to the value of number.to_i.abs. If number is omitted, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.

sub(pattern, replacement) => $_
sub(pattern) { block } => $_

Equivalent to $_.sub(args), except that $_ will be updated if substitution occurs.

sub!(pattern, replacement) => $_ or nil
sub!(pattern) {|...| block } => $_ or nil

Equivalent to $_.sub!(args).

syscall(fixnum [, args...]) => integer

Calls the operating system function identified by fixnum, passing in the arguments, which must be either String objects, or Integer objects that ultimately fit within a native long. Up to nine parameters may be passed (14 on the Atari-ST). The function identified by fixnum is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h.

   syscall 4, 1, "hello\n", 6   # '4' is write(2) on our box

produces:

   hello
system(cmd [, arg, ...]) => true or false

Executes cmd in a subshell, returning true if the command was found and ran successfully, false otherwise. An error status is available in $?. The arguments are processed in the same way as for Kernel::exec.

   system("echo *")
   system("echo", "*")

produces:

   config.h main.rb
   *
test(int_cmd, file1 [, file2] ) => obj

 Uses the integer <i>aCmd</i> to perform various tests on
 <i>file1</i> (first table below) or on <i>file1</i> and
 <i>file2</i> (second table).

 File tests on a single file:

   Test   Returns   Meaning
    ?A  | Time    | Last access time for file1
    ?b  | boolean | True if file1 is a block device
    ?c  | boolean | True if file1 is a character device
    ?C  | Time    | Last change time for file1
    ?d  | boolean | True if file1 exists and is a directory
    ?e  | boolean | True if file1 exists
    ?f  | boolean | True if file1 exists and is a regular file
    ?g  | boolean | True if file1 has the \CF{setgid} bit
        |         | set (false under NT)
    ?G  | boolean | True if file1 exists and has a group
        |         | ownership equal to the caller's group
    ?k  | boolean | True if file1 exists and has the sticky bit set
    ?l  | boolean | True if file1 exists and is a symbolic link
    ?M  | Time    | Last modification time for file1
    ?o  | boolean | True if file1 exists and is owned by
        |         | the caller's effective uid
    ?O  | boolean | True if file1 exists and is owned by
        |         | the caller's real uid
    ?p  | boolean | True if file1 exists and is a fifo
    ?r  | boolean | True if file1 is readable by the effective
        |         | uid/gid of the caller
    ?R  | boolean | True if file is readable by the real
        |         | uid/gid of the caller
    ?s  | int/nil | If file1 has nonzero size, return the size,
        |         | otherwise return nil
    ?S  | boolean | True if file1 exists and is a socket
    ?u  | boolean | True if file1 has the setuid bit set
    ?w  | boolean | True if file1 exists and is writable by
        |         | the effective uid/gid
    ?W  | boolean | True if file1 exists and is writable by
        |         | the real uid/gid
    ?x  | boolean | True if file1 exists and is executable by
        |         | the effective uid/gid
    ?X  | boolean | True if file1 exists and is executable by
        |         | the real uid/gid
    ?z  | boolean | True if file1 exists and has a zero length

Tests that take two files:

    ?-  | boolean | True if file1 and file2 are identical
    ?=  | boolean | True if the modification times of file1
        |         | and file2 are equal
    ?<  | boolean | True if the modification time of file1
        |         | is prior to that of file2
    ?>  | boolean | True if the modification time of file1
        |         | is after that of file2
throw(symbol [, obj])

Transfers control to the end of the active catch block waiting for symbol. Raises NameError if there is no catch block for the symbol. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.

trace_var(symbol, cmd ) => nil
trace_var(symbol) {|val| block } => nil

Controls tracing of assignments to global variables. The parameter +symbol_ identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc object) or block is executed whenever the variable is assigned. The block or Proc object receives the variable‘s new value as a parameter. Also see Kernel::untrace_var.

   trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
   $_ = "hello"
   $_ = ' there'

produces:

   $_ is now 'hello'
   $_ is now ' there'
Signal.trap( signal, proc ) => obj
Signal.trap( signal ) {| | block } => obj

Specifies the handling of signals. The first parameter is a signal name (a string such as ``SIGALRM’’, ``SIGUSR1’’, and so on) or a signal number. The characters ``SIG’’ may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string ``IGNORE’’ or ``SIG_IGN’’, the signal will be ignored. If the command is ``DEFAULT’’ or ``SIG_DFL’’, the operating system‘s default handler will be invoked. If the command is ``EXIT’’, the script will be terminated by the signal. Otherwise, the given command or block will be run. The special signal name ``EXIT’’ or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

    Signal.trap(0, proc { puts "Terminating: #{$$}" })
    Signal.trap("CLD")  { puts "Child died" }
    fork && Process.wait

produces:

    Terminating: 27461
    Child died
    Terminating: 27460
untrace_var(symbol [, cmd] ) => array or nil

Removes tracing for the specified command on the given global variable and returns nil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.

warn(msg)
warn(msg) => nil

Display the given message (followed by a newline) on STDERR unless warnings are disabled (for example with the -W0 flag).

Private Instance methods

Pathname(path)

create a pathname object.

This method is available since 1.8.5.

open(name, *rest, &block)

makes possible to open various resources including URIs. If the first argument respond to `open’ method, the method is called with the rest arguments.

If the first argument is a string which begins with xxx://, it is parsed by URI.parse. If the parsed object respond to `open’ method, the method is called with the rest arguments.

Otherwise original open is called.

Since open-uri.rb provides URI::HTTP#open, URI::HTTPS#open and URI::FTP#open, Kernel[#.]open can accepts such URIs and strings which begins with http://, https:// and ftp://. In these case, the opened file object is extended by OpenURI::Meta.

pp(*objs)

prints arguments in pretty form.

pp returns nil.


Module: Math

Module | Math
In: | math.c lib/complex.rb lib/mathn.rb

The Math module contains module functions for basic trigonometric and transcendental functions. See class Float for a list of constants that define Ruby‘s floating point accuracy.

Methods

acos acos acosh acosh asin asin asinh asinh atan atan atan2 atan2 atanh atanh cos cos cosh cosh erf erfc exp exp frexp hypot ldexp log log log10 log10 rsqrt sin sin sinh sinh sqrt sqrt sqrt tan tan tanh tanh

Constants

PI | = | rb_float_new(M_PI)
PI | = | rb_float_new(atan(1.0)*4.0)
E | = | rb_float_new(M_E)
E | = | rb_float_new(exp(1.0))

External Aliases

sqrt | -> | sqrt!
exp | -> | exp!
log | -> | log!
log10 | -> | log10!
cos | -> | cos!
sin | -> | sin!
tan | -> | tan!
cosh | -> | cosh!
sinh | -> | sinh!
tanh | -> | tanh!
acos | -> | acos!
asin | -> | asin!
atan | -> | atan!
atan2 | -> | atan2!
acosh | -> | acosh!
asinh | -> | asinh!
atanh | -> | atanh!

Public Class methods

Math.acos(x) => float

Computes the arc cosine of x. Returns 0..PI.

Math.acosh(x) => float

Computes the inverse hyperbolic cosine of x.

Math.asin(x) => float

Computes the arc sine of x. Returns 0..PI.

Math.asinh(x) => float

Computes the inverse hyperbolic sine of x.

Math.atan(x) => float

Computes the arc tangent of x. Returns -{PI/2} .. {PI/2}.

Math.atan2(y, x) => float

Computes the arc tangent given y and x. Returns -PI..PI.

Math.atanh(x) => float

Computes the inverse hyperbolic tangent of x.

Math.cos(x) => float

Computes the cosine of x (expressed in radians). Returns -1..1.

Math.cosh(x) => float

Computes the hyperbolic cosine of x (expressed in radians).

Math.erf(x) => float

Calculates the error function of x.

Math.erfc(x) => float

Calculates the complementary error function of x.

Math.exp(x) => float

Returns e**x.

Math.frexp(numeric) => [ fraction, exponent ]

Returns a two-element array containing the normalized fraction (a Float) and exponent (a Fixnum) of numeric.

   fraction, exponent = Math.frexp(1234)   #=> [0.6025390625, 11]
   fraction * 2**exponent                  #=> 1234.0
Math.hypot(x, y) => float

Returns sqrt(x**2 + y**2), the hypotenuse of a right-angled triangle with sides x and y.

   Math.hypot(3, 4)   #=> 5.0
Math.ldexp(flt, int) → float

Returns the value of flt*(2**int).

   fraction, exponent = Math.frexp(1234)
   Math.ldexp(fraction, exponent)   #=> 1234.0
Math.log(numeric) => float

Returns the natural logarithm of numeric.

Math.log10(numeric) => float

Returns the base 10 logarithm of numeric.

Math.sin(x) => float

Computes the sine of x (expressed in radians). Returns -1..1.

Math.sinh(x) => float

Computes the hyperbolic sine of x (expressed in radians).

Math.sqrt(numeric) => float

Returns the non-negative square root of numeric.

Math.tan(x) => float

Returns the tangent of x (expressed in radians).

Math.tanh() => float

Computes the hyperbolic tangent of x (expressed in radians).

Public Instance methods

acos(z)
acosh(z)
asin(z)
asinh(z)
atan(z)
atan2(y,x)
atanh(z)
cos(z)

Redefined to handle a Complex argument.

cosh(z)
exp(z)

Redefined to handle a Complex argument.

log(z)

Redefined to handle a Complex argument.

log10(z)

Redefined to handle a Complex argument.

rsqrt(a)
sin(z)

Redefined to handle a Complex argument.

sinh(z)
sqrt(z)

Redefined to handle a Complex argument.

sqrt(a)
tan(z)

Redefined to handle a Complex argument.

tanh(z)


Class: Module

Class | Module
In: | object.c lib/yaml/tag.rb

A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instance methods may not. (See Module#module_function)

In the descriptions that follow, the parameter syml refers to a symbol, which is either a quoted string or a Symbol (such as :name).

   module Mod
     include Math
     CONST = 1
     def meth
       #  ...
     end
   end
   Mod.class              #=> Module
   Mod.constants          #=> ["E", "PI", "CONST"]
   Mod.instance_methods   #=> ["meth"]

Methods

< <= <=> == === > >= alias_method ancestors append_features attr attr_accessor attr_reader attr_writer autoload autoload? class_eval class_variable_defined? class_variable_get class_variable_set class_variables const_defined? const_get const_missing const_set constants constants define_method extend_object extended freeze include include? included included_modules instance_method instance_methods method_added method_defined? method_removed method_undefined module_eval module_function name nesting new private private_class_method private_instance_methods private_method_defined? protected protected_instance_methods protected_method_defined? public public_class_method public_instance_methods public_method_defined? remove_class_variable remove_const remove_method to_s undef_method

Public Class methods

Module.constants => array

Returns an array of the names of all constants defined in the system. This list includes the names of all modules and classes.

   p Module.constants.sort[1..5]

produces:

   ["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]
Module.nesting => array

Returns the list of Modules nested at the point of call.

   module M1
     module M2
       $a = Module.nesting
     end
   end
   $a           #=> [M1::M2, M1]
   $a[0].name   #=> "M1::M2"
Module.new => mod
Module.new {|mod| block } => mod

Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module using module_eval.

   Fred = Module.new do
     def meth1
       "hello"
     end
     def meth2
       "bye"
     end
   end
   a = "my string"
   a.extend(Fred)   #=> "my string"
   a.meth1          #=> "hello"
   a.meth2          #=> "bye"

Public Instance methods

mod < other => true, false, or nil

Returns true if mod is a subclass of other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").

mod <= other => true, false, or nil

Returns true if mod is a subclass of other or is the same as other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").

mod <=> other_mod => -1, 0, +1, or nil

Comparison—Returns -1 if mod includes other_mod, 0 if mod is the same as other_mod, and +1 if mod is included by other_mod or if mod has no relationship with other_mod. Returns nil if other_mod is not a module.

obj == other => true or false
obj.equal?(other) => true or false
obj.eql?(other) => true or false

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

   1 == 1.0     #=> true
   1.eql? 1.0   #=> false
mod === obj => true or false

Case Equality—Returns true if anObject is an instance of mod or one of mod‘s descendents. Of limited use for modules, but can be used in case statements to classify objects by class.

mod > other => true, false, or nil

Returns true if mod is an ancestor of other. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").

mod >= other => true, false, or nil

Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if there‘s no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").

alias_method(new_name, old_name) => self

Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

   module Mod
     alias_method :orig_exit, :exit
     def exit(code=0)
       puts "Exiting with code #{code}"
       orig_exit(code)
     end
   end
   include Mod
   exit(99)

produces:

   Exiting with code 99
mod.ancestors → array

Returns a list of modules included in mod (including mod itself).

   module Mod
     include Math
     include Comparable
   end

   Mod.ancestors    #=> [Mod, Comparable, Math]
   Math.ancestors   #=> [Math]
append_features(mod) => mod

When this module is included in another, Ruby calls append_features in this module, passing it the receiving module in mod. Ruby‘s default implementation is to add the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors. See also Module#include.

attr(symbol, writable=false) => nil

Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. If the optional writable argument is true, also creates a method called name= to set the attribute.

   module Mod
     attr  :size, true
   end

is equivalent to:

   module Mod
     def size
       @size
     end
     def size=(val)
       @size = val
     end
   end
attr_accessor(symbol, ...) => nil

Equivalent to calling ``attr symbol, true’’ on each symbol in turn.

   module Mod
     attr_accessor(:one, :two)
   end
   Mod.instance_methods.sort   #=> ["one", "one=", "two", "two="]
attr_reader(symbol, ...) => nil

Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling ``attr:name’’ on each name in turn.

attr_writer(symbol, ...) => nil

Creates an accessor method to allow assignment to the attribute aSymbol.id2name.

mod.autoload(name, filename) => nil

Registers filename to be loaded (using Kernel::require) the first time that name (which may be a String or a symbol) is accessed in the namespace of mod.

   module A
   end
   A.autoload(:B, "b")
   A::B.doit            # autoloads "b"
mod.autoload?(name) => String or nil

Returns filename to be loaded if name is registered as autoload in the namespace of mod.

   module A
   end
   A.autoload(:B, "b")
   A.autoload?(:B)            # => "b"
mod.class_eval(string [, filename [, lineno]]) => obj
mod.module_eval {|| block } => obj

Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.

   class Thing
   end
   a = %q{def hello() "Hello there!" end}
   Thing.module_eval(a)
   puts Thing.new.hello()
   Thing.module_eval("invalid code", "dummy", 123)

produces:

   Hello there!
   dummy:123:in `module_eval': undefined local variable
       or method `code' for Thing:Class
obj.class_variable_defined?(symbol) => true or false

Returns true if the given class variable is defined in obj.

   class Fred
     @@foo = 99
   end
   Fred.class_variable_defined?(:@@foo)    #=> true
   Fred.class_variable_defined?(:@@bar)    #=> false
mod.class_variable_get(symbol) => obj

Returns the value of the given class variable (or throws a NameError exception). The @@ part of the variable name should be included for regular class variables

   class Fred
     @@foo = 99
   end

   def Fred.foo
     class_variable_get(:@@foo)     #=> 99
   end
obj.class_variable_set(symbol, obj) => obj

Sets the class variable names by symbol to object.

   class Fred
     @@foo = 99
     def foo
       @@foo
     end
   end

   def Fred.foo
     class_variable_set(:@@foo, 101)      #=> 101
   end
   Fred.foo
   Fred.new.foo                             #=> 101
mod.class_variables => array

Returns an array of the names of class variables in mod and the ancestors of mod.

   class One
     @@var1 = 1
   end
   class Two < One
     @@var2 = 2
   end
   One.class_variables   #=> ["@@var1"]
   Two.class_variables   #=> ["@@var2", "@@var1"]
mod.const_defined?(sym) => true or false

Returns true if a constant with the given name is defined by mod.

   Math.const_defined? "PI"   #=> true
mod.const_get(sym) => obj

Returns the value of the named constant in mod.

   Math.const_get(:PI)   #=> 3.14159265358979
mod.const_missing(sym) => obj

Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for the undefined constant, and returns a value to be used for that constant. The following code is a (very bad) example: if reference is made to an undefined constant, it attempts to load a file whose name is the lowercase version of the constant (thus class Fred is assumed to be in file fred.rb). If found, it returns the value of the loaded class. It therefore implements a perverse kind of autoload facility.

  def Object.const_missing(name)
    @looked_for ||= {}
    str_name = name.to_s
    raise "Class not found: #{name}" if @looked_for[str_name]
    @looked_for[str_name] = 1
    file = str_name.downcase
    require file
    klass = const_get(name)
    return klass if klass
    raise "Class not found: #{name}"
  end
mod.const_set(sym, obj) => obj

Sets the named constant to the given object, returning that object. Creates a new constant if no constant with the given name previously existed.

   Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)   #=> 3.14285714285714
   Math::HIGH_SCHOOL_PI - Math::PI              #=> 0.00126448926734968
mod.constants => array

Returns an array of the names of the constants accessible in mod. This includes the names of constants in any included modules (example at start of section).

define_method(symbol, method) => new_method
define_method(symbol) { block } => proc

Defines an instance method in the receiver. The method parameter can be a Proc or Method object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.)

   class A
     def fred
       puts "In Fred"
     end
     def create_method(name, &block)
       self.class.send(:define_method, name, &block)
     end
     define_method(:wilma) { puts "Charge it!" }
   end
   class B < A
     define_method(:barney, instance_method(:fred))
   end
   a = B.new
   a.barney
   a.wilma
   a.create_method(:betty) { p self }
   a.betty

produces:

   In Fred
   Charge it!
   #<B:0x401b39e8>
extend_object(obj) => obj

Extends the specified object by adding this module‘s constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.

   module Picky
     def Picky.extend_object(o)
       if String === o
         puts "Can't add Picky to a String"
       else
         puts "Picky added to #{o.class}"
         super
       end
     end
   end
   (s = Array.new).extend Picky  # Call Object.extend
   (s = "quick brown fox").extend Picky

produces:

   Picky added to Array
   Can't add Picky to a String
extended(p1)

Not documented

mod.freeze

Prevents further modifications to mod.

include(module, ...) => self

Invokes Module.append_features on each parameter in turn.

mod.include?(module) => true or false

Returns true if module is included in mod or one of mod‘s ancestors.

   module A
   end
   class B
     include A
   end
   class C < B
   end
   B.include?(A)   #=> true
   C.include?(A)   #=> true
   A.include?(A)   #=> false
included( othermod )

Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features if your code wants to perform some action when a module is included in another.

       module A
         def A.included(mod)
           puts "#{self} included in #{mod}"
         end
       end
       module Enumerable
         include A
       end
mod.included_modules → array

Returns the list of modules included in mod.

   module Mixin
   end

   module Outer
     include Mixin
   end

   Mixin.included_modules   #=> []
   Outer.included_modules   #=> [Mixin]
mod.instance_method(symbol) => unbound_method

Returns an UnboundMethod representing the given instance method in mod.

   class Interpreter
     def do_a() print "there, "; end
     def do_d() print "Hello ";  end
     def do_e() print "!\n";     end
     def do_v() print "Dave";    end
     Dispatcher = {
      ?a => instance_method(:do_a),
      ?d => instance_method(:do_d),
      ?e => instance_method(:do_e),
      ?v => instance_method(:do_v)
     }
     def interpret(string)
       string.each_byte {|b| Dispatcher[b].bind(self).call }
     end
   end

   interpreter = Interpreter.new
   interpreter.interpret('dave')

produces:

   Hello there, Dave!
mod.instance_methods(include_super=true) => array

Returns an array containing the names of public instance methods in the receiver. For a module, these are the public methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod‘s superclasses are returned.

   module A
     def method1()  end
   end
   class B
     def method2()  end
   end
   class C < B
     def method3()  end
   end

   A.instance_methods                #=> ["method1"]
   B.instance_methods(false)         #=> ["method2"]
   C.instance_methods(false)         #=> ["method3"]
   C.instance_methods(true).length   #=> 43
method_added(p1)

Not documented

mod.method_defined?(symbol) => true or false

Returns true if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors). Public and protected methods are matched.

   module A
     def method1()  end
   end
   class B
     def method2()  end
   end
   class C < B
     include A
     def method3()  end
   end

   A.method_defined? :method1    #=> true
   C.method_defined? "method1"   #=> true
   C.method_defined? "method2"   #=> true
   C.method_defined? "method3"   #=> true
   C.method_defined? "method4"   #=> false
method_removed(p1)

Not documented

method_undefined(p1)

Not documented

mod.class_eval(string [, filename [, lineno]]) => obj
mod.module_eval {|| block } => obj

Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.

   class Thing
   end
   a = %q{def hello() "Hello there!" end}
   Thing.module_eval(a)
   puts Thing.new.hello()
   Thing.module_eval("invalid code", "dummy", 123)

produces:

   Hello there!
   dummy:123:in `module_eval': undefined local variable
       or method `code' for Thing:Class
module_function(symbol, ...) => self

Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.

   module Mod
     def one
       "This is one"
     end
     module_function :one
   end
   class Cls
     include Mod
     def callOne
       one
     end
   end
   Mod.one     #=> "This is one"
   c = Cls.new
   c.callOne   #=> "This is one"
   module Mod
     def one
       "This is the new one"
     end
   end
   Mod.one     #=> "This is one"
   c.callOne   #=> "This is the new one"
mod.name => string

Returns the name of the module mod.

private => self
private(symbol, ...) => self

With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility.

   module Mod
     def a()  end
     def b()  end
     private
     def c()  end
     private :a
   end
   Mod.private_instance_methods   #=> ["a", "c"]
mod.private_class_method(symbol, ...) => mod

Makes existing class methods private. Often used to hide the default constructor new.

   class SimpleSingleton  # Not thread safe
     private_class_method :new
     def SimpleSingleton.create(*args, &block)
       @me = new(*args, &block) if ! @me
       @me
     end
   end
mod.private_instance_methods(include_super=true) => array

Returns a list of the private instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

   module Mod
     def method1()  end
     private :method1
     def method2()  end
   end
   Mod.instance_methods           #=> ["method2"]
   Mod.private_instance_methods   #=> ["method1"]
mod.private_method_defined?(symbol) => true or false

Returns true if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its ancestors).

   module A
     def method1()  end
   end
   class B
     private
     def method2()  end
   end
   class C < B
     include A
     def method3()  end
   end

   A.method_defined? :method1            #=> true
   C.private_method_defined? "method1"   #=> false
   C.private_method_defined? "method2"   #=> true
   C.method_defined? "method2"           #=> false
protected => self
protected(symbol, ...) => self

With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility.

mod.protected_instance_methods(include_super=true) => array

Returns a list of the protected instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

mod.protected_method_defined?(symbol) => true or false

Returns true if the named protected method is defined by mod (or its included modules and, if mod is a class, its ancestors).

   module A
     def method1()  end
   end
   class B
     protected
     def method2()  end
   end
   class C < B
     include A
     def method3()  end
   end

   A.method_defined? :method1              #=> true
   C.protected_method_defined? "method1"   #=> false
   C.protected_method_defined? "method2"   #=> true
   C.method_defined? "method2"             #=> true
public => self
public(symbol, ...) => self

With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility.

mod.public_class_method(symbol, ...) => mod

Makes a list of existing class methods public.

mod.public_instance_methods(include_super=true) => array

Returns a list of the public instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

mod.public_method_defined?(symbol) => true or false

Returns true if the named public method is defined by mod (or its included modules and, if mod is a class, its ancestors).

   module A
     def method1()  end
   end
   class B
     protected
     def method2()  end
   end
   class C < B
     include A
     def method3()  end
   end

   A.method_defined? :method1           #=> true
   C.public_method_defined? "method1"   #=> true
   C.public_method_defined? "method2"   #=> false
   C.method_defined? "method2"          #=> true
remove_class_variable(sym) => obj

Removes the definition of the sym, returning that constant‘s value.

   class Dummy
     @@var = 99
     puts @@var
     remove_class_variable(:@@var)
     puts(defined? @@var)
   end

produces:

   99
   nil
remove_const(sym) => obj

Removes the definition of the given constant, returning that constant‘s value. Predefined classes and singleton objects (such as true) cannot be removed.

remove_method(symbol) => self

Removes the method identified by symbol from the current class. For an example, see Module.undef_method.

mod.to_s => string

Return a string representing this module or class. For basic classes and modules, this is the name. For singletons, we show information on the thing we‘re attached to as well.

undef_method(symbol) => self

Prevents the current class from responding to calls to the named method. Contrast this with remove_method, which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver.

   class Parent
     def hello
       puts "In parent"
     end
   end
   class Child < Parent
     def hello
       puts "In child"
     end
   end

   c = Child.new
   c.hello

   class Child
     remove_method :hello  # remove from child, still in parent
   end
   c.hello

   class Child
     undef_method :hello   # prevent any calls to 'hello'
   end
   c.hello

produces:

   In child
   In parent
   prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)


Module: Net

Module | Net
In: | lib/net/pop.rb lib/net/protocol.rb lib/net/ftp.rb lib/net/telnet.rb lib/net/smtp.rb lib/net/https.rb lib/net/imap.rb lib/net/http.rb

Classes and Modules

Module Net::HTTPExceptions
Module Net::HTTPHeader
Module Net::SMTPError
Class Net::APOP
Class Net::FTP
Class Net::HTTP
Class Net::HTTPError
Class Net::HTTPFatalError
Class Net::HTTPGenericRequest
Class Net::HTTPRequest
Class Net::HTTPResponse
Class Net::HTTPRetriableError
Class Net::HTTPServerException
Class Net::IMAP
Class Net::POP3
Class Net::POPAuthenticationError
Class Net::POPBadResponse
Class Net::POPError
Class Net::POPMail
Class Net::ProtoAuthError
Class Net::ProtoCommandError
Class Net::ProtoFatalError
Class Net::ProtoRetriableError
Class Net::ProtoServerError
Class Net::ProtoSyntaxError
Class Net::ProtoUnknownError
Class Net::ProtocolError
Class Net::SMTP
Class Net::SMTPAuthenticationError
Class Net::SMTPFatalError
Class Net::SMTPServerBusy
Class Net::SMTPSyntaxError
Class Net::SMTPUnknownError
Class Net::Telnet
Class Net::WriteAdapter

Constants

HTTPSession = HTTP


Class: Net::APOP

Class | Net::APOP
In: | lib/net/pop.rb
Parent: | POP3

This class is equivalent to POP3, except that it uses APOP authentication.

Methods

apop?

Public Instance methods

apop?()

Always returns true.


Class: Net::FTP

Class | Net::FTP
In: | lib/net/ftp.rb
Parent: | Object

This class implements the File Transfer Protocol. If you have used a command-line FTP program, and are familiar with the commands, you will be able to use this class easily. Some extra features are included to take advantage of Ruby‘s style and strengths.

Example

  require 'net/ftp'

Example 1

  ftp = Net::FTP.new('ftp.netlab.co.jp')
  ftp.login
  files = ftp.chdir('pub/lang/ruby/contrib')
  files = ftp.list('n*')
  ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
  ftp.close

Example 2

  Net::FTP.open('ftp.netlab.co.jp') do |ftp|
    ftp.login
    files = ftp.chdir('pub/lang/ruby/contrib')
    files = ftp.list('n*')
    ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
  end

Major Methods

The following are the methods most likely to be useful to users:

  • FTP.open
  • getbinaryfile
  • gettextfile
  • putbinaryfile
  • puttextfile
  • chdir
  • nlst
  • size
  • rename
  • delete

Methods

abort acct chdir close closed? connect delete dir get getbinaryfile getdir gettextfile help list login ls mdtm mkdir mtime new nlst noop open put putbinaryfile puttextfile pwd quit rename retrbinary retrlines return_code return_code= rmdir sendcmd set_socket site size status storbinary storlines system voidcmd

Included Modules

MonitorMixin

External Aliases

last_response_code -> lastresp

Attributes

binary | [RW] | When true, transfers are performed in binary mode. Default: true.
debug_mode | [RW] | When true, all traffic to and from the server is written to +$stdout+. Default: false.
last_response | [R] | The server‘s last response.
last_response_code | [R] | The server‘s last response code.
passive | [RW] | When true, the connection is in passive mode. Default: false.
resume | [RW] | Sets or retrieves the resume status, which decides whether incomplete transfers are resumed or restarted. Default: false.
welcome | [R] | The server‘s welcome message.

Public Class methods

new(host = nil, user = nil, passwd = nil, acct = nil)

Creates and returns a new FTP object. If a host is given, a connection is made. Additionally, if the user is given, the given user name, password, and (optionally) account are used to log in. See login.

open(host, user = nil, passwd = nil, acct = nil) {|ftp| ...}

A synonym for FTP.new, but with a mandatory host parameter.

If a block is given, it is passed the FTP object, which will be closed when the block finishes, or when an exception is raised.

Public Instance methods

abort()

Aborts the previous command (ABOR command).

acct(account)

Sends the ACCT command. TODO: more info.

chdir(dirname)

Changes the (remote) directory.

close()

Closes the connection. Further operations are impossible until you open a new connection with connect.

closed?()

Returns true iff the connection is closed.

connect(host, port = FTP_PORT)

Establishes an FTP connection to host, optionally overriding the default port. If the environment variable SOCKS_SERVER is set, sets up the connection through a SOCKS proxy. Raises an exception (typically Errno::ECONNREFUSED) if the connection cannot be established.

delete(filename)

Deletes a file on the server.

dir(*args)

Alias for list

get(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE) {|data| ...}

Retrieves remotefile in whatever mode the session is set (text or binary). See gettextfile and getbinaryfile.

getbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE) {|data| ...}

Retrieves remotefile in binary mode, storing the result in localfile. If a block is supplied, it is passed the retrieved data in blocksize chunks.

getdir()

Alias for pwd

gettextfile(remotefile, localfile = File.basename(remotefile)) {|line| ...}

Retrieves remotefile in ASCII (text) mode, storing the result in localfile. If a block is supplied, it is passed the retrieved data one line at a time.

help(arg = nil)

Issues the HELP command.

list(*args) {|line| ...}

Returns an array of file information in the directory (the output is like `ls -l`). If a block is given, it iterates through the listing.

login(user = "anonymous", passwd = nil, acct = nil)

Logs in to the remote host. The session must have been previously connected. If user is the string "anonymous" and the password is nil, a password of user@host is synthesized. If the acct parameter is not nil, an FTP ACCT command is sent following the successful login. Raises an exception on error (typically Net::FTPPermError).

ls(*args)

Alias for list

mdtm(filename)

Issues the MDTM command. TODO: more info.

mkdir(dirname)

Creates a remote directory.

mtime(filename, local = false)

Returns the last modification time of the (remote) file. If local is true, it is returned as a local time, otherwise it‘s a UTC time.

nlst(dir = nil)

Returns an array of filenames in the remote directory.

noop()

Issues a NOOP command.

put(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block)

Transfers localfile to the server in whatever mode the session is set (text or binary). See puttextfile and putbinaryfile.

putbinaryfile(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE) {|data| ...}

Transfers localfile to the server in binary mode, storing the result in remotefile. If a block is supplied, calls it, passing in the transmitted data in blocksize chunks.

puttextfile(localfile, remotefile = File.basename(localfile)) {|line| ...}

Transfers localfile to the server in ASCII (text) mode, storing the result in remotefile. If callback or an associated block is supplied, calls it, passing in the transmitted data one line at a time.

pwd()

Returns the current remote directory.

quit()

Exits the FTP session.

rename(fromname, toname)

Renames a file on the server.

retrbinary(cmd, blocksize, rest_offset = nil) {|data| ...}

Puts the connection into binary (image) mode, issues the given command, and fetches the data returned, passing it to the associated block in chunks of blocksize characters. Note that cmd is a server command (such as "RETR myfile").

retrlines(cmd) {|line| ...}

Puts the connection into ASCII (text) mode, issues the given command, and passes the resulting data, one line at a time, to the associated block. If no block is given, prints the lines. Note that cmd is a server command (such as "RETR myfile").

return_code()

Obsolete

return_code=(s)

Obsolete

rmdir(dirname)

Removes a remote directory.

sendcmd(cmd)

Sends a command and returns the response.

set_socket(sock, get_greeting = true)

WRITEME or make private

site(arg)

Issues a SITE command.

size(filename)

Returns the size of the given (remote) filename.

status()

Returns the status (STAT command).

storbinary(cmd, file, blocksize, rest_offset = nil) {|data| ...}

Puts the connection into binary (image) mode, issues the given server-side command (such as "STOR myfile"), and sends the contents of the file named file to the server. If the optional block is given, it also passes it the data, in chunks of blocksize characters.

storlines(cmd, file) {|line| ...}

Puts the connection into ASCII (text) mode, issues the given server-side command (such as "STOR myfile"), and sends the contents of the file named file to the server, one line at a time. If the optional block is given, it also passes it the lines.

system()

Returns system information.

voidcmd(cmd)

Sends a command and expect a response beginning with ‘2’.


Class: Net::HTTP

Class | Net::HTTP
In: | lib/net/https.rb lib/net/http.rb
Parent: | Object

What Is This Library?

This library provides your program functions to access WWW documents via HTTP, Hyper Text Transfer Protocol version 1.1. For details of HTTP, refer [RFC2616] (www.ietf.org/rfc/rfc2616.txt).

Examples

Getting Document From WWW Server

Example 1: Simple GET+print

    require 'net/http'
    Net::HTTP.get_print 'www.example.com', '/index.html'

Example 2: Simple GET+print by URL

    require 'net/http'
    require 'uri'
    Net::HTTP.get_print URI.parse('http://www.example.com/index.html')

Example 3: More generic GET+print

    require 'net/http'
    require 'uri'

    url = URI.parse('http://www.example.com/index.html')
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.get('/index.html')
    }
    puts res.body

Example 4: More generic GET+print

    require 'net/http'

    url = URI.parse('http://www.example.com/index.html')
    req = Net::HTTP::Get.new(url.path)
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.request(req)
    }
    puts res.body

Posting Form Data

    require 'net/http'
    require 'uri'

    #1: Simple POST
    res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
                              {'q'=>'ruby', 'max'=>'50'})
    puts res.body

    #2: POST with basic authentication
    res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'),
                                        {'from'=>'2005-01-01', 'to'=>'2005-03-31'})
    puts res.body

    #3: Detailed control
    url = URI.parse('http://www.example.com/todo.cgi')
    req = Net::HTTP::Post.new(url.path)
    req.basic_auth 'jack', 'pass'
    req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, ';')
    res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
    case res
    when Net::HTTPSuccess, Net::HTTPRedirection
      # OK
    else
      res.error!
    end

Accessing via Proxy

Net::HTTP.Proxy creates http proxy class. It has same methods of Net::HTTP but its instances always connect to proxy, instead of given host.

    require 'net/http'

    proxy_addr = 'your.proxy.host'
    proxy_port = 8080
            :
    Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
      # always connect to your.proxy.addr:8080
            :
    }

Since Net::HTTP.Proxy returns Net::HTTP itself when proxy_addr is nil, there‘s no need to change code if there‘s proxy or not.

There are two additional parameters in Net::HTTP.Proxy which allow to specify proxy user name and password:

    Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user = nil, proxy_pass = nil)

You may use them to work with authorization-enabled proxies:

    require 'net/http'
    require 'uri'

    proxy_host = 'your.proxy.host'
    proxy_port = 8080
    uri = URI.parse(ENV['http_proxy'])
    proxy_user, proxy_pass = uri.userinfo.split(/:/) if uri.userinfo
    Net::HTTP::Proxy(proxy_host, proxy_port,
                     proxy_user, proxy_pass).start('www.example.com') {|http|
      # always connect to your.proxy.addr:8080 using specified username and password
            :
    }

Note that net/http never rely on HTTP_PROXY environment variable. If you want to use proxy, set it explicitly.

Following Redirection

    require 'net/http'
    require 'uri'

    def fetch(uri_str, limit = 10)
      # You should choose better exception.
      raise ArgumentError, 'HTTP redirect too deep' if limit == 0

      response = Net::HTTP.get_response(URI.parse(uri_str))
      case response
      when Net::HTTPSuccess     then response
      when Net::HTTPRedirection then fetch(response['location'], limit - 1)
      else
        response.error!
      end
    end

    print fetch('http://www.ruby-lang.org')

Net::HTTPSuccess and Net::HTTPRedirection is a HTTPResponse class. All HTTPResponse objects belong to its own response class which indicate HTTP result status. For details of response classes, see section "HTTP Response Classes".

Basic Authentication

    require 'net/http'

    Net::HTTP.start('www.example.com') {|http|
      req = Net::HTTP::Get.new('/secret-page.html')
      req.basic_auth 'account', 'password'
      response = http.request(req)
      print response.body
    }

HTTP Request Classes

Here is HTTP request class hierarchy.

  Net::HTTPRequest
      Net::HTTP::Get
      Net::HTTP::Head
      Net::HTTP::Post
      Net::HTTP::Put
      Net::HTTP::Proppatch
      Net::HTTP::Lock
      Net::HTTP::Unlock
      Net::HTTP::Options
      Net::HTTP::Propfind
      Net::HTTP::Delete
      Net::HTTP::Move
      Net::HTTP::Copy
      Net::HTTP::Mkcol
      Net::HTTP::Trace

HTTP Response Classes

Here is HTTP response class hierarchy. All classes are defined in Net module.

  HTTPResponse
      HTTPUnknownResponse
      HTTPInformation                    # 1xx
          HTTPContinue                       # 100
          HTTPSwitchProtocl                  # 101
      HTTPSuccess                        # 2xx
          HTTPOK                             # 200
          HTTPCreated                        # 201
          HTTPAccepted                       # 202
          HTTPNonAuthoritativeInformation    # 203
          HTTPNoContent                      # 204
          HTTPResetContent                   # 205
          HTTPPartialContent                 # 206
      HTTPRedirection                    # 3xx
          HTTPMultipleChoice                 # 300
          HTTPMovedPermanently               # 301
          HTTPFound                          # 302
          HTTPSeeOther                       # 303
          HTTPNotModified                    # 304
          HTTPUseProxy                       # 305
          HTTPTemporaryRedirect              # 307
      HTTPClientError                    # 4xx
          HTTPBadRequest                     # 400
          HTTPUnauthorized                   # 401
          HTTPPaymentRequired                # 402
          HTTPForbidden                      # 403
          HTTPNotFound                       # 404
          HTTPMethodNotAllowed               # 405
          HTTPNotAcceptable                  # 406
          HTTPProxyAuthenticationRequired    # 407
          HTTPRequestTimeOut                 # 408
          HTTPConflict                       # 409
          HTTPGone                           # 410
          HTTPLengthRequired                 # 411
          HTTPPreconditionFailed             # 412
          HTTPRequestEntityTooLarge          # 413
          HTTPRequestURITooLong              # 414
          HTTPUnsupportedMediaType           # 415
          HTTPRequestedRangeNotSatisfiable   # 416
          HTTPExpectationFailed              # 417
      HTTPServerError                    # 5xx
          HTTPInternalServerError            # 500
          HTTPNotImplemented                 # 501
          HTTPBadGateway                     # 502
          HTTPServiceUnavailable             # 503
          HTTPGatewayTimeOut                 # 504
          HTTPVersionNotSupported            # 505

Switching Net::HTTP versions

You can use net/http.rb 1.1 features (bundled with Ruby 1.6) by calling HTTP.version_1_1. Calling Net::HTTP.version_1_2 allows you to use 1.2 features again.

    # example
    Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }

    Net::HTTP.version_1_1
    Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }

    Net::HTTP.version_1_2
    Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }

This function is NOT thread-safe.

Methods

Proxy active? copy default_port delete finish get get get2 get_print get_response head head2 http_default_port https_default_port inspect lock mkcol move new new options peer_cert post post2 post_form propfind proppatch proxy? proxy_address proxy_class? proxy_pass proxy_port proxy_user proxyaddr proxyport read_timeout= request request_get request_head request_post send_request set_debug_output ssl_context_accessor ssl_timeout ssl_timeout= start start started? timeout= trace unlock use_ssl use_ssl= use_ssl? use_ssl? version_1_1 version_1_1? version_1_2 version_1_2?

Classes and Modules

Class Net::HTTP::Copy
Class Net::HTTP::Delete
Class Net::HTTP::Get
Class Net::HTTP::Head
Class Net::HTTP::Lock
Class Net::HTTP::Mkcol
Class Net::HTTP::Move
Class Net::HTTP::Options
Class Net::HTTP::Post
Class Net::HTTP::Propfind
Class Net::HTTP::Proppatch
Class Net::HTTP::Put
Class Net::HTTP::Trace
Class Net::HTTP::Unlock

External Aliases

version_1_1? | -> | is_version_1_1?
version_1_2? | -> | is_version_1_2?
new | -> | newobj
request_put | -> | put2

Attributes

address | [R] | The host name to connect to.
close_on_empty_response | [RW] |
enable_post_connection_check | [RW] | specify enabling SSL server certificate and hostname checking.
open_timeout | [RW] | Seconds to wait until connection is opened. If the HTTP object cannot open a connection in this many seconds, it raises a TimeoutError exception.
port | [R] | The port number to connect to.
proxy_address | [R] |
proxy_pass | [R] |
proxy_port | [R] |
proxy_user | [R] |
read_timeout | [R] | Seconds to wait until reading one block (by one read(2) call). If the HTTP object cannot open a connection in this many seconds, it raises a TimeoutError exception.

Public Class methods

Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)

Creates an HTTP proxy class. Arguments are address/port of proxy host and username/password if authorization on proxy server is required. You can replace the HTTP class with created proxy class.

If ADDRESS is nil, this method returns self (Net::HTTP).

    # Example
    proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080)
                    :
    proxy_class.start('www.ruby-lang.org') {|http|
      # connecting proxy.foo.org:8080
                    :
    }
default_port()

The default port to use for HTTP requests; defaults to 80.

get(uri_or_host, path = nil, port = nil)

Send a GET request to the target and return the response as a string. The target can either be specified as (uri), or as (host, path, port = 80); so:

   print Net::HTTP.get(URI.parse('http://www.example.com/index.html'))

or:

   print Net::HTTP.get('www.example.com', '/index.html')
get_print(uri_or_host, path = nil, port = nil)

Get body from target and output it to +$stdout+. The target can either be specified as (uri), or as (host, path, port = 80); so:

   Net::HTTP.get_print URI.parse('http://www.example.com/index.html')

or:

   Net::HTTP.get_print 'www.example.com', '/index.html'
get_response(uri_or_host, path = nil, port = nil, &block)

Send a GET request to the target and return the response as a Net::HTTPResponse object. The target can either be specified as (uri), or as (host, path, port = 80); so:

   res = Net::HTTP.get_response(URI.parse('http://www.example.com/index.html'))
   print res.body

or:

   res = Net::HTTP.get_response('www.example.com', '/index.html')
   print res.body
http_default_port()

The default port to use for HTTP requests; defaults to 80.

https_default_port()

The default port to use for HTTPS requests; defaults to 443.

new(address, port = nil)

Creates a new Net::HTTP object for the specified address. This method does not open the TCP connection.

new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)

Creates a new Net::HTTP object. If proxy_addr is given, creates an Net::HTTP object with proxy support. This method does not open the TCP connection.

post_form(url, params)

Posts HTML form data to the URL. Form data must be represented as a Hash of String to String, e.g:

  { "cmd" => "search", "q" => "ruby", "max" => "50" }

This method also does Basic Authentication iff URL.user exists.

Example:

  require 'net/http'
  require 'uri'

  HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
                 { "q" => "ruby", "max" => "50" }
proxy_class?()

returns true if self is a class which was created by HTTP::Proxy.

ssl_context_accessor(name)
start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil) {|+http+| ...}

creates a new Net::HTTP object and opens its TCP connection and HTTP session. If the optional block is given, the newly created Net::HTTP object is passed to it and closed when the block finishes. In this case, the return value of this method is the return value of the block. If no block is given, the return value of this method is the newly created Net::HTTP object itself, and the caller is responsible for closing it upon completion.

version_1_1()

Turns on net/http 1.1 (ruby 1.6) features. Defaults to OFF in ruby 1.8.

version_1_1?()

true if net/http is in version 1.1 compatible mode. Defaults to true.

version_1_2()

Turns on net/http 1.2 (ruby 1.8) features. Defaults to ON in ruby 1.8.

I strongly recommend to call this method always.

  require 'net/http'
  Net::HTTP.version_1_2
version_1_2?()

true if net/http is in version 1.2 mode. Defaults to true.

Public Instance methods

active?()

Alias for started?

copy(path, initheader = nil)

Sends a COPY request to the path and gets a response, as an HTTPResponse object.

delete(path, initheader = {'Depth' => 'Infinity'})

Sends a DELETE request to the path and gets a response, as an HTTPResponse object.

finish()

Finishes HTTP session and closes TCP connection. Raises IOError if not started.

get(path, initheader = nil, dest = nil) {|+body_segment+| ...}

Gets data from path on the connected-to host. header must be a Hash like { ‘Accept’ => ’*/*’, … }.

In version 1.1 (ruby 1.6), this method returns a pair of objects, a Net::HTTPResponse object and the entity body string. In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object.

If called with a block, yields each fragment of the entity body in turn as a string as it is read from the socket. Note that in this case, the returned response object will not contain a (meaningful) body.

dest argument is obsolete. It still works but you must not use it.

In version 1.1, this method might raise an exception for 3xx (redirect). In this case you can get a HTTPResponse object by "anException.response".

In version 1.2, this method never raises exception.

    # version 1.1 (bundled with Ruby 1.6)
    response, body = http.get('/index.html')

    # version 1.2 (bundled with Ruby 1.8 or later)
    response = http.get('/index.html')

    # using block
    File.open('result.txt', 'w') {|f|
      http.get('/~foo/') do |str|
        f.write str
      end
    }
get2(path, initheader = nil)

Alias for request_get

head(path, initheader = nil)

Gets only the header from path on the connected-to host. header is a Hash like { ‘Accept’ => ’*/*’, … }.

This method returns a Net::HTTPResponse object.

In version 1.1, this method might raise an exception for 3xx (redirect). On the case you can get a HTTPResponse object by "anException.response". In version 1.2, this method never raises an exception.

    response = nil
    Net::HTTP.start('some.www.server', 80) {|http|
      response = http.head('/index.html')
    }
    p response['content-type']
head2(path, initheader = nil, &block)

Alias for request_head

inspect()
lock(path, body, initheader = nil)

Sends a LOCK request to the path and gets a response, as an HTTPResponse object.

mkcol(path, body = nil, initheader = nil)

Sends a MKCOL request to the path and gets a response, as an HTTPResponse object.

move(path, initheader = nil)

Sends a MOVE request to the path and gets a response, as an HTTPResponse object.

options(path, initheader = nil)

Sends a OPTIONS request to the path and gets a response, as an HTTPResponse object.

peer_cert()
post(path, data, initheader = nil, dest = nil) {|+body_segment+| ...}

Posts data (must be a String) to path. header must be a Hash like { ‘Accept’ => ’*/*’, … }.

In version 1.1 (ruby 1.6), this method returns a pair of objects, a Net::HTTPResponse object and an entity body string. In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object.

If called with a block, yields each fragment of the entity body in turn as a string as it are read from the socket. Note that in this case, the returned response object will not contain a (meaningful) body.

dest argument is obsolete. It still works but you must not use it.

In version 1.1, this method might raise an exception for 3xx (redirect). In this case you can get an HTTPResponse object by "anException.response". In version 1.2, this method never raises exception.

    # version 1.1
    response, body = http.post('/cgi-bin/search.rb', 'query=foo')

    # version 1.2
    response = http.post('/cgi-bin/search.rb', 'query=foo')

    # using block
    File.open('result.txt', 'w') {|f|
      http.post('/cgi-bin/search.rb', 'query=foo') do |str|
        f.write str
      end
    }

You should set Content-Type: header field for POST. If no Content-Type: field given, this method uses "application/x-www-form-urlencoded" by default.

post2(path, data, initheader = nil)

Alias for request_post

propfind(path, body = nil, initheader = {'Depth' => '0'})

Sends a PROPFIND request to the path and gets a response, as an HTTPResponse object.

proppatch(path, body, initheader = nil)

Sends a PROPPATCH request to the path and gets a response, as an HTTPResponse object.

proxy?()

True if self is a HTTP proxy class.

proxy_address()

Address of proxy host. If self does not use a proxy, nil.

proxy_pass()

User password for accessing proxy. If self does not use a proxy, nil.

proxy_port()

Port number of proxy host. If self does not use a proxy, nil.

proxy_user()

User name for accessing proxy. If self does not use a proxy, nil.

proxyaddr()

Alias for proxy_address

proxyport()

Alias for proxy_port

read_timeout=(sec)

Setter for the read_timeout attribute.

request(req, body = nil) {|+response+| ...}

Sends an HTTPRequest object REQUEST to the HTTP server. This method also sends DATA string if REQUEST is a post/put request. Giving DATA for get/head request causes ArgumentError.

When called with a block, yields an HTTPResponse object. The body of this response will not have been read yet; the caller can process it using HTTPResponse#read_body, if desired.

Returns a HTTPResponse object.

This method never raises Net::* exceptions.

request_get(path, initheader = nil) {|+response+| ...}

Sends a GET request to the path and gets a response, as an HTTPResponse object.

When called with a block, yields an HTTPResponse object. The body of this response will not have been read yet; the caller can process it using HTTPResponse#read_body, if desired.

Returns the response.

This method never raises Net::* exceptions.

    response = http.request_get('/index.html')
    # The entity body is already read here.
    p response['content-type']
    puts response.body

    # using block
    http.request_get('/index.html') {|response|
      p response['content-type']
      response.read_body do |str|   # read body now
        print str
      end
    }
request_head(path, initheader = nil, &block)

Sends a HEAD request to the path and gets a response, as an HTTPResponse object.

Returns the response.

This method never raises Net::* exceptions.

    response = http.request_head('/index.html')
    p response['content-type']
request_post(path, data, initheader = nil) {|+response+| ...}

Sends a POST request to the path and gets a response, as an HTTPResponse object.

When called with a block, yields an HTTPResponse object. The body of this response will not have been read yet; the caller can process it using HTTPResponse#read_body, if desired.

Returns the response.

This method never raises Net::* exceptions.

    # example
    response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
    p response.status
    puts response.body          # body is already read

    # using block
    http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
      p response.status
      p response['content-type']
      response.read_body do |str|   # read body now
        print str
      end
    }
send_request(name, path, data = nil, header = nil)

Sends an HTTP request to the HTTP server. This method also sends DATA string if DATA is given.

Returns a HTTPResponse object.

This method never raises Net::* exceptions.

   response = http.send_request('GET', '/index.html')
   puts response.body
set_debug_output(output)

WARNING This method causes serious security hole. Never use this method in production code.

Set an output stream for debugging.

  http = Net::HTTP.new
  http.set_debug_output $stderr
  http.start { .... }
ssl_timeout()
ssl_timeout=(sec)
start( {|http| ...}

Opens TCP connection and HTTP session.

When this method is called with block, gives a HTTP object to the block and closes the TCP connection / HTTP session after the block executed.

When called with a block, returns the return value of the block; otherwise, returns self.

started?()

returns true if the HTTP session is started.

timeout=(sec)

Alias for ssl_timeout=

trace(path, initheader = nil)

Sends a TRACE request to the path and gets a response, as an HTTPResponse object.

unlock(path, body, initheader = nil)

Sends a UNLOCK request to the path and gets a response, as an HTTPResponse object.

use_ssl()

Alias for use_ssl?

use_ssl=(flag)

Turn on/off SSL. This flag must be set before starting session. If you change use_ssl value after session started, a Net::HTTP object raises IOError.

use_ssl?()

returns true if use SSL/TLS with HTTP.

use_ssl?()


Class: Net::HTTP::Copy

Class | Net::HTTP::Copy
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'COPY'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Delete

Class | Net::HTTP::Delete
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'DELETE'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Get

Class | Net::HTTP::Get
In: | lib/net/http.rb
Parent: | HTTPRequest

HTTP 1.1 methods — RFC2616

Constants

METHOD | = | 'GET'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Head

Class | Net::HTTP::Head
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'HEAD'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | false


Class: Net::HTTP::Lock

Class | Net::HTTP::Lock
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'LOCK'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Mkcol

Class | Net::HTTP::Mkcol
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'MKCOL'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Move

Class | Net::HTTP::Move
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'MOVE'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Options

Class | Net::HTTP::Options
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'OPTIONS'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | false


Class: Net::HTTP::Post

Class | Net::HTTP::Post
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'POST'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Propfind

Class | Net::HTTP::Propfind
In: | lib/net/http.rb
Parent: | HTTPRequest

WebDAV methods — RFC2518

Constants

METHOD | = | 'PROPFIND'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Proppatch

Class | Net::HTTP::Proppatch
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'PROPPATCH'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Put

Class | Net::HTTP::Put
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'PUT'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Trace

Class | Net::HTTP::Trace
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'TRACE'
REQUEST_HAS_BODY | = | false
RESPONSE_HAS_BODY | = | true


Class: Net::HTTP::Unlock

Class | Net::HTTP::Unlock
In: | lib/net/http.rb
Parent: | HTTPRequest

Constants

METHOD | = | 'UNLOCK'
REQUEST_HAS_BODY | = | true
RESPONSE_HAS_BODY | = | true


Class: Net::HTTPError

Class | Net::HTTPError
In: | lib/net/http.rb
Parent: | ProtocolError

Included Modules

HTTPExceptions


Module: Net::HTTPExceptions

Module | Net::HTTPExceptions
In: | lib/net/http.rb

HTTP exception class. You must use its subclasses.

External Aliases

response -> data

Attributes

response [R]


Class: Net::HTTPFatalError

Class | Net::HTTPFatalError
In: | lib/net/http.rb
Parent: | ProtoFatalError

Included Modules

HTTPExceptions


Class: Net::HTTPGenericRequest

Class | Net::HTTPGenericRequest
In: | lib/net/http.rb
Parent: | Object

Parent of HTTPRequest class. Do not use this directly; use a subclass of HTTPRequest.

Mixes in the HTTPHeader module.

Methods

body= body_exist? body_stream= inspect new request_body_permitted? response_body_permitted?

Included Modules

HTTPHeader

Attributes

body | [R]
body_stream | [R]
method | [R]
path | [R]

Public Class methods

new(m, reqbody, resbody, path, initheader = nil)

Public Instance methods

body=(str)
body_exist?()
body_stream=(input)
inspect()
request_body_permitted?()
response_body_permitted?()


Module: Net::HTTPHeader

Module | Net::HTTPHeader
In: | lib/net/http.rb

Header module.

Provides access to @header in the mixed-into class as a hash-like object, except with case-insensitive keys. Also provides methods for accessing commonly-used header values in a more convenient format.

Methods

[] []= add_field basic_auth canonical_each chunked? content_length content_length= content_range content_type content_type= delete each each_capitalized each_capitalized_name each_header each_key each_name each_value fetch form_data= get_fields initialize_http_header key? main_type proxy_basic_auth range range= range_length set_content_type set_form_data set_range sub_type to_hash type_params

External Aliases

size -> length

Public Instance methods

[](key)

Returns the header field corresponding to the case-insensitive key. For example, a key of "Content-Type" might return "text/html"

[]=(key, val)

Sets the header field corresponding to the case-insensitive key.

add_field(key, val)

[Ruby 1.8.3] Adds header field instead of replace. Second argument val must be a String. See also #[]=, #[] and get_fields.

  request.add_field 'X-My-Header', 'a'
  p request['X-My-Header']              #=> "a"
  p request.get_fields('X-My-Header')   #=> ["a"]
  request.add_field 'X-My-Header', 'b'
  p request['X-My-Header']              #=> "a, b"
  p request.get_fields('X-My-Header')   #=> ["a", "b"]
  request.add_field 'X-My-Header', 'c'
  p request['X-My-Header']              #=> "a, b, c"
  p request.get_fields('X-My-Header')   #=> ["a", "b", "c"]
basic_auth(account, password)

Set the Authorization: header for "Basic" authorization.

canonical_each()

Alias for each_capitalized

chunked?()

Returns "true" if the "transfer-encoding" header is present and set to "chunked". This is an HTTP/1.1 feature, allowing the the content to be sent in "chunks" without at the outset stating the entire content length.

content_length()

Returns an Integer object which represents the Content-Length: header field or nil if that field is not provided.

content_length=(len)
content_range()

Returns a Range object which represents Content-Range: header field. This indicates, for a partial entity body, where this fragment fits inside the full entity body, as range of byte offsets.

content_type()

Returns a content type string such as "text/html". This method returns nil if Content-Type: header field does not exist.

content_type=(type, params = {})

Alias for set_content_type

delete(key)

Removes a header field.

each(

Alias for each_header

each_capitalized() {|capitalize(k), v.join(', ')| ...}

As for each_header, except the keys are provided in capitalized form.

each_capitalized_name() {|+key+| ...}

Iterates for each capitalized header names.

each_header( {|+key+, +value+| ...}

Iterates for each header names and values.

each_key()

Alias for each_name

each_name() {|+key+| ...}

Iterates for each header names.

each_value( {|+value+| ...}

Iterates for each header values.

fetch(key, *args) {|+key+| ...}

Returns the header field corresponding to the case-insensitive key. Returns the default value args, or the result of the block, or nil, if there‘s no header field named key. See Hash#fetch

form_data=(params, sep = '&')

Alias for set_form_data

get_fields(key)

[Ruby 1.8.3] Returns an array of header field strings corresponding to the case-insensitive key. This method allows you to get duplicated header fields without any processing. See also #[].

  p response.get_fields('Set-Cookie')
    #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
         "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
  p response['Set-Cookie']
    #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
initialize_http_header(initheader)
key?(key)

true if key header exists.

main_type()

Returns a content type string such as "text". This method returns nil if Content-Type: header field does not exist.

proxy_basic_auth(account, password)

Set Proxy-Authorization: header for "Basic" authorization.

range()

Returns an Array of Range objects which represents Range: header field, or nil if there is no such header.

range=(r, e = nil)

Alias for set_range

range_length()

The length of the range represented in Content-Range: header.

set_content_type(type, params = {})

Set Content-Type: header field by type and params. type must be a String, params must be a Hash.

set_form_data(params, sep = '&')

Set header fields and a body from HTML form data. params should be a Hash containing HTML form data. Optional argument sep means data record separator.

This method also set Content-Type: header field to application/x-www-form-urlencoded.

set_range(r, e = nil)

Set Range: header from Range (arg r) or beginning index and length from it (arg idx&len).

  req.range = (0..1023)
  req.set_range 0, 1023
sub_type()

Returns a content type string such as "html". This method returns nil if Content-Type: header field does not exist or sub-type is not given (e.g. "Content-Type: text").

to_hash()

Returns a Hash consist of header names and values.

type_params()

Returns content type parameters as a Hash as like {"charset" => "iso-2022-jp"}.


Class: Net::HTTPRequest

Class | Net::HTTPRequest
In: | lib/net/http.rb
Parent: | HTTPGenericRequest

HTTP request class. This class wraps request header and entity path. You must use its subclass, Net::HTTP::Get, Post, Head.

Methods

new

Public Class methods

new(path, initheader = nil)

Creates HTTP request object.


Class: Net::HTTPResponse

Class | Net::HTTPResponse
In: | lib/net/http.rb
Parent: | Object

HTTP response class. This class wraps response header and entity. Mixes in the HTTPHeader module, which provides access to response header values both via hash-like methods and individual readers. Note that each possible HTTP response code defines its own HTTPResponse subclass. These are listed below. All classes are defined under the Net module. Indentation indicates inheritance.

  xxx        HTTPResponse

    1xx        HTTPInformation
      100        HTTPContinue
      101        HTTPSwitchProtocol

    2xx        HTTPSuccess
      200        HTTPOK
      201        HTTPCreated
      202        HTTPAccepted
      203        HTTPNonAuthoritativeInformation
      204        HTTPNoContent
      205        HTTPResetContent
      206        HTTPPartialContent

    3xx        HTTPRedirection
      300        HTTPMultipleChoice
      301        HTTPMovedPermanently
      302        HTTPFound
      303        HTTPSeeOther
      304        HTTPNotModified
      305        HTTPUseProxy
      307        HTTPTemporaryRedirect

    4xx        HTTPClientError
      400        HTTPBadRequest
      401        HTTPUnauthorized
      402        HTTPPaymentRequired
      403        HTTPForbidden
      404        HTTPNotFound
      405        HTTPMethodNotAllowed
      406        HTTPNotAcceptable
      407        HTTPProxyAuthenticationRequired
      408        HTTPRequestTimeOut
      409        HTTPConflict
      410        HTTPGone
      411        HTTPLengthRequired
      412        HTTPPreconditionFailed
      413        HTTPRequestEntityTooLarge
      414        HTTPRequestURITooLong
      415        HTTPUnsupportedMediaType
      416        HTTPRequestedRangeNotSatisfiable
      417        HTTPExpectationFailed

    5xx        HTTPServerError
      500        HTTPInternalServerError
      501        HTTPNotImplemented
      502        HTTPBadGateway
      503        HTTPServiceUnavailable
      504        HTTPGatewayTimeOut
      505        HTTPVersionNotSupported

    xxx        HTTPUnknownResponse

Methods

body body_permitted? entity inspect read_body to_ary value

Included Modules

HTTPHeader

Constants

CODE_CLASS_TO_OBJ = { '1' => HTTPInformation, '2' => HTTPSuccess, '3' => HTTPRedirection, '4' => HTTPClientError, '5' => HTTPServerError
CODE_TO_OBJ = { '100' => HTTPContinue, '101' => HTTPSwitchProtocol, '200' => HTTPOK, '201' => HTTPCreated, '202' => HTTPAccepted, '203' => HTTPNonAuthoritativeInformation, '204' => HTTPNoContent, '205' => HTTPResetContent, '206' => HTTPPartialContent, '300' => HTTPMultipleChoice, '301' => HTTPMovedPermanently, '302' => HTTPFound, '303' => HTTPSeeOther, '304' => HTTPNotModified, '305' => HTTPUseProxy, '307' => HTTPTemporaryRedirect, '400' => HTTPBadRequest, '401' => HTTPUnauthorized, '402' => HTTPPaymentRequired, '403' => HTTPForbidden, '404' => HTTPNotFound, '405' => HTTPMethodNotAllowed, '406' => HTTPNotAcceptable, '407' => HTTPProxyAuthenticationRequired, '408' => HTTPRequestTimeOut, '409' => HTTPConflict, '410' => HTTPGone, '411' => HTTPLengthRequired, '412' => HTTPPreconditionFailed, '413' => HTTPRequestEntityTooLarge, '414' => HTTPRequestURITooLong, '415' => HTTPUnsupportedMediaType, '416' => HTTPRequestedRangeNotSatisfiable, '417' => HTTPExpectationFailed, '500' => HTTPInternalServerError, '501' => HTTPNotImplemented, '502' => HTTPBadGateway, '503' => HTTPServiceUnavailable, '504' => HTTPGatewayTimeOut, '505' => HTTPVersionNotSupported

External Aliases

message -> msg

Attributes

code | [R] | HTTP result code string. For example, ‘302’. You can also determine the response type by which response subclass the response object is an instance of.
http_version | [R] | The HTTP version supported by the server.
message | [R] | HTTP result message. For example, ‘Not Found’.

Public Class methods

body_permitted?()

true if the response has body.

Public Instance methods

body()

Returns the entity body.

Calling this method a second or subsequent time will return the already read string.

  http.request_get('/index.html') {|res|
    puts res.body
  }

  http.request_get('/index.html') {|res|
    p res.body.object_id   # 538149362
    p res.body.object_id   # 538149362
  }
entity()

Alias for body

inspect()
read_body(dest = nil, &block)

Gets entity body. If the block given, yields it to block. The body is provided in fragments, as it is read in from the socket.

Calling this method a second or subsequent time will return the already read string.

  http.request_get('/index.html') {|res|
    puts res.read_body
  }

  http.request_get('/index.html') {|res|
    p res.read_body.object_id   # 538149362
    p res.read_body.object_id   # 538149362
  }

  # using iterator
  http.request_get('/index.html') {|res|
    res.read_body do |segment|
      print segment
    end
  }
to_ary()

For backward compatibility. To allow Net::HTTP 1.1 style assignment e.g.

   response, body = Net::HTTP.get(....)
value()

Raises HTTP error if the response is not 2xx.


Class: Net::HTTPRetriableError

Class | Net::HTTPRetriableError
In: | lib/net/http.rb
Parent: | ProtoRetriableError

Included Modules

HTTPExceptions


Class: Net::HTTPServerException

Class | Net::HTTPServerException
In: | lib/net/http.rb
Parent: | ProtoServerError

Included Modules

HTTPExceptions


Class: Net::IMAP

Class | Net::IMAP
In: | lib/net/imap.rb
Parent: | Object

Net::IMAP implements Internet Message Access Protocol (IMAP) client functionality. The protocol is described in [IMAP].

IMAP Overview

An IMAP client connects to a server, and then authenticates itself using either authenticate() or login(). Having authenticated itself, there is a range of commands available to it. Most work with mailboxes, which may be arranged in an hierarchical namespace, and each of which contains zero or more messages. How this is implemented on the server is implementation-dependent; on a UNIX server, it will frequently be implemented as a files in mailbox format within a hierarchy of directories.

To work on the messages within a mailbox, the client must first select that mailbox, using either select() or (for read-only access) examine(). Once the client has successfully selected a mailbox, they enter selected state, and that mailbox becomes the current mailbox, on which mail-item related commands implicitly operate.

Messages have two sorts of identifiers: message sequence numbers, and UIDs.

Message sequence numbers number messages within a mail box from 1 up to the number of items in the mail box. If new message arrives during a session, it receives a sequence number equal to the new size of the mail box. If messages are expunged from the mailbox, remaining messages have their sequence numbers "shuffled down" to fill the gaps.

UIDs, on the other hand, are permanently guaranteed not to identify another message within the same mailbox, even if the existing message is deleted. UIDs are required to be assigned in ascending (but not necessarily sequential) order within a mailbox; this means that if a non-IMAP client rearranges the order of mailitems within a mailbox, the UIDs have to be reassigned. An IMAP client cannot thus rearrange message orders.

Examples of Usage

List sender and subject of all recent messages in the default mailbox

  imap = Net::IMAP.new('mail.example.com')
  imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  imap.examine('INBOX')
  imap.search(["RECENT"]).each do |message_id|
    envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
    puts "#{envelope.from[0].name}: \t#{envelope.subject}"
  end

Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"

  imap = Net::IMAP.new('mail.example.com')
  imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  imap.select('Mail/sent-mail')
  if not imap.list('Mail/', 'sent-apr03')
    imap.create('Mail/sent-apr03')
  end
  imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
    imap.copy(message_id, "Mail/sent-apr03")
    imap.store(message_id, "+FLAGS", [:Deleted])
  end
  imap.expunge

Thread Safety

Net::IMAP supports concurrent threads. For example,

  imap = Net::IMAP.new("imap.foo.net", "imap2")
  imap.authenticate("cram-md5", "bar", "password")
  imap.select("inbox")
  fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
  search_result = imap.search(["BODY", "hello"])
  fetch_result = fetch_thread.value
  imap.disconnect

This script invokes the FETCH command and the SEARCH command concurrently.

Errors

An IMAP server can send three different types of responses to indicate failure:

NO: | the attempted command could not be successfully completed. For instance, the username/password used for logging in are incorrect; the selected mailbox does not exists; etc.
BAD: | the request from the client does not follow the server‘s understanding of the IMAP protocol. This includes attempting commands from the wrong client state; for instance, attempting to perform a SEARCH command without having SELECTed a current mailbox. It can also signal an internal server failure (such as a disk crash) has occurred.
BYE: | the server is saying goodbye. This can be part of a normal logout sequence, and can be used as part of a login sequence to indicate that the server is (for some reason) unwilling to accept our connection. As a response to any other command, it indicates either that the server is shutting down, or that the server is timing out the client connection due to inactivity.

These three error response are represented by the errors Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and Net::IMAP::ByeResponseError, all of which are subclasses of Net::IMAP::ResponseError. Essentially, all methods that involve sending a request to the server can generate one of these errors. Only the most pertinent instances have been documented below.

Because the IMAP class uses Sockets for communication, its methods are also susceptible to the various errors that can occur when working with sockets. These are generally represented as Errno errors. For instance, any method that involves sending a request to the server and/or receiving a response from it could raise an Errno::EPIPE error if the network connection unexpectedly goes down. See the socket(7), ip(7), tcp(7), socket(2), connect(2), and associated man pages.

Finally, a Net::IMAP::DataFormatError is thrown if low-level data is found to be in an incorrect format (for instance, when converting between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is thrown if a server response is non-parseable.

References

[IMAP]
M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1", RFC 2060, December 1996. (Note: since obsoleted by RFC 3501)
[LANGUAGE-TAGS]
Alvestrand, H., "Tags for the Identification of Languages", RFC 1766, March 1995.
[MD5]
Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC 1864, October 1995.
[MIME-IMB]
Freed, N., and N. Borenstein, "MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies", RFC 2045, November 1996.
[RFC-822]
Crocker, D., "Standard for the Format of ARPA Internet Text Messages", STD 11, RFC 822, University of Delaware, August 1982.
[RFC-2087]
Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
[RFC-2086]
Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
[RFC-2195]
Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension for Simple Challenge/Response", RFC 2195, September 1997.
[SORT-THREAD-EXT]
Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD Extensions", draft-ietf-imapext-sort, May 2003.
[OSSL]
www.openssl.org
[RSSL]
savannah.gnu.org/projects/rubypki
[UTF7]
Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of Unicode", RFC 2152, May 1997.

Methods

add_authenticator add_response_handler append authenticate capability check close copy create debug debug= decode_utf7 delete disconnect disconnected? encode_utf7 examine expunge fetch getacl getquota getquotaroot list login logout lsub new noop remove_response_handler rename search select setacl setquota sort status store subscribe thread uid_copy uid_fetch uid_search uid_sort uid_store uid_thread unsubscribe

Included Modules

MonitorMixin OpenSSL SSL

Classes and Modules

Class Net::IMAP::BadResponseError
Class Net::IMAP::BodyTypeBasic
Class Net::IMAP::BodyTypeMessage
Class Net::IMAP::BodyTypeMultipart
Class Net::IMAP::BodyTypeText
Class Net::IMAP::ByeResponseError
Class Net::IMAP::CramMD5Authenticator
Class Net::IMAP::DataFormatError
Class Net::IMAP::Error
Class Net::IMAP::LoginAuthenticator
Class Net::IMAP::NoResponseError
Class Net::IMAP::ResponseError
Class Net::IMAP::ResponseParseError

Constants

SEEN = :Seen Flag indicating a message has been seen
ANSWERED = :Answered Flag indicating a message has been answered
FLAGGED = :Flagged Flag indicating a message has been flagged for special or urgent attention
DELETED = :Deleted Flag indicating a message has been marked for deletion. This will occur when the mailbox is closed or expunged.
DRAFT = :Draft Flag indicating a message is only a draft or work-in-progress version.
RECENT = :Recent Flag indicating that the message is "recent", meaning that this session is the first session in which the client has been notified of this message.
NOINFERIORS = :Noinferiors Flag indicating that a mailbox context name cannot contain children.
NOSELECT = :Noselect Flag indicating that a mailbox is not selected.
MARKED = :Marked Flag indicating that a mailbox has been marked "interesting" by the server; this commonly indicates that the mailbox contains new messages.
UNMARKED = :Unmarked Flag indicating that the mailbox does not contains new messages.
DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
ContinuationRequest = Struct.new(:data, :raw_data) Net::IMAP::ContinuationRequest represents command continuation requests.

The command continuation request response is indicated by a "+" token instead of a tag. This form of response indicates that the server is ready to accept the continuation of a command from the client. The remainder of this response is a line of text.

  continue_req    ::= "+" SPACE (resp_text / base64)

Fields:

data: | Returns the data (Net::IMAP::ResponseText).
raw_data: | Returns the raw data string.
UntaggedResponse = Struct.new(:name, :data, :raw_data) Net::IMAP::UntaggedResponse represents untagged responses.

Data transmitted by the server to the client and status responses that do not indicate command completion are prefixed with the token "*", and are called untagged responses.

  response_data   ::= "*" SPACE (resp_cond_state / resp_cond_bye /
                      mailbox_data / message_data / capability_data)

Fields:

name: Returns the name such as "FLAGS", "LIST", "FETCH".…
data: Returns the data such as an array of flag symbols,
 a ((<Net::IMAP::MailboxList>)) object....
raw_data: Returns the raw data string.
TaggedResponse = Struct.new(:tag, :name, :data, :raw_data) Net::IMAP::TaggedResponse represents tagged responses.

The server completion result response indicates the success or failure of the operation. It is tagged with the same tag as the client command which began the operation.

  response_tagged ::= tag SPACE resp_cond_state CRLF

  tag             ::= 1*<any ATOM_CHAR except "+">

  resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text

Fields:

tag: | Returns the tag.
name: | Returns the name. the name is one of "OK", "NO", "BAD".
data: | Returns the data. See ((<Net::IMAP::ResponseText>)).
raw_data: | Returns the raw data string.
ResponseText = Struct.new(:code, :text) Net::IMAP::ResponseText represents texts of responses. The text may be prefixed by the response code.
  resp_text       ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
                      ;; text SHOULD NOT begin with "[" or "="

Fields:

code: | Returns the response code. See ((<Net::IMAP::ResponseCode>)).
text: | Returns the text.
ResponseCode = Struct.new(:name, :data) Net::IMAP::ResponseCode represents response codes.
  resp_text_code  ::= "ALERT" / "PARSE" /
                      "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
                      "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
                      "UIDVALIDITY" SPACE nz_number /
                      "UNSEEN" SPACE nz_number /
                      atom [SPACE 1*<any TEXT_CHAR except "]">]

Fields:

name: | Returns the name such as "ALERT", "PERMANENTFLAGS", "UIDVALIDITY".…
data: | Returns the data if it exists.
MailboxList = Struct.new(:attr, :delim, :name) Net::IMAP::MailboxList represents contents of the LIST response.
  mailbox_list    ::= "(" #("\Marked" / "\Noinferiors" /
                      "\Noselect" / "\Unmarked" / flag_extension) ")"
                      SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox

Fields:

attr: | Returns the name attributes. Each name attribute is a symbol capitalized by String#capitalize, such as :Noselect (not :NoSelect).
delim: | Returns the hierarchy delimiter
name: | Returns the mailbox name.
MailboxQuota = Struct.new(:mailbox, :usage, :quota) Net::IMAP::MailboxQuota represents contents of GETQUOTA response. This object can also be a response to GETQUOTAROOT. In the syntax specification below, the delimiter used with the "#" construct is a single space (SPACE).
   quota_list      ::= "(" #quota_resource ")"

   quota_resource  ::= atom SPACE number SPACE number

   quota_response  ::= "QUOTA" SPACE astring SPACE quota_list

Fields:

mailbox: | The mailbox with the associated quota.
usage: | Current storage usage of mailbox.
quota: | Quota limit imposed on mailbox.
MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots) Net::IMAP::MailboxQuotaRoot represents part of the GETQUOTAROOT response. (GETQUOTAROOT can also return Net::IMAP::MailboxQuota.)
   quotaroot_response ::= "QUOTAROOT" SPACE astring *(SPACE astring)

Fields:

mailbox: | The mailbox with the associated quota.
quotaroots: | Zero or more quotaroots that effect the quota on the specified mailbox.
MailboxACLItem = Struct.new(:user, :rights) Net::IMAP::MailboxACLItem represents response from GETACL.
   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE rights)

   identifier      ::= astring

   rights          ::= astring

Fields:

user: | Login name that has certain rights to the mailbox that was specified with the getacl command.
rights: | The access rights the indicated user has to the mailbox.
StatusData = Struct.new(:mailbox, :attr) Net::IMAP::StatusData represents contents of the STATUS response.

Fields:

mailbox: | Returns the mailbox name.
attr: | Returns a hash. Each key is one of "MESSAGES", "RECENT", "UIDNEXT", "UIDVALIDITY", "UNSEEN". Each value is a number.
FetchData = Struct.new(:seqno, :attr) Net::IMAP::FetchData represents contents of the FETCH response.

Fields:

seqno: Returns the message sequence number. (Note: not the unique identifier, even for the UID command response.)
attr: Returns a hash. Each key is a data item name, and each value is its value.

The current data items are:

BODY
A form of BODYSTRUCTURE without extension data.
BODY[<section>]<<origin_octet>>
A string expressing the body contents of the specified section.
BODYSTRUCTURE
An object that describes the [MIME-IMB] body structure of a message. See Net::IMAP::BodyTypeBasic, Net::IMAP::BodyTypeText, Net::IMAP::BodyTypeMessage, Net::IMAP::BodyTypeMultipart.
ENVELOPE
A Net::IMAP::Envelope object that describes the envelope structure of a message.
FLAGS
A array of flag symbols that are set for this message. flag symbols are capitalized by String#capitalize.
INTERNALDATE
A string representing the internal date of the message.
RFC822
Equivalent to BODY[].
RFC822.HEADER
Equivalent to BODY.PEEK[HEADER].
RFC822.SIZE
A number expressing the [RFC-822] size of the message.
RFC822.TEXT
Equivalent to BODY[TEXT].
UID
A number expressing the unique identifier of the message.
Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to, :to, :cc, :bcc, :in_reply_to, :message_id) Net::IMAP::Envelope represents envelope structures of messages.

Fields:

date: | Returns a string that represents the date.
subject: | Returns a string that represents the subject.
from: | Returns an array of Net::IMAP::Address that represents the from.
sender: | Returns an array of Net::IMAP::Address that represents the sender.
reply_to: | Returns an array of Net::IMAP::Address that represents the reply-to.
to: | Returns an array of Net::IMAP::Address that represents the to.
cc: | Returns an array of Net::IMAP::Address that represents the cc.
bcc: | Returns an array of Net::IMAP::Address that represents the bcc.
in_reply_to: | Returns a string that represents the in-reply-to.
message_id: | Returns a string that represents the message-id.
Address = Struct.new(:name, :route, :mailbox, :host) Net::IMAP::Address represents electronic mail addresses.

Fields:

name: | Returns the phrase from [RFC-822] mailbox.
route: | Returns the route from [RFC-822] route-addr.
mailbox: | nil indicates end of [RFC-822] group. If non-nil and host is nil, returns [RFC-822] group name. Otherwise, returns [RFC-822] local-part
host: | nil indicates [RFC-822] group syntax. Otherwise, returns [RFC-822] domain name.
ContentDisposition = Struct.new(:dsp_type, :param) Net::IMAP::ContentDisposition represents Content-Disposition fields.

Fields:

dsp_type: | Returns the disposition type.
param: | Returns a hash that represents parameters of the Content-Disposition field.
ThreadMember = Struct.new(:seqno, :children) Net::IMAP::ThreadMember represents a thread-node returned by Net::IMAP#thread

Fields:

seqno: | The sequence number of this message.
children: | an array of Net::IMAP::ThreadMember objects for mail

items that are children of this in the thread.

Attributes

client_thread | [RW] | The thread to receive exceptions.
greeting | [R] | Returns an initial greeting response from the server.
response_handlers | [R] | Returns all response handlers.
responses [R] Returns recorded untagged responses. For example:
  imap.select("inbox")
  p imap.responses["EXISTS"][-1]
  #=> 2
  p imap.responses["UIDVALIDITY"][-1]
  #=> 968263756

Public Class methods

add_authenticator(auth_type, authenticator)

Adds an authenticator for Net::IMAP#authenticate. auth_type is the type of authentication this authenticator supports (for instance, "LOGIN"). The authenticator is an object which defines a process() method to handle authentication with the server. See Net::IMAP::LoginAuthenticator and Net::IMAP::CramMD5Authenticator for examples.

If auth_type refers to an existing authenticator, it will be replaced by the new one.

debug()

Returns the debug mode.

debug=(val)

Sets the debug mode.

decode_utf7(s)

Decode a string from modified UTF-7 format to UTF-8.

UTF-7 is a 7-bit encoding of Unicode [UTF7]. IMAP uses a slightly modified version of this to encode mailbox names containing non-ASCII characters; see [IMAP] section 5.1.3.

Net::IMAP does not automatically encode and decode mailbox names to and from utf7.

encode_utf7(s)

Encode a string from UTF-8 format to modified UTF-7.

new(host, port = PORT, usessl = false, certs = nil, verify = false)

Creates a new Net::IMAP object and connects it to the specified port (143 by default) on the named host. If usessl is true, then an attempt will be made to use SSL (now TLS) to connect to the server. For this to work OpenSSL [OSSL] and the Ruby OpenSSL [RSSL] extensions need to be installed. The certs parameter indicates the path or file containing the CA cert of the server, and the verify parameter is for the OpenSSL verification callback.

The most common errors are:

Errno::ECONNREFUSED: | connection refused by host or an intervening firewall.
Errno::ETIMEDOUT: | connection timed out (possibly due to packets being dropped by an intervening firewall).
Errno::ENETUNREACH: | there is no route to that network.
SocketError: | hostname not known or other socket error.
Net::IMAP::ByeResponseError: | we connected to the host, but they immediately said goodbye to us.

Public Instance methods

add_response_handler(handler = Proc.new)

Adds a response handler. For example, to detect when the server sends us a new EXISTS response (which normally indicates new messages being added to the mail box), you could add the following handler after selecting the mailbox.

  imap.add_response_handler { |resp|
    if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
      puts "Mailbox now has #{resp.data} messages"
    end
  }
append(mailbox, message, flags = nil, date_time = nil)

Sends a APPEND command to append the message to the end of the mailbox. The optional flags argument is an array of flags to initially passing to the new message. The optional date_time argument specifies the creation time to assign to the new message; it defaults to the current time. For example:

  imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
  Subject: hello
  From: shugo@ruby-lang.org
  To: shugo@ruby-lang.org

  hello world
  EOF

A Net::IMAP::NoResponseError is raised if the mailbox does not exist (it is not created automatically), or if the flags, date_time, or message arguments contain errors.

authenticate(auth_type, *args)

Sends an AUTHENTICATE command to authenticate the client. The auth_type parameter is a string that represents the authentication mechanism to be used. Currently Net::IMAP supports authentication mechanisms:

  LOGIN:: login using cleartext user and password.
  CRAM-MD5:: login with cleartext user and encrypted password
             (see [RFC-2195] for a full description).  This
             mechanism requires that the server have the user's
             password stored in clear-text password.

For both these mechanisms, there should be two args: username and (cleartext) password. A server may not support one or other of these mechanisms; check capability() for a capability of the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".

Authentication is done using the appropriate authenticator object: see @@authenticators for more information on plugging in your own authenticator.

For example:

   imap.authenticate('LOGIN', user, password)

A Net::IMAP::NoResponseError is raised if authentication fails.

capability()

Sends a CAPABILITY command, and returns an array of capabilities that the server supports. Each capability is a string. See [IMAP] for a list of possible capabilities.

Note that the Net::IMAP class does not modify its behaviour according to the capabilities of the server; it is up to the user of the class to ensure that a certain capability is supported by a server before using it.

check()

Sends a CHECK command to request a checkpoint of the currently selected mailbox. This performs implementation-specific housekeeping, for instance, reconciling the mailbox‘s in-memory and on-disk state.

close()

Sends a CLOSE command to close the currently selected mailbox. The CLOSE command permanently removes from the mailbox all messages that have the \Deleted flag set.

copy(set, mailbox)

Sends a COPY command to copy the specified message(s) to the end of the specified destination mailbox. The set parameter is a number or an array of numbers or a Range object. The number is a message sequence number.

create(mailbox)

Sends a CREATE command to create a new mailbox.

A Net::IMAP::NoResponseError is raised if a mailbox with that name cannot be created.

delete(mailbox)

Sends a DELETE command to remove the mailbox.

A Net::IMAP::NoResponseError is raised if a mailbox with that name cannot be deleted, either because it does not exist or because the client does not have permission to delete it.

disconnect()

Disconnects from the server.

disconnected?()

Returns true if disconnected from the server.

examine(mailbox)

Sends a EXAMINE command to select a mailbox so that messages in the mailbox can be accessed. Behaves the same as select(), except that the selected mailbox is identified as read-only.

A Net::IMAP::NoResponseError is raised if the mailbox does not exist or is for some reason non-examinable.

expunge()

Sends a EXPUNGE command to permanently remove from the currently selected mailbox all messages that have the \Deleted flag set.

fetch(set, attr)

Sends a FETCH command to retrieve data associated with a message in the mailbox. The set parameter is a number or an array of numbers or a Range object. The number is a message sequence number. attr is a list of attributes to fetch; see the documentation for Net::IMAP::FetchData for a list of valid attributes. The return value is an array of Net::IMAP::FetchData. For example:

  p imap.fetch(6..8, "UID")
  #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, \\
       #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, \\
       #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
  p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
  #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
  data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
  p data.seqno
  #=> 6
  p data.attr["RFC822.SIZE"]
  #=> 611
  p data.attr["INTERNALDATE"]
  #=> "12-Oct-2000 22:40:59 +0900"
  p data.attr["UID"]
  #=> 98
getacl(mailbox)

Send the GETACL command along with specified mailbox. If this mailbox exists, an array containing objects of Net::IMAP::MailboxACLItem will be returned.

getquota(mailbox)

Sends the GETQUOTA command along with specified mailbox. If this mailbox exists, then an array containing a Net::IMAP::MailboxQuota object is returned. This command generally is only available to server admin.

getquotaroot(mailbox)

Sends the GETQUOTAROOT command along with specified mailbox. This command is generally available to both admin and user. If mailbox exists, returns an array containing objects of Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.

list(refname, mailbox)

Sends a LIST command, and returns a subset of names from the complete set of all names available to the client. refname provides a context (for instance, a base directory in a directory-based mailbox hierarchy). mailbox specifies a mailbox or (via wildcards) mailboxes under that context. Two wildcards may be used in mailbox: ’*’, which matches all characters including the hierarchy delimiter (for instance, ’/’ on a UNIX-hosted directory-based mailbox hierarchy); and ’%’, which matches all characters except the hierarchy delimiter.

If refname is empty, mailbox is used directly to determine which mailboxes to match. If mailbox is empty, the root name of refname and the hierarchy delimiter are returned.

The return value is an array of +Net::IMAP::MailboxList+. For example:

  imap.create("foo/bar")
  imap.create("foo/baz")
  p imap.list("", "foo/%")
  #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
       #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
       #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
login(user, password)

Sends a LOGIN command to identify the client and carries the plaintext password authenticating this user. Note that, unlike calling authenticate() with an auth_type of "LOGIN", login() does not use the login authenticator.

A Net::IMAP::NoResponseError is raised if authentication fails.

logout()

Sends a LOGOUT command to inform the server that the client is done with the connection.

lsub(refname, mailbox)

Sends a LSUB command, and returns a subset of names from the set of names that the user has declared as being "active" or "subscribed". refname and mailbox are interpreted as for list(). The return value is an array of +Net::IMAP::MailboxList+.

noop()

Sends a NOOP command to the server. It does nothing.

remove_response_handler(handler)

Removes the response handler.

rename(mailbox, newname)

Sends a RENAME command to change the name of the mailbox to newname.

A Net::IMAP::NoResponseError is raised if a mailbox with the name mailbox cannot be renamed to newname for whatever reason; for instance, because mailbox does not exist, or because there is already a mailbox with the name newname.

search(keys, charset = nil)

Sends a SEARCH command to search the mailbox for messages that match the given searching criteria, and returns message sequence numbers. keys can either be a string holding the entire search string, or a single-dimension array of search keywords and arguments. The following are some common search criteria; see [IMAP] section 6.4.4 for a full list.

<message set>: | a set of message sequence numbers. ’,’ indicates an interval, ’:’ indicates a range. For instance, ‘2,10:12,15’ means "2,10,11,12,15".
BEFORE <date>: | messages with an internal date strictly before <date>. The date argument has a format similar to 8-Aug-2002.
BODY <string>: | messages that contain <string> within their body.
CC <string>: | messages containing <string> in their CC field.
FROM <string>: | messages that contain <string> in their FROM field.
NEW: | messages with the \Recent, but not the \Seen, flag set.
NOT <search-key>: | negate the following search key.
OR <search-key> <search-key>: | "or" two search keys together.
ON <date>: | messages with an internal date exactly equal to <date>, which has a format similar to 8-Aug-2002.
SINCE <date>: | messages with an internal date on or after <date>.
SUBJECT <string>: | messages with <string> in their subject.
TO <string>: | messages with <string> in their TO field.

For example:

  p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
  #=> [1, 6, 7, 8]
select(mailbox)

Sends a SELECT command to select a mailbox so that messages in the mailbox can be accessed.

After you have selected a mailbox, you may retrieve the number of items in that mailbox from @responses["EXISTS"][-1], and the number of recent messages from @responses["RECENT"][-1]. Note that these values can change if new messages arrive during a session; see add_response_handler() for a way of detecting this event.

A Net::IMAP::NoResponseError is raised if the mailbox does not exist or is for some reason non-selectable.

setacl(mailbox, user, rights)

Sends the SETACL command along with mailbox, user and the rights that user is to have on that mailbox. If rights is nil, then that user will be stripped of any rights to that mailbox. The IMAP ACL commands are described in [RFC-2086].

setquota(mailbox, quota)

Sends a SETQUOTA command along with the specified mailbox and quota. If quota is nil, then quota will be unset for that mailbox. Typically one needs to be logged in as server admin for this to work. The IMAP quota commands are described in [RFC-2087].

sort(sort_keys, search_keys, charset)

Sends a SORT command to sort messages in the mailbox. Returns an array of message sequence numbers. For example:

  p imap.sort(["FROM"], ["ALL"], "US-ASCII")
  #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
  p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
  #=> [6, 7, 8, 1]

See [SORT-THREAD-EXT] for more details.

status(mailbox, attr)

Sends a STATUS command, and returns the status of the indicated mailbox. attr is a list of one or more attributes that we are request the status of. Supported attributes include:

  MESSAGES:: the number of messages in the mailbox.
  RECENT:: the number of recent messages in the mailbox.
  UNSEEN:: the number of unseen messages in the mailbox.

The return value is a hash of attributes. For example:

  p imap.status("inbox", ["MESSAGES", "RECENT"])
  #=> {"RECENT"=>0, "MESSAGES"=>44}

A Net::IMAP::NoResponseError is raised if status values for mailbox cannot be returned, for instance because it does not exist.

store(set, attr, flags)

Sends a STORE command to alter data associated with messages in the mailbox, in particular their flags. The set parameter is a number or an array of numbers or a Range object. Each number is a message sequence number. attr is the name of a data item to store: ‘FLAGS’ means to replace the message‘s flag list with the provided one; ’+FLAGS’ means to add the provided flags; and ’-FLAGS’ means to remove them. flags is a list of flags.

The return value is an array of Net::IMAP::FetchData. For example:

  p imap.store(6..8, "+FLAGS", [:Deleted])
  #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
       #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
       #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
subscribe(mailbox)

Sends a SUBSCRIBE command to add the specified mailbox name to the server‘s set of "active" or "subscribed" mailboxes as returned by lsub().

A Net::IMAP::NoResponseError is raised if mailbox cannot be subscribed to, for instance because it does not exist.

thread(algorithm, search_keys, charset)

As for search(), but returns message sequence numbers in threaded format, as a Net::IMAP::ThreadMember tree. The supported algorithms are:

ORDEREDSUBJECT: | split into single-level threads according to subject, ordered by date.
REFERENCES: | split into threads by parent/child relationships determined by which message is a reply to which.

Unlike search(), charset is a required argument. US-ASCII and UTF-8 are sample values.

See [SORT-THREAD-EXT] for more details.

uid_copy(set, mailbox)

As for copy(), but set contains unique identifiers.

uid_fetch(set, attr)

As for fetch(), but set contains unique identifiers.

uid_search(keys, charset = nil)

As for search(), but returns unique identifiers.

uid_sort(sort_keys, search_keys, charset)

As for sort(), but returns an array of unique identifiers.

uid_store(set, attr, flags)

As for store(), but set contains unique identifiers.

uid_thread(algorithm, search_keys, charset)

As for thread(), but returns unique identifiers instead of message sequence numbers.

unsubscribe(mailbox)

Sends a UNSUBSCRIBE command to remove the specified mailbox name from the server‘s set of "active" or "subscribed" mailboxes.

A Net::IMAP::NoResponseError is raised if mailbox cannot be unsubscribed from, for instance because the client is not currently subscribed to it.


Class: Net::IMAP::BadResponseError

Class | Net::IMAP::BadResponseError
In: | lib/net/imap.rb
Parent: | ResponseError

Error raised upon a "BAD" response from the server, indicating that the client command violated the IMAP protocol, or an internal server failure has occurred.


Class: Net::IMAP::BodyTypeBasic

Class | Net::IMAP::BodyTypeBasic
In: | lib/net/imap.rb
Parent: | Struct.new(:media_type, :subtype, :param, :content_id, :description, :encoding, :size, :md5, :disposition, :language, :extension)

Net::IMAP::BodyTypeBasic represents basic body structures of messages.

Fields:

media_type: | Returns the content media type name as defined in [MIME-IMB].
subtype: | Returns the content subtype name as defined in [MIME-IMB].
param: | Returns a hash that represents parameters as defined in [MIME-IMB].
content_id: | Returns a string giving the content id as defined in [MIME-IMB].
description: | Returns a string giving the content description as defined in [MIME-IMB].
encoding: | Returns a string giving the content transfer encoding as defined in [MIME-IMB].
size: | Returns a number giving the size of the body in octets.
md5: | Returns a string giving the body MD5 value as defined in [MD5].
disposition: | Returns a Net::IMAP::ContentDisposition object giving the content disposition.
language: | Returns a string or an array of strings giving the body language value as defined in [LANGUAGE-TAGS].
extension: | Returns extension data.
multipart?: | Returns false.

Methods

media_subtype multipart?

Public Instance methods

media_subtype()

Obsolete: use subtype instead. Calling this will generate a warning message to stderr, then return the value of subtype.

multipart?()


Class: Net::IMAP::BodyTypeMessage

Class | Net::IMAP::BodyTypeMessage
In: | lib/net/imap.rb
Parent: | Struct.new(:media_type, :subtype, :param, :content_id, :description, :encoding, :size, :envelope, :body, :lines, :md5, :disposition, :language, :extension)

Net::IMAP::BodyTypeMessage represents MESSAGE/RFC822 body structures of messages.

Fields:

envelope: | Returns a Net::IMAP::Envelope giving the envelope structure.
body: | Returns an object giving the body structure.

And Net::IMAP::BodyTypeMessage has all methods of Net::IMAP::BodyTypeText.

Methods

media_subtype multipart?

Public Instance methods

media_subtype()

Obsolete: use subtype instead. Calling this will generate a warning message to stderr, then return the value of subtype.

multipart?()


Class: Net::IMAP::BodyTypeMultipart

Class | Net::IMAP::BodyTypeMultipart
In: | lib/net/imap.rb
Parent: | Struct.new(:media_type, :subtype, :parts, :param, :disposition, :language, :extension)

Net::IMAP::BodyTypeMultipart represents multipart body structures of messages.

Fields:

media_type: | Returns the content media type name as defined in [MIME-IMB].
subtype: | Returns the content subtype name as defined in [MIME-IMB].
parts: | Returns multiple parts.
param: | Returns a hash that represents parameters as defined in [MIME-IMB].
disposition: | Returns a Net::IMAP::ContentDisposition object giving the content disposition.
language: | Returns a string or an array of strings giving the body language value as defined in [LANGUAGE-TAGS].
extension: | Returns extension data.
multipart?: | Returns true.

Methods

media_subtype multipart?

Public Instance methods

media_subtype()

Obsolete: use subtype instead. Calling this will generate a warning message to stderr, then return the value of subtype.

multipart?()


Class: Net::IMAP::BodyTypeText

Class | Net::IMAP::BodyTypeText
In: | lib/net/imap.rb
Parent: | Struct.new(:media_type, :subtype, :param, :content_id, :description, :encoding, :size, :lines, :md5, :disposition, :language, :extension)

Net::IMAP::BodyTypeText represents TEXT body structures of messages.

Fields:

lines: Returns the size of the body in text lines.

And Net::IMAP::BodyTypeText has all fields of Net::IMAP::BodyTypeBasic.

Methods

media_subtype multipart?

Public Instance methods

media_subtype()

Obsolete: use subtype instead. Calling this will generate a warning message to stderr, then return the value of subtype.

multipart?()


Class: Net::IMAP::ByeResponseError

Class | Net::IMAP::ByeResponseError
In: | lib/net/imap.rb
Parent: | ResponseError

Error raised upon a "BYE" response from the server, indicating that the client is not being allowed to login, or has been timed out due to inactivity.


Class: Net::IMAP::CramMD5Authenticator

Class | Net::IMAP::CramMD5Authenticator
In: | lib/net/imap.rb
Parent: | Object

Authenticator for the "CRAM-MD5" authentication type. See authenticate().

Methods

new process

Public Class methods

new(user, password)

Public Instance methods

process(challenge)


Class: Net::IMAP::DataFormatError

Class | Net::IMAP::DataFormatError
In: | lib/net/imap.rb
Parent: | Error

Error raised when data is in the incorrect format.


Class: Net::IMAP::Error

Class | Net::IMAP::Error
In: | lib/net/imap.rb
Parent: | StandardError

Superclass of IMAP errors.


Class: Net::IMAP::LoginAuthenticator

Class | Net::IMAP::LoginAuthenticator
In: | lib/net/imap.rb
Parent: | Object

Authenticator for the "LOGIN" authentication type. See authenticate().

Methods

new process

Constants

STATE_USER | = | :USER
STATE_PASSWORD | = | :PASSWORD

Public Class methods

new(user, password)

Public Instance methods

process(data)


Class: Net::IMAP::NoResponseError

Class | Net::IMAP::NoResponseError
In: | lib/net/imap.rb
Parent: | ResponseError

Error raised upon a "NO" response from the server, indicating that the client command could not be completed successfully.


Class: Net::IMAP::ResponseError

Class | Net::IMAP::ResponseError
In: | lib/net/imap.rb
Parent: | Error

Superclass of all errors used to encapsulate "fail" responses from the server.


Class: Net::IMAP::ResponseParseError

Class | Net::IMAP::ResponseParseError
In: | lib/net/imap.rb
Parent: | Error

Error raised when a response from the server is non-parseable.


Class: Net::POP3

Class | Net::POP3
In: | lib/net/pop.rb
Parent: | Protocol

Net::POP3

What is This Library?

This library provides functionality for retrieving email via POP3, the Post Office Protocol version 3. For details of POP3, see [RFC1939] (www.ietf.org/rfc/rfc1939.txt).

Examples

Retrieving Messages

This example retrieves messages from the server and deletes them on the server.

Messages are written to files named ‘inbox/1’, ‘inbox/2’, .… Replace ‘pop.example.com’ with your POP3 server address, and ‘YourAccount’ and ‘YourPassword’ with the appropriate account details.

    require 'net/pop'

    pop = Net::POP3.new('pop.example.com')
    pop.start('YourAccount', 'YourPassword')             # (1)
    if pop.mails.empty?
      puts 'No mail.'
    else
      i = 0
      pop.each_mail do |m|   # or "pop.mails.each ..."   # (2)
        File.open("inbox/#{i}", 'w') do |f|
          f.write m.pop
        end
        m.delete
        i += 1
      end
      puts "#{pop.mails.size} mails popped."
    end
    pop.finish                                           # (3)
  1. Call Net::POP3#start and start POP session.
  2. Access messages by using POP3#each_mail and/or POP3#mails.
  3. Close POP session by calling POP3#finish or use the block form of start.

Shortened Code

The example above is very verbose. You can shorten the code by using some utility methods. First, the block form of Net::POP3.start can be used instead of POP3.new, POP3#start and POP3#finish.

    require 'net/pop'

    Net::POP3.start('pop.example.com', 110,
                    'YourAccount', 'YourPassword') do |pop|
      if pop.mails.empty?
        puts 'No mail.'
      else
        i = 0
        pop.each_mail do |m|   # or "pop.mails.each ..."
          File.open("inbox/#{i}", 'w') do |f|
            f.write m.pop
          end
          m.delete
          i += 1
        end
        puts "#{pop.mails.size} mails popped."
      end
    end

POP3#delete_all is an alternative for each_mail and delete.

    require 'net/pop'

    Net::POP3.start('pop.example.com', 110,
                    'YourAccount', 'YourPassword') do |pop|
      if pop.mails.empty?
        puts 'No mail.'
      else
        i = 1
        pop.delete_all do |m|
          File.open("inbox/#{i}", 'w') do |f|
            f.write m.pop
          end
          i += 1
        end
      end
    end

And here is an even shorter example.

    require 'net/pop'

    i = 0
    Net::POP3.delete_all('pop.example.com', 110,
                         'YourAccount', 'YourPassword') do |m|
      File.open("inbox/#{i}", 'w') do |f|
        f.write m.pop
      end
      i += 1
    end

Memory Space Issues

All the examples above get each message as one big string. This example avoids this.

    require 'net/pop'

    i = 1
    Net::POP3.delete_all('pop.example.com', 110,
                         'YourAccount', 'YourPassword') do |m|
      File.open("inbox/#{i}", 'w') do |f|
        m.pop do |chunk|    # get a message little by little.
          f.write chunk
        end
        i += 1
      end
    end

Using APOP

The net/pop library supports APOP authentication. To use APOP, use the Net::APOP class instead of the Net::POP3 class. You can use the utility method, Net::POP3.APOP(). For example:

    require 'net/pop'

    # Use APOP authentication if $isapop == true
    pop = Net::POP3.APOP($is_apop).new('apop.example.com', 110)
    pop.start(YourAccount', 'YourPassword') do |pop|
      # Rest of the code is the same.
    end

Fetch Only Selected Mail Using ‘UIDL’ POP Command

If your POP server provides UIDL functionality, you can grab only selected mails from the POP server. e.g.

    def need_pop?( id )
      # determine if we need pop this mail...
    end

    Net::POP3.start('pop.example.com', 110,
                    'Your account', 'Your password') do |pop|
      pop.mails.select { |m| need_pop?(m.unique_id) }.each do |m|
        do_something(m.pop)
      end
    end

The POPMail#unique_id() method returns the unique-id of the message as a String. Normally the unique-id is a hash of the message.

Methods

APOP active? apop? auth_only auth_only default_port delete_all delete_all each each_mail finish foreach inspect mails n_bytes n_mails new read_timeout= reset set_debug_output start start started?

Constants

Revision = %q$Revision: 11708 $.split[1]

Attributes

address | [R] | The address to connect to.
open_timeout | [RW] | Seconds to wait until a connection is opened. If the POP3 object cannot open a connection within this time, it raises a TimeoutError exception.
port | [R] | The port number to connect to.
read_timeout | [R] | Seconds to wait until reading one block (by one read(1) call). If the POP3 object cannot complete a read() within this time, it raises a TimeoutError exception.

Public Class methods

APOP( isapop )

Returns the APOP class if isapop is true; otherwise, returns the POP class. For example:

    # Example 1
    pop = Net::POP3::APOP($is_apop).new(addr, port)

    # Example 2
    Net::POP3::APOP($is_apop).start(addr, port) do |pop|
      ....
    end
auth_only( address, port = nil, account = nil, password = nil, isapop = false )

Opens a POP3 session, attempts authentication, and quits.

This method raises POPAuthenticationError if authentication fails.

Example: normal POP3

    Net::POP3.auth_only('pop.example.com', 110,
                        'YourAccount', 'YourPassword')

Example: APOP

    Net::POP3.auth_only('pop.example.com', 110,
                        'YourAccount', 'YourPassword', true)
default_port()

The default port for POP3 connections, port 110

delete_all( address, port = nil, account = nil, password = nil, isapop = false, &block )

Starts a POP3 session and deletes all messages on the server. If a block is given, each POPMail object is yielded to it before being deleted.

This method raises a POPAuthenticationError if authentication fails.

Example

    Net::POP3.delete_all('pop.example.com', 110,
                         'YourAccount', 'YourPassword') do |m|
      file.write m.pop
    end
foreach( address, port = nil, account = nil, password = nil, isapop = false ) {|message| ...}

Starts a POP3 session and iterates over each POPMail object, yielding it to the block. This method is equivalent to:

    Net::POP3.start(address, port, account, password) do |pop|
      pop.each_mail do |m|
        yield m
      end
    end

This method raises a POPAuthenticationError if authentication fails.

Example

    Net::POP3.foreach('pop.example.com', 110,
                      'YourAccount', 'YourPassword') do |m|
      file.write m.pop
      m.delete if $DELETE
    end
new( addr, port = nil, isapop = false )

Creates a new POP3 object.

address is the hostname or ip address of your POP3 server.

The optional port is the port to connect to; it defaults to 110.

The optional isapop specifies whether this connection is going to use APOP authentication; it defaults to false.

This method does not open the TCP connection.

start( address, port = nil, account = nil, password = nil, isapop = false ) {|pop| ...}

Creates a new POP3 object and open the connection. Equivalent to

  Net::POP3.new(address, port, isapop).start(account, password)

If block is provided, yields the newly-opened POP3 object to it, and automatically closes it at the end of the session.

Example

   Net::POP3.start(addr, port, account, password) do |pop|
     pop.each_mail do |m|
       file.write m.pop
       m.delete
     end
   end

Public Instance methods

active?()

Alias for started?

apop?()

Does this instance use APOP authentication?

auth_only( account, password )

Starts a pop3 session, attempts authentication, and quits. This method must not be called while POP3 session is opened. This method raises POPAuthenticationError if authentication fails.

delete_all( {|message| ...}

Deletes all messages on the server.

If called with a block, yields each message in turn before deleting it.

Example

    n = 1
    pop.delete_all do |m|
      File.open("inbox/#{n}") do |f|
        f.write m.pop
      end
      n += 1
    end

This method raises a POPError if an error occurs.

each( )

Alias for each_mail

each_mail( ) {|message| ...}

Yields each message to the passed-in block in turn. Equivalent to:

  pop3.mails.each do |popmail|
    ....
  end

This method raises a POPError if an error occurs.

finish()

Finishes a POP3 session and closes TCP connection.

inspect()

Provide human-readable stringification of class state.

mails()

Returns an array of Net::POPMail objects, representing all the messages on the server. This array is renewed when the session restarts; otherwise, it is fetched from the server the first time this method is called (directly or indirectly) and cached.

This method raises a POPError if an error occurs.

n_bytes()

Returns the total size in bytes of all the messages on the POP server.

n_mails()

Returns the number of messages on the POP server.

read_timeout=( sec )

Set the read timeout.

reset()

Resets the session. This clears all "deleted" marks from messages.

This method raises a POPError if an error occurs.

set_debug_output( arg )

WARNING: This method causes a serious security hole. Use this method only for debugging.

Set an output stream for debugging.

Example

  pop = Net::POP.new(addr, port)
  pop.set_debug_output $stderr
  pop.start(account, passwd) do |pop|
    ....
  end
start( account, password ) {|pop| ...}

Starts a POP3 session.

When called with block, gives a POP3 object to the block and closes the session after block call finishes.

This method raises a POPAuthenticationError if authentication fails.

started?()

true if the POP3 session has started.


Class: Net::POPAuthenticationError

Class | Net::POPAuthenticationError
In: | lib/net/pop.rb
Parent: | ProtoAuthError

POP3 authentication error.


Class: Net::POPBadResponse

Class | Net::POPBadResponse
In: | lib/net/pop.rb
Parent: | POPError

Unexpected response from the server.


Class: Net::POPError

Class | Net::POPError
In: | lib/net/pop.rb
Parent: | ProtocolError

Non-authentication POP3 protocol error (reply code "-ERR", except authentication).


Class: Net::POPMail

Class | Net::POPMail
In: | lib/net/pop.rb
Parent: | Object

This class represents a message which exists on the POP server. Instances of this class are created by the POP3 class; they should not be directly created by the user.

Methods

all delete delete! deleted? header inspect mail pop top uidl unique_id

External Aliases

length -> size

Attributes

length | [R] | The length of the message in octets.
number | [R] | The sequence number of the message on the server.

Public Instance methods

all( dest = '' )

Alias for pop

delete()

Marks a message for deletion on the server. Deletion does not actually occur until the end of the session; deletion may be cancelled for all marked messages by calling POP3#reset().

This method raises a POPError if an error occurs.

Example

    POP3.start('pop.example.com', 110,
               'YourAccount, 'YourPassword') do |pop|
      n = 1
      pop.mails.each do |popmail|
        File.open("inbox/#{n}", 'w') do |f|
          f.write popmail.pop
        end
        popmail.delete         ####
        n += 1
      end
    end
delete!()

Alias for delete

deleted?()

True if the mail has been deleted.

header( dest = '' )

Fetches the message header.

The optional dest argument is obsolete.

This method raises a POPError if an error occurs.

inspect()

Provide human-readable stringification of class state.

mail( dest = '' )

Alias for pop

pop( dest = '' ) {|message_chunk| ...}

This method fetches the message. If called with a block, the message is yielded to the block one chunk at a time. If called without a block, the message is returned as a String. The optional dest argument will be prepended to the returned String; this argument is essentially obsolete.

Example without block

    POP3.start('pop.example.com', 110,
               'YourAccount, 'YourPassword') do |pop|
      n = 1
      pop.mails.each do |popmail|
        File.open("inbox/#{n}", 'w') do |f|
          f.write popmail.pop
        end
        popmail.delete
        n += 1
      end
    end

Example with block

    POP3.start('pop.example.com', 110,
               'YourAccount, 'YourPassword') do |pop|
      n = 1
      pop.mails.each do |popmail|
        File.open("inbox/#{n}", 'w') do |f|
          popmail.pop do |chunk|            ####
            f.write chunk
          end
        end
        n += 1
      end
    end

This method raises a POPError if an error occurs.

top( lines, dest = '' )

Fetches the message header and lines lines of body.

The optional dest argument is obsolete.

This method raises a POPError if an error occurs.

uidl()

Alias for unique_id

unique_id()

Returns the unique-id of the message. Normally the unique-id is a hash string of the message.

This method raises a POPError if an error occurs.


Class: Net::ProtoAuthError

Class | Net::ProtoAuthError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtoCommandError

Class | Net::ProtoCommandError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtoFatalError

Class | Net::ProtoFatalError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtoRetriableError

Class | Net::ProtoRetriableError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtoServerError

Class | Net::ProtoServerError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtoSyntaxError

Class | Net::ProtoSyntaxError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtoUnknownError

Class | Net::ProtoUnknownError
In: | lib/net/protocol.rb
Parent: | ProtocolError


Class: Net::ProtocolError

Class | Net::ProtocolError
In: | lib/net/protocol.rb
Parent: | StandardError


Class: Net::SMTP

Class | Net::SMTP
In: | lib/net/smtp.rb
Parent: | Object

Net::SMTP

What is This Library?

This library provides functionality to send internet mail via SMTP, the Simple Mail Transfer Protocol. For details of SMTP itself, see [RFC2821] (www.ietf.org/rfc/rfc2821.txt).

What is This Library NOT?

This library does NOT provide functions to compose internet mails. You must create them by yourself. If you want better mail support, try RubyMail or TMail. You can get both libraries from RAA. (www.ruby-lang.org/en/raa.html)

FYI: the official documentation on internet mail is: [RFC2822] (www.ietf.org/rfc/rfc2822.txt).

Examples

Sending Messages

You must open a connection to an SMTP server before sending messages. The first argument is the address of your SMTP server, and the second argument is the port number. Using SMTP.start with a block is the simplest way to do this. This way, the SMTP connection is closed automatically after the block is executed.

    require 'net/smtp'
    Net::SMTP.start('your.smtp.server', 25) do |smtp|
      # Use the SMTP object smtp only in this block.
    end

Replace ‘your.smtp.server’ with your SMTP server. Normally your system manager or internet provider supplies a server for you.

Then you can send messages.

    msgstr = <<END_OF_MESSAGE
    From: Your Name <your@mail.address>
    To: Destination Address <someone@example.com>
    Subject: test message
    Date: Sat, 23 Jun 2001 16:26:43 +0900
    Message-Id: <unique.message.id.string@example.com>

    This is a test message.
    END_OF_MESSAGE

    require 'net/smtp'
    Net::SMTP.start('your.smtp.server', 25) do |smtp|
      smtp.send_message msgstr,
                        'your@mail.address',
                        'his_addess@example.com'
    end

Closing the Session

You MUST close the SMTP session after sending messages, by calling the finish method:

    # using SMTP#finish
    smtp = Net::SMTP.start('your.smtp.server', 25)
    smtp.send_message msgstr, 'from@address', 'to@address'
    smtp.finish

You can also use the block form of SMTP.start/SMTP#start. This closes the SMTP session automatically:

    # using block form of SMTP.start
    Net::SMTP.start('your.smtp.server', 25) do |smtp|
      smtp.send_message msgstr, 'from@address', 'to@address'
    end

I strongly recommend this scheme. This form is simpler and more robust.

HELO domain

In almost all situations, you must provide a third argument to SMTP.start/SMTP#start. This is the domain name which you are on (the host to send mail from). It is called the "HELO domain". The SMTP server will judge whether it should send or reject the SMTP session by inspecting the HELO domain.

    Net::SMTP.start('your.smtp.server', 25,
                    'mail.from.domain') { |smtp| ... }

SMTP Authentication

The Net::SMTP class supports three authentication schemes; PLAIN, LOGIN and CRAM MD5. (SMTP Authentication: [RFC2554]) To use SMTP authentication, pass extra arguments to SMTP.start/SMTP#start.

    # PLAIN
    Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
                    'Your Account', 'Your Password', :plain)
    # LOGIN
    Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
                    'Your Account', 'Your Password', :login)

    # CRAM MD5
    Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
                    'Your Account', 'Your Password', :cram_md5)

Methods

default_port esmtp esmtp= esmtp? finish inspect new open_message_stream read_timeout= ready send_mail send_message sendmail set_debug_output start start started?

Constants

Revision = %q$Revision: 11708 $.split[1]

Attributes

address | [R] | The address of the SMTP server to connect to.
open_timeout | [RW] | Seconds to wait while attempting to open a connection. If the connection cannot be opened within this time, a TimeoutError is raised.
port | [R] | The port number of the SMTP server to connect to.
read_timeout | [R] | Seconds to wait while reading one block (by one read(2) call). If the read(2) call does not complete within this time, a TimeoutError is raised.

Public Class methods

default_port()

The default SMTP port, port 25.

new( address, port = nil )

Creates a new Net::SMTP object.

address is the hostname or ip address of your SMTP server. port is the port to connect to; it defaults to port 25.

This method does not open the TCP connection. You can use SMTP.start instead of SMTP.new if you want to do everything at once. Otherwise, follow SMTP.new with SMTP#start.

start( address, port = nil, helo = 'localhost.localdomain', user = nil, secret = nil, authtype = nil) {|smtp| ...}

Creates a new Net::SMTP object and connects to the server.

This method is equivalent to:

  Net::SMTP.new(address, port).start(helo_domain, account, password, authtype)

Example

    Net::SMTP.start('your.smtp.server') do |smtp|
      smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
    end

Block Usage

If called with a block, the newly-opened Net::SMTP object is yielded to the block, and automatically closed when the block finishes. If called without a block, the newly-opened Net::SMTP object is returned to the caller, and it is the caller‘s responsibility to close it when finished.

Parameters

address is the hostname or ip address of your smtp server.

port is the port to connect to; it defaults to port 25.

helo is the HELO domain provided by the client to the server (see overview comments); it defaults to ‘localhost.localdomain’.

The remaining arguments are used for SMTP authentication, if required or desired. user is the account name; secret is your password or other authentication token; and authtype is the authentication type, one of :plain, :login, or :cram_md5. See the discussion of SMTP Authentication in the overview notes.

Errors

This method may raise:

  • Net::SMTPAuthenticationError
  • Net::SMTPServerBusy
  • Net::SMTPSyntaxError
  • Net::SMTPFatalError
  • Net::SMTPUnknownError
  • IOError
  • TimeoutError

Public Instance methods

esmtp()

Alias for esmtp?

esmtp=( bool )

Set whether to use ESMTP or not. This should be done before calling start. Note that if start is called in ESMTP mode, and the connection fails due to a ProtocolError, the SMTP object will automatically switch to plain SMTP mode and retry (but not vice versa).

esmtp?()

true if the SMTP object uses ESMTP (which it does by default).

finish()

Finishes the SMTP session and closes TCP connection. Raises IOError if not started.

inspect()

Provide human-readable stringification of class state.

open_message_stream( from_addr, *to_addrs ) {|stream| ...}

Opens a message writer stream and gives it to the block. The stream is valid only in the block, and has these methods:

puts(str = ’’): | outputs STR and CR LF.
print(str): | outputs STR.
printf(fmt, *args): | outputs sprintf(fmt,*args).
write(str): | outputs STR and returns the length of written bytes.
<<(str): | outputs STR and returns self.

If a single CR ("\r") or LF ("\n") is found in the message, it is converted to the CR LF pair. You cannot send a binary message with this method.

Parameters

from_addr is a String representing the source mail address.

to_addr is a String or Strings or Array of Strings, representing the destination mail address or addresses.

Example

    Net::SMTP.start('smtp.example.com', 25) do |smtp|
      smtp.open_message_stream('from@example.com', ['dest@example.com']) do |f|
        f.puts 'From: from@example.com'
        f.puts 'To: dest@example.com'
        f.puts 'Subject: test message'
        f.puts
        f.puts 'This is a test message.'
      end
    end

Errors

This method may raise:

  • Net::SMTPServerBusy
  • Net::SMTPSyntaxError
  • Net::SMTPFatalError
  • Net::SMTPUnknownError
  • IOError
  • TimeoutError
read_timeout=( sec )

Set the number of seconds to wait until timing-out a read(2) call.

ready( from_addr, *to_addrs )

Alias for open_message_stream

send_mail( msgstr, from_addr, *to_addrs )

Alias for send_message

send_message( msgstr, from_addr, *to_addrs )

Sends msgstr as a message. Single CR ("\r") and LF ("\n") found in the msgstr, are converted into the CR LF pair. You cannot send a binary message with this method. msgstr should include both the message headers and body.

from_addr is a String representing the source mail address.

to_addr is a String or Strings or Array of Strings, representing the destination mail address or addresses.

Example

    Net::SMTP.start('smtp.example.com') do |smtp|
      smtp.send_message msgstr,
                        'from@example.com',
                        ['dest@example.com', 'dest2@example.com']
    end

Errors

This method may raise:

  • Net::SMTPServerBusy
  • Net::SMTPSyntaxError
  • Net::SMTPFatalError
  • Net::SMTPUnknownError
  • IOError
  • TimeoutError
sendmail( msgstr, from_addr, *to_addrs )

Alias for send_message

set_debug_output( arg )

WARNING: This method causes serious security holes. Use this method for only debugging.

Set an output stream for debug logging. You must call this before start.

  # example
  smtp = Net::SMTP.new(addr, port)
  smtp.set_debug_output $stderr
  smtp.start do |smtp|
    ....
  end
start( helo = 'localhost.localdomain', user = nil, secret = nil, authtype = nil ) {|smtp| ...}

Opens a TCP connection and starts the SMTP session.

Parameters

helo is the HELO domain that you‘ll dispatch mails from; see the discussion in the overview notes.

If both of user and secret are given, SMTP authentication will be attempted using the AUTH command. authtype specifies the type of authentication to attempt; it must be one of :login, :plain, and :cram_md5. See the notes on SMTP Authentication in the overview.

Block Usage

When this methods is called with a block, the newly-started SMTP object is yielded to the block, and automatically closed after the block call finishes. Otherwise, it is the caller‘s responsibility to close the session when finished.

Example

This is very similar to the class method SMTP.start.

    require 'net/smtp'
    smtp = Net::SMTP.new('smtp.mail.server', 25)
    smtp.start(helo_domain, account, password, authtype) do |smtp|
      smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
    end

The primary use of this method (as opposed to SMTP.start) is probably to set debugging (set_debug_output) or ESMTP (esmtp=), which must be done before the session is started.

Errors

If session has already been started, an IOError will be raised.

This method may raise:

  • Net::SMTPAuthenticationError
  • Net::SMTPServerBusy
  • Net::SMTPSyntaxError
  • Net::SMTPFatalError
  • Net::SMTPUnknownError
  • IOError
  • TimeoutError
started?()

true if the SMTP session has been started.


Class: Net::SMTPAuthenticationError

Class | Net::SMTPAuthenticationError
In: | lib/net/smtp.rb
Parent: | ProtoAuthError

Represents an SMTP authentication error.

Included Modules

SMTPError


Module: Net::SMTPError

Module | Net::SMTPError
In: | lib/net/smtp.rb

Module mixed in to all SMTP error classes


Class: Net::SMTPFatalError

Class | Net::SMTPFatalError
In: | lib/net/smtp.rb
Parent: | ProtoFatalError

Represents a fatal SMTP error (error code 5xx, except for 500)

Included Modules

SMTPError


Class: Net::SMTPServerBusy

Class | Net::SMTPServerBusy
In: | lib/net/smtp.rb
Parent: | ProtoServerError

Represents SMTP error code 420 or 450, a temporary error.

Included Modules

SMTPError


Class: Net::SMTPSyntaxError

Class | Net::SMTPSyntaxError
In: | lib/net/smtp.rb
Parent: | ProtoSyntaxError

Represents an SMTP command syntax error (error code 500)

Included Modules

SMTPError


Class: Net::SMTPUnknownError

Class | Net::SMTPUnknownError
In: | lib/net/smtp.rb
Parent: | ProtoUnknownError

Unexpected reply code returned from server.

Included Modules

SMTPError


Class: Net::Telnet

Class | Net::Telnet
In: | lib/net/telnet.rb
Parent: | SimpleDelegator

Net::Telnet

Provides telnet client functionality.

This class also has, through delegation, all the methods of a socket object (by default, a TCPSocket, but can be set by the Proxy option to new()). This provides methods such as close() to end the session and sysread() to read data directly from the host, instead of via the waitfor() mechanism. Note that if you do use sysread() directly when in telnet mode, you should probably pass the output through preprocess() to extract telnet command sequences.

Overview

The telnet protocol allows a client to login remotely to a user account on a server and execute commands via a shell. The equivalent is done by creating a Net::Telnet class with the Host option set to your host, calling login() with your user and password, issuing one or more cmd() calls, and then calling close() to end the session. The waitfor(), print(), puts(), and write() methods, which cmd() is implemented on top of, are only needed if you are doing something more complicated.

A Net::Telnet object can also be used to connect to non-telnet services, such as SMTP or HTTP. In this case, you normally want to provide the Port option to specify the port to connect to, and set the Telnetmode option to false to prevent the client from attempting to interpret telnet command sequences. Generally, login() will not work with other protocols, and you have to handle authentication yourself.

For some protocols, it will be possible to specify the Prompt option once when you create the Telnet object and use cmd() calls; for others, you will have to specify the response sequence to look for as the Match option to every cmd() call, or call puts() and waitfor() directly; for yet others, you will have to use sysread() instead of waitfor() and parse server responses yourself.

It is worth noting that when you create a new Net::Telnet object, you can supply a proxy IO channel via the Proxy option. This can be used to attach the Telnet object to other Telnet objects, to already open sockets, or to any read-write IO object. This can be useful, for instance, for setting up a test fixture for unit testing.

Examples

Log in and send a command, echoing all output to stdout

  localhost = Net::Telnet::new("Host" => "localhost",
                               "Timeout" => 10,
                               "Prompt" => /[$%#>] \z/n)
  localhost.login("username", "password") { |c| print c }
  localhost.cmd("command") { |c| print c }
  localhost.close

Check a POP server to see if you have mail

  pop = Net::Telnet::new("Host" => "your_destination_host_here",
                         "Port" => 110,
                         "Telnetmode" => false,
                         "Prompt" => /^\+OK/n)
  pop.cmd("user " + "your_username_here") { |c| print c }
  pop.cmd("pass " + "your_password_here") { |c| print c }
  pop.cmd("list") { |c| print c }

References

There are a large number of RFCs relevant to the Telnet protocol. RFCs 854-861 define the base protocol. For a complete listing of relevant RFCs, see www.omnifarious.org/~hopper/technical/telnet-rfc.html

Methods

binmode binmode= cmd login new preprocess print puts telnetmode telnetmode= waitfor write

Attributes

sock [R] The socket the Telnet object is using. Note that this object becomes a delegate of the Telnet object, so normally you invoke its methods directly on the Telnet object.

Public Class methods

new(options) {|mesg| ...}

Creates a new Net::Telnet object.

Attempts to connect to the host (unless the Proxy option is provided: see below). If a block is provided, it is yielded status messages on the attempt to connect to the server, of the form:

  Trying localhost...
  Connected to localhost.

options is a hash of options. The following example lists all options and their default values.

  host = Net::Telnet::new(
           "Host"       => "localhost",  # default: "localhost"
           "Port"       => 23,           # default: 23
           "Binmode"    => false,        # default: false
           "Output_log" => "output_log", # default: nil (no output)
           "Dump_log"   => "dump_log",   # default: nil (no output)
           "Prompt"     => /[$%#>] \z/n, # default: /[$%#>] \z/n
           "Telnetmode" => true,         # default: true
           "Timeout"    => 10,           # default: 10
             # if ignore timeout then set "Timeout" to false.
           "Waittime"   => 0,            # default: 0
           "Proxy"      => proxy         # default: nil
                           # proxy is Net::Telnet or IO object
         )

The options have the following meanings:

Host: | the hostname or IP address of the host to connect to, as a String. Defaults to "localhost".
Port: | the port to connect to. Defaults to 23.
Binmode: | if false (the default), newline substitution is performed. Outgoing LF is converted to CRLF, and incoming CRLF is converted to LF. If true, this substitution is not performed. This value can also be set with the binmode() method. The outgoing conversion only applies to the puts() and print() methods, not the write() method. The precise nature of the newline conversion is also affected by the telnet options SGA and BIN.
Output_log: | the name of the file to write connection status messages and all received traffic to. In the case of a proper Telnet session, this will include the client input as echoed by the host; otherwise, it only includes server responses. Output is appended verbatim to this file. By default, no output log is kept.
Dump_log: | as for Output_log, except that output is written in hexdump format (16 bytes per line as hex pairs, followed by their printable equivalent), with connection status messages preceded by ’#’, sent traffic preceded by ’>’, and received traffic preceded by ’<’. By default, not dump log is kept.
Prompt: | a regular expression matching the host‘s command-line prompt sequence. This is needed by the Telnet class to determine when the output from a command has finished and the host is ready to receive a new command. By default, this regular expression is /[$%#>] \z/n.
Telnetmode: | a boolean value, true by default. In telnet mode, traffic received from the host is parsed for special command sequences, and these sequences are escaped in outgoing traffic sent using puts() or print() (but not write()). If you are using the Net::Telnet object to connect to a non-telnet service (such as SMTP or POP), this should be set to "false" to prevent undesired data corruption. This value can also be set by the telnetmode() method.
Timeout: | the number of seconds to wait before timing out both the initial attempt to connect to host (in this constructor), and all attempts to read data from the host (in waitfor(), cmd(), and login()). Exceeding this timeout causes a TimeoutError to be raised. The default value is 10 seconds. You can disable the timeout by setting this value to false. In this case, the connect attempt will eventually timeout on the underlying connect(2) socket call with an Errno::ETIMEDOUT error (but generally only after a few minutes), but other attempts to read data from the host will hand indefinitely if no data is forthcoming.
Waittime: | the amount of time to wait after seeing what looks like a prompt (that is, received data that matches the Prompt option regular expression) to see if more data arrives. If more data does arrive in this time, Net::Telnet assumes that what it saw was not really a prompt. This is to try to avoid false matches, but it can also lead to missing real prompts (if, for instance, a background process writes to the terminal soon after the prompt is displayed). By default, set to 0, meaning not to wait for more data.
Proxy: | a proxy object to used instead of opening a direct connection to the host. Must be either another Net::Telnet object or an IO object. If it is another Net::Telnet object, this instance will use that one‘s socket for communication. If an IO object, it is used directly for communication. Any other kind of object will cause an error to be raised.

Public Instance methods

binmode(mode = nil)

Turn newline conversion on (mode == false) or off (mode == true), or return the current value (mode is not specified).

binmode=(mode)

Turn newline conversion on (false) or off (true).

cmd(options) {|recvdata| ...}

Send a command to the host.

More exactly, sends a string to the host, and reads in all received data until is sees the prompt or other matched sequence.

If a block is given, the received data will be yielded to it as it is read in. Whether a block is given or not, the received data will be return as a string. Note that the received data includes the prompt and in most cases the host‘s echo of our command.

options is either a String, specified the string or command to send to the host; or it is a hash of options. If a hash, the following options can be specified:

String: | the command or other string to send to the host.
Match: | a regular expression, the sequence to look for in the received data before returning. If not specified, the Prompt option value specified when this instance was created will be used, or, failing that, the default prompt of /[$%#>] \z/n.
Timeout: | the seconds to wait for data from the host before raising a Timeout error. If not specified, the Timeout option value specified when this instance was created will be used, or, failing that, the default value of 10 seconds.

The command or other string will have the newline sequence appended to it.

login(options, password = nil) {|recvdata| ...}

Login to the host with a given username and password.

The username and password can either be provided as two string arguments in that order, or as a hash with keys "Name" and "Password".

This method looks for the strings "login" and "Password" from the host to determine when to send the username and password. If the login sequence does not follow this pattern (for instance, you are connecting to a service other than telnet), you will need to handle login yourself.

The password can be omitted, either by only provided one String argument, which will be used as the username, or by providing a has that has no "Password" key. In this case, the method will not look for the "Password:" prompt; if it is sent, it will have to be dealt with by later calls.

The method returns all data received during the login process from the host, including the echoed username but not the password (which the host should not echo). If a block is passed in, this received data is also yielded to the block as it is received.

preprocess(string)

Preprocess received data from the host.

Performs newline conversion and detects telnet command sequences. Called automatically by waitfor(). You should only use this method yourself if you have read input directly using sysread() or similar, and even then only if in telnet mode.

print(string)

Sends a string to the host.

This does not automatically append a newline to the string. Embedded newlines may be converted and telnet command sequences escaped depending upon the values of telnetmode, binmode, and telnet options set by the host.

puts(string)

Sends a string to the host.

Same as print(), but appends a newline to the string.

telnetmode(mode = nil)

Set telnet command interpretation on (mode == true) or off (mode == false), or return the current value (mode not provided). It should be on for true telnet sessions, off if using Net::Telnet to connect to a non-telnet service such as SMTP.

telnetmode=(mode)

Turn telnet command interpretation on (true) or off (false). It should be on for true telnet sessions, off if using Net::Telnet to connect to a non-telnet service such as SMTP.

waitfor(options) {|recvdata| ...}

Read data from the host until a certain sequence is matched.

If a block is given, the received data will be yielded as it is read in (not necessarily all in one go), or nil if EOF occurs before any data is received. Whether a block is given or not, all data read will be returned in a single string, or again nil if EOF occurs before any data is received. Note that received data includes the matched sequence we were looking for.

options can be either a regular expression or a hash of options. If a regular expression, this specifies the data to wait for. If a hash, this can specify the following options:

Match: | a regular expression, specifying the data to wait for.
Prompt: | as for Match; used only if Match is not specified.
String: | as for Match, except a string that will be converted into a regular expression. Used only if Match and Prompt are not specified.
Timeout: | the number of seconds to wait for data from the host before raising a TimeoutError. If set to false, no timeout will occur. If not specified, the Timeout option value specified when this instance was created will be used, or, failing that, the default value of 10 seconds.
Waittime: | the number of seconds to wait after matching against the input data to see if more data arrives. If more data arrives within this time, we will judge ourselves not to have matched successfully, and will continue trying to match. If not specified, the Waittime option value specified when this instance was created will be used, or, failing that, the default value of 0 seconds, which means not to wait for more input.
write(string)

Write string to the host.

Does not perform any conversions on string. Will log string to the dumplog, if the Dump_log option is set.


Class: Net::WriteAdapter

Class | Net::WriteAdapter
In: | lib/net/protocol.rb
Parent: | Object

The writer adapter class

Methods

<< inspect new print printf puts write

Public Class methods

new(socket, method)

Public Instance methods

<<(str)
inspect()
print(str)

Alias for write

printf(*args)
puts(str = '')
write(str)


Class: Numeric

Class | Numeric
In: | numeric.c lib/complex.rb
Parent: | Object

Numeric is a built-in class on which Fixnum, Bignum, etc., are based. Here some methods are added so that all number types can be treated to some extent as Complex numbers.

Methods

+@ -@ <=> abs angle arg ceil coerce conj conjugate div divmod eql? floor im imag image integer? modulo nonzero? polar quo real remainder round singleton_method_added step to_int truncate zero?

Included Modules

Comparable

Public Instance methods

+num => num

Unary Plus—Returns the receiver‘s value.

-num => numeric

Unary Minus—Returns the receiver‘s value, negated.

num <=> other → 0 or nil

Returns zero if num equals other, nil otherwise.

num.abs => num or numeric

Returns the absolute value of num.

   12.abs         #=> 12
   (-34.56).abs   #=> 34.56
   -34.56.abs     #=> 34.56
angle()

Alias for arg

arg()

See Complex#arg.

num.ceil => integer

Returns the smallest Integer greater than or equal to num. Class Numeric achieves this by converting itself to a Float then invoking Float#ceil.

   1.ceil        #=> 1
   1.2.ceil      #=> 2
   (-1.2).ceil   #=> -1
   (-1.0).ceil   #=> -1
num.coerce(numeric) => array

If aNumeric is the same type as num, returns an array containing aNumeric and num. Otherwise, returns an array with both aNumeric and num represented as Float objects. This coercion mechanism is used by Ruby to handle mixed-type numeric operations: it is intended to find a compatible common type between the two operands of the operator.

   1.coerce(2.5)   #=> [2.5, 1.0]
   1.2.coerce(3)   #=> [3.0, 1.2]
   1.coerce(2)     #=> [2, 1]
conj()

Alias for conjugate

conjugate()

See Complex#conjugate (short answer: returns self).

num.div(numeric) => integer

Uses / to perform division, then converts the result to an integer. Numeric does not define the / operator; this is left to subclasses.

num.divmod( aNumeric ) → anArray

Returns an array containing the quotient and modulus obtained by dividing num by aNumeric. If q, r = x.divmod(y), then

    q = floor(float(x)/float(y))
    x = q*y + r

The quotient is rounded toward -infinity, as shown in the following table:

   a    |  b  |  a.divmod(b)  |   a/b   | a.modulo(b) | a.remainder(b)
  ------+-----+---------------+---------+-------------+---------------
   13   |  4  |   3,    1     |   3     |    1        |     1
  ------+-----+---------------+---------+-------------+---------------
   13   | -4  |  -4,   -3     |  -3     |   -3        |     1
  ------+-----+---------------+---------+-------------+---------------
  -13   |  4  |  -4,    3     |  -4     |    3        |    -1
  ------+-----+---------------+---------+-------------+---------------
  -13   | -4  |   3,   -1     |   3     |   -1        |    -1
  ------+-----+---------------+---------+-------------+---------------
   11.5 |  4  |   2,    3.5   |   2.875 |    3.5      |     3.5
  ------+-----+---------------+---------+-------------+---------------
   11.5 | -4  |  -3,   -0.5   |  -2.875 |   -0.5      |     3.5
  ------+-----+---------------+---------+-------------+---------------
  -11.5 |  4  |  -3,    0.5   |  -2.875 |    0.5      |    -3.5
  ------+-----+---------------+---------+-------------+---------------
  -11.5 | -4  |   2    -3.5   |   2.875 |   -3.5      |    -3.5

Examples

   11.divmod(3)         #=> [3, 2]
   11.divmod(-3)        #=> [-4, -1]
   11.divmod(3.5)       #=> [3, 0.5]
   (-11).divmod(3.5)    #=> [-4, 3.0]
   (11.5).divmod(3.5)   #=> [3, 1.0]
num.eql?(numeric) => true or false

Returns true if num and numeric are the same type and have equal values.

   1 == 1.0          #=> true
   1.eql?(1.0)       #=> false
   (1.0).eql?(1.0)   #=> true
num.floor => integer

Returns the largest integer less than or equal to num. Numeric implements this by converting anInteger to a Float and invoking Float#floor.

   1.floor      #=> 1
   (-1).floor   #=> -1
im()

Returns a Complex number (0,self).

imag()

Alias for image

image()

The imaginary part of a complex number, i.e. 0.

num.integer? → true or false

Returns true if num is an Integer (including Fixnum and Bignum).

num.modulo(numeric) => result

Equivalent to num.divmod(aNumeric)[1].

num.nonzero? => num or nil

Returns num if num is not zero, nil otherwise. This behavior is useful when chaining comparisons:

   a = %w( z Bb bB bb BB a aA Aa AA A )
   b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
   b   #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
polar()

See Complex#polar.

num.quo(numeric) => result

Equivalent to Numeric#/, but overridden in subclasses.

real()

The real part of a complex number, i.e. self.

num.remainder(numeric) => result

If num and numeric have different signs, returns mod-numeric; otherwise, returns mod. In both cases mod is the value num.modulo(numeric). The differences between remainder and modulo (%) are shown in the table under Numeric#divmod.

num.round => integer

Rounds num to the nearest integer. Numeric implements this by converting itself to a Float and invoking Float#round.

singleton_method_added(p1)

Trap attempts to add methods to Numeric objects. Always raises a TypeError

num.step(limit, step ) {|i| block } => num

Invokes block with the sequence of numbers starting at num, incremented by step on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.

   1.step(10, 2) { |i| print i, " " }
   Math::E.step(Math::PI, 0.2) { |f| print f, " " }

produces:

   1 3 5 7 9
   2.71828182845905 2.91828182845905 3.11828182845905
num.to_int => integer

Invokes the child class‘s to_i method to convert num to an integer.

num.truncate => integer

Returns num truncated to an integer. Numeric implements this by converting its value to a float and invoking Float#truncate.

num.zero? => true or false

Returns true if num has a zero value.


Class: Object

Class | Object
In: | object.c lib/irb/ext/use-loader.rb lib/pp.rb lib/rexml/xpath_parser.rb lib/soap/soap.rb lib/yaml/rubytypes.rb

Object is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.

Object mixes in the Kernel module, making the built-in kernel functions globally accessible. Although the instance methods of Object are defined by the Kernel module, we have chosen to document them here for clarity.

In the descriptions of Object‘s methods, the parameter symbol refers to a symbol, which is either a quoted string or a Symbol (such as :name).

Methods

== === =~ __id__ __send__ class clone dclone display dup enum_for eql? equal? extend freeze frozen? hash id inspect instance_eval instance_of? instance_variable_defined? instance_variable_get instance_variable_get instance_variable_set instance_variable_set instance_variables is_a? kind_of? method methods new nil? object_id private_methods protected_methods public_methods remove_instance_variable respond_to? send singleton_method_added singleton_method_removed singleton_method_undefined singleton_methods taint tainted? to_a to_enum to_s to_yaml to_yaml_properties to_yaml_style type untaint

Included Modules

Kernel PP::ObjectMixin

Constants

TOPLEVEL_BINDING | = | rb_f_binding(ruby_top_self)
DATA | = | f
ARGV | = | rb_argv
ENV | = | envtbl
ENV | = | envtbl
NIL | = | Qnil
TRUE | = | Qtrue
FALSE | = | Qfalse
STDIN | = | rb_stdin | constants to hold original stdin/stdout/stderr
STDOUT | = | rb_stdout
STDERR | = | rb_stderr
ARGF | = | argf
RUBY_VERSION | = | v
RUBY_RELEASE_DATE | = | d
RUBY_PLATFORM | = | p
RUBY_PATCHLEVEL | = | INT2FIX(RUBY_PATCHLEVEL)
VERSION | = | v | obsolete constants
RELEASE_DATE | = | d
PLATFORM | = | p
MatchingData | = | rb_cMatch
IPsocket | = | rb_cIPSocket
TCPsocket | = | rb_cTCPSocket
SOCKSsocket | = | rb_cSOCKSSocket
TCPserver | = | rb_cTCPServer
UDPsocket | = | rb_cUDPSocket
UNIXsocket | = | rb_cUNIXSocket
UNIXserver | = | rb_cUNIXServer

External Aliases

load | -> | __original__load__IRB_use_loader__
require | -> | __original__require__IRB_use_loader__

Public Class methods

new()

Not documented

Public Instance methods

obj == other => true or false
obj.equal?(other) => true or false
obj.eql?(other) => true or false

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

   1 == 1.0     #=> true
   1.eql? 1.0   #=> false
obj === other => true or false

Case Equality—For class Object, effectively the same as calling #==, but typically overridden by descendents to provide meaningful semantics in case statements.

obj =~ other => false

Pattern Match—Overridden by descendents (notably Regexp and String) to provide meaningful pattern-match semantics.

obj.__id__ => fixnum
obj.object_id => fixnum

Document-method: object_id

Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.

obj.send(symbol [, args...]) => obj
obj.__send__(symbol [, args...]) => obj

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

   class Klass
     def hello(*args)
       "Hello " + args.join(' ')
     end
   end
   k = Klass.new
   k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"
obj.class => class

Returns the class of obj, now preferred over Object#type, as an object‘s type in Ruby is only loosely tied to that object‘s class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.

   1.class      #=> Fixnum
   self.class   #=> Object
obj.clone → an_object

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.

   class Klass
      attr_accessor :str
   end
   s1 = Klass.new      #=> #<Klass:0x401b3a38>
   s1.str = "Hello"    #=> "Hello"
   s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
   s2.str[1,4] = "i"   #=> "i"
   s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
   s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

dclone()
obj.display(port=$>) => nil

Prints obj on the given port (default $>). Equivalent to:

   def display(port=$>)
     port.write self
   end

For example:

   1.display
   "cat".display
   [ 4, 5, 6 ].display
   puts

produces:

   1cat456
obj.dup → an_object

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

obj.to_enum(method = :each, *args)
obj.enum_for(method = :each, *args)

Returns Enumerable::Enumerator.new(self, method, *args).

e.g.:

   str = "xyz"

   enum = str.enum_for(:each_byte)
   a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]

   # protects an array from being modified
   a = [1, 2, 3]
   some_method(a.to_enum)
obj == other => true or false
obj.equal?(other) => true or false
obj.eql?(other) => true or false

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

   1 == 1.0     #=> true
   1.eql? 1.0   #=> false
obj == other => true or false
obj.equal?(other) => true or false
obj.eql?(other) => true or false

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

   1 == 1.0     #=> true
   1.eql? 1.0   #=> false
obj.extend(module, ...) => obj

Adds to obj the instance methods from each module given as a parameter.

   module Mod
     def hello
       "Hello from Mod.\n"
     end
   end

   class Klass
     def hello
       "Hello from Klass.\n"
     end
   end

   k = Klass.new
   k.hello         #=> "Hello from Klass.\n"
   k.extend(Mod)   #=> #<Klass:0x401b3bc8>
   k.hello         #=> "Hello from Mod.\n"
obj.freeze => obj

Prevents further modifications to obj. A TypeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.

   a = [ "a", "b", "c" ]
   a.freeze
   a << "z"

produces:

   prog.rb:3:in `<<': can't modify frozen array (TypeError)
    from prog.rb:3
obj.frozen? => true or false

Returns the freeze status of obj.

   a = [ "a", "b", "c" ]
   a.freeze    #=> ["a", "b", "c"]
   a.frozen?   #=> true
obj.hash => fixnum

Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.

obj.id => fixnum

Soon-to-be deprecated version of Object#object_id.

obj.inspect => string

Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.

   [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
   Time.new.inspect                 #=> "Wed Apr 09 08:54:39 CDT 2003"
obj.instance_eval(string [, filename [, lineno]] ) => obj
obj.instance_eval {| | block } => obj

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj‘s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

   class Klass
     def initialize
       @secret = 99
     end
   end
   k = Klass.new
   k.instance_eval { @secret }   #=> 99
obj.instance_of?(class) => true or false

Returns true if obj is an instance of the given class. See also Object#kind_of?.

obj.instance_variable_defined?(symbol) => true or false

Returns true if the given instance variable is defined in obj.

   class Fred
     def initialize(p1, p2)
       @a, @b = p1, p2
     end
   end
   fred = Fred.new('cat', 99)
   fred.instance_variable_defined?(:@a)    #=> true
   fred.instance_variable_defined?("@b")   #=> true
   fred.instance_variable_defined?("@c")   #=> false
obj.instance_variable_get(symbol) => obj

Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.

   class Fred
     def initialize(p1, p2)
       @a, @b = p1, p2
     end
   end
   fred = Fred.new('cat', 99)
   fred.instance_variable_get(:@a)    #=> "cat"
   fred.instance_variable_get("@b")   #=> 99
instance_variable_get(ivarname)
instance_variable_set(ivarname, value)
obj.instance_variable_set(symbol, obj) => obj

Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class‘s author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.

   class Fred
     def initialize(p1, p2)
       @a, @b = p1, p2
     end
   end
   fred = Fred.new('cat', 99)
   fred.instance_variable_set(:@a, 'dog')   #=> "dog"
   fred.instance_variable_set(:@c, 'cat')   #=> "cat"
   fred.inspect                             #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
obj.instance_variables => array

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

   class Fred
     attr_accessor :a1
     def initialize
       @iv = 3
     end
   end
   Fred.new.instance_variables   #=> ["@iv"]
obj.is_a?(class) => true or false
obj.kind_of?(class) => true or false

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

   module M;    end
   class A
     include M
   end
   class B < A; end
   class C < B; end
   b = B.new
   b.instance_of? A   #=> false
   b.instance_of? B   #=> true
   b.instance_of? C   #=> false
   b.instance_of? M   #=> false
   b.kind_of? A       #=> true
   b.kind_of? B       #=> true
   b.kind_of? C       #=> false
   b.kind_of? M       #=> true
obj.is_a?(class) => true or false
obj.kind_of?(class) => true or false

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

   module M;    end
   class A
     include M
   end
   class B < A; end
   class C < B; end
   b = B.new
   b.instance_of? A   #=> false
   b.instance_of? B   #=> true
   b.instance_of? C   #=> false
   b.instance_of? M   #=> false
   b.kind_of? A       #=> true
   b.kind_of? B       #=> true
   b.kind_of? C       #=> false
   b.kind_of? M       #=> true
obj.method(sym) => method

Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj‘s object instance, so instance variables and the value of self remain available.

   class Demo
     def initialize(n)
       @iv = n
     end
     def hello()
       "Hello, @iv = #{@iv}"
     end
   end

   k = Demo.new(99)
   m = k.method(:hello)
   m.call   #=> "Hello, @iv = 99"

   l = Demo.new('Fred')
   m = l.method("hello")
   m.call   #=> "Hello, @iv = Fred"
obj.methods => array

Returns a list of the names of methods publicly accessible in obj. This will include all the methods accessible in obj‘s ancestors.

   class Klass
     def kMethod()
     end
   end
   k = Klass.new
   k.methods[0..9]    #=> ["kMethod", "freeze", "nil?", "is_a?",
                           "class", "instance_variable_set",
                            "methods", "extend", "__send__", "instance_eval"]
   k.methods.length   #=> 42
nil?()

call_seq:

  nil.nil?               => true
  <anything_else>.nil?   => false

Only the object nil responds true to nil?.

obj.__id__ => fixnum
obj.object_id => fixnum

Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.

obj.private_methods(all=true) => array

Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

obj.protected_methods(all=true) => array

Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

obj.public_methods(all=true) => array

Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

obj.remove_instance_variable(symbol) => obj

Removes the named instance variable from obj, returning that variable‘s value.

   class Dummy
     attr_reader :var
     def initialize
       @var = 99
     end
     def remove
       remove_instance_variable(:@var)
     end
   end
   d = Dummy.new
   d.var      #=> 99
   d.remove   #=> 99
   d.var      #=> nil
obj.respond_to?(symbol, include_private=false) => true or false

Returns true> if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.

obj.send(symbol [, args...]) => obj
obj.__send__(symbol [, args...]) => obj

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

   class Klass
     def hello(*args)
       "Hello " + args.join(' ')
     end
   end
   k = Klass.new
   k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"
singleton_method_added(symbol)

Invoked as a callback whenever a singleton method is added to the receiver.

   module Chatty
     def Chatty.singleton_method_added(id)
       puts "Adding #{id.id2name}"
     end
     def self.one()     end
     def two()          end
     def Chatty.three() end
   end

produces:

   Adding singleton_method_added
   Adding one
   Adding three
singleton_method_removed(symbol)

Invoked as a callback whenever a singleton method is removed from the receiver.

   module Chatty
     def Chatty.singleton_method_removed(id)
       puts "Removing #{id.id2name}"
     end
     def self.one()     end
     def two()          end
     def Chatty.three() end
     class <<self
       remove_method :three
       remove_method :one
     end
   end

produces:

   Removing three
   Removing one
singleton_method_undefined(symbol)

Invoked as a callback whenever a singleton method is undefined in the receiver.

   module Chatty
     def Chatty.singleton_method_undefined(id)
       puts "Undefining #{id.id2name}"
     end
     def Chatty.one()   end
     class << self
        undef_method(:one)
     end
   end

produces:

   Undefining one
obj.singleton_methods(all=true) => array

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj.

   module Other
     def three() end
   end

   class Single
     def Single.four() end
   end

   a = Single.new

   def a.one()
   end

   class << a
     include Other
     def two()
     end
   end

   Single.singleton_methods    #=> ["four"]
   a.singleton_methods(false)  #=> ["two", "one"]
   a.singleton_methods         #=> ["two", "one", "three"]
obj.taint → obj

Marks obj as tainted—if the $SAFE level is set appropriately, many method calls which might alter the running programs environment will refuse to accept tainted strings.

obj.tainted? => true or false

Returns true if the object is tainted.

obj.to_a → anArray

Returns an array representation of obj. For objects of class Object and others that don‘t explicitly override the method, the return value is an array containing self. However, this latter behavior will soon be obsolete.

   self.to_a       #=> -:1: warning: default `to_a' will be obsolete
   "hello".to_a    #=> ["hello"]
   Time.new.to_a   #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"]
obj.to_enum(method = :each, *args)
obj.enum_for(method = :each, *args)

Returns Enumerable::Enumerator.new(self, method, *args).

e.g.:

   str = "xyz"

   enum = str.enum_for(:each_byte)
   a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]

   # protects an array from being modified
   a = [1, 2, 3]
   some_method(a.to_enum)
obj.to_s => string

Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘

to_yaml( opts = {} )
to_yaml_properties()
to_yaml_style()
obj.type => class

Deprecated synonym for Object#class.

obj.untaint => obj

Removes the taint from obj.


Class: String

Class | String
In: | string.c lib/jcode.rb lib/mkmf.rb lib/scanf.rb lib/yaml/rubytypes.rb ext/nkf/lib/kconv.rb

A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals.

Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object. Typically, methods with names ending in ``!’’ modify their receiver, while those without a ``!’’ return a new String. However, there are exceptions, such as String#[]=.

Methods

% * + << <=> == =~ [] []= block_scanf capitalize capitalize! casecmp center chomp chomp! chop chop chop! chop! concat count crypt delete delete delete! delete! downcase downcase! dump each each_byte each_char each_line empty? end_regexp eql? gsub gsub! hash hex include? index initialize_copy insert inspect intern is_binary_data? is_complex_yaml? iseuc issjis isutf8 jcount jlength jsize kconv length ljust lstrip lstrip! match mbchar? new next next! oct quote replace reverse reverse! rindex rjust rstrip rstrip! scan scanf size slice slice! split squeeze squeeze squeeze! squeeze! strip strip! sub sub! succ succ succ! succ! sum swapcase swapcase! to_f to_i to_s to_str to_sym to_yaml toeuc tojis tosjis toutf16 toutf8 tr tr tr! tr! tr_s tr_s tr_s! tr_s! unpack upcase upcase! upto yaml_new

Included Modules

Comparable Enumerable

Constants

PATTERN_SJIS | = | '[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc]'
PATTERN_EUC | = | '[\xa1-\xfe][\xa1-\xfe]'
PATTERN_UTF8 | = | '[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]'
RE_SJIS | = | Regexp.new(PATTERN_SJIS, 0, 'n')
RE_EUC | = | Regexp.new(PATTERN_EUC, 0, 'n')
RE_UTF8 | = | Regexp.new(PATTERN_UTF8, 0, 'n')
SUCC | = | {}
HashCache | = | {}
TrPatternCache | = | {}
DeletePatternCache | = | {}
SqueezePatternCache | = | {}

Public Class methods

String.new(str="") => new_str

Returns a new string object containing a copy of str.

yaml_new( klass, tag, val )

Public Instance methods

str % arg => new_str

Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted. See Kernel::sprintf for details of the format string.

   "%05d" % 123                       #=> "00123"
   "%-5s: %08x" % [ "ID", self.id ]   #=> "ID   : 200e14d6"
str * integer => new_str

Copy—Returns a new String containing integer copies of the receiver.

   "Ho! " * 3   #=> "Ho! Ho! Ho! "
str + other_str => new_str

Concatenation—Returns a new String containing other_str concatenated to str.

   "Hello from " + self.to_s   #=> "Hello from main"
str << fixnum => str
str.concat(fixnum) => str
str << obj => str
str.concat(obj) => str

Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.

   a = "hello "
   a << "world"   #=> "hello world"
   a.concat(33)   #=> "hello world!"
str <=> other_str => -1, 0, +1

Comparison—Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater than str. If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one. If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. In older versions of Ruby, setting $= allowed case-insensitive comparisons; this is now deprecated in favor of using String#casecmp.

<=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable. The method String#== does not use Comparable#==.

   "abcdef" <=> "abcde"     #=> 1
   "abcdef" <=> "abcdef"    #=> 0
   "abcdef" <=> "abcdefg"   #=> -1
   "abcdef" <=> "ABCDEF"    #=> 1
str == obj => true or false

Equality—If obj is not a String, returns false. Otherwise, returns true if str <=> obj returns zero.

str =~ obj => fixnum or nil

Match—If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false.

   "cat o' 9 tails" =~ /\d/   #=> 7
   "cat o' 9 tails" =~ 9      #=> false
str[fixnum] => fixnum or nil
str[fixnum, fixnum] => new_str or nil
str[range] => new_str or nil
str[regexp] => new_str or nil
str[regexp, fixnum] => new_str or nil
str[other_str] => new_str or nil
str.slice(fixnum) => fixnum or nil
str.slice(fixnum, fixnum) => new_str or nil
str.slice(range) => new_str or nil
str.slice(regexp) => new_str or nil
str.slice(regexp, fixnum) => new_str or nil
str.slice(other_str) => new_str or nil

Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end.

If a Regexp is supplied, the matching portion of str is returned. If a numeric parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

   a = "hello there"
   a[1]                   #=> 101
   a[1,3]                 #=> "ell"
   a[1..3]                #=> "ell"
   a[-3,2]                #=> "er"
   a[-4..-2]              #=> "her"
   a[12..-1]              #=> nil
   a[-2..-4]              #=> ""
   a[/[aeiou](.)\1/]      #=> "ell"
   a[/[aeiou](.)\1/, 0]   #=> "ell"
   a[/[aeiou](.)\1/, 1]   #=> "l"
   a[/[aeiou](.)\1/, 2]   #=> nil
   a["lo"]                #=> "lo"
   a["bye"]               #=> nil
str[fixnum] = fixnum
str[fixnum] = new_str
str[fixnum, fixnum] = new_str
str[range] = aString
str[regexp] = new_str
str[regexp, fixnum] = new_str
str[other_str] = new_str

Element Assignment—Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as String#[]. If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. If the regular expression or string is used as the index doesn‘t match a position in the string, IndexError is raised. If the regular expression form is used, the optional second Fixnum allows you to specify which portion of the match to replace (effectively using the MatchData indexing rules. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

block_scanf(fstr) {|current| ...}
str.capitalize => new_str

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

   "hello".capitalize    #=> "Hello"
   "HELLO".capitalize    #=> "Hello"
   "123ABC".capitalize   #=> "123abc"
str.capitalize! => str or nil

Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made.

   a = "hello"
   a.capitalize!   #=> "Hello"
   a               #=> "Hello"
   a.capitalize!   #=> nil
str.casecmp(other_str) => -1, 0, +1

Case-insensitive version of String#<=>.

   "abcdef".casecmp("abcde")     #=> 1
   "aBcDeF".casecmp("abcdef")    #=> 0
   "abcdef".casecmp("abcdefg")   #=> -1
   "abcdef".casecmp("ABCDEF")    #=> 0
str.center(integer, padstr) => new_str

If integer is greater than the length of str, returns a new String of length integer with str centered and padded with padstr; otherwise, returns str.

   "hello".center(4)         #=> "hello"
   "hello".center(20)        #=> "       hello        "
   "hello".center(20, '123') #=> "1231231hello12312312"
str.chomp(separator=$/) => new_str

Returns a new String with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is it will remove \n, \r, and \r\n).

   "hello".chomp            #=> "hello"
   "hello\n".chomp          #=> "hello"
   "hello\r\n".chomp        #=> "hello"
   "hello\n\r".chomp        #=> "hello\n"
   "hello\r".chomp          #=> "hello"
   "hello \n there".chomp   #=> "hello \n there"
   "hello".chomp("llo")     #=> "he"
str.chomp!(separator=$/) => str or nil

Modifies str in place as described for String#chomp, returning str, or nil if no modifications were made.

chop()
str.chop => new_str

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn‘t end in a record separator.

   "string\r\n".chop   #=> "string"
   "string\n\r".chop   #=> "string\n"
   "string\n".chop     #=> "string"
   "string".chop       #=> "strin"
   "x".chop.chop       #=> ""
str.chop! => str or nil

Processes str as for String#chop, returning str, or nil if str is the empty string. See also String#chomp!.

chop!()
str << fixnum => str
str.concat(fixnum) => str
str << obj => str
str.concat(obj) => str

Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.

   a = "hello "
   a << "world"   #=> "hello world"
   a.concat(33)   #=> "hello world!"
str.count([other_str]+) => fixnum

Each other_str parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any other_str that starts with a caret (^) is negated. The sequence c1—c2 means all characters between c1 and c2.

   a = "hello world"
   a.count "lo"            #=> 5
   a.count "lo", "o"       #=> 2
   a.count "hello", "^l"   #=> 4
   a.count "ej-m"          #=> 4
str.crypt(other_str) => new_str

Applies a one-way cryptographic hash to str by invoking the standard library function crypt. The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./].

delete(del)
str.delete([other_str]+) => new_str

Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count.

   "hello".delete "l","lo"        #=> "heo"
   "hello".delete "lo"            #=> "he"
   "hello".delete "aeiou", "^e"   #=> "hell"
   "hello".delete "ej-m"          #=> "ho"
delete!(del)
str.delete!([other_str]+>) => str or nil

Performs a delete operation in place, returning str, or nil if str was not modified.

str.downcase => new_str

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale insensitive—only characters ``A’’ to ``Z’’ are affected.

   "hEllO".downcase   #=> "hello"
str.downcase! => str or nil

Downcases the contents of str, returning nil if no changes were made.

str.dump => new_str

Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.

str.each(separator=$/) {|substr| block } => str
str.each_line(separator=$/) {|substr| block } => str

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together.

   print "Example one\n"
   "hello\nworld".each {|s| p s}
   print "Example two\n"
   "hello\nworld".each('l') {|s| p s}
   print "Example three\n"
   "hello\n\n\nworld".each('') {|s| p s}

produces:

   Example one
   "hello\n"
   "world"
   Example two
   "hel"
   "l"
   "o\nworl"
   "d"
   Example three
   "hello\n\n\n"
   "world"
str.each_byte {|fixnum| block } => str

Passes each byte in str to the given block.

   "hello".each_byte {|c| print c, ' ' }

produces:

   104 101 108 108 111
each_char() {|x| ...}
str.each(separator=$/) {|substr| block } => str
str.each_line(separator=$/) {|substr| block } => str

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together.

   print "Example one\n"
   "hello\nworld".each {|s| p s}
   print "Example two\n"
   "hello\nworld".each('l') {|s| p s}
   print "Example three\n"
   "hello\n\n\nworld".each('') {|s| p s}

produces:

   Example one
   "hello\n"
   "world"
   Example two
   "hel"
   "l"
   "o\nworl"
   "d"
   Example three
   "hello\n\n\n"
   "world"
str.empty? => true or false

Returns true if str has a length of zero.

   "hello".empty?   #=> false
   "".empty?        #=> true
end_regexp()
str.eql?(other) => true or false

Two strings are equal if the have the same length and content.

str.gsub(pattern, replacement) => new_str
str.gsub(pattern) {|match| block } => new_str

Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but ’\d‘ will match a backslash followed by a ‘d’).

If a string is used as the replacement, special variables from the match (such as $& and $1) cannot be substituted into it, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, and so on may be used to interpolate successive groups in the match.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $’ will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

   "hello".gsub(/[aeiou]/, '*')              #=> "h*ll*"
   "hello".gsub(/([aeiou])/, '<\1>')         #=> "h<e>ll<o>"
   "hello".gsub(/./) {|s| s[0].to_s + ' '}   #=> "104 101 108 108 111 "
str.gsub!(pattern, replacement) => str or nil
str.gsub!(pattern) {|match| block } => str or nil

Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed.

str.hash => fixnum

Return a hash based on the string‘s length and content.

str.hex => integer

Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error.

   "0x0a".hex     #=> 10
   "-1234".hex    #=> -4660
   "0".hex        #=> 0
   "wombat".hex   #=> 0
str.include? other_str => true or false
str.include? fixnum => true or false

Returns true if str contains the given string or character.

   "hello".include? "lo"   #=> true
   "hello".include? "ol"   #=> false
   "hello".include? ?h     #=> true
str.index(substring [, offset]) => fixnum or nil
str.index(fixnum [, offset]) => fixnum or nil
str.index(regexp [, offset]) => fixnum or nil

Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

   "hello".index('e')             #=> 1
   "hello".index('lo')            #=> 3
   "hello".index('a')             #=> nil
   "hello".index(101)             #=> 1
   "hello".index(/[aeiou]/, -3)   #=> 4
str.replace(other_str) => str

Replaces the contents and taintedness of str with the corresponding values in other_str.

   s = "hello"         #=> "hello"
   s.replace "world"   #=> "world"
str.insert(index, other_str) => str

Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is insert aString so that it starts at the given index.

   "abcd".insert(0, 'X')    #=> "Xabcd"
   "abcd".insert(3, 'X')    #=> "abcXd"
   "abcd".insert(4, 'X')    #=> "abcdX"
   "abcd".insert(-3, 'X')   #=> "abXcd"
   "abcd".insert(-1, 'X')   #=> "abcdX"
str.inspect => string

Returns a printable version of str, with special characters escaped.

   str = "hello"
   str[3] = 8
   str.inspect       #=> "hel\010o"
str.intern => symbol
str.to_sym => symbol

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

   "Koala".intern         #=> :Koala
   s = 'cat'.to_sym       #=> :cat
   s == :cat              #=> true
   s = '@cat'.to_sym      #=> :@cat
   s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

   'cat and dog'.to_sym   #=> :"cat and dog"
is_binary_data?()
is_complex_yaml?()
String#iseuc → obj or nil

Returns whether self‘s encoding is EUC-JP or not.

Note don‘t expect this return value is MatchData.

String#issjis → obj or nil

Returns whether self‘s encoding is Shift_JIS or not.

Note don‘t expect this return value is MatchData.

String#isutf8 → obj or nil

Returns whether self‘s encoding is UTF-8 or not.

Note don‘t expect this return value is MatchData.

jcount(str)
jlength()
jsize()

Alias for jlength

String#kconv(out_code, in_code = Kconv::AUTO)

Convert self to out_code. out_code and in_code are given as constants of Kconv.

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want to decode them, use NKF.nkf.

str.length => integer

Returns the length of str.

str.ljust(integer, padstr=' ') => new_str

If integer is greater than the length of str, returns a new String of length integer with str left justified and padded with padstr; otherwise, returns str.

   "hello".ljust(4)            #=> "hello"
   "hello".ljust(20)           #=> "hello               "
   "hello".ljust(20, '1234')   #=> "hello123412341234123"
str.lstrip => new_str

Returns a copy of str with leading whitespace removed. See also String#rstrip and String#strip.

   "  hello  ".lstrip   #=> "hello  "
   "hello".lstrip       #=> "hello"
str.lstrip! => self or nil

Removes leading whitespace from str, returning nil if no change was made. See also String#rstrip! and String#strip!.

   "  hello  ".lstrip   #=> "hello  "
   "hello".lstrip!      #=> nil
str.match(pattern) => matchdata or nil

Converts pattern to a Regexp (if it isn‘t already one), then invokes its match method on str.

   'hello'.match('(.)\1')      #=> #<MatchData:0x401b3d30>
   'hello'.match('(.)\1')[0]   #=> "ll"
   'hello'.match(/(.)\1/)[0]   #=> "ll"
   'hello'.match('xx')         #=> nil
mbchar?()
str.succ => new_str
str.next => new_str

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set‘s collating sequence.

If the increment generates a ``carry,’’ the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

   "abcd".succ        #=> "abce"
   "THX1138".succ     #=> "THX1139"
   "<<koala>>".succ   #=> "<<koalb>>"
   "1999zzz".succ     #=> "2000aaa"
   "ZZZ9999".succ     #=> "AAAA0000"
   "***".succ         #=> "**+"
str.succ! => str
str.next! => str

Equivalent to String#succ, but modifies the receiver in place.

str.oct => integer

Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails.

   "123".oct       #=> 83
   "-377".oct      #=> -255
   "bad".oct       #=> 0
   "0377bad".oct   #=> 255
quote()
str.replace(other_str) => str

Replaces the contents and taintedness of str with the corresponding values in other_str.

   s = "hello"         #=> "hello"
   s.replace "world"   #=> "world"
str.reverse => new_str

Returns a new string with the characters from str in reverse order.

   "stressed".reverse   #=> "desserts"
str.reverse! => str

Reverses str in place.

str.rindex(substring [, fixnum]) => fixnum or nil
str.rindex(fixnum [, fixnum]) => fixnum or nil
str.rindex(regexp [, fixnum]) => fixnum or nil

Returns the index of the last occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search—characters beyond this point will not be considered.

   "hello".rindex('e')             #=> 1
   "hello".rindex('l')             #=> 3
   "hello".rindex('a')             #=> nil
   "hello".rindex(101)             #=> 1
   "hello".rindex(/[aeiou]/, -2)   #=> 1
str.rjust(integer, padstr=' ') => new_str

If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str.

   "hello".rjust(4)            #=> "hello"
   "hello".rjust(20)           #=> "               hello"
   "hello".rjust(20, '1234')   #=> "123412341234123hello"
str.rstrip => new_str

Returns a copy of str with trailing whitespace removed. See also String#lstrip and String#strip.

   "  hello  ".rstrip   #=> "  hello"
   "hello".rstrip       #=> "hello"
str.rstrip! => self or nil

Removes trailing whitespace from str, returning nil if no change was made. See also String#lstrip! and String#strip!.

   "  hello  ".rstrip   #=> "  hello"
   "hello".rstrip!      #=> nil
str.scan(pattern) => array
str.scan(pattern) {|match, ...| block } => str

Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group.

   a = "cruel world"
   a.scan(/\w+/)        #=> ["cruel", "world"]
   a.scan(/.../)        #=> ["cru", "el ", "wor"]
   a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
   a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

And the block form:

   a.scan(/\w+/) {|w| print "<<#{w}>> " }
   print "\n"
   a.scan(/(.)(.)/) {|x,y| print y, x }
   print "\n"

produces:

   <<cruel>> <<world>>
   rceu lowlr
scanf(fstr,&b)
str.length => integer

Returns the length of str.

str[fixnum] => fixnum or nil
str[fixnum, fixnum] => new_str or nil
str[range] => new_str or nil
str[regexp] => new_str or nil
str[regexp, fixnum] => new_str or nil
str[other_str] => new_str or nil
str.slice(fixnum) => fixnum or nil
str.slice(fixnum, fixnum) => new_str or nil
str.slice(range) => new_str or nil
str.slice(regexp) => new_str or nil
str.slice(regexp, fixnum) => new_str or nil
str.slice(other_str) => new_str or nil

Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end.

If a Regexp is supplied, the matching portion of str is returned. If a numeric parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

   a = "hello there"
   a[1]                   #=> 101
   a[1,3]                 #=> "ell"
   a[1..3]                #=> "ell"
   a[-3,2]                #=> "er"
   a[-4..-2]              #=> "her"
   a[12..-1]              #=> nil
   a[-2..-4]              #=> ""
   a[/[aeiou](.)\1/]      #=> "ell"
   a[/[aeiou](.)\1/, 0]   #=> "ell"
   a[/[aeiou](.)\1/, 1]   #=> "l"
   a[/[aeiou](.)\1/, 2]   #=> nil
   a["lo"]                #=> "lo"
   a["bye"]               #=> nil
str.slice!(fixnum) => fixnum or nil
str.slice!(fixnum, fixnum) => new_str or nil
str.slice!(range) => new_str or nil
str.slice!(regexp) => new_str or nil
str.slice!(other_str) => new_str or nil

Deletes the specified portion from str, and returns the portion deleted. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

   string = "this is a string"
   string.slice!(2)        #=> 105
   string.slice!(3..6)     #=> " is "
   string.slice!(/s.*t/)   #=> "sa st"
   string.slice!("r")      #=> "r"
   string                  #=> "thing"
str.split(pattern=$;, [limit]) => anArray

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ’ were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

   " now's  the time".split        #=> ["now's", "the", "time"]
   " now's  the time".split(' ')   #=> ["now's", "the", "time"]
   " now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
   "1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
   "hello".split(//)               #=> ["h", "e", "l", "l", "o"]
   "hello".split(//, 3)            #=> ["h", "e", "llo"]
   "hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]

   "mellow yellow".split("ello")   #=> ["m", "w y", "w"]
   "1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
   "1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
   "1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]
squeeze(del=nil)
str.squeeze([other_str]*) => new_str

Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.

   "yellow moon".squeeze                  #=> "yelow mon"
   "  now   is  the".squeeze(" ")         #=> " now is the"
   "putters shoot balls".squeeze("m-z")   #=> "puters shot balls"
squeeze!(del=nil)
str.squeeze!([other_str]*) => str or nil

Squeezes str in place, returning either str, or nil if no changes were made.

str.strip => new_str

Returns a copy of str with leading and trailing whitespace removed.

   "    hello    ".strip   #=> "hello"
   "\tgoodbye\r\n".strip   #=> "goodbye"
str.strip! => str or nil

Removes leading and trailing whitespace from str. Returns nil if str was not altered.

str.sub(pattern, replacement) => new_str
str.sub(pattern) {|match| block } => new_str

Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but ’\d‘ will match a backslash followed by a ‘d’).

If the method call specifies replacement, special variables such as $& will not be useful, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, etc., may be used.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $’ will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

   "hello".sub(/[aeiou]/, '*')               #=> "h*llo"
   "hello".sub(/([aeiou])/, '<\1>')          #=> "h<e>llo"
   "hello".sub(/./) {|s| s[0].to_s + ' ' }   #=> "104 ello"
str.sub!(pattern, replacement) => str or nil
str.sub!(pattern) {|match| block } => str or nil

Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed.

str.succ => new_str
str.next => new_str

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set‘s collating sequence.

If the increment generates a ``carry,’’ the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

   "abcd".succ        #=> "abce"
   "THX1138".succ     #=> "THX1139"
   "<<koala>>".succ   #=> "<<koalb>>"
   "1999zzz".succ     #=> "2000aaa"
   "ZZZ9999".succ     #=> "AAAA0000"
   "***".succ         #=> "**+"
succ()
str.succ! => str
str.next! => str

Equivalent to String#succ, but modifies the receiver in place.

succ!()
str.sum(n=16) => integer

Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2n - 1. This is not a particularly good checksum.

str.swapcase => new_str

Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.

   "Hello".swapcase          #=> "hELLO"
   "cYbEr_PuNk11".swapcase   #=> "CyBeR_pUnK11"
str.swapcase! => str or nil

Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made.

str.to_f => float

Returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception.

   "123.45e1".to_f        #=> 1234.5
   "45.67 degrees".to_f   #=> 45.67
   "thx1138".to_f         #=> 0.0
str.to_i(base=10) => integer

Returns the result of interpreting leading characters in str as an integer base base (2, 8, 10, or 16). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception.

   "12345".to_i             #=> 12345
   "99 red balloons".to_i   #=> 99
   "0a".to_i                #=> 0
   "0a".to_i(16)            #=> 10
   "hello".to_i             #=> 0
   "1100101".to_i(2)        #=> 101
   "1100101".to_i(8)        #=> 294977
   "1100101".to_i(10)       #=> 1100101
   "1100101".to_i(16)       #=> 17826049
str.to_s => str
str.to_str => str

Returns the receiver.

str.to_s => str
str.to_str => str

Returns the receiver.

str.intern => symbol
str.to_sym => symbol

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

   "Koala".intern         #=> :Koala
   s = 'cat'.to_sym       #=> :cat
   s == :cat              #=> true
   s = '@cat'.to_sym      #=> :@cat
   s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

   'cat and dog'.to_sym   #=> :"cat and dog"
to_yaml( opts = {} )
String#toeuc → string

Convert self to EUC-JP

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-exm0’, str).

String#tojis → string

Convert self to ISO-2022-JP

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-jxm0’, str).

String#tosjis → string

Convert self to Shift_JIS

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-sxm0’, str).

String#toutf16 → string

Convert self to UTF-16

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-w16xm0’, str).

String#toutf8 → string

Convert self to UTF-8

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-wxm0’, str).

str.tr(from_str, to_str) => new_str

Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character. Both strings may use the c1—c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed.

   "hello".tr('aeiou', '*')    #=> "h*ll*"
   "hello".tr('^aeiou', '*')   #=> "*e**o"
   "hello".tr('el', 'ip')      #=> "hippo"
   "hello".tr('a-y', 'b-z')    #=> "ifmmp"
tr(from, to)
str.tr!(from_str, to_str) => str or nil

Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made.

tr!(from, to)
str.tr_s(from_str, to_str) => new_str

Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation.

   "hello".tr_s('l', 'r')     #=> "hero"
   "hello".tr_s('el', '*')    #=> "h*o"
   "hello".tr_s('el', 'hx')   #=> "hhxo"
tr_s(from, to)
tr_s!(from, to)
str.tr_s!(from_str, to_str) => str or nil

Performs String#tr_s processing on str in place, returning str, or nil if no changes were made.

str.unpack(format) => anArray

Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (``*’’) will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (``_’’) to use the underlying platform‘s native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also Array#pack.

   "abc \0\0abc \0\0".unpack('A6Z6')   #=> ["abc", "abc "]
   "abc \0\0".unpack('a3a3')           #=> ["abc", " \000\000"]
   "abc \0abc \0".unpack('Z*Z*')       #=> ["abc ", "abc "]
   "aa".unpack('b8B8')                 #=> ["10000110", "01100001"]
   "aaa".unpack('h2H2c')               #=> ["16", "61", 97]
   "\xfe\xff\xfe\xff".unpack('sS')     #=> [-2, 65534]
   "now=20is".unpack('M*')             #=> ["now is"]
   "whole".unpack('xax2aX2aX1aX2a')    #=> ["h", "e", "l", "l", "o"]

This table summarizes the various formats and the Ruby classes returned by each.

   Format | Returns | Function
   -------+---------+-----------------------------------------
     A    | String  | with trailing nulls and spaces removed
   -------+---------+-----------------------------------------
     a    | String  | string
   -------+---------+-----------------------------------------
     B    | String  | extract bits from each character (msb first)
   -------+---------+-----------------------------------------
     b    | String  | extract bits from each character (lsb first)
   -------+---------+-----------------------------------------
     C    | Fixnum  | extract a character as an unsigned integer
   -------+---------+-----------------------------------------
     c    | Fixnum  | extract a character as an integer
   -------+---------+-----------------------------------------
     d,D  | Float   | treat sizeof(double) characters as
          |         | a native double
   -------+---------+-----------------------------------------
     E    | Float   | treat sizeof(double) characters as
          |         | a double in little-endian byte order
   -------+---------+-----------------------------------------
     e    | Float   | treat sizeof(float) characters as
          |         | a float in little-endian byte order
   -------+---------+-----------------------------------------
     f,F  | Float   | treat sizeof(float) characters as
          |         | a native float
   -------+---------+-----------------------------------------
     G    | Float   | treat sizeof(double) characters as
          |         | a double in network byte order
   -------+---------+-----------------------------------------
     g    | Float   | treat sizeof(float) characters as a
          |         | float in network byte order
   -------+---------+-----------------------------------------
     H    | String  | extract hex nibbles from each character
          |         | (most significant first)
   -------+---------+-----------------------------------------
     h    | String  | extract hex nibbles from each character
          |         | (least significant first)
   -------+---------+-----------------------------------------
     I    | Integer | treat sizeof(int) (modified by _)
          |         | successive characters as an unsigned
          |         | native integer
   -------+---------+-----------------------------------------
     i    | Integer | treat sizeof(int) (modified by _)
          |         | successive characters as a signed
          |         | native integer
   -------+---------+-----------------------------------------
     L    | Integer | treat four (modified by _) successive
          |         | characters as an unsigned native
          |         | long integer
   -------+---------+-----------------------------------------
     l    | Integer | treat four (modified by _) successive
          |         | characters as a signed native
          |         | long integer
   -------+---------+-----------------------------------------
     M    | String  | quoted-printable
   -------+---------+-----------------------------------------
     m    | String  | base64-encoded
   -------+---------+-----------------------------------------
     N    | Integer | treat four characters as an unsigned
          |         | long in network byte order
   -------+---------+-----------------------------------------
     n    | Fixnum  | treat two characters as an unsigned
          |         | short in network byte order
   -------+---------+-----------------------------------------
     P    | String  | treat sizeof(char *) characters as a
          |         | pointer, and  return \emph{len} characters
          |         | from the referenced location
   -------+---------+-----------------------------------------
     p    | String  | treat sizeof(char *) characters as a
          |         | pointer to a  null-terminated string
   -------+---------+-----------------------------------------
     Q    | Integer | treat 8 characters as an unsigned
          |         | quad word (64 bits)
   -------+---------+-----------------------------------------
     q    | Integer | treat 8 characters as a signed
          |         | quad word (64 bits)
   -------+---------+-----------------------------------------
     S    | Fixnum  | treat two (different if _ used)
          |         | successive characters as an unsigned
          |         | short in native byte order
   -------+---------+-----------------------------------------
     s    | Fixnum  | Treat two (different if _ used)
          |         | successive characters as a signed short
          |         | in native byte order
   -------+---------+-----------------------------------------
     U    | Integer | UTF-8 characters as unsigned integers
   -------+---------+-----------------------------------------
     u    | String  | UU-encoded
   -------+---------+-----------------------------------------
     V    | Fixnum  | treat four characters as an unsigned
          |         | long in little-endian byte order
   -------+---------+-----------------------------------------
     v    | Fixnum  | treat two characters as an unsigned
          |         | short in little-endian byte order
   -------+---------+-----------------------------------------
     w    | Integer | BER-compressed integer (see Array.pack)
   -------+---------+-----------------------------------------
     X    | ---     | skip backward one character
   -------+---------+-----------------------------------------
     x    | ---     | skip forward one character
   -------+---------+-----------------------------------------
     Z    | String  | with trailing nulls removed
          |         | upto first null with *
   -------+---------+-----------------------------------------
     @    | ---     | skip to the offset given by the
          |         | length argument
   -------+---------+-----------------------------------------
str.upcase => new_str

Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive—only characters ``a’’ to ``z’’ are affected.

   "hEllO".upcase   #=> "HELLO"
str.upcase! => str or nil

Upcases the contents of str, returning nil if no changes were made.

str.upto(other_str) {|s| block } => str

Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ method is used to generate each value.

   "a8".upto("b6") {|s| print s, ' ' }
   for s in "a8".."b6"
     print s, ' '
   end

produces:

   a8 a9 b0 b1 b2 b3 b4 b5 b6
   a8 a9 b0 b1 b2 b3 b4 b5 b6


Class: Time

Class | Time
In: | time.c lib/date.rb lib/rss/rss.rb lib/time.rb lib/yaml/rubytypes.rb
Parent: | Object

Implements the extensions to the Time class that are described in the documentation for the time.rb library.

Methods

+ - <=> _dump _load asctime at ctime day dst? eql? getgm getlocal getutc gm gmt? gmt_offset gmtime gmtoff hash hour httpdate httpdate inspect isdst iso8601 local localtime marshal_dump marshal_load mday min mktime mon month new now parse rfc2822 rfc2822 rfc822 sec strftime succ times to_a to_f to_i to_s to_yaml tv_sec tv_usec usec utc utc utc? utc_offset w3cdtf wday xmlschema xmlschema yaml_new yday year zone zone_offset

Included Modules

Comparable

Constants

ZoneOffset | = | { 'UTC' => 0, # ISO 8601 'Z' => 0, # RFC 822 'UT' => 0, 'GMT' => 0, 'EST' => -5, 'EDT' => -4, 'CST' => -6, 'CDT' => -5, 'MST' => -7, 'MDT' => -6, 'PST' => -8, 'PDT' => -7, # Following definition of military zones is original one. # See RFC 1123 and RFC 2822 for the error in RFC 822. 'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6, 'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12, 'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6, 'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12, }
LeapYearMonthDays | = | [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
CommonYearMonthDays | = | [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
MonthValue | = | { 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
RFC2822_DAY_NAME | = | [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
RFC2822_MONTH_NAME | = | [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'

External Aliases

iso8601 | -> | w3cdtf
rfc2822 | -> | rfc822
xmlschema | -> | iso8601

Public Class methods

Time._load(string) => time

Unmarshal a dumped Time object.

Time.at( aTime ) => time
Time.at( seconds [, microseconds] ) => time

Creates a new time object with the value given by aTime, or the given number of seconds (and optional microseconds) from epoch. A non-portable feature allows the offset to be negative on some systems.

   Time.at(0)            #=> Wed Dec 31 18:00:00 CST 1969
   Time.at(946702800)    #=> Fri Dec 31 23:00:00 CST 1999
   Time.at(-284061600)   #=> Sat Dec 31 00:00:00 CST 1960
Time.utc( year [, month, day, hour, min, sec, usec] ) => time
Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz
) => time
Time.gm( year [, month, day, hour, min, sec, usec] ) => time
Time.gm( sec, min, hour, day, month, year, wday, yday, isdst, tz
) => time

Creates a time based on given values, interpreted as UTC (GMT). The year must be specified. Other values default to the minimum value for that field (and may be nil or omitted). Months may be specified by numbers from 1 to 12, or by the three-letter English month names. Hours are specified on a 24-hour clock (0..23). Raises an ArgumentError if any values are out of range. Will also accept ten arguments in the order output by Time#to_a.

   Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
   Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
httpdate(date)

Parses date as HTTP-date defined by RFC 2616 and converts it to a Time object.

ArgumentError is raised if date is not compliant with RFC 2616 or Time class cannot represent specified date.

See httpdate for more information on this format.

Time.local( year [, month, day, hour, min, sec, usec] ) => time
Time.local( sec, min, hour, day, month, year, wday, yday, isdst,
tz ) => time
Time.mktime( year, month, day, hour, min, sec, usec ) => time

Same as Time::gm, but interprets the values in the local time zone.

   Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
Time.local( year [, month, day, hour, min, sec, usec] ) => time
Time.local( sec, min, hour, day, month, year, wday, yday, isdst,
tz ) => time
Time.mktime( year, month, day, hour, min, sec, usec ) => time

Same as Time::gm, but interprets the values in the local time zone.

   Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
Time.new → time

Document-method: now

Synonym for Time.new. Returns a Time object initialized tot he current system time.

Returns a Time object initialized to the current system time. Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

   a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
   b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
   a == b            #=> false
   "%.6f" % a.to_f   #=> "1049896563.230740"
   "%.6f" % b.to_f   #=> "1049896563.231466"
Time.new → time

Synonym for Time.new. Returns a Time object initialized tot he current system time.

Returns a Time object initialized to the current system time. Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

   a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
   b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
   a == b            #=> false
   "%.6f" % a.to_f   #=> "1049896563.230740"
   "%.6f" % b.to_f   #=> "1049896563.231466"
parse(date, now=Time.now) {|year| ...}

Parses date using Date._parse and converts it to a Time object.

If a block is given, the year described in date is converted by the block. For example:

    Time.parse(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}

If the upper components of the given time are broken or missing, they are supplied with those of now. For the lower components, the minimum values (1 or 0) are assumed if broken or missing. For example:

    # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
    # your timezone is GMT:
    Time.parse("16:30")     #=> Thu Nov 29 16:30:00 GMT 2001
    Time.parse("7/23")      #=> Mon Jul 23 00:00:00 GMT 2001
    Time.parse("Aug 31")    #=> Fri Aug 31 00:00:00 GMT 2001

Since there are numerous conflicts among locally defined timezone abbreviations all over the world, this method is not made to understand all of them. For example, the abbreviation "CST" is used variously as:

    -06:00 in America/Chicago,
    -05:00 in America/Havana,
    +08:00 in Asia/Harbin,
    +09:30 in Australia/Darwin,
    +10:30 in Australia/Adelaide,
    etc.

Based on the fact, this method only understands the timezone abbreviations described in RFC 822 and the system timezone, in the order named. (i.e. a definition in RFC 822 overrides the system timezone definition.) The system timezone is taken from Time.local(year, 1, 1).zone and Time.local(year, 7, 1).zone. If the extracted timezone abbreviation does not match any of them, it is ignored and the given time is regarded as a local time.

ArgumentError is raised if Date._parse cannot extract information from date or Time class cannot represent specified date.

This method can be used as fail-safe for other parsing methods as:

  Time.rfc2822(date) rescue Time.parse(date)
  Time.httpdate(date) rescue Time.parse(date)
  Time.xmlschema(date) rescue Time.parse(date)

A failure for Time.parse should be checked, though.

rfc2822(date)

Parses date as date-time defined by RFC 2822 and converts it to a Time object. The format is identical to the date format defined by RFC 822 and updated by RFC 1123.

ArgumentError is raised if date is not compliant with RFC 2822 or Time class cannot represent specified date.

See rfc2822 for more information on this format.

Time.times => struct_tms

Deprecated in favor of Process::times

Time.utc( year [, month, day, hour, min, sec, usec] ) => time
Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz
) => time
Time.gm( year [, month, day, hour, min, sec, usec] ) => time
Time.gm( sec, min, hour, day, month, year, wday, yday, isdst, tz
) => time

Creates a time based on given values, interpreted as UTC (GMT). The year must be specified. Other values default to the minimum value for that field (and may be nil or omitted). Months may be specified by numbers from 1 to 12, or by the three-letter English month names. Hours are specified on a 24-hour clock (0..23). Raises an ArgumentError if any values are out of range. Will also accept ten arguments in the order output by Time#to_a.

   Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
   Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
w3cdtf(date)
xmlschema(date)

Parses date as dateTime defined by XML Schema and converts it to a Time object. The format is restricted version of the format defined by ISO 8601.

ArgumentError is raised if date is not compliant with the format or Time class cannot represent specified date.

See xmlschema for more information on this format.

yaml_new( klass, tag, val )
zone_offset(zone, year=Time.now.year)

Public Instance methods

time + numeric => time

Addition—Adds some number of seconds (possibly fractional) to time and returns that value as a new time.

   t = Time.now         #=> Wed Apr 09 08:56:03 CDT 2003
   t + (60 * 60 * 24)   #=> Thu Apr 10 08:56:03 CDT 2003
time - other_time => float
time - numeric => time

Difference—Returns a new time that represents the difference between two times, or subtracts the given number of seconds in numeric from time.

   t = Time.now       #=> Wed Apr 09 08:56:03 CDT 2003
   t2 = t + 2592000   #=> Fri May 09 08:56:03 CDT 2003
   t2 - t             #=> 2592000.0
   t2 - 2592000       #=> Wed Apr 09 08:56:03 CDT 2003
time <=> other_time => -1, 0, +1
time <=> numeric => -1, 0, +1

Comparison—Compares time with other_time or with numeric, which is the number of seconds (possibly fractional) since epoch.

   t = Time.now       #=> Wed Apr 09 08:56:03 CDT 2003
   t2 = t + 2592000   #=> Fri May 09 08:56:03 CDT 2003
   t <=> t2           #=> -1
   t2 <=> t           #=> 1
   t <=> t            #=> 0
time._dump => string

Dump time for marshaling.

time.asctime => string
time.ctime => string

Returns a canonical string representation of time.

   Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"
time.asctime => string
time.ctime => string

Returns a canonical string representation of time.

   Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"
time.day => fixnum
time.mday => fixnum

Returns the day of the month (1..n) for time.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.day          #=> 9
   t.mday         #=> 9
time.isdst => true or false
time.dst? => true or false

Returns true if time occurs during Daylight Saving Time in its time zone.

   Time.local(2000, 7, 1).isdst   #=> true
   Time.local(2000, 1, 1).isdst   #=> false
   Time.local(2000, 7, 1).dst?    #=> true
   Time.local(2000, 1, 1).dst?    #=> false
time.eql?(other_time)

Return true if time and other_time are both Time objects with the same seconds and fractional seconds.

time.getgm => new_time
time.getutc => new_time

Returns a new new_time object representing time in UTC.

   t = Time.local(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
   t.gmt?                             #=> false
   y = t.getgm                        #=> Sun Jan 02 02:15:01 UTC 2000
   y.gmt?                             #=> true
   t == y                             #=> true
time.getlocal => new_time

Returns a new new_time object representing time in local time (using the local time zone in effect for this process).

   t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
   t.gmt?                          #=> true
   l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
   l.gmt?                          #=> false
   t == l                          #=> true
time.getgm => new_time
time.getutc => new_time

Returns a new new_time object representing time in UTC.

   t = Time.local(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
   t.gmt?                             #=> false
   y = t.getgm                        #=> Sun Jan 02 02:15:01 UTC 2000
   y.gmt?                             #=> true
   t == y                             #=> true
time.utc? => true or false
time.gmt? => true or false

Returns true if time represents a time in UTC (GMT).

   t = Time.now                        #=> Wed Apr 09 08:56:04 CDT 2003
   t.utc?                              #=> false
   t = Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
   t.utc?                              #=> true

   t = Time.now                        #=> Wed Apr 09 08:56:03 CDT 2003
   t.gmt?                              #=> false
   t = Time.gm(2000,1,1,20,15,1)       #=> Sat Jan 01 20:15:01 UTC 2000
   t.gmt?                              #=> true
time.gmt_offset => fixnum
time.gmtoff => fixnum
time.utc_offset => fixnum

Returns the offset in seconds between the timezone of time and UTC.

   t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
   t.gmt_offset                    #=> 0
   l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
   l.gmt_offset                    #=> -21600
time.gmtime => time
time.utc => time

Converts time to UTC (GMT), modifying the receiver.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.gmt?         #=> false
   t.gmtime       #=> Wed Apr 09 13:56:03 UTC 2003
   t.gmt?         #=> true

   t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t.utc?         #=> false
   t.utc          #=> Wed Apr 09 13:56:04 UTC 2003
   t.utc?         #=> true
time.gmt_offset => fixnum
time.gmtoff => fixnum
time.utc_offset => fixnum

Returns the offset in seconds between the timezone of time and UTC.

   t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
   t.gmt_offset                    #=> 0
   l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
   l.gmt_offset                    #=> -21600
time.hash => fixnum

Return a hash code for this time object.

time.hour => fixnum

Returns the hour of the day (0..23) for time.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.hour         #=> 8
httpdate()

Returns a string which represents the time as rfc1123-date of HTTP-date defined by RFC 2616:

  day-of-week, DD month-name CCYY hh:mm:ss GMT

Note that the result is always UTC (GMT).

time.inspect => string
time.to_s => string

Returns a string representing time. Equivalent to calling Time#strftime with a format string of ``%a %b %d %H:%M:%S %Z %Y’’.

   Time.now.to_s   #=> "Wed Apr 09 08:56:04 CDT 2003"
time.isdst => true or false
time.dst? => true or false

Returns true if time occurs during Daylight Saving Time in its time zone.

   Time.local(2000, 7, 1).isdst   #=> true
   Time.local(2000, 1, 1).isdst   #=> false
   Time.local(2000, 7, 1).dst?    #=> true
   Time.local(2000, 1, 1).dst?    #=> false
iso8601(fraction_digits=0)

Alias for xmlschema

time.localtime => time

Converts time to local time (using the local time zone in effect for this process) modifying the receiver.

   t = Time.gm(2000, "jan", 1, 20, 15, 1)
   t.gmt?        #=> true
   t.localtime   #=> Sat Jan 01 14:15:01 CST 2000
   t.gmt?        #=> false
marshal_dump()

undocumented

marshal_load(p1)

undocumented

time.day => fixnum
time.mday => fixnum

Returns the day of the month (1..n) for time.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.day          #=> 9
   t.mday         #=> 9
time.min => fixnum

Returns the minute of the hour (0..59) for time.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.min          #=> 56
time.mon => fixnum
time.month => fixnum

Returns the month of the year (1..12) for time.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.mon          #=> 4
   t.month        #=> 4
time.mon => fixnum
time.month => fixnum

Returns the month of the year (1..12) for time.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.mon          #=> 4
   t.month        #=> 4
rfc2822()

Returns a string which represents the time as date-time defined by RFC 2822:

  day-of-week, DD month-name CCYY hh:mm:ss zone

where zone is [+-]hhmm.

If self is a UTC time, -0000 is used as zone.

rfc822()

Alias for rfc2822

time.sec => fixnum

Returns the second of the minute (0..60)[Yes, seconds really can range from zero to 60. This allows the system to inject leap seconds every now and then to correct for the fact that years are not really a convenient number of hours long.] for time.

   t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t.sec          #=> 4
time.strftime( string ) => string

Formats time according to the directives in the given format string. Any text not listed as a directive will be passed through to the output string.

Format meaning:

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character

   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"
time.succ => new_time

Return a new time object, one second later than time.

time.to_a => array

Returns a ten-element array of values for time: {[ sec, min, hour, day, month, year, wday, yday, isdst, zone ]}. See the individual methods for an explanation of the valid ranges of each value. The ten elements can be passed directly to Time::utc or Time::local to create a new Time.

   now = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t = now.to_a     #=> [4, 56, 8, 9, 4, 2003, 3, 99, true, "CDT"]
time.to_f => float

Returns the value of time as a floating point number of seconds since epoch.

   t = Time.now
   "%10.5f" % t.to_f   #=> "1049896564.13654"
   t.to_i              #=> 1049896564
time.to_i => int
time.tv_sec => int

Returns the value of time as an integer number of seconds since epoch.

   t = Time.now
   "%10.5f" % t.to_f   #=> "1049896564.17839"
   t.to_i              #=> 1049896564
time.inspect => string
time.to_s => string

Returns a string representing time. Equivalent to calling Time#strftime with a format string of ``%a %b %d %H:%M:%S %Z %Y’’.

   Time.now.to_s   #=> "Wed Apr 09 08:56:04 CDT 2003"
to_yaml( opts = {} )
time.to_i => int
time.tv_sec => int

Returns the value of time as an integer number of seconds since epoch.

   t = Time.now
   "%10.5f" % t.to_f   #=> "1049896564.17839"
   t.to_i              #=> 1049896564
time.usec => int
time.tv_usec => int

Returns just the number of microseconds for time.

   t = Time.now        #=> Wed Apr 09 08:56:04 CDT 2003
   "%10.6f" % t.to_f   #=> "1049896564.259970"
   t.usec              #=> 259970
time.usec => int
time.tv_usec => int

Returns just the number of microseconds for time.

   t = Time.now        #=> Wed Apr 09 08:56:04 CDT 2003
   "%10.6f" % t.to_f   #=> "1049896564.259970"
   t.usec              #=> 259970
time.gmtime => time
time.utc => time

Converts time to UTC (GMT), modifying the receiver.

   t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
   t.gmt?         #=> false
   t.gmtime       #=> Wed Apr 09 13:56:03 UTC 2003
   t.gmt?         #=> true

   t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t.utc?         #=> false
   t.utc          #=> Wed Apr 09 13:56:04 UTC 2003
   t.utc?         #=> true
time.utc? => true or false
time.gmt? => true or false

Returns true if time represents a time in UTC (GMT).

   t = Time.now                        #=> Wed Apr 09 08:56:04 CDT 2003
   t.utc?                              #=> false
   t = Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
   t.utc?                              #=> true

   t = Time.now                        #=> Wed Apr 09 08:56:03 CDT 2003
   t.gmt?                              #=> false
   t = Time.gm(2000,1,1,20,15,1)       #=> Sat Jan 01 20:15:01 UTC 2000
   t.gmt?                              #=> true
time.gmt_offset => fixnum
time.gmtoff => fixnum
time.utc_offset => fixnum

Returns the offset in seconds between the timezone of time and UTC.

   t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
   t.gmt_offset                    #=> 0
   l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
   l.gmt_offset                    #=> -21600
time.wday => fixnum

Returns an integer representing the day of the week, 0..6, with Sunday == 0.

   t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t.wday         #=> 3
xmlschema(fraction_digits=0)

Returns a string which represents the time as dateTime defined by XML Schema:

  CCYY-MM-DDThh:mm:ssTZD
  CCYY-MM-DDThh:mm:ss.sssTZD

where TZD is Z or [+-]hh:mm.

If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.

fractional_seconds specifies a number of digits of fractional seconds. Its default value is 0.

time.yday => fixnum

Returns an integer representing the day of the year, 1..366.

   t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t.yday         #=> 99
time.year => fixnum

Returns the year for time (including the century).

   t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
   t.year         #=> 2003
time.zone => string

Returns the name of the time zone used for time. As of Ruby 1.8, returns ``UTC’’ rather than ``GMT’’ for UTC times.

   t = Time.gm(2000, "jan", 1, 20, 15, 1)
   t.zone   #=> "UTC"
   t = Time.local(2000, "jan", 1, 20, 15, 1)
   t.zone   #=> "CST"


Class: ACL

Class | ACL
In: | lib/drb/acl.rb
Parent: | Object

Methods

allow_addr? allow_socket? install_list new

Classes and Modules

Class ACL::ACLEntry
Class ACL::ACLList

Constants

VERSION | = | ["2.0.0"]
DENY_ALLOW | = | 0
ALLOW_DENY | = | 1

Public Class methods

new(list=nil, order = DENY_ALLOW)

Public Instance methods

allow_addr?(addr)
allow_socket?(soc)
install_list(list)


Class: ACL::ACLEntry

Class | ACL::ACLEntry
In: | lib/drb/acl.rb
Parent: | Object

Methods

match new

Public Class methods

new(str)

Public Instance methods

match(addr)


Class: ACL::ACLList

Class | ACL::ACLList
In: | lib/drb/acl.rb
Parent: | Object

Methods

add match new

Public Class methods

new()

Public Instance methods

add(str)
match(addr)


Module: Abbrev

Module | Abbrev
In: | lib/abbrev.rb

Calculate the set of unique abbreviations for a given set of strings.

  require 'abbrev'
  require 'pp'

  pp Abbrev::abbrev(['ruby', 'rules']).sort

Generates:

  [["rub", "ruby"],
   ["ruby", "ruby"],
   ["rul", "rules"],
   ["rule", "rules"],
   ["rules", "rules"]]

Also adds an abbrev method to class Array.

Methods

abbrev

Public Instance methods

abbrev(words, pattern = nil)

Given a set of strings, calculate the set of unambiguous abbreviations for those strings, and return a hash where the keys are all the possible abbreviations and the values are the full strings. Thus, given input of "car" and "cone", the keys pointing to "car" would be "ca" and "car", while those pointing to "cone" would be "co", "con", and "cone".

The optional pattern parameter is a pattern or a string. Only those input strings matching the pattern, or begging the string, are considered for inclusion in the output hash


Module: Acceptables

Module | Acceptables
In: | lib/optparse.rb

Acceptable argument classes. Now contains DecimalInteger, OctalInteger and DecimalNumeric. See Acceptable argument classes (in source code).


Class: AmbiguousArgument

Class | AmbiguousArgument
In: | lib/optparse.rb
Parent: | InvalidArgument

Raises when the given argument word can‘t be completed uniquely.


Class: AmbiguousOption

Class | AmbiguousOption
In: | lib/optparse.rb
Parent: | ParseError

Raises when ambiguously completable string is encountered.


Module: Arguable

Module | Arguable
In: | lib/optparse.rb

Extends command line arguments array (ARGV) to parse itself.

Methods

extend_object getopts new options options= order! parse! permute!

Public Class methods

extend_object(obj)

Initializes instance variable.

new(*args)

Public Instance methods

getopts(*args)

Substitution of getopts is possible as follows. Also see OptionParser#getopts.

  def getopts(*args)
    ($OPT = ARGV.getopts(*args)).each do |opt, val|
      eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
    end
  rescue OptionParser::ParseError
  end
options() {|@optparse| ...}

Actual OptionParser object, automatically created if nonexistent.

If called with a block, yields the OptionParser object and returns the result of the block. If an OptionParser::ParseError exception occurs in the block, it is rescued, a error message printed to STDERR and nil returned.

options=(opt)

Sets OptionParser object, when opt is false or nil, methods OptionParser::Arguable#options and OptionParser::Arguable#options= are undefined. Thus, there is no ways to access the OptionParser object via the receiver object.

order!(&blk)

Parses self destructively in order and returns self containing the rest arguments left unparsed.

parse!()

Parses self destructively and returns self containing the rest arguments left unparsed.

permute!()

Parses self destructively in permutation mode and returns self containing the rest arguments left unparsed.


Class: ArgumentError

Class | ArgumentError
In: | error.c
Parent: | StandardError


Module: Base64

Module | Base64
In: | lib/base64.rb

The Base64 module provides for the encoding (encode64) and decoding (decode64) of binary data using a Base64 representation.

The following particular features are also provided:

  • encode into lines of a given length (b64encode)
  • decode the special format specified in RFC2047 for the representation of email headers (decode_b)

Example

A simple encoding and decoding.

    require "base64"

    enc   = Base64.encode64('Send reinforcements')
                        # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
    plain = Base64.decode64(enc)
                        # -> "Send reinforcements"

The purpose of using base64 to encode data is that it translates any binary data into purely printable characters. It is specified in RFC 2045 (www.faqs.org/rfcs/rfc2045.html).

Methods

b64encode decode64 decode_b encode64

Public Instance methods

b64encode(bin, len = 60)

Prints the Base64 encoded version of bin (a String) in lines of len (default 60) characters.

   require 'base64'
   data = "Now is the time for all good coders\nto learn Ruby"
   Base64.b64encode(data)

Generates:

   Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
   UnVieQ==
decode64(str)

Returns the Base64-decoded version of str.

  require 'base64'
  str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
        'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
        'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
  puts Base64.decode64(str)

Generates:

   This is line one
   This is line two
   This is line three
   And so on...
decode_b(str)

Decodes text formatted using a subset of RFC2047 (the one used for mime-encoding mail headers).

Only supports an encoding type of ‘b’ (base 64), and only supports the character sets ISO-2022-JP and SHIFT_JIS (so the only two encoded word sequences recognized are =?ISO-2022-JP?B?…= and =?SHIFT_JIS?B?…=). Recognition of these sequences is case insensitive.

encode64(bin)

Returns the Base64-encoded version of str.

   require 'base64'
   Base64.b64encode("Now is the time for all good coders\nto learn Ruby")

Generates:

   Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
   UnVieQ==


Class: BasicSocket

Class | BasicSocket
In: | ext/socket/socket.c
Parent: | IO

Methods

getsockopt recv_nonblock setsockopt

Public Instance methods

getsockopt(level, optname)

Gets a socket option. These are protocol and system specific, see your local sytem documentation for details. The option is returned as a String with the data being the binary value of the socket option.

Parameters

  • level is an integer, usually one of the SOL_ constants such as Socket::SOL_SOCKET, or a protocol level.
  • optname is an integer, usually one of the SO_ constants, such as Socket::SO_REUSEADDR.

Examples

Some socket options are integers with boolean values, in this case getsockopt could be called like this:

  optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
  optval = optval.unpack "i"
  reuseaddr = optval[0] == 0 ? false : true

Some socket options are integers with numeric values, in this case getsockopt could be called like this:

  optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL)
  ipttl = optval.unpack("i")[0]

Option values may be structs. Decoding them can be complex as it involves examining your system headers to determine the correct definition. An example is a +struct linger+, which may be defined in your system headers as:

  struct linger {
    int l_onoff;
    int l_linger;
  };

In this case getsockopt could be called like this:

  optval =  sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER)
  onoff, linger = optval.unpack "ii"
basicsocket.recv_nonblock(maxlen) => mesg
basicsocket.recv_nonblock(maxlen, flags) => mesg

Receives up to maxlen bytes from socket using recvfrom(2) after O_NONBLOCK is set for the underlying file descriptor. flags is zero or more of the MSG_ options. The result, mesg, is the data received.

When recvfrom(2) returns 0, Socket#recv_nonblock returns an empty string as data. The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.

Parameters

  • maxlen - the number of bytes to receive from the socket
  • flags - zero or more of the MSG_ options

Example

     serv = TCPServer.new("127.0.0.1", 0)
     af, port, host, addr = serv.addr
     c = TCPSocket.new(addr, port)
     s = serv.accept
     c.send "aaa", 0
     IO.select([s])
     p s.recv_nonblock(10) #=> "aaa"

Refer to Socket#recvfrom for the exceptions that may be thrown if the call to recv_nonblock fails.

BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure, including Errno::EAGAIN.

See

  • Socket#recvfrom
setsockopt(level, optname, optval)

Sets a socket option. These are protocol and system specific, see your local sytem documentation for details.

Parameters

  • level is an integer, usually one of the SOL_ constants such as Socket::SOL_SOCKET, or a protocol level.
  • optname is an integer, usually one of the SO_ constants, such as Socket::SO_REUSEADDR.
  • optval is the value of the option, it is passed to the underlying setsockopt() as a pointer to a certain number of bytes. How this is done depends on the type:
    • Fixnum: value is assigned to an int, and a pointer to the int is passed, with length of sizeof(int).
    • true or false: 1 or 0 (respectively) is assigned to an int, and the int is passed as for a Fixnum. Note that false must be passed, not nil.
    • String: the string‘s data and length is passed to the socket.

Examples

Some socket options are integers with boolean values, in this case setsockopt could be called like this:

  sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)

Some socket options are integers with numeric values, in this case setsockopt could be called like this:

  sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255)

Option values may be structs. Passing them can be complex as it involves examining your system headers to determine the correct definition. An example is an ip_mreq, which may be defined in your system headers as:

  struct ip_mreq {
    struct  in_addr imr_multiaddr;
    struct  in_addr imr_interface;
  };

In this case setsockopt could be called like this:

  optval =  IPAddr.new("224.0.0.251") + Socket::INADDR_ANY
  sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval)


Module: Benchmark

Module | Benchmark
In: | lib/benchmark.rb

The Benchmark module provides methods to measure and report the time used to execute Ruby code.

  • Measure the time to construct the string given by the expression "a"*1_000_000:
        require 'benchmark'

    puts Benchmark.measure { "a"*1_000_000 }

    On my machine (FreeBSD 3.2 on P5, 100MHz) this generates:

        1.166667   0.050000   1.216667 (  0.571355)

    This report shows the user CPU time, system CPU time, the sum of the user and system CPU times, and the elapsed real time. The unit of time is seconds.

  • Do some experiments sequentially using the bm method:
        require 'benchmark'

    n = 50000
    Benchmark.bm do |x|
      x.report { for i in 1..n; a = "1"; end }
      x.report { n.times do   ; a = "1"; end }
      x.report { 1.upto(n) do ; a = "1"; end }
    end

    The result:

               user     system      total        real
       1.033333   0.016667   1.016667 (  0.492106)
       1.483333   0.000000   1.483333 (  0.694605)
       1.516667   0.000000   1.516667 (  0.711077)
  • Continuing the previous example, put a label in each report:
        require 'benchmark'

    n = 50000
    Benchmark.bm(7) do |x|
      x.report("for:")   { for i in 1..n; a = "1"; end }
      x.report("times:") { n.times do   ; a = "1"; end }
      x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
    end

The result:

                    user     system      total        real
       for:     1.050000   0.000000   1.050000 (  0.503462)
       times:   1.533333   0.016667   1.550000 (  0.735473)
       upto:    1.500000   0.016667   1.516667 (  0.711239)
  • The times for some benchmarks depend on the order in which items are run. These differences are due to the cost of memory allocation and garbage collection. To avoid these discrepancies, the bmbm method is provided. For example, to compare ways to sort an array of floats:
        require 'benchmark'

    array = (1..1000000).map { rand }

    Benchmark.bmbm do |x|
      x.report("sort!") { array.dup.sort! }
      x.report("sort")  { array.dup.sort  }
    end

    The result:

         Rehearsal -----------------------------------------
     sort!  11.928000   0.010000  11.938000 ( 12.756000)
     sort   13.048000   0.020000  13.068000 ( 13.857000)
     ------------------------------- total: 25.006000sec

                 user     system      total        real
     sort!  12.959000   0.010000  12.969000 ( 13.793000)
     sort   12.007000   0.000000  12.007000 ( 12.791000)
  • Report statistics of sequential experiments with unique labels, using the benchmark method:
        require 'benchmark'

    n = 50000
    Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
      tf = x.report("for:")   { for i in 1..n; a = "1"; end }
      tt = x.report("times:") { n.times do   ; a = "1"; end }
      tu = x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
      [tf+tt+tu, (tf+tt+tu)/3]
    end

    The result:

                      user     system      total        real
     for:     1.016667   0.016667   1.033333 (  0.485749)
     times:   1.450000   0.016667   1.466667 (  0.681367)
     upto:    1.533333   0.000000   1.533333 (  0.722166)
     >total:  4.000000   0.033333   4.033333 (  1.889282)
     >avg:    1.333333   0.011111   1.344444 (  0.629761)

Methods

benchmark bm bmbm measure realtime

Classes and Modules

Class Benchmark::Tms

Constants

BENCHMARK_VERSION | = | "2002-04-25"
CAPTION | = | Benchmark::Tms::CAPTION | The default caption string (heading above the output times).
FMTSTR | = | Benchmark::Tms::FMTSTR | The default format string used to display times. See also Benchmark::Tms#format.

Public Instance methods

benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) {|report| ...}

Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width leading spaces for labels on each line. Prints caption at the top of the report, and uses fmt to format each line. If the block returns an array of Benchmark::Tms objects, these will be used to format additional lines of output. If label parameters are given, these are used to label these extra lines.

Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark, and the bm and bmbm methods.

Example:

    require 'benchmark'
    include Benchmark          # we need the CAPTION and FMTSTR constants

    n = 50000
    Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
      tf = x.report("for:")   { for i in 1..n; a = "1"; end }
      tt = x.report("times:") { n.times do   ; a = "1"; end }
      tu = x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
      [tf+tt+tu, (tf+tt+tu)/3]
    end

Generates:

                    user     system      total        real
       for:     1.016667   0.016667   1.033333 (  0.485749)
       times:   1.450000   0.016667   1.466667 (  0.681367)
       upto:    1.533333   0.000000   1.533333 (  0.722166)
       >total:  4.000000   0.033333   4.033333 (  1.889282)
       >avg:    1.333333   0.011111   1.344444 (  0.629761)
bm(label_width = 0, *labels) {|report| ...}

A simple interface to the benchmark method, bm is generates sequential reports with labels. The parameters have the same meaning as for benchmark.

    require 'benchmark'

    n = 50000
    Benchmark.bm(7) do |x|
      x.report("for:")   { for i in 1..n; a = "1"; end }
      x.report("times:") { n.times do   ; a = "1"; end }
      x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
    end

Generates:

                    user     system      total        real
       for:     1.050000   0.000000   1.050000 (  0.503462)
       times:   1.533333   0.016667   1.550000 (  0.735473)
       upto:    1.500000   0.016667   1.516667 (  0.711239)
bmbm(width = 0) {|job| ...}

Sometimes benchmark results are skewed because code executed earlier encounters different garbage collection overheads than that run later. bmbm attempts to minimize this effect by running the tests twice, the first time as a rehearsal in order to get the runtime environment stable, the second time for real. GC.start is executed before the start of each of the real timings; the cost of this is not included in the timings. In reality, though, there‘s only so much that bmbm can do, and the results are not guaranteed to be isolated from garbage collection and other effects.

Because bmbm takes two passes through the tests, it can calculate the required label width.

      require 'benchmark'

      array = (1..1000000).map { rand }

      Benchmark.bmbm do |x|
        x.report("sort!") { array.dup.sort! }
        x.report("sort")  { array.dup.sort  }
      end

Generates:

       Rehearsal -----------------------------------------
       sort!  11.928000   0.010000  11.938000 ( 12.756000)
       sort   13.048000   0.020000  13.068000 ( 13.857000)
       ------------------------------- total: 25.006000sec

                   user     system      total        real
       sort!  12.959000   0.010000  12.969000 ( 13.793000)
       sort   12.007000   0.000000  12.007000 ( 12.791000)

bmbm yields a Benchmark::Job object and returns an array of Benchmark::Tms objects.

measure(label = "") {|| ...}

Returns the time used to execute the given block as a Benchmark::Tms object.

realtime() {|| ...}

Returns the elapsed real time used to execute the given block.


Class: Benchmark::Tms

Class | Benchmark::Tms
In: | lib/benchmark.rb
Parent: | Object

A data object, representing the times associated with a benchmark measurement.

Methods

* + - / add add! format memberwise new to_a to_s

Constants

CAPTION | = | " user system total real\n"
FMTSTR | = | "%10.6u %10.6y %10.6t %10.6r\n"

Attributes

cstime | [R] | System CPU time of children
cutime | [R] | User CPU time of children
label | [R] | Label
real | [R] | Elapsed real time
stime | [R] | System CPU time
total | [R] | Total time, that is utime + stime + cutime + cstime
utime | [R] | User CPU time

Public Class methods

new(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)

Returns an initialized Tms object which has u as the user CPU time, s as the system CPU time, cu as the children‘s user CPU time, cs as the children‘s system CPU time, real as the elapsed real time and l as the label.

Public Instance methods

*(x)

Returns a new Tms object obtained by memberwise multiplication of the individual times for this Tms object by x.

+(other)

Returns a new Tms object obtained by memberwise summation of the individual times for this Tms object with those of the other Tms object. This method and #/() are useful for taking statistics.

-(other)

Returns a new Tms object obtained by memberwise subtraction of the individual times for the other Tms object from those of this Tms object.

/(x)

Returns a new Tms object obtained by memberwise division of the individual times for this Tms object by x. This method and #+() are useful for taking statistics.

add() {|| ...}

Returns a new Tms object whose times are the sum of the times for this Tms object, plus the time required to execute the code block (blk).

add!()

An in-place version of add.

format(arg0 = nil, *args)

Returns the contents of this Tms object as a formatted string, according to a format string like that passed to Kernel.format. In addition, format accepts the following extensions:

%u: | Replaced by the user CPU time, as reported by Tms#utime.
%y: | Replaced by the system CPU time, as reported by stime (Mnemonic: y of "s*y*stem")
%U: | Replaced by the children‘s user CPU time, as reported by Tms#cutime
%Y: | Replaced by the children‘s system CPU time, as reported by Tms#cstime
%t: | Replaced by the total CPU time, as reported by Tms#total
%r: | Replaced by the elapsed real time, as reported by Tms#real
%n: | Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")

If fmtstr is not given, FMTSTR is used as default value, detailing the user, system and real elapsed time.

to_a()

Returns a new 6-element array, consisting of the label, user CPU time, system CPU time, children‘s user CPU time, children‘s system CPU time and elapsed real time.

to_s()

Same as format.

Protected Instance methods

memberwise(op, x)


Class: Bignum

Class | Bignum
In: | bignum.c lib/mathn.rb lib/rational.rb
Parent: | Integer

Bignum objects hold integers outside the range of Fixnum. Bignum objects are created automatically when integer calculations would otherwise overflow a Fixnum. When a calculation involving Bignum objects returns a result that will fit in a Fixnum, the result is automatically converted.

For the purposes of the bitwise operations and [], a Bignum is treated as if it were an infinite-length bitstring with 2‘s complement representation.

While Fixnum values are immediate, Bignum objects are not—assignment and parameter passing work with references to objects, not the objects themselves.

Methods

% & * ** ** + - -@ / / << <=> == >> [] ^ abs coerce div divmod eql? hash modulo power! quo quo rdiv remainder rpower size to_f to_s | ~

Public Instance methods

big % other => Numeric
big.modulo(other) => Numeric

Returns big modulo other. See Numeric.divmod for more information.

big & numeric => integer

Performs bitwise and between big and numeric.

big * other => Numeric

Multiplies big and other, returning the result.

**(other)

Alias for rpower

big ** exponent #=> numeric

Raises big to the exponent power (which may be an integer, float, or anything that will coerce to a number). The result may be a Fixnum, Bignum, or Float

  123456789 ** 2      #=> 15241578750190521
  123456789 ** 1.2    #=> 5126464716.09932
  123456789 ** -2     #=> 6.5610001194102e-17
big + other => Numeric

Adds big and other, returning the result.

big - other => Numeric

Subtracts other from big, returning the result.

-big => other_big

Unary minus (returns a new Bignum whose value is 0-big)

big / other => Numeric
big.div(other) => Numeric

Divides big by other, returning the result.

/(p1)

Alias for quo

big << numeric => integer

Shifts big left numeric positions (right if numeric is negative).

big <=> numeric => -1, 0, +1

Comparison—Returns -1, 0, or +1 depending on whether big is less than, equal to, or greater than numeric. This is the basis for the tests in Comparable.

big == obj => true or false

Returns true only if obj has the same value as big. Contrast this with Bignum#eql?, which requires obj to be a Bignum.

   68719476736 == 68719476736.0   #=> true
big >> numeric => integer

Shifts big right numeric positions (left if numeric is negative).

big[n] → 0, 1

Bit Reference—Returns the nth bit in the (assumed) binary representation of big, where big[0] is the least significant bit.

   a = 9**15
   50.downto(0) do |n|
     print a[n]
   end

produces:

   000101110110100000111000011110010100111100010111001
big ^ numeric => integer

Performs bitwise +exclusive or+ between big and numeric.

big.abs → aBignum

Returns the absolute value of big.

   -1234567890987654321.abs   #=> 1234567890987654321
coerce(p1)

MISSING: documentation

big / other => Numeric
big.div(other) => Numeric

Divides big by other, returning the result.

big.divmod(numeric) => array

See Numeric#divmod.

big.eql?(obj) => true or false

Returns true only if obj is a Bignum with the same value as big. Contrast this with Bignum#==, which performs type conversions.

   68719476736.eql?(68719476736.0)   #=> false
big.hash => fixnum

Compute a hash based on the value of big.

big % other => Numeric
big.modulo(other) => Numeric

Returns big modulo other. See Numeric.divmod for more information.

power!(p1)

Alias for #**

big.quo(numeric) → float

Returns the floating point result of dividing big by numeric.

   -1234567890987654321.quo(13731)      #=> -89910996357705.5
   -1234567890987654321.quo(13731.24)   #=> -89909424858035.7
quo(other)

If Rational is defined, returns a Rational number instead of a Bignum.

rdiv(p1)

Alias for quo

big.remainder(numeric) => number

Returns the remainder after dividing big by numeric.

   -1234567890987654321.remainder(13731)      #=> -6966
   -1234567890987654321.remainder(13731.24)   #=> -9906.22531493148
rpower(other)

Returns a Rational number if the result is in fact rational (i.e. other < 0).

big.size → integer

Returns the number of bytes in the machine representation of big.

   (256**10 - 1).size   #=> 12
   (256**20 - 1).size   #=> 20
   (256**40 - 1).size   #=> 40
big.to_f → float

Converts big to a Float. If big doesn‘t fit in a Float, the result is infinity.

big.to_s(base=10) => string

Returns a string containing the representation of big radix base (2 through 36).

   12345654321.to_s         #=> "12345654321"
   12345654321.to_s(2)      #=> "1011011111110110111011110000110001"
   12345654321.to_s(8)      #=> "133766736061"
   12345654321.to_s(16)     #=> "2dfdbbc31"
   78546939656932.to_s(36)  #=> "rubyrules"
big | numeric => integer

Performs bitwise or between big and numeric.

~big => integer

Inverts the bits in big. As Bignums are conceptually infinite length, the result acts as if it had an infinite number of one bits to the left. In hex representations, this is displayed as two periods to the left of the digits.

  sprintf("%X", ~0x1122334455)    #=> "..FEEDDCCBBAA"


Class: Binding

Class | Binding
In: | eval.c
Parent: | Object

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created using Kernel#binding, and are made available to the callback of Kernel#set_trace_func.

These binding objects can be passed as the second argument of the Kernel#eval method, establishing an environment for the evaluation.

   class Demo
     def initialize(n)
       @secret = n
     end
     def getBinding
       return binding()
     end
   end

   k1 = Demo.new(99)
   b1 = k1.getBinding
   k2 = Demo.new(-3)
   b2 = k2.getBinding

   eval("@secret", b1)   #=> 99
   eval("@secret", b2)   #=> -3
   eval("@secret")       #=> nil

Binding objects have no class-specific methods.

Methods

clone dup

Public Instance methods

clone()

MISSING: documentation

dup()

MISSING: documentation


Class: CGI

Class | CGI
In: | lib/cgi/session.rb lib/cgi.rb lib/cgi-lib.rb
Parent: | Object

CGI class. See documentation for the file cgi.rb for an overview of the CGI protocol.

Introduction

CGI is a large class, providing several categories of methods, many of which are mixed in from other modules. Some of the documentation is in this class, some in the modules CGI::QueryExtension and CGI::HtmlExtension. See CGI::Cookie for specific information on handling cookies, and cgi/session.rb (CGI::Session) for information on sessions.

For queries, CGI provides methods to get at environmental variables, parameters, cookies, and multipart request data. For responses, CGI provides methods for writing output and generating HTML.

Read on for more details. Examples are provided at the bottom.

Queries

The CGI class dynamically mixes in parameter and cookie-parsing functionality, environmental variable access, and support for parsing multipart requests (including uploaded files) from the CGI::QueryExtension module.

Environmental Variables

The standard CGI environmental variables are available as read-only attributes of a CGI object. The following is a list of these variables:

  AUTH_TYPE               HTTP_HOST          REMOTE_IDENT
  CONTENT_LENGTH          HTTP_NEGOTIATE     REMOTE_USER
  CONTENT_TYPE            HTTP_PRAGMA        REQUEST_METHOD
  GATEWAY_INTERFACE       HTTP_REFERER       SCRIPT_NAME
  HTTP_ACCEPT             HTTP_USER_AGENT    SERVER_NAME
  HTTP_ACCEPT_CHARSET     PATH_INFO          SERVER_PORT
  HTTP_ACCEPT_ENCODING    PATH_TRANSLATED    SERVER_PROTOCOL
  HTTP_ACCEPT_LANGUAGE    QUERY_STRING       SERVER_SOFTWARE
  HTTP_CACHE_CONTROL      REMOTE_ADDR
  HTTP_FROM               REMOTE_HOST

For each of these variables, there is a corresponding attribute with the same name, except all lower case and without a preceding HTTP_. content_length and server_port are integers; the rest are strings.

Parameters

The method params() returns a hash of all parameters in the request as name/value-list pairs, where the value-list is an Array of one or more values. The CGI object itself also behaves as a hash of parameter names to values, but only returns a single value (as a String) for each parameter name.

For instance, suppose the request contains the parameter "favourite_colours" with the multiple values "blue" and "green". The following behaviour would occur:

  cgi.params["favourite_colours"]  # => ["blue", "green"]
  cgi["favourite_colours"]         # => "blue"

If a parameter does not exist, the former method will return an empty array, the latter an empty string. The simplest way to test for existence of a parameter is by the has_key? method.

Cookies

HTTP Cookies are automatically parsed from the request. They are available from the cookies() accessor, which returns a hash from cookie name to CGI::Cookie object.

Multipart requests

If a request‘s method is POST and its content type is multipart/form-data, then it may contain uploaded files. These are stored by the QueryExtension module in the parameters of the request. The parameter name is the name attribute of the file input field, as usual. However, the value is not a string, but an IO object, either an IOString for small files, or a Tempfile for larger ones. This object also has the additional singleton methods:

local_path(): | the path of the uploaded file on the local filesystem
original_filename(): | the name of the file on the client computer
content_type(): | the content type of the file

Responses

The CGI class provides methods for sending header and content output to the HTTP client, and mixes in methods for programmatic HTML generation from CGI::HtmlExtension and CGI::TagMaker modules. The precise version of HTML to use for HTML generation is specified at object creation time.

Writing output

The simplest way to send output to the HTTP client is using the out() method. This takes the HTTP headers as a hash parameter, and the body content via a block. The headers can be generated as a string using the header() method. The output stream can be written directly to using the print() method.

Generating HTML

Each HTML element has a corresponding method for generating that element as a String. The name of this method is the same as that of the element, all lowercase. The attributes of the element are passed in as a hash, and the body as a no-argument block that evaluates to a String. The HTML generation module knows which elements are always empty, and silently drops any passed-in body. It also knows which elements require matching closing tags and which don‘t. However, it does not know what attributes are legal for which elements.

There are also some additional HTML generation methods mixed in from the CGI::HtmlExtension module. These include individual methods for the different types of form inputs, and methods for elements that commonly take particular attributes where the attributes can be directly specified as arguments, rather than via a hash.

Examples of use

Get form values

  require "cgi"
  cgi = CGI.new
  value = cgi['field_name']   # <== value string for 'field_name'
    # if not 'field_name' included, then return "".
  fields = cgi.keys            # <== array of field names

  # returns true if form has 'field_name'
  cgi.has_key?('field_name')
  cgi.has_key?('field_name')
  cgi.include?('field_name')

CAUTION! cgi[‘field_name’] returned an Array with the old cgi.rb(included in ruby 1.6)

Get form values as hash

  require "cgi"
  cgi = CGI.new
  params = cgi.params

cgi.params is a hash.

  cgi.params['new_field_name'] = ["value"]  # add new param
  cgi.params['field_name'] = ["new_value"]  # change value
  cgi.params.delete('field_name')           # delete param
  cgi.params.clear                          # delete all params

Save form values to file

  require "pstore"
  db = PStore.new("query.db")
  db.transaction do
    db["params"] = cgi.params
  end

Restore form values from file

  require "pstore"
  db = PStore.new("query.db")
  db.transaction do
    cgi.params = db["params"]
  end

Get multipart form values

  require "cgi"
  cgi = CGI.new
  value = cgi['field_name']   # <== value string for 'field_name'
  value.read                  # <== body of value
  value.local_path            # <== path to local file of value
  value.original_filename     # <== original filename of value
  value.content_type          # <== content_type of value

and value has StringIO or Tempfile class methods.

Get cookie values

  require "cgi"
  cgi = CGI.new
  values = cgi.cookies['name']  # <== array of 'name'
    # if not 'name' included, then return [].
  names = cgi.cookies.keys      # <== array of cookie names

and cgi.cookies is a hash.

Get cookie objects

  require "cgi"
  cgi = CGI.new
  for name, cookie in cgi.cookies
    cookie.expires = Time.now + 30
  end
  cgi.out("cookie" => cgi.cookies) {"string"}

  cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }

  require "cgi"
  cgi = CGI.new
  cgi.cookies['name'].expires = Time.now + 30
  cgi.out("cookie" => cgi.cookies['name']) {"string"}

Print http header and html string to $DEFAULT_OUTPUT ($>)

  require "cgi"
  cgi = CGI.new("html3")  # add HTML generation methods
  cgi.out() do
    cgi.html() do
      cgi.head{ cgi.title{"TITLE"} } +
      cgi.body() do
        cgi.form() do
          cgi.textarea("get_text") +
          cgi.br +
          cgi.submit
        end +
        cgi.pre() do
          CGI::escapeHTML(
            "params: " + cgi.params.inspect + "\n" +
            "cookies: " + cgi.cookies.inspect + "\n" +
            ENV.collect() do |key, value|
              key + " --> " + value + "\n"
            end.join("")
          )
        end
      end
    end
  end

  # add HTML generation methods
  CGI.new("html3")    # html3.2
  CGI.new("html4")    # html4.01 (Strict)
  CGI.new("html4Tr")  # html4.01 Transitional
  CGI.new("html4Fr")  # html4.01 Frameset

Methods

cookie error escape escape escapeElement escapeHTML escapeHTML header header message new new out parse pretty print print read_from_cmdline rfc1123_date rfc1123_date tag unescape unescape unescapeElement unescapeHTML

Classes and Modules

Module CGI::HtmlExtension
Module CGI::QueryExtension
Class CGI::Cookie
Class CGI::Session

Constants

CR | = | "\015"
LF | = | "\012"
EOL | = | CR + LF
RFC822_DAYS | = | %w[ Sun Mon Tue Wed Thu Fri Sat ]
RFC822_MONTHS | = | %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]

Attributes

cookie | [R]
inputs | [R]

Public Class methods

cookie(options)

make raw cookie string

error()

print error message to $> and exit

escape(str)

escape url encode

escape(string)

URL-encode a string.

  url_encoded_string = CGI::escape("'Stop!' said Fred")
     # => "%27Stop%21%27+said+Fred"
escapeElement(string, *elements)

Escape only the tags of certain HTML elements in string.

Takes an element or elements or array of elements. Each element is specified by the name of the element, without angle brackets. This matches both the start and the end tag of that element. The attribute list of the open tag will also be escaped (for instance, the double-quotes surrounding attribute values).

  print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
    # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt"

  print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
    # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt"
escapeHTML(str)

escape HTML

escapeHTML(string)

Escape special characters in HTML, namely &\"<>

  CGI::escapeHTML('Usage: foo "bar" <baz>')
     # => "Usage: foo &quot;bar&quot; &lt;baz&gt;"
header(*options)

make HTTP header string

message(message, title = "", header = ["Content-Type: text/html"])

print message to $>

new(input = $stdin)
new(type = "query")

Creates a new CGI instance.

type specifies which version of HTML to load the HTML generation methods for. The following versions of HTML are supported:

html3: | HTML 3.x
html4: | HTML 4.0
html4Tr: | HTML 4.0 Transitional
html4Fr: | HTML 4.0 with Framesets

If not specified, no HTML generation methods will be loaded.

If the CGI object is not created in a standard CGI call environment (that is, it can‘t locate REQUEST_METHOD in its environment), then it will run in "offline" mode. In this mode, it reads its parameters from the command line or (failing that) from standard input. Otherwise, cookies and other parameters are parsed automatically from the standard CGI locations, which varies according to the REQUEST_METHOD.

parse(query)

Parse an HTTP query string into a hash of key=>value pairs.

  params = CGI::parse("query_string")
    # {"name1" => ["value1", "value2", ...],
    #  "name2" => ["value1", "value2", ...], ... }
pretty(string, shift = " ")

Prettify (indent) an HTML string.

string is the HTML string to indent. shift is the indentation unit to use; it defaults to two spaces.

  print CGI::pretty("<HTML><BODY></BODY></HTML>")
    # <HTML>
    #   <BODY>
    #   </BODY>
    # </HTML>

  print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
    # <HTML>
    #         <BODY>
    #         </BODY>
    # </HTML>
print(*options) {|.to_s| ...}

print HTTP header and string to $>

rfc1123_date(time)

Format a Time object as a String using the format specified by RFC 1123.

  CGI::rfc1123_date(Time.now)
    # Sat, 01 Jan 2000 00:00:00 GMT
rfc1123_date(time)

make rfc1123 date string

tag(element, attributes = {}) {|.to_s + "</" + escapeHTML(element) + ">" : "")| ...}

make HTML tag string

unescape(string)

URL-decode a string.

  string = CGI::unescape("%27Stop%21%27+said+Fred")
     # => "'Stop!' said Fred"
unescape(str)

unescape url encoded

unescapeElement(string, *elements)

Undo escaping such as that done by CGI::escapeElement()

  print CGI::unescapeElement(
          CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
    # "&lt;BR&gt;<A HREF="url"></A>"

  print CGI::unescapeElement(
          CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
    # "&lt;BR&gt;<A HREF="url"></A>"
unescapeHTML(string)

Unescape a string that has been HTML-escaped

  CGI::unescapeHTML("Usage: foo &quot;bar&quot; &lt;baz&gt;")
     # => "Usage: foo \"bar\" <baz>"

Public Instance methods

header(options = "text/html")

Create an HTTP header block as a string.

Includes the empty line that ends the header block.

options can be a string specifying the Content-Type (defaults to text/html), or a hash of header key/value pairs. The following header keys are recognized:

type: | the Content-Type header. Defaults to "text/html"
charset: | the charset of the body, appended to the Content-Type header.
nph: | a boolean value. If true, prepend protocol string and status code, and date; and sets default values for "server" and "connection" if not explicitly set.
status: | the HTTP status code, returned as the Status header. See the list of available status codes below.
server: | the server software, returned as the Server header.
connection: | the connection type, returned as the Connection header (for instance, "close".
length: | the length of the content that will be sent, returned as the Content-Length header.
language: | the language of the content, returned as the Content-Language header.
expires: | the time on which the current content expires, as a Time object, returned as the Expires header.
cookie: | a cookie or cookies, returned as one or more Set-Cookie headers. The value can be the literal string of the cookie; a CGI::Cookie object; an Array of literal cookie strings or Cookie objects; or a hash all of whose values are literal cookie strings or Cookie objects. These cookies are in addition to the cookies held in the @output_cookies field.

Other header lines can also be set; they are appended as key: value.

  header
    # Content-Type: text/html

  header("text/plain")
    # Content-Type: text/plain

  header("nph"        => true,
         "status"     => "OK",  # == "200 OK"
           # "status"     => "200 GOOD",
         "server"     => ENV['SERVER_SOFTWARE'],
         "connection" => "close",
         "type"       => "text/html",
         "charset"    => "iso-2022-jp",
           # Content-Type: text/html; charset=iso-2022-jp
         "length"     => 103,
         "language"   => "ja",
         "expires"    => Time.now + 30,
         "cookie"     => [cookie1, cookie2],
         "my_header1" => "my_value"
         "my_header2" => "my_value")

The status codes are:

  "OK"                  --> "200 OK"
  "PARTIAL_CONTENT"     --> "206 Partial Content"
  "MULTIPLE_CHOICES"    --> "300 Multiple Choices"
  "MOVED"               --> "301 Moved Permanently"
  "REDIRECT"            --> "302 Found"
  "NOT_MODIFIED"        --> "304 Not Modified"
  "BAD_REQUEST"         --> "400 Bad Request"
  "AUTH_REQUIRED"       --> "401 Authorization Required"
  "FORBIDDEN"           --> "403 Forbidden"
  "NOT_FOUND"           --> "404 Not Found"
  "METHOD_NOT_ALLOWED"  --> "405 Method Not Allowed"
  "NOT_ACCEPTABLE"      --> "406 Not Acceptable"
  "LENGTH_REQUIRED"     --> "411 Length Required"
  "PRECONDITION_FAILED" --> "412 Precondition Failed"
  "SERVER_ERROR"        --> "500 Internal Server Error"
  "NOT_IMPLEMENTED"     --> "501 Method Not Implemented"
  "BAD_GATEWAY"         --> "502 Bad Gateway"
  "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"

This method does not perform charset conversion.

out(options = "text/html") {|| ...}

Print an HTTP header and body to $DEFAULT_OUTPUT ($>)

The header is provided by options, as for header(). The body of the document is that returned by the passed- in block. This block takes no arguments. It is required.

  cgi = CGI.new
  cgi.out{ "string" }
    # Content-Type: text/html
    # Content-Length: 6
    #
    # string

  cgi.out("text/plain") { "string" }
    # Content-Type: text/plain
    # Content-Length: 6
    #
    # string

  cgi.out("nph"        => true,
          "status"     => "OK",  # == "200 OK"
          "server"     => ENV['SERVER_SOFTWARE'],
          "connection" => "close",
          "type"       => "text/html",
          "charset"    => "iso-2022-jp",
            # Content-Type: text/html; charset=iso-2022-jp
          "language"   => "ja",
          "expires"    => Time.now + (3600 * 24 * 30),
          "cookie"     => [cookie1, cookie2],
          "my_header1" => "my_value",
          "my_header2" => "my_value") { "string" }

Content-Length is automatically calculated from the size of the String returned by the content block.

If ENV[‘REQUEST_METHOD’] == "HEAD", then only the header is outputted (the content block is still required, but it is ignored).

If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then the content is converted to this charset, and the language is set to "ja".

print(*options)

Print an argument or list of arguments to the default output stream

  cgi = CGI.new
  cgi.print    # default:  cgi.print == $DEFAULT_OUTPUT.print
read_from_cmdline()

offline mode. read name=value pairs on standard input.


Class: CGI::Cookie

Class | CGI::Cookie
In: | lib/cgi.rb
Parent: | DelegateClass(Array)

Class representing an HTTP cookie.

In addition to its specific fields and methods, a Cookie instance is a delegator to the array of its values.

See RFC 2965.

Examples of use

  cookie1 = CGI::Cookie::new("name", "value1", "value2", ...)
  cookie1 = CGI::Cookie::new("name" => "name", "value" => "value")
  cookie1 = CGI::Cookie::new('name'    => 'name',
                             'value'   => ['value1', 'value2', ...],
                             'path'    => 'path',   # optional
                             'domain'  => 'domain', # optional
                             'expires' => Time.now, # optional
                             'secure'  => true      # optional
                            )

  cgi.out("cookie" => [cookie1, cookie2]) { "string" }

  name    = cookie1.name
  values  = cookie1.value
  path    = cookie1.path
  domain  = cookie1.domain
  expires = cookie1.expires
  secure  = cookie1.secure

  cookie1.name    = 'name'
  cookie1.value   = ['value1', 'value2', ...]
  cookie1.path    = 'path'
  cookie1.domain  = 'domain'
  cookie1.expires = Time.now + 30
  cookie1.secure  = true

Methods

new parse secure= to_s

Attributes

domain | [RW]
expires | [RW]
name | [RW]
path | [RW]
secure | [R]
value | [RW]

Public Class methods

new(name = "", *value)

Create a new CGI::Cookie object.

The contents of the cookie can be specified as a name and one or more value arguments. Alternatively, the contents can be specified as a single hash argument. The possible keywords of this hash are as follows:

name: | the name of the cookie. Required.
value: | the cookie‘s value or list of values.
path: | the path for which this cookie applies. Defaults to the base directory of the CGI script.
domain: | the domain for which this cookie applies.
expires: | the time at which this cookie expires, as a Time object.
secure: | whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.

These keywords correspond to attributes of the cookie object.

parse(raw_cookie)

Parse a raw cookie string into a hash of cookie-name=>Cookie pairs.

  cookies = CGI::Cookie::parse("raw_cookie_string")
    # { "name1" => cookie1, "name2" => cookie2, ... }

Public Instance methods

secure=(val)

Set whether the Cookie is a secure cookie or not.

val must be a boolean.

to_s()

Convert the Cookie to its string representation.


Module: CGI::HtmlExtension

Module | CGI::HtmlExtension
In: | lib/cgi.rb

Mixin module providing HTML generation methods.

For example,

  cgi.a("http://www.example.com") { "Example" }
    # => "<A HREF=\"http://www.example.com\">Example</A>"

Modules Http3, Http4, etc., contain more basic HTML-generation methods (:title, :center, etc.).

See class CGI for a detailed example.

Methods

a base blockquote caption checkbox checkbox_group file_field form hidden html image_button img multipart_form password_field popup_menu radio_button radio_group reset scrolling_list submit text_field textarea

Public Instance methods

a(href = "") {|| ...}

Generate an Anchor element as a string.

href can either be a string, giving the URL for the HREF attribute, or it can be a hash of the element‘s attributes.

The body of the element is the string returned by the no-argument block passed in.

  a("http://www.example.com") { "Example" }
    # => "<A HREF=\"http://www.example.com\">Example</A>"

  a("HREF" => "http://www.example.com", "TARGET" => "_top") { "Example" }
    # => "<A HREF=\"http://www.example.com\" TARGET=\"_top\">Example</A>"
base(href = "") {|| ...}

Generate a Document Base URI element as a String.

href can either by a string, giving the base URL for the HREF attribute, or it can be a has of the element‘s attributes.

The passed-in no-argument block is ignored.

  base("http://www.example.com/cgi")
    # => "<BASE HREF=\"http://www.example.com/cgi\">"
blockquote(cite = nil) {|| ...}

Generate a BlockQuote element as a string.

cite can either be a string, give the URI for the source of the quoted text, or a hash, giving all attributes of the element, or it can be omitted, in which case the element has no attributes.

The body is provided by the passed-in no-argument block

  blockquote("http://www.example.com/quotes/foo.html") { "Foo!" }
    #=> "<BLOCKQUOTE CITE=\"http://www.example.com/quotes/foo.html\">Foo!</BLOCKQUOTE>
caption(align = nil) {|| ...}

Generate a Table Caption element as a string.

align can be a string, giving the alignment of the caption (one of top, bottom, left, or right). It can be a hash of all the attributes of the element. Or it can be omitted.

The body of the element is provided by the passed-in no-argument block.

  caption("left") { "Capital Cities" }
    # => <CAPTION ALIGN=\"left\">Capital Cities</CAPTION>
checkbox(name = "", value = nil, checked = nil)

Generate a Checkbox Input element as a string.

The attributes of the element can be specified as three arguments, name, value, and checked. checked is a boolean value; if true, the CHECKED attribute will be included in the element.

Alternatively, the attributes can be specified as a hash.

  checkbox("name")
    # = checkbox("NAME" => "name")

  checkbox("name", "value")
    # = checkbox("NAME" => "name", "VALUE" => "value")

  checkbox("name", "value", true)
    # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true)
checkbox_group(name = "", *values)

Generate a sequence of checkbox elements, as a String.

The checkboxes will all have the same name attribute. Each checkbox is followed by a label. There will be one checkbox for each value. Each value can be specified as a String, which will be used both as the value of the VALUE attribute and as the label for that checkbox. A single-element array has the same effect.

Each value can also be specified as a three-element array. The first element is the VALUE attribute; the second is the label; and the third is a boolean specifying whether this checkbox is CHECKED.

Each value can also be specified as a two-element array, by omitting either the value element (defaults to the same as the label), or the boolean checked element (defaults to false).

  checkbox_group("name", "foo", "bar", "baz")
    # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
    # <INPUT TYPE="checkbox" NAME="name" VALUE="bar">bar
    # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz

  checkbox_group("name", ["foo"], ["bar", true], "baz")
    # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
    # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="bar">bar
    # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz

  checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
    # <INPUT TYPE="checkbox" NAME="name" VALUE="1">Foo
    # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="2">Bar
    # <INPUT TYPE="checkbox" NAME="name" VALUE="Baz">Baz

  checkbox_group("NAME" => "name",
                   "VALUES" => ["foo", "bar", "baz"])

  checkbox_group("NAME" => "name",
                   "VALUES" => [["foo"], ["bar", true], "baz"])

  checkbox_group("NAME" => "name",
                   "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
file_field(name = "", size = 20, maxlength = nil)

Generate an File Upload Input element as a string.

The attributes of the element can be specified as three arguments, name, size, and maxlength. maxlength is the maximum length of the file‘s name, not of the file‘s contents.

Alternatively, the attributes can be specified as a hash.

See multipart_form() for forms that include file uploads.

  file_field("name")
    # <INPUT TYPE="file" NAME="name" SIZE="20">

  file_field("name", 40)
    # <INPUT TYPE="file" NAME="name" SIZE="40">

  file_field("name", 40, 100)
    # <INPUT TYPE="file" NAME="name" SIZE="40" MAXLENGTH="100">

  file_field("NAME" => "name", "SIZE" => 40)
    # <INPUT TYPE="file" NAME="name" SIZE="40">
form(method = "post", action = script_name, enctype = "application/x-www-form-urlencoded") {|| ...}

Generate a Form element as a string.

method should be either "get" or "post", and defaults to the latter. action defaults to the current CGI script name. enctype defaults to "application/x-www-form-urlencoded".

Alternatively, the attributes can be specified as a hash.

See also multipart_form() for forms that include file uploads.

  form{ "string" }
    # <FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">string</FORM>

  form("get") { "string" }
    # <FORM METHOD="get" ENCTYPE="application/x-www-form-urlencoded">string</FORM>

  form("get", "url") { "string" }
    # <FORM METHOD="get" ACTION="url" ENCTYPE="application/x-www-form-urlencoded">string</FORM>

  form("METHOD" => "post", "ENCTYPE" => "enctype") { "string" }
    # <FORM METHOD="post" ENCTYPE="enctype">string</FORM>
hidden(name = "", value = nil)

Generate a Hidden Input element as a string.

The attributes of the element can be specified as two arguments, name and value.

Alternatively, the attributes can be specified as a hash.

  hidden("name")
    # <INPUT TYPE="hidden" NAME="name">

  hidden("name", "value")
    # <INPUT TYPE="hidden" NAME="name" VALUE="value">

  hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo")
    # <INPUT TYPE="hidden" NAME="name" VALUE="value" ID="foo">
html(attributes = {}) {|| ...}

Generate a top-level HTML element as a string.

The attributes of the element are specified as a hash. The pseudo-attribute "PRETTY" can be used to specify that the generated HTML string should be indented. "PRETTY" can also be specified as a string as the sole argument to this method. The pseudo-attribute "DOCTYPE", if given, is used as the leading DOCTYPE SGML tag; it should include the entire text of this tag, including angle brackets.

The body of the html element is supplied as a block.

  html{ "string" }
    # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML>string</HTML>

  html("LANG" => "ja") { "string" }
    # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML LANG="ja">string</HTML>

  html("DOCTYPE" => false) { "string" }
    # <HTML>string</HTML>

  html("DOCTYPE" => '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">') { "string" }
    # <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML>string</HTML>

  html("PRETTY" => "  ") { "<BODY></BODY>" }
    # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    # <HTML>
    #   <BODY>
    #   </BODY>
    # </HTML>

  html("PRETTY" => "\t") { "<BODY></BODY>" }
    # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    # <HTML>
    #         <BODY>
    #         </BODY>
    # </HTML>

  html("PRETTY") { "<BODY></BODY>" }
    # = html("PRETTY" => "  ") { "<BODY></BODY>" }

  html(if $VERBOSE then "PRETTY" end) { "HTML string" }
image_button(src = "", name = nil, alt = nil)

Generate an Image Button Input element as a string.

src is the URL of the image to use for the button. name is the input name. alt is the alternative text for the image.

Alternatively, the attributes can be specified as a hash.

  image_button("url")
    # <INPUT TYPE="image" SRC="url">

  image_button("url", "name", "string")
    # <INPUT TYPE="image" SRC="url" NAME="name" ALT="string">

  image_button("SRC" => "url", "ATL" => "strng")
    # <INPUT TYPE="image" SRC="url" ALT="string">
img(src = "", alt = "", width = nil, height = nil)

Generate an Image element as a string.

src is the URL of the image. alt is the alternative text for the image. width is the width of the image, and height is its height.

Alternatively, the attributes can be specified as a hash.

  img("src", "alt", 100, 50)
    # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">

  img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50)
    # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
multipart_form(action = nil, enctype = "multipart/form-data") {|| ...}

Generate a Form element with multipart encoding as a String.

Multipart encoding is used for forms that include file uploads.

action is the action to perform. enctype is the encoding type, which defaults to "multipart/form-data".

Alternatively, the attributes can be specified as a hash.

  multipart_form{ "string" }
    # <FORM METHOD="post" ENCTYPE="multipart/form-data">string</FORM>

  multipart_form("url") { "string" }
    # <FORM METHOD="post" ACTION="url" ENCTYPE="multipart/form-data">string</FORM>
password_field(name = "", value = nil, size = 40, maxlength = nil)

Generate a Password Input element as a string.

name is the name of the input field. value is its default value. size is the size of the input field display. maxlength is the maximum length of the inputted password.

Alternatively, attributes can be specified as a hash.

  password_field("name")
    # <INPUT TYPE="password" NAME="name" SIZE="40">

  password_field("name", "value")
    # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="40">

  password_field("password", "value", 80, 200)
    # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">

  password_field("NAME" => "name", "VALUE" => "value")
    # <INPUT TYPE="password" NAME="name" VALUE="value">
popup_menu(name = "", *values)

Generate a Select element as a string.

name is the name of the element. The values are the options that can be selected from the Select menu. Each value can be a String or a one, two, or three-element Array. If a String or a one-element Array, this is both the value of that option and the text displayed for it. If a three-element Array, the elements are the option value, displayed text, and a boolean value specifying whether this option starts as selected. The two-element version omits either the option value (defaults to the same as the display text) or the boolean selected specifier (defaults to false).

The attributes and options can also be specified as a hash. In this case, options are specified as an array of values as described above, with the hash key of "VALUES".

  popup_menu("name", "foo", "bar", "baz")
    # <SELECT NAME="name">
    #   <OPTION VALUE="foo">foo</OPTION>
    #   <OPTION VALUE="bar">bar</OPTION>
    #   <OPTION VALUE="baz">baz</OPTION>
    # </SELECT>

  popup_menu("name", ["foo"], ["bar", true], "baz")
    # <SELECT NAME="name">
    #   <OPTION VALUE="foo">foo</OPTION>
    #   <OPTION VALUE="bar" SELECTED>bar</OPTION>
    #   <OPTION VALUE="baz">baz</OPTION>
    # </SELECT>

  popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
    # <SELECT NAME="name">
    #   <OPTION VALUE="1">Foo</OPTION>
    #   <OPTION SELECTED VALUE="2">Bar</OPTION>
    #   <OPTION VALUE="Baz">Baz</OPTION>
    # </SELECT>

  popup_menu("NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
              "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
    # <SELECT NAME="name" MULTIPLE SIZE="2">
    #   <OPTION VALUE="1">Foo</OPTION>
    #   <OPTION SELECTED VALUE="2">Bar</OPTION>
    #   <OPTION VALUE="Baz">Baz</OPTION>
    # </SELECT>
radio_button(name = "", value = nil, checked = nil)

Generates a radio-button Input element.

name is the name of the input field. value is the value of the field if checked. checked specifies whether the field starts off checked.

Alternatively, the attributes can be specified as a hash.

  radio_button("name", "value")
    # <INPUT TYPE="radio" NAME="name" VALUE="value">

  radio_button("name", "value", true)
    # <INPUT TYPE="radio" NAME="name" VALUE="value" CHECKED>

  radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo")
    # <INPUT TYPE="radio" NAME="name" VALUE="value" ID="foo">
radio_group(name = "", *values)

Generate a sequence of radio button Input elements, as a String.

This works the same as checkbox_group(). However, it is not valid to have more than one radiobutton in a group checked.

  radio_group("name", "foo", "bar", "baz")
    # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
    # <INPUT TYPE="radio" NAME="name" VALUE="bar">bar
    # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz

  radio_group("name", ["foo"], ["bar", true], "baz")
    # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
    # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="bar">bar
    # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz

  radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
    # <INPUT TYPE="radio" NAME="name" VALUE="1">Foo
    # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="2">Bar
    # <INPUT TYPE="radio" NAME="name" VALUE="Baz">Baz

  radio_group("NAME" => "name",
                "VALUES" => ["foo", "bar", "baz"])

  radio_group("NAME" => "name",
                "VALUES" => [["foo"], ["bar", true], "baz"])

  radio_group("NAME" => "name",
                "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
reset(value = nil, name = nil)

Generate a reset button Input element, as a String.

This resets the values on a form to their initial values. value is the text displayed on the button. name is the name of this button.

Alternatively, the attributes can be specified as a hash.

  reset
    # <INPUT TYPE="reset">

  reset("reset")
    # <INPUT TYPE="reset" VALUE="reset">

  reset("VALUE" => "reset", "ID" => "foo")
    # <INPUT TYPE="reset" VALUE="reset" ID="foo">
scrolling_list(name = "", *values)

Alias for popup_menu

submit(value = nil, name = nil)

Generate a submit button Input element, as a String.

value is the text to display on the button. name is the name of the input.

Alternatively, the attributes can be specified as a hash.

  submit
    # <INPUT TYPE="submit">

  submit("ok")
    # <INPUT TYPE="submit" VALUE="ok">

  submit("ok", "button1")
    # <INPUT TYPE="submit" VALUE="ok" NAME="button1">

  submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo")
    # <INPUT TYPE="submit" VALUE="ok" NAME="button1" ID="foo">
text_field(name = "", value = nil, size = 40, maxlength = nil)

Generate a text field Input element, as a String.

name is the name of the input field. value is its initial value. size is the size of the input area. maxlength is the maximum length of input accepted.

Alternatively, the attributes can be specified as a hash.

  text_field("name")
    # <INPUT TYPE="text" NAME="name" SIZE="40">

  text_field("name", "value")
    # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="40">

  text_field("name", "value", 80)
    # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80">

  text_field("name", "value", 80, 200)
    # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">

  text_field("NAME" => "name", "VALUE" => "value")
    # <INPUT TYPE="text" NAME="name" VALUE="value">
textarea(name = "", cols = 70, rows = 10) {|| ...}

Generate a TextArea element, as a String.

name is the name of the textarea. cols is the number of columns and rows is the number of rows in the display.

Alternatively, the attributes can be specified as a hash.

The body is provided by the passed-in no-argument block

  textarea("name")
     # = textarea("NAME" => "name", "COLS" => 70, "ROWS" => 10)

  textarea("name", 40, 5)
     # = textarea("NAME" => "name", "COLS" => 40, "ROWS" => 5)


Module: CGI::QueryExtension

Module | CGI::QueryExtension
In: | lib/cgi.rb

Mixin module. It provides the follow functionality groups:

  1. Access to CGI environment variables as methods. See documentation to the CGI class for a list of these variables.
  2. Access to cookies, including the cookies attribute.
  3. Access to parameters, including the params attribute, and overloading
    to perform parameter value lookup by key.
  4. The initialize_query method, for initialising the above mechanisms, handling multipart forms, and allowing the class to be used in "offline" mode.

Methods

[] has_key? include? key? keys multipart? params= raw_cookie raw_cookie2

External Aliases

path -> local_path

Attributes

cookies | [RW] | Get the cookies as a hash of cookie-name=>Cookie pairs.
params | [R] | Get the parameters as a hash of name=>values pairs, where values is an Array.

Public Instance methods

[](key)

Get the value for the parameter with a given key.

If the parameter has multiple values, only the first will be retrieved; use params() to get the array of values.

has_key?(*args)

Returns true if a given parameter key exists in the query.

include?(*args)

Alias for has_key?

key?(*args)

Alias for has_key?

keys(*args)

Return all parameter keys as an array.

multipart?()
params=(hash)

Set all the parameters.

raw_cookie()

Get the raw cookies as a string.

raw_cookie2()

Get the raw RFC2965 cookies as a string.


Class: CGI::Session

Class | CGI::Session
In: | lib/cgi/session.rb
Parent: | Object

Class representing an HTTP session. See documentation for the file cgi/session.rb for an introduction to HTTP sessions.

Lifecycle

A CGI::Session instance is created from a CGI object. By default, this CGI::Session instance will start a new session if none currently exists, or continue the current session for this client if one does exist. The new_session option can be used to either always or never create a new session. See new() for more details.

delete() deletes a session from session storage. It does not however remove the session id from the client. If the client makes another request with the same id, the effect will be to start a new session with the old session‘s id.

Setting and retrieving session data.

The Session class associates data with a session as key-value pairs. This data can be set and retrieved by indexing the Session instance using ’[]’, much the same as hashes (although other hash methods are not supported).

When session processing has been completed for a request, the session should be closed using the close() method. This will store the session‘s state to persistent storage. If you want to store the session‘s state to persistent storage without finishing session processing for this request, call the update() method.

Storing session state

The caller can specify what form of storage to use for the session‘s data with the database_manager option to CGI::Session::new. The following storage classes are provided as part of the standard library:

CGI::Session::FileStore: | stores data as plain text in a flat file. Only works with String data. This is the default storage type.
CGI::Session::MemoryStore: | stores data in an in-memory hash. The data only persists for as long as the current ruby interpreter instance does.
CGI::Session::PStore: | stores data in Marshalled format. Provided by cgi/session/pstore.rb. Supports data of any type, and provides file-locking and transaction support.

Custom storage types can also be created by defining a class with the following methods:

   new(session, options)
   restore  # returns hash of session data.
   update
   close
   delete

Changing storage type mid-session does not work. Note in particular that by default the FileStore and PStore session data files have the same name. If your application switches from one to the other without making sure that filenames will be different and clients still have old sessions lying around in cookies, then things will break nastily!

Maintaining the session id.

Most session state is maintained on the server. However, a session id must be passed backwards and forwards between client and server to maintain a reference to this session state.

The simplest way to do this is via cookies. The CGI::Session class provides transparent support for session id communication via cookies if the client has cookies enabled.

If the client has cookies disabled, the session id must be included as a parameter of all requests sent by the client to the server. The CGI::Session class in conjunction with the CGI class will transparently add the session id as a hidden input field to all forms generated using the CGI#form() HTML generation method. No built-in support is provided for other mechanisms, such as URL re-writing. The caller is responsible for extracting the session id from the session_id attribute and manually encoding it in URLs and adding it as a hidden input to HTML forms created by other mechanisms. Also, session expiry is not automatically handled.

Examples of use

Setting the user‘s name

  require 'cgi'
  require 'cgi/session'
  require 'cgi/session/pstore'     # provides CGI::Session::PStore

  cgi = CGI.new("html4")

  session = CGI::Session.new(cgi,
      'database_manager' => CGI::Session::PStore,  # use PStore
      'session_key' => '_rb_sess_id',              # custom session key
      'session_expires' => Time.now + 30 * 60,     # 30 minute timeout
      'prefix' => 'pstore_sid_')                   # PStore option
  if cgi.has_key?('user_name') and cgi['user_name'] != ''
      # coerce to String: cgi[] returns the
      # string-like CGI::QueryExtension::Value
      session['user_name'] = cgi['user_name'].to_s
  elsif !session['user_name']
      session['user_name'] = "guest"
  end
  session.close

Creating a new session safely

  require 'cgi'
  require 'cgi/session'

  cgi = CGI.new("html4")

  # We make sure to delete an old session if one exists,
  # not just to free resources, but to prevent the session
  # from being maliciously hijacked later on.
  begin
      session = CGI::Session.new(cgi, 'new_session' => false)
      session.delete
  rescue ArgumentError  # if no old session
  end
  session = CGI::Session.new(cgi, 'new_session' => true)
  session.close

Methods

[] []= close delete new update

Classes and Modules

Class CGI::Session::FileStore
Class CGI::Session::MemoryStore

Attributes

new_session | [R] | The id of this session.
session_id | [R] | The id of this session.

Public Class methods

new(request, option={})

Create a new CGI::Session object for request.

request is an instance of the CGI class (see cgi.rb). option is a hash of options for initialising this CGI::Session instance. The following options are recognised:

session_key: | the parameter name used for the session id. Defaults to ‘_session_id’.
session_id: | the session id to use. If not provided, then it is retrieved from the session_key parameter of the request, or automatically generated for a new session.
new_session: | if true, force creation of a new session. If not set, a new session is only created if none currently exists. If false, a new session is never created, and if none currently exists and the session_id option is not set, an ArgumentError is raised.
database_manager: | the name of the class providing storage facilities for session state persistence. Built-in support is provided for FileStore (the default), MemoryStore, and PStore (from cgi/session/pstore.rb). See the documentation for these classes for more details.

The following options are also recognised, but only apply if the session id is stored in a cookie.

session_expires: | the time the current session expires, as a Time object. If not set, the session will terminate when the user‘s browser is closed.
session_domain: | the hostname domain for which this session is valid. If not set, defaults to the hostname of the server.
session_secure: | if true, this session will only work over HTTPS.
session_path: | the path for which this session applies. Defaults to the directory of the CGI script.

option is also passed on to the session storage class initialiser; see the documentation for each session storage class for the options they support.

The retrieved or created session is automatically added to request as a cookie, and also to its output_hidden table, which is used to add hidden input elements to forms.

WARNING the output_hidden fields are surrounded by a <fieldset> tag in HTML 4 generation, which is not invisible on many browsers; you may wish to disable the use of fieldsets with code similar to the following (see blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)

  cgi = CGI.new("html4")
  class << cgi
      undef_method :fieldset
  end

Public Instance methods

[](key)

Retrieve the session data for key key.

[]=(key, val)

Set the session date for key key.

close()

Store session data on the server and close the session storage. For some session storage types, this is a no-op.

delete()

Delete the session from storage. Also closes the storage.

Note that the session‘s data is not automatically deleted upon the session expiring.

update()

Store session data on the server. For some session storage types, this is a no-op.


Class: CGI::Session::FileStore

Class | CGI::Session::FileStore
In: | lib/cgi/session.rb
Parent: | Object

File-based session storage class.

Implements session storage as a flat file of ‘key=value’ values. This storage type only works directly with String values; the user is responsible for converting other types to Strings when storing and from Strings when retrieving.

Methods

close delete new restore update

Public Class methods

new(session, option={})

Create a new FileStore instance.

This constructor is used internally by CGI::Session. The user does not generally need to call it directly.

session is the session for which this instance is being created. The session id must only contain alphanumeric characters; automatically generated session ids observe this requirement.

option is a hash of options for the initialiser. The following options are recognised:

tmpdir: | the directory to use for storing the FileStore file. Defaults to Dir::tmpdir (generally "/tmp" on Unix systems).
prefix: | the prefix to add to the session id when generating the filename for this session‘s FileStore file. Defaults to the empty string.
suffix: | the prefix to add to the session id when generating the filename for this session‘s FileStore file. Defaults to the empty string.

This session‘s FileStore file will be created if it does not exist, or opened if it does.

Public Instance methods

close()

Update and close the session‘s FileStore file.

delete()

Close and delete the session‘s FileStore file.

restore()

Restore session state from the session‘s FileStore file.

Returns the session state as a hash.

update()

Save session state to the session‘s FileStore file.


Class: CGI::Session::MemoryStore

Class | CGI::Session::MemoryStore
In: | lib/cgi/session.rb
Parent: | Object

In-memory session storage class.

Implements session storage as a global in-memory hash. Session data will only persist for as long as the ruby interpreter instance does.

Methods

close delete new restore update

Public Class methods

new(session, option=nil)

Create a new MemoryStore instance.

session is the session this instance is associated with. option is a list of initialisation options. None are currently recognised.

Public Instance methods

close()

Close session storage.

A no-op.

delete()

Delete the session state.

restore()

Restore session state.

Returns session data as a hash.

update()

Update session state.

A no-op.


Module: CONST1

Module | CONST1
In: | ext/win32ole/tests/testWIN32OLE.rb


Module: CONST2

Module | CONST2
In: | ext/win32ole/tests/testWIN32OLE.rb


Module: CONST3

Module | CONST3
In: | ext/win32ole/tests/testWIN32OLE.rb


Class: CSV

Class | CSV
In: | lib/csv.rb
Parent: | Object

This program is copyrighted free software by NAKAMURA, Hiroshi. You can redistribute it and/or modify it under the same terms of Ruby‘s license; either the dual license version in 2003, or any later version.

Methods

foreach generate generate_line generate_row open parse parse_line parse_row read readlines

Classes and Modules

Class CSV::BasicWriter
Class CSV::Cell
Class CSV::IOBuf
Class CSV::IOReader
Class CSV::IllegalFormatError
Class CSV::Reader
Class CSV::Row
Class CSV::StreamBuf
Class CSV::StringReader
Class CSV::Writer

Public Class methods

foreach(path, rs = nil, &block)
generate(path, fs = nil, rs = nil, &block)
generate_line(row, fs = nil, rs = nil)

Create a line from cells. each cell is stringified by to_s.

generate_row(src, cells, out_dev, fs = nil, rs = nil)

Convert a line from cells data to string. Consider using CSV.generate_line instead. To generate multi-row CSV string, see EXAMPLE below.

EXAMPLE

  row1 = ['a', 'b']
  row2 = ['c', 'd']
  row3 = ['e', 'f']
  src = [row1, row2, row3]
  buf = ''
  src.each do |row|
    parsed_cells = CSV.generate_row(row, 2, buf)
    puts "Created #{ parsed_cells } cells."
  end
  p buf

ARGS

  src: an Array of String to be converted to CSV string.  Must respond to
    'size' and '[](idx)'.  src[idx] must return String.
  cells: num of cells in a line.
  out_dev: buffer for generated CSV string.  Must respond to '<<(string)'.
  col_sep: Column separator.  ?, by default.  If you want to separate
    fields with semicolon, give ?; here.
  row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
    want to separate records with \r, give ?\r here.

RETURNS

  parsed_cells: num of converted cells.
open(path, mode, fs = nil, rs = nil, &block)

Open a CSV formatted file for reading or writing.

For reading.

EXAMPLE 1

  CSV.open('csvfile.csv', 'r') do |row|
    p row
  end

EXAMPLE 2

  reader = CSV.open('csvfile.csv', 'r')
  row1 = reader.shift
  row2 = reader.shift
  if row2.empty?
    p 'row2 not find.'
  end
  reader.close

ARGS

  filename: filename to parse.
  col_sep: Column separator.  ?, by default.  If you want to separate
    fields with semicolon, give ?; here.
  row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
    want to separate records with \r, give ?\r here.

RETURNS

  reader instance.  To get parse result, see CSV::Reader#each.

For writing.

EXAMPLE 1

  CSV.open('csvfile.csv', 'w') do |writer|
    writer << ['r1c1', 'r1c2']
    writer << ['r2c1', 'r2c2']
    writer << [nil, nil]
  end

EXAMPLE 2

  writer = CSV.open('csvfile.csv', 'w')
  writer << ['r1c1', 'r1c2'] << ['r2c1', 'r2c2'] << [nil, nil]
  writer.close

ARGS

  filename: filename to generate.
  col_sep: Column separator.  ?, by default.  If you want to separate
    fields with semicolon, give ?; here.
  row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
    want to separate records with \r, give ?\r here.

RETURNS

  writer instance.  See CSV::Writer#<< and CSV::Writer#add_row to know how
  to generate CSV string.
parse(str_or_readable, fs = nil, rs = nil) {|row| ...}

Parse lines from given string or stream. Return rows as an Array of Arrays.

parse_line(src, fs = nil, rs = nil)

Parse a line from given string. Bear in mind it parses ONE LINE. Rest of the string is ignored for example "a,b\r\nc,d" => [‘a’, ‘b’] and the second line ‘c,d’ is ignored.

If you don‘t know whether a target string to parse is exactly 1 line or not, use CSV.parse_row instead of this method.

parse_row(src, idx, out_dev, fs = nil, rs = nil)

Parse a line from string. Consider using CSV.parse_line instead. To parse lines in CSV string, see EXAMPLE below.

EXAMPLE

  src = "a,b\r\nc,d\r\ne,f"
  idx = 0
  begin
    parsed = []
    parsed_cells, idx = CSV.parse_row(src, idx, parsed)
    puts "Parsed #{ parsed_cells } cells."
    p parsed
  end while parsed_cells > 0

ARGS

  src: a CSV data to be parsed.  Must respond '[](idx)'.
    src[](idx) must return a char. (Not a string such as 'a', but 97).
    src[](idx_out_of_bounds) must return nil.  A String satisfies this
    requirement.
  idx: index of parsing location of 'src'.  0 origin.
  out_dev: buffer for parsed cells.  Must respond '<<(aString)'.
  col_sep: Column separator.  ?, by default.  If you want to separate
    fields with semicolon, give ?; here.
  row_sep: Row separator.  nil by default.  nil means "\r\n or \n".  If you
    want to separate records with \r, give ?\r here.

RETURNS

  parsed_cells: num of parsed cells.
  idx: index of next parsing location of 'src'.
read(path, length = nil, offset = nil)
readlines(path, rs = nil)


Class: CSV::BasicWriter

Class | CSV::BasicWriter
In: | lib/csv.rb
Parent: | Writer

Methods

close_on_terminate new

Public Class methods

new(str_or_writable, fs = ',', rs = nil)

Public Instance methods

close_on_terminate()

Tell this writer to close the IO when terminated (Triggered by invoking CSV::BasicWriter#close).


Class: CSV::Cell

Class | CSV::Cell
In: | lib/csv.rb
Parent: | String

deprecated

Methods

data new

Public Class methods

new(data = "", is_null = false)

Public Instance methods

data()


Class: CSV::IOBuf

Class | CSV::IOBuf
In: | lib/csv.rb
Parent: | StreamBuf

Buffered IO.

EXAMPLE

  # File 'bigdata' could be a giga-byte size one!
  buf = CSV::IOBuf.new(File.open('bigdata', 'rb'))
  CSV::Reader.new(buf).each do |row|
    p row
    break if row[0].data == 'admin'
  end

Methods

close new

Public Class methods

new(s)

Public Instance methods

close()


Class: CSV::IOReader

Class | CSV::IOReader
In: | lib/csv.rb
Parent: | Reader

Methods

close_on_terminate new

Public Class methods

new(io, fs = ',', rs = nil)

Public Instance methods

close_on_terminate()

Tell this reader to close the IO when terminated (Triggered by invoking CSV::IOReader#close).


Class: CSV::IllegalFormatError

Class | CSV::IllegalFormatError
In: | lib/csv.rb
Parent: | RuntimeError


Class: CSV::Reader

Class | CSV::Reader
In: | lib/csv.rb
Parent: | Object

CSV formatted string/stream reader.

EXAMPLE

  read CSV lines untill the first column is 'stop'.

  CSV::Reader.parse(File.open('bigdata', 'rb')) do |row|
    p row
    break if !row[0].is_null && row[0].data == 'stop'
  end

Methods

close create each new parse shift

Included Modules

Enumerable

Public Class methods

create(str_or_readable, fs = ',', rs = nil)

Returns reader instance.

new(dev)
parse(str_or_readable, fs = ',', rs = nil) {|row| ...}

Parse CSV data and get lines. Given block is called for each parsed row. Block value is always nil. Rows are not cached for performance reason.

Public Instance methods

close()
each() {|row| ...}
shift()


Class: CSV::Row

Class | CSV::Row
In: | lib/csv.rb
Parent: | Array

deprecated


Class: CSV::StreamBuf

Class | CSV::StreamBuf
In: | lib/csv.rb
Parent: | Object

Buffered stream.

EXAMPLE 1 — an IO.

  class MyBuf < StreamBuf
    # Do initialize myself before a super class.  Super class might call my
    # method 'read'. (Could be awful for C++ user. :-)
    def initialize(s)
      @s = s
      super()
    end

    # define my own 'read' method.
    # CAUTION: Returning nil means EnfOfStream.
    def read(size)
      @s.read(size)
    end

    # release buffers. in Ruby which has GC, you do not have to call this...
    def terminate
      @s = nil
      super()
    end
  end

  buf = MyBuf.new(STDIN)
  my_str = ''
  p buf[0, 0]               # => '' (null string)
  p buf[0]                  # => 97 (char code of 'a')
  p buf[0, 1]               # => 'a'
  my_str = buf[0, 5]
  p my_str                  # => 'abcde' (5 chars)
  p buf[0, 6]               # => "abcde\n" (6 chars)
  p buf[0, 7]               # => "abcde\n" (6 chars)
  p buf.drop(3)             # => 3 (dropped chars)
  p buf.get(0, 2)           # => 'de' (2 chars)
  p buf.is_eos?             # => false (is not EOS here)
  p buf.drop(5)             # => 3 (dropped chars)
  p buf.is_eos?             # => true (is EOS here)
  p buf[0]                  # => nil (is EOS here)

EXAMPLE 2 — String.

  This is a conceptual example.  No pros with this.

  class StrBuf < StreamBuf
    def initialize(s)
      @str = s
      @idx = 0
      super()
    end

    def read(size)
      str = @str[@idx, size]
      @idx += str.size
      str
    end
  end

Methods

[] drop get is_eos? new read terminate

Constants

BufSize = 1024 * 8

Public Class methods

new()

WARN: Do not instantiate this class directly. Define your own class which derives this class and define ‘read’ instance method.

Public Instance methods

[](idx, n = nil)

get a char or a partial string from the stream. idx: index of a string to specify a start point of a string to get. unlike String instance, idx < 0 returns nil. n: size of a string to get. returns char at idx if n == nil. returns a partial string, from idx to (idx + n) if n != nil. at EOF, the string size could not equal to arg n.

drop(n)

drop a string from the stream. returns dropped size. at EOF, dropped size might not equals to arg n. Once you drop the head of the stream, access to the dropped part via [] or get returns nil.

get(idx, n = nil)

Alias for #[]

is_eos?()

Protected Instance methods

read(size)

protected method ‘read’ must be defined in derived classes. CAUTION: Returning a string which size is not equal to ‘size’ means EnfOfStream. When it is not at EOS, you must block the callee, try to read and return the sized string.

terminate()


Class: CSV::StringReader

Class | CSV::StringReader
In: | lib/csv.rb
Parent: | Reader

Methods

new

Public Class methods

new(string, fs = ',', rs = nil)


Class: CSV::Writer

Class | CSV::Writer
In: | lib/csv.rb
Parent: | Object

CSV formatted string/stream writer.

EXAMPLE

  Write rows to 'csvout' file.

  outfile = File.open('csvout', 'wb')
  CSV::Writer.generate(outfile) do |csv|
    csv << ['c1', nil, '', '"', "\r\n", 'c2']
    ...
  end

  outfile.close

Methods

<< add_row close create generate new

Public Class methods

create(str_or_writable, fs = ',', rs = nil)

str_or_writable must handle ’<<(string)’.

generate(str_or_writable, fs = ',', rs = nil) {|writer| ...}

Given block is called with the writer instance. str_or_writable must handle ’<<(string)’.

new(dev)

Public Instance methods

<<(row)

dump CSV stream to the device. argument must be an Array of String.

add_row(row)

Alias for #<<

close()


Class: Class

Class | Class
In: | object.c lib/yaml/rubytypes.rb
Parent: | Module

Classes in Ruby are first-class objects—each is an instance of class Class.

When a new class is created (typically using class Name … end), an object of type Class is created and assigned to a global constant (Name in this case). When Name.new is called to create a new object, the new method in Class is run by default. This can be demonstrated by overriding new in Class:

   class Class
      alias oldNew  new
      def new(*args)
        print "Creating a new ", self.name, "\n"
        oldNew(*args)
      end
    end

    class Name
    end

    n = Name.new

produces:

   Creating a new Name

Classes, modules, and objects are interrelated. In the diagram that follows, the vertical arrows represent inheritance, and the parentheses meta-classes. All metaclasses are instances of the class `Class’.

                          +------------------+
                          |                  |
            Object---->(Object)              |
             ^  ^        ^  ^                |
             |  |        |  |                |
             |  |  +-----+  +---------+      |
             |  |  |                  |      |
             |  +-----------+         |      |
             |     |        |         |      |
      +------+     |     Module--->(Module)  |
      |            |        ^         ^      |
 OtherClass-->(OtherClass)  |         |      |
                            |         |      |
                          Class---->(Class)  |
                            ^                |
                            |                |
                            +----------------+

Methods

allocate inherited new new superclass to_yaml

Public Class methods

Class.new(super_class=Object) => a_class

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given). You can give a class a name by assigning the class object to a constant.

Public Instance methods

class.allocate() => obj

Allocates space for a new object of class‘s class. The returned object must be an instance of class.

inherited(subclass)

Callback invoked whenever a subclass of the current class is created.

Example:

   class Foo
      def self.inherited(subclass)
         puts "New subclass: #{subclass}"
      end
   end

   class Bar < Foo
   end

   class Baz < Bar
   end

produces:

   New subclass: Bar
   New subclass: Baz
class.new(args, ...) => obj

Calls allocate to create a new object of class‘s class, then invokes that object‘s initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new.

class.superclass → a_super_class or nil

Returns the superclass of class, or nil.

   File.superclass     #=> IO
   IO.superclass       #=> Object
   Object.superclass   #=> nil
to_yaml( opts = {} )


Module: Comparable

Module | Comparable
In: | compar.c

The Comparable mixin is used by classes whose objects may be ordered. The class must define the <=> operator, which compares the receiver against another object, returning -1, 0, or +1 depending on whether the receiver is less than, equal to, or greater than the other object. Comparable uses <=> to implement the conventional comparison operators (<, <=, ==, >=, and >) and the method between?.

   class SizeMatters
     include Comparable
     attr :str
     def <=>(anOther)
       str.size <=> anOther.str.size
     end
     def initialize(str)
       @str = str
     end
     def inspect
       @str
     end
   end

   s1 = SizeMatters.new("Z")
   s2 = SizeMatters.new("YY")
   s3 = SizeMatters.new("XXX")
   s4 = SizeMatters.new("WWWW")
   s5 = SizeMatters.new("VVVVV")

   s1 < s2                       #=> true
   s4.between?(s1, s3)           #=> false
   s4.between?(s3, s5)           #=> true
   [ s3, s2, s5, s4, s1 ].sort   #=> [Z, YY, XXX, WWWW, VVVVV]

Methods

< <= == > >= between?

Public Instance methods

obj < other => true or false

Compares two objects based on the receiver‘s <=> method, returning true if it returns -1.

obj <= other => true or false

Compares two objects based on the receiver‘s <=> method, returning true if it returns -1 or 0.

obj == other => true or false

Compares two objects based on the receiver‘s <=> method, returning true if it returns 0. Also returns true if obj and other are the same object.

obj > other => true or false

Compares two objects based on the receiver‘s <=> method, returning true if it returns 1.

obj >= other => true or false

Compares two objects based on the receiver‘s <=> method, returning true if it returns 0 or 1.

obj.between?(min, max) => true or false

Returns false if obj <=> min is less than zero or if anObject <=> max is greater than zero, true otherwise.

   3.between?(1, 5)               #=> true
   6.between?(1, 5)               #=> false
   'cat'.between?('ant', 'dog')   #=> true
   'gnu'.between?('ant', 'dog')   #=> false


Class: CompletingHash

Class | CompletingHash
In: | lib/optparse.rb
Parent: | Hash

Hash with completion search feature. See OptionParser::Completion.

Methods

match

Included Modules

Completion

Public Instance methods

match(key)

Completion for hash key.


Class: Complex

Class | Complex
In: | lib/complex.rb lib/mathn.rb
Parent: | Numeric

The complex number class. See complex.rb for an overview.

Methods

% * ** + - / <=> == abs abs2 angle arg coerce conj conjugate denominator hash inspect new new! numerator polar polar to_s

Constants

I | = | Complex(0,1) | I is the imaginary number. It exists at point (0,1) on the complex plane.
Unify | = | true

External Aliases

image -> imag

Attributes

image | [R] | The imaginary part of a complex number.
real | [R] | The real part of a complex number.

Public Class methods

new(a, b)
new!(a, b=0)

Creates a Complex number a+b i.

polar(r, theta)

Creates a Complex number in terms of r (radius) and theta (angle).

Public Instance methods

%(other)

Remainder after division by a real or complex number.

*(other)

Multiplication with real or complex number.

**(other)

Raise this complex number to the given (real or complex) power.

+(other)

Addition with real or complex number.

-(other)

Subtraction with real or complex number.

/(other)

Division by real or complex number.

<=>(other)

Compares the absolute values of the two numbers.

==(other)

Test for numerical equality (a == a + 0i).

abs()

Absolute value (aka modulus): distance from the zero point on the complex plane.

abs2()

Square of the absolute value.

angle()

Alias for arg

arg()

Argument (angle from (1,0) on the complex plane).

coerce(other)

Attempts to coerce other to a Complex number.

conj()

Alias for conjugate

conjugate()

Complex conjugate (z + z.conjugate = 2 * z.real).

denominator()

FIXME

hash()

Returns a hash code for the complex number.

inspect()

Returns "Complex(real, image)".

numerator()

FIXME

polar()

Returns the absolute value and the argument.

to_s()

Standard string representation of the complex number.


Class: ConditionVariable

Class | ConditionVariable
In: | lib/thread.rb
Parent: | Object

ConditionVariable objects augment class Mutex. Using condition variables, it is possible to suspend while in the middle of a critical section until a resource becomes available.

Example:

  require 'thread'

  mutex = Mutex.new
  resource = ConditionVariable.new

  a = Thread.new {
    mutex.synchronize {
      # Thread 'a' now needs the resource
      resource.wait(mutex)
      # 'a' can now have the resource
    }
  }

  b = Thread.new {
    mutex.synchronize {
      # Thread 'b' has finished using the resource
      resource.signal
    }
  }

Methods

broadcast new signal wait

Public Class methods

new()

Creates a new ConditionVariable

Public Instance methods

broadcast()

Wakes up all threads waiting for this lock.

signal()

Wakes up the first thread in line waiting for this lock.

wait(mutex)

Releases the lock held in mutex and waits; reacquires the lock on wakeup.


Class: Continuation

Class | Continuation
In: | eval.c
Parent: | Object

Continuation objects are generated by Kernel#callcc. They hold a return address and execution context, allowing a nonlocal return to the end of the callcc block from anywhere within a program. Continuations are somewhat analogous to a structured version of C‘s setjmp/longjmp (although they contain more state, so you might consider them closer to threads).

For instance:

   arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
   callcc{|$cc|}
   puts(message = arr.shift)
   $cc.call unless message =~ /Max/

produces:

   Freddie
   Herbie
   Ron
   Max

This (somewhat contrived) example allows the inner loop to abandon processing early:

   callcc {|cont|
     for i in 0..4
       print "\n#{i}: "
       for j in i*5...(i+1)*5
         cont.call() if j == 17
         printf "%3d", j
       end
     end
   }
   print "\n"

produces:

   0:   0  1  2  3  4
   1:   5  6  7  8  9
   2:  10 11 12 13 14
   3:  15 16

Methods

[] call

Public Instance methods

cont.call(args, ...)
cont[args, ...]

Invokes the continuation. The program continues from the end of the callcc block. If no arguments are given, the original callcc returns nil. If one argument is given, callcc returns it. Otherwise, an array containing args is returned.

   callcc {|cont|  cont.call }           #=> nil
   callcc {|cont|  cont.call 1 }         #=> 1
   callcc {|cont|  cont.call 1, 2, 3 }   #=> [1, 2, 3]
cont.call(args, ...)
cont[args, ...]

Invokes the continuation. The program continues from the end of the callcc block. If no arguments are given, the original callcc returns nil. If one argument is given, callcc returns it. Otherwise, an array containing args is returned.

   callcc {|cont|  cont.call }           #=> nil
   callcc {|cont|  cont.call 1 }         #=> 1
   callcc {|cont|  cont.call 1, 2, 3 }   #=> [1, 2, 3]


Class: DEBUGGER__

Class | DEBUGGER__
In: | lib/debug.rb
Parent: | Object

Methods

break_points context debug_thread_info display get_thread interrupt make_thread_list resume set_last_thread set_trace stdout stdout= suspend thread_list thread_list_all waiting

Classes and Modules

Class DEBUGGER__::Context
Class DEBUGGER__::Mutex

Constants

MUTEX = Mutex.new

Public Class methods

break_points()
context(thread=Thread.current)
debug_thread_info(input, binding)
display()
get_thread(num)
interrupt()
make_thread_list()
resume()
set_last_thread(th)
set_trace( arg )
stdout()
stdout=(s)
suspend()
thread_list(num)
thread_list_all()
waiting()


Class: DEBUGGER__::Context

Class | DEBUGGER__::Context
In: | lib/debug.rb
Parent: | Object

Methods

break_points check_break_points check_suspend clear_suspend context debug_command debug_eval debug_funcname debug_method_info debug_print_help debug_silent_eval debug_variable_info display display_expression display_expressions display_frames display_list excn_handle format_frame frame_set_pos line_at new readline readline resume_all set_last_thread set_suspend set_trace set_trace_all stdout stop_next suspend_all thnum trace? trace_func var_list

Constants

DEBUG_LAST_CMD | = | []
USE_READLINE | = | false

Public Class methods

new()

Public Instance methods

break_points()
check_break_points(file, klass, pos, binding, id)
check_suspend()
clear_suspend()
context(th)
debug_command(file, line, id, binding)
debug_eval(str, binding)
debug_funcname(id)
debug_method_info(input, binding)
debug_print_help()
debug_silent_eval(str, binding)
debug_variable_info(input, binding)
display()
display_expression(exp, binding)
display_expressions(binding)
display_frames(pos)
display_list(b, e, file, line)
excn_handle(file, line, id, binding)
format_frame(pos)
frame_set_pos(file, line)
line_at(file, line)
readline(prompt, hist)
readline(prompt, hist)
resume_all()
set_last_thread(th)
set_suspend()
set_trace(arg)
set_trace_all(arg)
stdout()
stop_next(n=1)
suspend_all()
thnum()
trace?()
trace_func(event, file, line, id, binding, klass)
var_list(ary, binding)


Class: DEBUGGER__::Mutex

Class | DEBUGGER__::Mutex
In: | lib/debug.rb
Parent: | Object

Methods

lock locked? new unlock

Public Class methods

new()

Public Instance methods

lock()
locked?()
unlock()


Module: DOT

Module | DOT
In: | lib/rdoc/dot/dot.rb

Methods

change_tab

Classes and Modules

Class DOT::DOTDigraph
Class DOT::DOTEdge
Class DOT::DOTElement
Class DOT::DOTNode
Class DOT::DOTPort
Class DOT::DOTSimpleElement
Class DOT::DOTSubgraph

Constants

NODE_OPTS | = | [ 'bgcolor', 'color', 'fontcolor', 'fontname', 'fontsize', 'height', 'width', 'label', 'layer', 'rank', 'shape', 'shapefile', 'style', 'URL', ] | options for node declaration
EDGE_OPTS | = | [ 'color', 'decorate', 'dir', 'fontcolor', 'fontname', 'fontsize', 'id', 'label', 'layer', 'lhead', 'ltail', 'minlen', 'style', 'weight' | options for edge declaration
GRAPH_OPTS | = | [ 'bgcolor', 'center', 'clusterrank', 'color', 'compound', 'concentrate', 'fillcolor', 'fontcolor', 'fontname', 'fontsize', 'label', 'layerseq', 'margin', 'mclimit', 'nodesep', 'nslimit', 'ordering', 'orientation', 'page', 'rank', 'rankdir', 'ranksep', 'ratio', 'size', 'style', 'URL' | options for graph declaration

Public Instance methods

change_tab( t )

if we don‘t like 4 spaces, we can change it any time


Class: DOT::DOTDigraph

Class | DOT::DOTDigraph
In: | lib/rdoc/dot/dot.rb
Parent: | DOTSubgraph

this is graph

Methods

new

Public Class methods

new( params = {}, option_list = GRAPH_OPTS )


Class: DOT::DOTEdge

Class | DOT::DOTEdge
In: | lib/rdoc/dot/dot.rb
Parent: | DOTElement

this is edge

Methods

new to_s

Attributes

from | [RW]
to | [RW]

Public Class methods

new( params = {}, option_list = EDGE_OPTS )

Public Instance methods

to_s( t = '' )


Class: DOT::DOTElement

Class | DOT::DOTElement
In: | lib/rdoc/dot/dot.rb
Parent: | DOTSimpleElement

an element that has options ( node, edge or graph )

Methods

each_option each_option_pair new

Attributes

name | [RW] | attr_reader :parent
options | [RW] | attr_reader :parent

Public Class methods

new( params = {}, option_list = [] )

Public Instance methods

each_option() {|i| ...}
each_option_pair() {|key, val| ...}


Class: DOT::DOTNode

Class | DOT::DOTNode
In: | lib/rdoc/dot/dot.rb
Parent: | DOTElement

node element

Methods

<< each_port new pop push to_s

Public Class methods

new( params = {}, option_list = NODE_OPTS )

Public Instance methods

<<( thing )
each_port() {|i| ...}
pop()
push( thing )
to_s( t = '' )


Class: DOT::DOTPort

Class | DOT::DOTPort
In: | lib/rdoc/dot/dot.rb
Parent: | DOTSimpleElement

this is used when we build nodes that have shape=record ports don‘t have options :)

Methods

new to_s

Attributes

label [RW]

Public Class methods

new( params = {} )

Public Instance methods

to_s()


Class: DOT::DOTSimpleElement

Class | DOT::DOTSimpleElement
In: | lib/rdoc/dot/dot.rb
Parent: | Object

a root class for any element in dot notation

Methods

new to_s

Attributes

name [RW]

Public Class methods

new( params = {} )

Public Instance methods

to_s()


Class: DOT::DOTSubgraph

Class | DOT::DOTSubgraph
In: | lib/rdoc/dot/dot.rb
Parent: | DOTElement

subgraph element is the same to graph, but has another header in dot notation

Methods

<< each_node new pop push to_s

Public Class methods

new( params = {}, option_list = GRAPH_OPTS )

Public Instance methods

<<( thing )
each_node() {|i| ...}
pop()
push( thing )
to_s( t = '' )


Module: DRb

Module | DRb
In: | lib/drb/timeridconv.rb lib/drb/invokemethod.rb lib/drb/gw.rb lib/drb/eq.rb lib/drb/observer.rb lib/drb/drb.rb lib/drb/extservm.rb lib/drb/extserv.rb lib/drb/ssl.rb lib/drb/unix.rb

Overview

dRuby is a distributed object system for Ruby. It is written in pure Ruby and uses its own protocol. No add-in services are needed beyond those provided by the Ruby runtime, such as TCP sockets. It does not rely on or interoperate with other distributed object systems such as CORBA, RMI, or .NET.

dRuby allows methods to be called in one Ruby process upon a Ruby object located in another Ruby process, even on another machine. References to objects can be passed between processes. Method arguments and return values are dumped and loaded in marshalled format. All of this is done transparently to both the caller of the remote method and the object that it is called upon.

An object in a remote process is locally represented by a DRb::DRbObject instance. This acts as a sort of proxy for the remote object. Methods called upon this DRbObject instance are forwarded to its remote object. This is arranged dynamically at run time. There are no statically declared interfaces for remote objects, such as CORBA‘s IDL.

dRuby calls made into a process are handled by a DRb::DRbServer instance within that process. This reconstitutes the method call, invokes it upon the specified local object, and returns the value to the remote caller. Any object can receive calls over dRuby. There is no need to implement a special interface, or mixin special functionality. Nor, in the general case, does an object need to explicitly register itself with a DRbServer in order to receive dRuby calls.

One process wishing to make dRuby calls upon another process must somehow obtain an initial reference to an object in the remote process by some means other than as the return value of a remote method call, as there is initially no remote object reference it can invoke a method upon. This is done by attaching to the server by URI. Each DRbServer binds itself to a URI such as ‘druby://example.com:8787’. A DRbServer can have an object attached to it that acts as the server‘s front object. A DRbObject can be explicitly created from the server‘s URI. This DRbObject‘s remote object will be the server‘s front object. This front object can then return references to other Ruby objects in the DRbServer‘s process.

Method calls made over dRuby behave largely the same as normal Ruby method calls made within a process. Method calls with blocks are supported, as are raising exceptions. In addition to a method‘s standard errors, a dRuby call may also raise one of the dRuby-specific errors, all of which are subclasses of DRb::DRbError.

Any type of object can be passed as an argument to a dRuby call or returned as its return value. By default, such objects are dumped or marshalled at the local end, then loaded or unmarshalled at the remote end. The remote end therefore receives a copy of the local object, not a distributed reference to it; methods invoked upon this copy are executed entirely in the remote process, not passed on to the local original. This has semantics similar to pass-by-value.

However, if an object cannot be marshalled, a dRuby reference to it is passed or returned instead. This will turn up at the remote end as a DRbObject instance. All methods invoked upon this remote proxy are forwarded to the local object, as described in the discussion of DRbObjects. This has semantics similar to the normal Ruby pass-by-reference.

The easiest way to signal that we want an otherwise marshallable object to be passed or returned as a DRbObject reference, rather than marshalled and sent as a copy, is to include the DRb::DRbUndumped mixin module.

dRuby supports calling remote methods with blocks. As blocks (or rather the Proc objects that represent them) are not marshallable, the block executes in the local, not the remote, context. Each value yielded to the block is passed from the remote object to the local block, then the value returned by each block invocation is passed back to the remote execution context to be collected, before the collected values are finally returned to the local context as the return value of the method invocation.

Examples of usage

For more dRuby samples, see the samples directory in the full dRuby distribution.

dRuby in client/server mode

This illustrates setting up a simple client-server drb system. Run the server and client code in different terminals, starting the server code first.

Server code

  require 'drb/drb'

  # The URI for the server to connect to
  URI="druby://localhost:8787"

  class TimeServer

    def get_current_time
      return Time.now
    end

  end

  # The object that handles requests on the server
  FRONT_OBJECT=TimeServer.new

  $SAFE = 1   # disable eval() and friends

  DRb.start_service(URI, FRONT_OBJECT)
  # Wait for the drb server thread to finish before exiting.
  DRb.thread.join

Client code

  require 'drb/drb'

  # The URI to connect to
  SERVER_URI="druby://localhost:8787"

  # Start a local DRbServer to handle callbacks.
  #
  # Not necessary for this small example, but will be required
  # as soon as we pass a non-marshallable object as an argument
  # to a dRuby call.
  DRb.start_service

  timeserver = DRbObject.new_with_uri(SERVER_URI)
  puts timeserver.get_current_time

Remote objects under dRuby

This example illustrates returning a reference to an object from a dRuby call. The Logger instances live in the server process. References to them are returned to the client process, where methods can be invoked upon them. These methods are executed in the server process.

Server code

  require 'drb/drb'

  URI="druby://localhost:8787"

  class Logger

      # Make dRuby send Logger instances as dRuby references,
      # not copies.
      include DRb::DRbUndumped

      def initialize(n, fname)
          @name = n
          @filename = fname
      end

      def log(message)
          File.open(@filename, "a") do |f|
              f.puts("#{Time.now}: #{@name}: #{message}")
          end
      end

  end

  # We have a central object for creating and retrieving loggers.
  # This retains a local reference to all loggers created.  This
  # is so an existing logger can be looked up by name, but also
  # to prevent loggers from being garbage collected.  A dRuby
  # reference to an object is not sufficient to prevent it being
  # garbage collected!
  class LoggerFactory

      def initialize(bdir)
          @basedir = bdir
          @loggers = {}
      end

      def get_logger(name)
          if !@loggers.has_key? name
              # make the filename safe, then declare it to be so
              fname = name.gsub(/[.\/]/, "_").untaint
              @loggers[name] = Logger.new(name, @basedir + "/" + fname)
          end
          return @loggers[name]
      end

  end

  FRONT_OBJECT=LoggerFactory.new("/tmp/dlog")

  $SAFE = 1   # disable eval() and friends

  DRb.start_service(URI, FRONT_OBJECT)
  DRb.thread.join

Client code

  require 'drb/drb'

  SERVER_URI="druby://localhost:8787"

  DRb.start_service

  log_service=DRbObject.new_with_uri(SERVER_URI)

  ["loga", "logb", "logc"].each do |logname|

      logger=log_service.get_logger(logname)

      logger.log("Hello, world!")
      logger.log("Goodbye, world!")
      logger.log("=== EOT ===")

  end

Security

As with all network services, security needs to be considered when using dRuby. By allowing external access to a Ruby object, you are not only allowing outside clients to call the methods you have defined for that object, but by default to execute arbitrary Ruby code on your server. Consider the following:

   # !!! UNSAFE CODE !!!
   ro = DRbObject::new_with_uri("druby://your.server.com:8989")
   class << ro
     undef :instance_eval  # force call to be passed to remote object
   end
   ro.instance_eval("`rm -rf *`")

The dangers posed by instance_eval and friends are such that a DRbServer should generally be run with $SAFE set to at least level 1. This will disable eval() and related calls on strings passed across the wire. The sample usage code given above follows this practice.

A DRbServer can be configured with an access control list to selectively allow or deny access from specified IP addresses. The main druby distribution provides the ACL class for this purpose. In general, this mechanism should only be used alongside, rather than as a replacement for, a good firewall.

dRuby internals

dRuby is implemented using three main components: a remote method call marshaller/unmarshaller; a transport protocol; and an ID-to-object mapper. The latter two can be directly, and the first indirectly, replaced, in order to provide different behaviour and capabilities.

Marshalling and unmarshalling of remote method calls is performed by a DRb::DRbMessage instance. This uses the Marshal module to dump the method call before sending it over the transport layer, then reconstitute it at the other end. There is normally no need to replace this component, and no direct way is provided to do so. However, it is possible to implement an alternative marshalling scheme as part of an implementation of the transport layer.

The transport layer is responsible for opening client and server network connections and forwarding dRuby request across them. Normally, it uses DRb::DRbMessage internally to manage marshalling and unmarshalling. The transport layer is managed by DRb::DRbProtocol. Multiple protocols can be installed in DRbProtocol at the one time; selection between them is determined by the scheme of a dRuby URI. The default transport protocol is selected by the scheme ‘druby:’, and implemented by DRb::DRbTCPSocket. This uses plain TCP/IP sockets for communication. An alternative protocol, using UNIX domain sockets, is implemented by DRb::DRbUNIXSocket in the file drb/unix.rb, and selected by the scheme ‘drbunix:’. A sample implementation over HTTP can be found in the samples accompanying the main dRuby distribution.

The ID-to-object mapping component maps dRuby object ids to the objects they refer to, and vice versa. The implementation to use can be specified as part of a DRb::DRbServer‘s configuration. The default implementation is provided by DRb::DRbIdConv. It uses an object‘s ObjectSpace id as its dRuby id. This means that the dRuby reference to that object only remains meaningful for the lifetime of the object‘s process and the lifetime of the object within that process. A modified implementation is provided by DRb::TimerIdConv in the file drb/timeridconv.rb. This implementation retains a local reference to all objects exported over dRuby for a configurable period of time (defaulting to ten minutes), to prevent them being garbage-collected within this time. Another sample implementation is provided in sample/name.rb in the main dRuby distribution. This allows objects to specify their own id or "name". A dRuby reference can be made persistent across processes by having each process register an object using the same dRuby name.

Methods

config current_server fetch_server front here? install_acl install_id_conv regist_server remove_server start_service stop_service thread to_id to_obj uri

Classes and Modules

Module DRb::DRbObservable
Module DRb::DRbProtocol
Module DRb::DRbUndumped
Class DRb::DRbArray
Class DRb::DRbBadScheme
Class DRb::DRbBadURI
Class DRb::DRbConn
Class DRb::DRbConnError
Class DRb::DRbError
Class DRb::DRbIdConv
Class DRb::DRbMessage
Class DRb::DRbObject
Class DRb::DRbRemoteError
Class DRb::DRbSSLSocket
Class DRb::DRbServer
Class DRb::DRbServerNotFound
Class DRb::DRbTCPSocket
Class DRb::DRbUNIXSocket
Class DRb::DRbUnknown
Class DRb::DRbUnknownError
Class DRb::ExtServ
Class DRb::ExtServManager
Class DRb::GW
Class DRb::GWIdConv
Class DRb::TimerIdConv

Attributes

primary_server [RW] The primary local dRuby server.

This is the server created by the start_service call.

Public Instance methods

config()

Get the configuration of the current server.

If there is no current server, this returns the default configuration. See current_server and DRbServer::make_config.

current_server()

Get the ‘current’ server.

In the context of execution taking place within the main thread of a dRuby server (typically, as a result of a remote call on the server or one of its objects), the current server is that server. Otherwise, the current server is the primary server.

If the above rule fails to find a server, a DRbServerNotFound error is raised.

fetch_server(uri)
front()

Get the front object of the current server.

This raises a DRbServerNotFound error if there is no current server. See current_server.

here?(uri)

Is uri the URI for the current local server?

install_acl(acl)

Set the default acl.

See DRb::DRbServer.default_acl.

install_id_conv(idconv)

Set the default id conv object.

See DRbServer#default_id_conv.

regist_server(server)
remove_server(server)
start_service(uri=nil, front=nil, config=nil)

Start a dRuby server locally.

The new dRuby server will become the primary server, even if another server is currently the primary server.

uri is the URI for the server to bind to. If nil, the server will bind to random port on the default local host name and use the default dRuby protocol.

front is the server‘s front object. This may be nil.

config is the configuration for the new server. This may be nil.

See DRbServer::new.

stop_service()

Stop the local dRuby server.

This operates on the primary server. If there is no primary server currently running, it is a noop.

thread()

Get the thread of the primary server.

This returns nil if there is no primary server. See primary_server.

to_id(obj)

Get a reference id for an object using the current server.

This raises a DRbServerNotFound error if there is no current server. See current_server.

to_obj(ref)

Convert a reference into an object using the current server.

This raises a DRbServerNotFound error if there is no current server. See current_server.

uri()

Get the URI defining the local dRuby space.

This is the URI of the current server. See current_server.


Class: DRb::DRbArray

Class | DRb::DRbArray
In: | lib/drb/drb.rb
Parent: | Object

Methods

_dump _load new

Public Class methods

_load(s)
new(ary)

Public Instance methods

_dump(lv)


Class: DRb::DRbBadScheme

Class | DRb::DRbBadScheme
In: | lib/drb/drb.rb
Parent: | DRbError

Error raised by a dRuby protocol when it doesn‘t support the scheme specified in a URI. See DRb::DRbProtocol.


Class: DRb::DRbBadURI

Class | DRb::DRbBadURI
In: | lib/drb/drb.rb
Parent: | DRbError

Error raised by the DRbProtocol module when it cannot find any protocol implementation support the scheme specified in a URI.


Class: DRb::DRbConn

Class | DRb::DRbConn
In: | lib/drb/drb.rb
Parent: | Object

Class handling the connection between a DRbObject and the server the real object lives on.

This class maintains a pool of connections, to reduce the overhead of starting and closing down connections for each method call.

This class is used internally by DRbObject. The user does not normally need to deal with it directly.


Class: DRb::DRbConnError

Class | DRb::DRbConnError
In: | lib/drb/drb.rb
Parent: | DRbError

Error raised when an error occurs on the underlying communication protocol.


Class: DRb::DRbError

Class | DRb::DRbError
In: | lib/drb/drb.rb
Parent: | RuntimeError

Superclass of all errors raised in the DRb module.


Class: DRb::DRbIdConv

Class | DRb::DRbIdConv
In: | lib/drb/drb.rb
Parent: | Object

Class responsible for converting between an object and its id.

This, the default implementation, uses an object‘s local ObjectSpace id as its id. This means that an object‘s identification over drb remains valid only while that object instance remains alive within the server runtime.

For alternative mechanisms, see DRb::TimerIdConv in rdb/timeridconv.rb and DRbNameIdConv in sample/name.rb in the full drb distribution.

Methods

to_id to_obj

Public Instance methods

to_id(obj)

Convert an object into a reference id.

This implementation returns the object‘s id in the local object space.

to_obj(ref)

Convert an object reference id to an object.

This implementation looks up the reference id in the local object space and returns the object it refers to.


Class: DRb::DRbMessage

Class | DRb::DRbMessage
In: | lib/drb/drb.rb
Parent: | Object

Handler for sending and receiving drb messages.

This takes care of the low-level marshalling and unmarshalling of drb requests and responses sent over the wire between server and client. This relieves the implementor of a new drb protocol layer with having to deal with these details.

The user does not have to directly deal with this object in normal use.


Class: DRb::DRbObject

Class | DRb::DRbObject
In: | lib/drb/gw.rb lib/drb/eq.rb lib/drb/drb.rb
Parent: | Object

Object wrapping a reference to a remote drb object.

Method calls on this object are relayed to the remote object that this object is a stub for.

Methods

== __drbref __drburi _dump _dump _load _load eql? hash method_missing new new_with new_with_uri prepare_backtrace respond_to? with_friend

Public Class methods

_load(s)
_load(s)

Unmarshall a marshalled DRbObject.

If the referenced object is located within the local server, then the object itself is returned. Otherwise, a new DRbObject is created to act as a stub for the remote referenced object.

new(obj, uri=nil)

Create a new remote object stub.

obj is the (local) object we want to create a stub for. Normally this is nil. uri is the URI of the remote object that this will be a stub for.

new_with(uri, ref)
new_with_uri(uri)

Create a new DRbObject from a URI alone.

prepare_backtrace(uri, result)
with_friend(uri) {|| ...}

Public Instance methods

==(other)
__drbref()

Get the reference of the object, if local.

__drburi()

Get the URI of the remote object.

_dump(lv)
_dump(lv)

Marshall this object.

The URI and ref of the object are marshalled.

eql?(other)

Alias for #==

hash()
method_missing(msg_id, *a, &b)

Routes method calls to the referenced object.

respond_to?(msg_id, priv=false)


Module: DRb::DRbObservable

Module | DRb::DRbObservable
In: | lib/drb/observer.rb

Methods

notify_observers

Included Modules

Observable

Public Instance methods

notify_observers(*arg)


Module: DRb::DRbProtocol

Module | DRb::DRbProtocol
In: | lib/drb/drb.rb

Module managing the underlying network protocol(s) used by drb.

By default, drb uses the DRbTCPSocket protocol. Other protocols can be defined. A protocol must define the following class methods:

  [open(uri, config)] Open a client connection to the server at +uri+,
                      using configuration +config+.  Return a protocol
                      instance for this connection.
  [open_server(uri, config)] Open a server listening at +uri+,
                             using configuration +config+.  Return a
                             protocol instance for this listener.
  [uri_option(uri, config)] Take a URI, possibly containing an option
                            component (e.g. a trailing '?param=val'),
                            and return a [uri, option] tuple.

All of these methods should raise a DRbBadScheme error if the URI does not identify the protocol they support (e.g. "druby:" for the standard Ruby protocol). This is how the DRbProtocol module, given a URI, determines which protocol implementation serves that protocol.

The protocol instance returned by open_server must have the following methods:

accept
Accept a new connection to the server. Returns a protocol instance capable of communicating with the client.
close
Close the server connection.
uri
Get the URI for this server.

The protocol instance returned by open must have the following methods:

send_request (ref, msg_id, arg, b)
Send a request to ref with the given message id and arguments. This is most easily implemented by calling DRbMessage.send_request, providing a stream that sits on top of the current protocol.
recv_reply
Receive a reply from the server and return it as a [success-boolean, reply-value] pair. This is most easily implemented by calling DRb.recv_reply, providing a stream that sits on top of the current protocol.
alive?
Is this connection still alive?
close
Close this connection.

The protocol instance returned by open_server().accept() must have the following methods:

recv_request
Receive a request from the client and return a [object, message, args, block] tuple. This is most easily implemented by calling DRbMessage.recv_request, providing a stream that sits on top of the current protocol.
send_reply(succ, result)
Send a reply to the client. This is most easily implemented by calling DRbMessage.send_reply, providing a stream that sits on top of the current protocol.
close
Close this connection.

A new protocol is registered with the DRbProtocol module using the add_protocol method.

For examples of other protocols, see DRbUNIXSocket in drb/unix.rb, and HTTP0 in sample/http0.rb and sample/http0serv.rb in the full drb distribution.

Methods

add_protocol open open_server uri_option

Public Instance methods

add_protocol(prot)

Add a new protocol to the DRbProtocol module.

open(uri, config, first=true)

Open a client connection to uri with the configuration config.

The DRbProtocol module asks each registered protocol in turn to try to open the URI. Each protocol signals that it does not handle that URI by raising a DRbBadScheme error. If no protocol recognises the URI, then a DRbBadURI error is raised. If a protocol accepts the URI, but an error occurs in opening it, a DRbConnError is raised.

open_server(uri, config, first=true)

Open a server listening for connections at uri with configuration config.

The DRbProtocol module asks each registered protocol in turn to try to open a server at the URI. Each protocol signals that it does not handle that URI by raising a DRbBadScheme error. If no protocol recognises the URI, then a DRbBadURI error is raised. If a protocol accepts the URI, but an error occurs in opening it, the underlying error is passed on to the caller.

uri_option(uri, config, first=true)

Parse uri into a [uri, option] pair.

The DRbProtocol module asks each registered protocol in turn to try to parse the URI. Each protocol signals that it does not handle that URI by raising a DRbBadScheme error. If no protocol recognises the URI, then a DRbBadURI error is raised.


Class: DRb::DRbRemoteError

Class | DRb::DRbRemoteError
In: | lib/drb/drb.rb
Parent: | DRbError

An exception wrapping an error object

Methods

new

Attributes

reason [R] the class of the error, as a string.

Public Class methods

new(error)


Class: DRb::DRbSSLSocket

Class | DRb::DRbSSLSocket
In: | lib/drb/ssl.rb
Parent: | DRbTCPSocket

Methods

accept close new open open_server parse_uri stream uri_option

Classes and Modules

Class DRb::DRbSSLSocket::SSLConfig

Public Class methods

new(uri, soc, config, is_established)
open(uri, config)
open_server(uri, config)
parse_uri(uri)
uri_option(uri, config)

Public Instance methods

accept()
close()
stream()


Class: DRb::DRbSSLSocket::SSLConfig

Class | DRb::DRbSSLSocket::SSLConfig
In: | lib/drb/ssl.rb
Parent: | Object

Methods

[] accept connect new setup_certificate setup_ssl_context

Constants

DEFAULT = { :SSLCertificate => nil, :SSLPrivateKey => nil, :SSLClientCA => nil, :SSLCACertificatePath => nil, :SSLCACertificateFile => nil, :SSLVerifyMode => ::OpenSSL::SSL::VERIFY_NONE, :SSLVerifyDepth => nil, :SSLVerifyCallback => nil, # custom verification :SSLCertificateStore => nil, # Must specify if you use auto generated certificate. :SSLCertName => nil, # e.g. [["CN","fqdn.example.com"]] :SSLCertComment => "Generated by Ruby/OpenSSL"

Public Class methods

new(config)

Public Instance methods

[](key)
accept(tcp)
connect(tcp)
setup_certificate()
setup_ssl_context()


Class: DRb::DRbServer

Class | DRb::DRbServer
In: | lib/drb/invokemethod.rb lib/drb/drb.rb
Parent: | Object

Class representing a drb server instance.

A DRbServer must be running in the local process before any incoming dRuby calls can be accepted, or any local objects can be passed as dRuby references to remote processes, even if those local objects are never actually called remotely. You do not need to start a DRbServer in the local process if you are only making outgoing dRuby calls passing marshalled parameters.

Unless multiple servers are being used, the local DRbServer is normally started by calling DRb.start_service.

Methods

alive? check_insecure_method default_acl default_argc_limit default_id_conv default_load_limit default_safe_level new stop_service to_id to_obj verbose verbose verbose= verbose=

Classes and Modules

Module DRb::DRbServer::InvokeMethod18Mixin

Constants

INSECURE_METHOD = [ :__send__ List of insecure methods.

These methods are not callable via dRuby.

Attributes

config | [R] | The configuration of this DRbServer
front | [R] | The front object of the DRbServer. This object receives remote method calls made on the server‘s URI alone, with an object id.
safe_level | [R] |
thread | [R] | The main thread of this DRbServer. This is the thread that listens for and accepts connections from clients, not that handles each client‘s request-response session.
uri | [R] | The URI of this DRbServer.

Public Class methods

default_acl(acl)

Set the default value for the :acl option.

See new(). The initial default value is nil.

default_argc_limit(argc)

Set the default value for the :argc_limit option.

See new(). The initial default value is 256.

default_id_conv(idconv)

Set the default value for the :id_conv option.

See new(). The initial default value is a DRbIdConv instance.

default_load_limit(sz)

Set the default value for the :load_limit option.

See new(). The initial default value is 25 MB.

default_safe_level(level)
new(uri=nil, front=nil, config_or_acl=nil)

Create a new DRbServer instance.

uri is the URI to bind to. This is normally of the form ‘druby://<hostname>:<port>’ where <hostname> is a hostname of the local machine. If nil, then the system‘s default hostname will be bound to, on a port selected by the system; these value can be retrieved from the uri attribute. ‘druby:’ specifies the default dRuby transport protocol: another protocol, such as ‘drbunix:’, can be specified instead.

front is the front object for the server, that is, the object to which remote method calls on the server will be passed. If nil, then the server will not accept remote method calls.

If config_or_acl is a hash, it is the configuration to use for this server. The following options are recognised:

:idconv : | an id-to-object conversion object. This defaults to an instance of the class DRb::DRbIdConv.
:verbose : | if true, all unsuccessful remote calls on objects in the server will be logged to $stdout. false by default.
:tcp_acl : | the access control list for this server. See the ACL class from the main dRuby distribution.
:load_limit : | the maximum message size in bytes accepted by the server. Defaults to 25 MB (26214400).
:argc_limit : | the maximum number of arguments to a remote method accepted by the server. Defaults to 256.

The default values of these options can be modified on a class-wide basis by the class methods default_argc_limit, default_load_limit, default_acl, default_id_conv, and verbose=

If config_or_acl is not a hash, but is not nil, it is assumed to be the access control list for this server. See the :tcp_acl option for more details.

If no other server is currently set as the primary server, this will become the primary server.

The server will immediately start running in its own thread.

verbose()

Get the default value of the :verbose option.

verbose=(on)

Set the default value of the :verbose option.

See new(). The initial default value is false.

Public Instance methods

alive?()

Is this server alive?

check_insecure_method(obj, msg_id)

Check that a method is callable via dRuby.

obj is the object we want to invoke the method on. msg_id is the method name, as a Symbol.

If the method is an insecure method (see insecure_method?) a SecurityError is thrown. If the method is private or undefined, a NameError is thrown.

stop_service()

Stop this server.

to_id(obj)

Convert a local object to a dRuby reference.

to_obj(ref)

Convert a dRuby reference to the local object it refers to.

verbose()

Get whether the server is in verbose mode.

In verbose mode, failed calls are logged to stdout.

verbose=(v)

Set whether to operate in verbose mode.

In verbose mode, failed calls are logged to stdout.


Module: DRb::DRbServer::InvokeMethod18Mixin

Module | DRb::DRbServer::InvokeMethod18Mixin
In: | lib/drb/invokemethod.rb

Methods

block_yield perform_with_block

Public Instance methods

block_yield(x)
perform_with_block()


Class: DRb::DRbServerNotFound

Class | DRb::DRbServerNotFound
In: | lib/drb/drb.rb
Parent: | DRbError

Error raised by the DRb module when an attempt is made to refer to the context‘s current drb server but the context does not have one. See current_server.


Class: DRb::DRbTCPSocket

Class | DRb::DRbTCPSocket
In: | lib/drb/drb.rb
Parent: | Object

The default drb protocol.

Communicates over a TCP socket.

Methods

accept alive? close getservername new open open_server open_server_inaddr_any peeraddr recv_reply recv_request send_reply send_request stream uri_option

Attributes

uri [R] Get the URI that we are connected to.

Public Class methods

getservername()
new(uri, soc, config={})

Create a new DRbTCPSocket instance.

uri is the URI we are connected to. soc is the tcp socket we are bound to. config is our configuration.

open(uri, config)

Open a client connection to uri using configuration config.

open_server(uri, config)

Open a server listening for connections at uri using configuration config.

open_server_inaddr_any(host, port)
uri_option(uri, config)

Parse uri into a [uri, option] pair.

Public Instance methods

accept()

On the server side, for an instance returned by open_server, accept a client connection and return a new instance to handle the server‘s side of this client-server session.

alive?()

Check to see if this connection is alive.

close()

Close the connection.

If this is an instance returned by open_server, then this stops listening for new connections altogether. If this is an instance returned by open or by accept, then it closes this particular client-server session.

peeraddr()

Get the address of our TCP peer (the other end of the socket we are bound to.

recv_reply()

On the client side, receive a reply from the server.

recv_request()

On the server side, receive a request from the client.

send_reply(succ, result)

On the server side, send a reply to the client.

send_request(ref, msg_id, arg, b)

On the client side, send a request to the server.

stream()

Get the socket.


Class: DRb::DRbUNIXSocket

Class | DRb::DRbUNIXSocket
In: | lib/drb/unix.rb
Parent: | DRbTCPSocket

Methods

accept close new open open_server parse_uri set_sockopt uri_option

Constants

Max_try = 10 import from tempfile.rb

Public Class methods

new(uri, soc, config={}, server_mode = false)
open(uri, config)
open_server(uri, config)
parse_uri(uri)
uri_option(uri, config)

Public Instance methods

accept()
close()
set_sockopt(soc)


Module: DRb::DRbUndumped

Module | DRb::DRbUndumped
In: | lib/drb/drb.rb

Mixin module making an object undumpable or unmarshallable.

If an object which includes this module is returned by method called over drb, then the object remains in the server space and a reference to the object is returned, rather than the object being marshalled and moved into the client space.


Class: DRb::DRbUnknown

Class | DRb::DRbUnknown
In: | lib/drb/drb.rb
Parent: | Object

Class wrapping a marshalled object whose type is unknown locally.

If an object is returned by a method invoked over drb, but the class of the object is unknown in the client namespace, or the object is a constant unknown in the client namespace, then the still-marshalled object is returned wrapped in a DRbUnknown instance.

If this object is passed as an argument to a method invoked over drb, then the wrapped object is passed instead.

The class or constant name of the object can be read from the name attribute. The marshalled object is held in the buf attribute.

Methods

exception new reload

Attributes

buf | [R] | Buffer contained the marshalled, unknown object.
name | [R] | The name of the unknown thing. Class name for unknown objects; variable name for unknown constants.

Public Class methods

new(err, buf)

Create a new DRbUnknown object.

buf is a string containing a marshalled object that could not be unmarshalled. err is the error message that was raised when the unmarshalling failed. It is used to determine the name of the unmarshalled object.

Public Instance methods

exception()

Create a DRbUnknownError exception containing this object.

reload()

Attempt to load the wrapped marshalled object again.

If the class of the object is now known locally, the object will be unmarshalled and returned. Otherwise, a new but identical DRbUnknown object will be returned.


Class: DRb::DRbUnknownError

Class | DRb::DRbUnknownError
In: | lib/drb/drb.rb
Parent: | DRbError

An exception wrapping a DRb::DRbUnknown object

Methods

new

Attributes

unknown [R] Get the wrapped DRb::DRbUnknown object.

Public Class methods

new(unknown)

Create a new DRbUnknownError for the DRb::DRbUnknown object unknown


Class: DRb::ExtServ

Class | DRb::ExtServ
In: | lib/drb/extserv.rb
Parent: | Object

Methods

alive? front new stop_service

Included Modules

DRbUndumped

Attributes

server [R]

Public Class methods

new(there, name, server=nil)

Public Instance methods

alive?()
front()
stop_service()


Class: DRb::ExtServManager

Class | DRb::ExtServManager
In: | lib/drb/extservm.rb
Parent: | Object

Methods

command command= new regist service unregist

Included Modules

DRbUndumped

Attributes

uri [RW]

Public Class methods

command()
command=(cmd)
new()

Public Instance methods

regist(name, ro)
service(name)
unregist(name)


Class: DRb::GW

Class | DRb::GW
In: | lib/drb/gw.rb
Parent: | Object

Methods

[] []= new

Included Modules

MonitorMixin

Public Class methods

new()

Public Instance methods

[](key)
[]=(key, v)


Class: DRb::GWIdConv

Class | DRb::GWIdConv
In: | lib/drb/gw.rb
Parent: | DRbIdConv

Methods

to_obj

Public Instance methods

to_obj(ref)


Class: DRb::TimerIdConv

Class | DRb::TimerIdConv
In: | lib/drb/timeridconv.rb
Parent: | DRbIdConv

Methods

new to_id to_obj

Classes and Modules

Class DRb::TimerIdConv::TimerHolder2

Public Class methods

new(timeout=600)

Public Instance methods

to_id(obj)
to_obj(ref)


Class: DRb::TimerIdConv::TimerHolder2

Class | DRb::TimerIdConv::TimerHolder2
In: | lib/drb/timeridconv.rb
Parent: | Object

Methods

add fetch include? new peek

Included Modules

MonitorMixin

Classes and Modules

Class DRb::TimerIdConv::TimerHolder2::InvalidIndexError

Public Class methods

new(timeout=600)

Public Instance methods

add(obj)
fetch(key, dv=@sentinel)
include?(key)
peek(key)


Class: DRb::TimerIdConv::TimerHolder2::InvalidIndexError

Class | DRb::TimerIdConv::TimerHolder2::InvalidIndexError
In: | lib/drb/timeridconv.rb
Parent: | RuntimeError


Class: Data

Class | Data
In: | object.c
Parent: | Object


Class: DateTime

Class | DateTime
In: | lib/date/format.rb lib/date.rb
Parent: | Date

Class representing a date and time.

See the documentation to the file date.rb for an overview.

DateTime objects are immutable once created.

Other methods.

The following methods are defined in Date, but declared private there. They are made public in DateTime. They are documented here.

hour()

Get the hour-of-the-day of the time. This is given using the 24-hour clock, counting from midnight. The first hour after midnight is hour 0; the last hour of the day is hour 23.

min()

Get the minute-of-the-hour of the time.

sec()

Get the second-of-the-minute of the time.

sec_fraction()

Get the fraction of a second of the time. This is returned as a Rational. The unit is in days. I do NOT recommend you to use this method.

zone()

Get the time zone as a String. This is representation of the time offset such as "+1000", not the true time-zone name.

offset()

Get the time zone offset as a fraction of a day. This is returned as a Rational.

new_offset(of=0)

Create a new DateTime object, identical to the current one, except with a new time zone offset of of. of is the new offset from UTC as a fraction of a day.

Methods

_strptime civil commercial jd ordinal parse strftime strptime

External Aliases

civil -> new

Public Class methods

_strptime(str, fmt='%FT%T%z')
civil(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=ITALY)

Create a new DateTime object corresponding to the specified Civil Date and hour h, minute min, second s.

The 24-hour clock is used. Negative values of h, min, and sec are treating as counting backwards from the end of the next larger unit (e.g. a min of -2 is treated as 58). No wraparound is performed. If an invalid time portion is specified, an ArgumentError is raised.

of is the offset from UTC as a fraction of a day (defaults to 0). sg specifies the Day of Calendar Reform.

y defaults to -4712, m to 1, and d to 1; this is Julian Day Number day 0. The time values default to 0.

commercial(y=1582, w=41, d=5, h=0, min=0, s=0, of=0, sg=ITALY)

Create a new DateTime object corresponding to the specified Commercial Date and hour h, minute min, second s.

The 24-hour clock is used. Negative values of h, min, and sec are treating as counting backwards from the end of the next larger unit (e.g. a min of -2 is treated as 58). No wraparound is performed. If an invalid time portion is specified, an ArgumentError is raised.

of is the offset from UTC as a fraction of a day (defaults to 0). sg specifies the Day of Calendar Reform.

y defaults to 1582, w to 41, and d to 5; this is the Day of Calendar Reform for Italy and the Catholic countries. The time values default to 0.

jd(jd=0, h=0, min=0, s=0, of=0, sg=ITALY)

Create a new DateTime object corresponding to the specified Julian Day Number jd and hour h, minute min, second s.

The 24-hour clock is used. Negative values of h, min, and sec are treating as counting backwards from the end of the next larger unit (e.g. a min of -2 is treated as 58). No wraparound is performed. If an invalid time portion is specified, an ArgumentError is raised.

of is the offset from UTC as a fraction of a day (defaults to 0). sg specifies the Day of Calendar Reform.

All day/time values default to 0.

ordinal(y=-4712, d=1, h=0, min=0, s=0, of=0, sg=ITALY)

Create a new DateTime object corresponding to the specified Ordinal Date and hour h, minute min, second s.

The 24-hour clock is used. Negative values of h, min, and sec are treating as counting backwards from the end of the next larger unit (e.g. a min of -2 is treated as 58). No wraparound is performed. If an invalid time portion is specified, an ArgumentError is raised.

of is the offset from UTC as a fraction of a day (defaults to 0). sg specifies the Day of Calendar Reform.

y defaults to -4712, and d to 1; this is Julian Day Number day 0. The time values default to 0.

parse(str='-4712-01-01T00:00:00+00:00', comp=false, sg=ITALY)

Create a new DateTime object by parsing from a String, without specifying the format.

str is a String holding a date-time representation. comp specifies whether to interpret 2-digit years as 19XX (>= 69) or 20XX (< 69); the default is not to. The method will attempt to parse a date-time from the String using various heuristics; see _parse in date/format.rb for more details. If parsing fails, an ArgumentError will be raised.

The default str is ’-4712-01-01T00:00:00+00:00’; this is Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

strptime(str='-4712-01-01T00:00:00+00:00', fmt='%FT%T%z', sg=ITALY)

Create a new DateTime object by parsing from a String according to a specified format.

str is a String holding a date-time representation. fmt is the format that the date-time is in. See date/format.rb for details on supported formats.

The default str is ’-4712-01-01T00:00:00+00:00’, and the default fmt is ’%FT%T%z’. This gives midnight on Julian Day Number day 0.

sg specifies the Day of Calendar Reform.

An ArgumentError will be raised if str cannot be parsed.

Public Instance methods

strftime(fmt='%FT%T%:z')


Class: DefaultDisplay

Class | DefaultDisplay
In: | lib/rdoc/ri/ri_display.rb
Parent: | Object

A paging display module. Uses the ri_formatter class to do the actual presentation

Methods

display_class_info display_class_list display_method_info display_method_list display_usage list_known_classes list_known_names new

Included Modules

RiDisplay

Public Class methods

new(options)

Public Instance methods

display_class_info(klass, ri_reader)
display_class_list(namespaces)
display_method_info(method)
display_method_list(methods)

Display a list of method names

display_usage()
list_known_classes(classes)
list_known_names(names)


Class: Delegator

Class | Delegator
In: | lib/delegate.rb
Parent: | Object

Delegator is an abstract class used to build delegator pattern objects from subclasses. Subclasses should redefine __getobj__. For a concrete implementation, see SimpleDelegator.

Methods

__getobj__ marshal_dump marshal_load method_missing new respond_to?

External Aliases

initialize -> initialize_methods

Public Class methods

new(obj)

Pass in the obj to delegate method calls to. All methods supported by obj will be delegated to.

Public Instance methods

__getobj__()

This method must be overridden by subclasses and should return the object method calls are being delegated to.

marshal_dump()

Serialization support for the object returned by __getobj__.

marshal_load(obj)

Reinitializes delegation from a serialized object.

method_missing(m, *args)

Handles the magic of delegation through __getobj__.

respond_to?(m)

Checks for a method provided by this the delegate object by fowarding the call through __getobj__.


Class: EOFError

Class | EOFError
In: | io.c
Parent: | IOError


Class: ERB

Class | ERB
In: | lib/erb.rb
Parent: | Object

ERB — Ruby Templating

Introduction

ERB provides an easy to use but powerful templating system for Ruby. Using ERB, actual Ruby code can be added to any plain text document for the purposes of generating document information details and/or flow control.

A very simple example is this:

  require 'erb'

  x = 42
  template = ERB.new <<-EOF
    The value of x is: <%= x %>
  EOF
  puts template.result(binding)

Prints: The value of x is: 42

More complex examples are given below.

Recognized Tags

ERB recognizes certain tags in the provided template and converts them based on the rules below:

  <% Ruby code -- inline with output %>
  <%= Ruby expression -- replace with result %>
  <%# comment -- ignored -- useful in testing %>
  % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
  %% replaced with % if first thing on a line and % processing is used
  <%% or %%> -- replace with <% or %> respectively

All other text is passed through ERB filtering unchanged.

Options

There are several settings you can change when you use ERB:

  • the nature of the tags that are recognized;
  • the value of $SAFE under which the template is run;
  • the binding used to resolve local variables in the template.

See the ERB.new and ERB#result methods for more detail.

Examples

Plain Text

ERB is useful for any generic templating situation. Note that in this example, we use the convenient "% at start of line" tag, and we quote the template literally with %q{…} to avoid trouble with the backslash.

  require "erb"

  # Create template.
  template = %q{
    From:  James Edward Gray II <james@grayproductions.net>
    To:  <%= to %>
    Subject:  Addressing Needs

    <%= to[/\w+/] %>:

    Just wanted to send a quick note assuring that your needs are being
    addressed.

    I want you to know that my team will keep working on the issues,
    especially:

    <%# ignore numerous minor requests -- focus on priorities %>
    % priorities.each do |priority|
      * <%= priority %>
    % end

    Thanks for your patience.

    James Edward Gray II
  }.gsub(/^  /, '')

  message = ERB.new(template, 0, "%<>")

  # Set up template data.
  to = "Community Spokesman <spokesman@ruby_community.org>"
  priorities = [ "Run Ruby Quiz",
                 "Document Modules",
                 "Answer Questions on Ruby Talk" ]

  # Produce result.
  email = message.result
  puts email

Generates:

  From:  James Edward Gray II <james@grayproductions.net>
  To:  Community Spokesman <spokesman@ruby_community.org>
  Subject:  Addressing Needs

  Community:

  Just wanted to send a quick note assuring that your needs are being addressed.

  I want you to know that my team will keep working on the issues, especially:

      * Run Ruby Quiz
      * Document Modules
      * Answer Questions on Ruby Talk

  Thanks for your patience.

  James Edward Gray II

Ruby in HTML

ERB is often used in .rhtml files (HTML with embedded Ruby). Notice the need in this example to provide a special binding when the template is run, so that the instance variables in the Product object can be resolved.

  require "erb"

  # Build template data class.
  class Product
    def initialize( code, name, desc, cost )
      @code = code
      @name = name
      @desc = desc
      @cost = cost

      @features = [ ]
    end

    def add_feature( feature )
      @features << feature
    end

    # Support templating of member data.
    def get_binding
      binding
    end

    # ...
  end

  # Create template.
  template = %{
    <html>
      <head><title>Ruby Toys -- <%= @name %></title></head>
      <body>

        <h1><%= @name %> (<%= @code %>)</h1>
        <p><%= @desc %></p>

        <ul>
          <% @features.each do |f| %>
            <li><b><%= f %></b></li>
          <% end %>
        </ul>

        <p>
          <% if @cost < 10 %>
            <b>Only <%= @cost %>!!!</b>
          <% else %>
             Call for a price, today!
          <% end %>
        </p>

      </body>
    </html>
  }.gsub(/^  /, '')

  rhtml = ERB.new(template)

  # Set up template data.
  toy = Product.new( "TZ-1002",
                     "Rubysapien",
                     "Geek's Best Friend!  Responds to Ruby commands...",
                     999.95 )
  toy.add_feature("Listens for verbal commands in the Ruby language!")
  toy.add_feature("Ignores Perl, Java, and all C variants.")
  toy.add_feature("Karate-Chop Action!!!")
  toy.add_feature("Matz signature on left leg.")
  toy.add_feature("Gem studded eyes... Rubies, of course!")

  # Produce result.
  rhtml.run(toy.get_binding)

Generates (some blank lines removed):

   <html>
     <head><title>Ruby Toys -- Rubysapien</title></head>
     <body>

       <h1>Rubysapien (TZ-1002)</h1>
       <p>Geek's Best Friend!  Responds to Ruby commands...</p>

       <ul>
           <li><b>Listens for verbal commands in the Ruby language!</b></li>
           <li><b>Ignores Perl, Java, and all C variants.</b></li>
           <li><b>Karate-Chop Action!!!</b></li>
           <li><b>Matz signature on left leg.</b></li>
           <li><b>Gem studded eyes... Rubies, of course!</b></li>
       </ul>

       <p>
            Call for a price, today!
       </p>

     </body>
   </html>

Notes

There are a variety of templating solutions available in various Ruby projects:

  • ERB‘s big brother, eRuby, works the same but is written in C for speed;
  • Amrita (smart at producing HTML/XML);
  • cs/Template (written in C for speed);
  • RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
  • and others; search the RAA.

Rails, the web application framework, uses ERB to create views.

Methods

new result run set_eoutvar version

Classes and Modules

Module ERB::Util

Constants

Revision = '$Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $'

Attributes

filename | [RW] | The optional filename argument passed to Kernel#eval when the ERB code is run
src | [R] | The Ruby code generated by ERB

Public Class methods

new(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')

Constructs a new ERB object with the template specified in str.

An ERB object works by building a chunk of Ruby code that will output the completed template when run. If safe_level is set to a non-nil value, ERB code will be run in a separate thread with $SAFE set to the provided level.

If trim_mode is passed a String containing one or more of the following modifiers, ERB will adjust its code generation as listed:

    %  enables Ruby code processing for lines beginning with %
    <> omit newline for lines starting with <% and ending in %>
    >  omit newline for lines ending in %>

eoutvar can be used to set the name of the variable ERB will build up its output in. This is useful when you need to run multiple ERB templates through the same binding and/or when you want to control where output ends up. Pass the name of the variable to be used inside a String.

Example

 require "erb"

 # build data class
 class Listings
   PRODUCT = { :name => "Chicken Fried Steak",
               :desc => "A well messages pattie, breaded and fried.",
               :cost => 9.95 }

   attr_reader :product, :price

   def initialize( product = "", price = "" )
     @product = product
     @price = price
   end

   def build
     b = binding
     # create and run templates, filling member data variebles
     ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
       <%= PRODUCT[:name] %>
       <%= PRODUCT[:desc] %>
     END_PRODUCT
     ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
       <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
       <%= PRODUCT[:desc] %>
     END_PRICE
   end
 end

 # setup template data
 listings = Listings.new
 listings.build

 puts listings.product + "\n" + listings.price

Generates

 Chicken Fried Steak
 A well messages pattie, breaded and fried.

 Chicken Fried Steak -- 9.95
 A well messages pattie, breaded and fried.
version()

Returns revision information for the erb.rb module.

Public Instance methods

result(b=TOPLEVEL_BINDING)

Executes the generated ERB code to produce a completed template, returning the results of that code. (See ERB#new for details on how this process can be affected by safe_level.)

b accepts a Binding or Proc object which is used to set the context of code evaluation.

run(b=TOPLEVEL_BINDING)

Generate results and print them. (see ERB#result)

set_eoutvar(compiler, eoutvar = '_erbout')

Can be used to set eoutvar as described in ERB#new. It‘s probably easier to just use the constructor though, since calling this method requires the setup of an ERB compiler object.


Module: ERB::Util

Module | ERB::Util
In: | lib/erb.rb

A utility module for conversion routines, often handy in HTML generation.

Methods

h html_escape u url_encode

Public Instance methods

h(s)

Alias for html_escape

html_escape(s)

A utility method for escaping HTML tag characters in s.

  require "erb"
  include ERB::Util

  puts html_escape("is a > 0 & a < 10?")

Generates

  is a &gt; 0 &amp; a &lt; 10?
u(s)

Alias for url_encode

url_encode(s)

A utility method for encoding the String s as a URL.

  require "erb"
  include ERB::Util

  puts url_encode("Programming Ruby:  The Pragmatic Programmer's Guide")

Generates

  Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide


Module: EXCEL_CONST

Module | EXCEL_CONST
In: | ext/win32ole/tests/testWIN32OLE.rb


Module: Errno

Module | Errno
In: | error.c lib/webrick/compat.rb

compat.rb — cross platform compatibility

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2002 GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: compat.rb,v 1.6 2002/10/01 17:16:32 gotoyuzo Exp $

Classes and Modules

Class Errno::ECONNABORTED
Class Errno::ECONNRESET
Class Errno::EPROTO


Class: Errno::ECONNABORTED

Class | Errno::ECONNABORTED
In: | lib/webrick/compat.rb
Parent: | SystemCallError


Class: Errno::ECONNRESET

Class | Errno::ECONNRESET
In: | lib/webrick/compat.rb
Parent: | SystemCallError


Class: Errno::EPROTO

Class | Errno::EPROTO
In: | lib/webrick/compat.rb
Parent: | SystemCallError


Module: Exception2MessageMapper

Module | Exception2MessageMapper
In: | lib/e2mmap.rb

Methods

Fail Raise bind def_e2message def_exception fail

Classes and Modules

Module Exception2MessageMapper::E2MM

Constants

E2MM = Exception2MessageMapper

External Aliases

fail | -> | fail!
 | backward compatibility
e2mm_message | -> | message

Public Instance methods

Fail(err = nil, *rest)

Alias for Raise

Raise(err = nil, *rest)

Fail(err, *rest)

    err:        exception
    rest:       message arguments
bind(cl)
def_e2message(c, m)

def_e2message(c, m)

        c:  exception
        m:  message_form
    define exception c with message m.
def_exception(n, m, s = StandardError)

def_exception(n, m, s)

        n:  exception_name
        m:  message_form
        s:      superclass(default: StandardError)
    define exception named ``c'' with message m.
fail(err = nil, *rest)


Module: Exception2MessageMapper::E2MM

Module | Exception2MessageMapper::E2MM
In: |

Methods

Raise def_e2message def_exception e2mm_message extend_object extend_to

Public Class methods

Raise(klass = E2MM, err = nil, *rest)

Fail(klass, err, *rest)

    klass:  class to define exception under.
    err:        exception
    rest:       message arguments
def_e2message(k, c, m)

E2MM.def_exception(k, e, m)

        k:  class to define exception under.
        e:  exception
        m:  message_form
    define exception c with message m.
def_exception(k, n, m, s = StandardError)

E2MM.def_exception(k, n, m, s)

        k:  class to define exception under.
        n:  exception_name
        m:  message_form
        s:      superclass(default: StandardError)
    define exception named ``c'' with message m.
e2mm_message(klass, exp)
extend_object(cl)
extend_to(b)

backward compatibility


Class: FalseClass

Class | FalseClass
In: | object.c lib/yaml/rubytypes.rb
Parent: | Object

The global value false is the only instance of class FalseClass and represents a logically false value in boolean expressions. The class provides operators allowing false to participate correctly in logical expressions.

Methods

& ^ to_s to_yaml |

Public Instance methods

false & obj => false
nil & obj => false

And—Returns false. obj is always evaluated as it is the argument to a method call—there is no short-circuit evaluation in this case.

false ^ obj => true or false
nil ^ obj => true or false

Exclusive Or—If obj is nil or false, returns false; otherwise, returns true.

false.to_s => "false"

‘nuf said…

to_yaml( opts = {} )
false | obj => true or false
nil | obj => true or false

Or—Returns false if obj is nil or false; true otherwise.


Module: FileTest

Module | FileTest
In: | file.c

FileTest implements file test operations similar to those used in File::Stat. It exists as a standalone module, and its methods are also insinuated into the File class. (Note that this is not done by inclusion: the interpreter cheats).

Methods

blockdev? chardev? directory? executable? executable_real? exist? exists? file? grpowned? identical? owned? pipe? readable? readable_real? setgid? setuid? size size? socket? sticky? symlink? writable? writable_real? zero?

Public Instance methods

File.blockdev?(file_name) => true or false

Returns true if the named file is a block device.

File.chardev?(file_name) => true or false

Returns true if the named file is a character device.

File.directory?(file_name) => true or false

Returns true if the named file is a directory, false otherwise.

   File.directory?(".")
File.executable?(file_name) => true or false

Returns true if the named file is executable by the effective user id of this process.

File.executable_real?(file_name) => true or false

Returns true if the named file is executable by the real user id of this process.

File.exist?(file_name) => true or false
File.exists?(file_name) => true or false (obsolete)

Return true if the named file exists.

File.exist?(file_name) => true or false
File.exists?(file_name) => true or false (obsolete)

Return true if the named file exists.

File.file?(file_name) => true or false

Returns true if the named file exists and is a regular file.

File.grpowned?(file_name) => true or false

Returns true if the named file exists and the effective group id of the calling process is the owner of the file. Returns false on Windows.

File.identical?(file_1, file_2) => true or false

Returns true if the named files are identical.

    open("a", "w") {}
    p File.identical?("a", "a")      #=> true
    p File.identical?("a", "./a")    #=> true
    File.link("a", "b")
    p File.identical?("a", "b")      #=> true
    File.symlink("a", "c")
    p File.identical?("a", "c")      #=> true
    open("d", "w") {}
    p File.identical?("a", "d")      #=> false
File.owned?(file_name) => true or false

Returns true if the named file exists and the effective used id of the calling process is the owner of the file.

File.pipe?(file_name) => true or false

Returns true if the named file is a pipe.

File.readable?(file_name) => true or false

Returns true if the named file is readable by the effective user id of this process.

File.readable_real?(file_name) => true or false

Returns true if the named file is readable by the real user id of this process.

File.setgid?(file_name) => true or false

Returns true if the named file has the setgid bit set.

File.setuid?(file_name) => true or false

Returns true if the named file has the setuid bit set.

File.size(file_name) => integer

Returns the size of file_name.

File.size?(file_name) => Integer or nil

Returns nil if file_name doesn‘t exist or has zero size, the size of the file otherwise.

File.socket?(file_name) => true or false

Returns true if the named file is a socket.

File.sticky?(file_name) => true or false

Returns true if the named file has the sticky bit set.

File.symlink?(file_name) => true or false

Returns true if the named file is a symbolic link.

File.writable?(file_name) => true or false

Returns true if the named file is writable by the effective user id of this process.

File.writable_real?(file_name) => true or false

Returns true if the named file is writable by the real user id of this process.

File.zero?(file_name) => true or false

Returns true if the named file exists and has a zero size.


Module: FileUtils

Module | FileUtils
In: | lib/fileutils.rb lib/un.rb

fileutils.rb

Copyright (c) 2000-2006 Minero Aoki

This program is free software. You can distribute/modify this program under the same terms of ruby.

module FileUtils

Namespace for several file utility methods for copying, moving, removing, etc.

Module Functions

  cd(dir, options)
  cd(dir, options) {|dir| .... }
  pwd()
  mkdir(dir, options)
  mkdir(list, options)
  mkdir_p(dir, options)
  mkdir_p(list, options)
  rmdir(dir, options)
  rmdir(list, options)
  ln(old, new, options)
  ln(list, destdir, options)
  ln_s(old, new, options)
  ln_s(list, destdir, options)
  ln_sf(src, dest, options)
  cp(src, dest, options)
  cp(list, dir, options)
  cp_r(src, dest, options)
  cp_r(list, dir, options)
  mv(src, dest, options)
  mv(list, dir, options)
  rm(list, options)
  rm_r(list, options)
  rm_rf(list, options)
  install(src, dest, mode = <src's>, options)
  chmod(mode, list, options)
  chmod_R(mode, list, options)
  chown(user, group, list, options)
  chown_R(user, group, list, options)
  touch(list, options)

The options parameter is a hash of options, taken from the list :force, :noop, :preserve, and :verbose. :noop means that no changes are made. The other two are obvious. Each method documents the options that it honours.

All methods that have the concept of a "source" file or directory can take either one file or a list of files in that argument. See the method documentation for examples.

There are some `low level’ methods, which do not accept any option:

  copy_entry(src, dest, preserve = false, dereference = false)
  copy_file(src, dest, preserve = false, dereference = true)
  copy_stream(srcstream, deststream)
  remove_entry(path, force = false)
  remove_entry_secure(path, force = false)
  remove_file(path, force = false)
  compare_file(path_a, path_b)
  compare_stream(stream_a, stream_b)
  uptodate?(file, cmp_list)

module FileUtils::Verbose

This module has all methods of FileUtils module, but it outputs messages before acting. This equates to passing the :verbose flag to methods in FileUtils.

module FileUtils::NoWrite

This module has all methods of FileUtils module, but never changes files/directories. This equates to passing the :noop flag to methods in FileUtils.

module FileUtils::DryRun

This module has all methods of FileUtils module, but never changes files/directories. This equates to passing the :noop and :verbose flags to methods in FileUtils.

Methods

cd chdir chmod chmod_R chown chown_R cmp compare_file compare_stream copy copy_entry copy_file copy_stream cp cp_r fu_have_symlink? fu_world_writable? getwd identical? install link ln ln_s ln_sf makedirs mkdir mkdir_p mkpath move mv pwd remove remove_dir remove_entry remove_entry_secure remove_file rm rm_f rm_r rm_rf rmdir rmtree safe_unlink symlink touch uptodate?

Included Modules

StreamUtils_

Classes and Modules

Module FileUtils::DryRun
Module FileUtils::NoWrite
Module FileUtils::StreamUtils_
Module FileUtils::Verbose

Constants

METHODS = singleton_methods() - %w( private_module_function commands options have_option? options_of collect_method )

Public Instance methods

cd(dir, options = {}) {|dir| ...}

Options: verbose

Changes the current directory to the directory dir.

If this method is called with block, resumes to the old working directory after the block execution finished.

  FileUtils.cd('/', :verbose => true)   # chdir and report it
chdir(dir, options = {})

Alias for cd

chmod(mode, list, options = {})

Options: noop verbose

Changes permission bits on the named files (in list) to the bit pattern represented by mode.

  FileUtils.chmod 0755, 'somecommand'
  FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
  FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true
chmod_R(mode, list, options = {})

Options: noop verbose force

Changes permission bits on the named files (in list) to the bit pattern represented by mode.

  FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
chown(user, group, list, options = {})

Options: noop verbose

Changes owner and group on the named files (in list) to the user user and the group group. user and group may be an ID (Integer/String) or a name (String). If user or group is nil, this method does not change the attribute.

  FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
  FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
chown_R(user, group, list, options = {})

Options: noop verbose force

Changes owner and group on the named files (in list) to the user user and the group group recursively. user and group may be an ID (Integer/String) or a name (String). If user or group is nil, this method does not change the attribute.

  FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
  FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
cmp(a, b)

Alias for compare_file

compare_file(a, b)

Returns true if the contents of a file A and a file B are identical.

  FileUtils.compare_file('somefile', 'somefile')  #=> true
  FileUtils.compare_file('/bin/cp', '/bin/mv')    #=> maybe false
compare_stream(a, b)

Returns true if the contents of a stream a and b are identical.

copy(src, dest, options = {})

Alias for cp

copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)

Copies a file system entry src to dest. If src is a directory, this method copies its contents recursively. This method preserves file types, c.f. symlink, directory… (FIFO, device files and etc. are not supported yet)

Both of src and dest must be a path name. src must exist, dest must not exist.

If preserve is true, this method preserves owner, group, permissions and modified time.

If dereference_root is true, this method dereference tree root.

If remove_destination is true, this method removes each destination file before copy.

copy_file(src, dest, preserve = false, dereference = true)

Copies file contents of src to dest. Both of src and dest must be a path name.

copy_stream(src, dest)

Copies stream src to dest. src must respond to read(n) and dest must respond to write(str).

cp(src, dest, options = {})

Options: preserve noop verbose

Copies a file content src to dest. If dest is a directory, copies src to +dest/src+.

If src is a list of files, then dest must be a directory.

  FileUtils.cp 'eval.c', 'eval.c.org'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
  FileUtils.cp 'symlink', 'dest'   # copy content, "dest" is not a symlink
cp_r(src, dest, options = {})

Options: preserve noop verbose dereference_root remove_destination

Copies src to dest. If src is a directory, this method copies all its contents recursively. If dest is a directory, copies src to +dest/src+.

src can be a list of files.

  # Installing ruby library "mylib" under the site_ruby
  FileUtils.rm_r site_ruby + '/mylib', :force
  FileUtils.cp_r 'lib/', site_ruby + '/mylib'

  # Examples of copying several files to target directory.
  FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
  FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true

  # If you want to copy all contents of a directory instead of the
  # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
  # use following code.
  FileUtils.cp_r 'src/.', 'dest'     # cp_r('src', 'dest') makes src/dest,
                                     # but this doesn't.
fu_have_symlink?(
fu_world_writable?(st)
getwd()

Alias for pwd

identical?(a, b)

Alias for compare_file

install(src, dest, options = {})

Options: mode preserve noop verbose

If src is not same as dest, copies it and changes the permission mode to mode. If dest is a directory, destination is dest/src. This method removes destination before copy.

  FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
  FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true
link(src, dest, options = {})

Alias for ln

ln(src, dest, options = {})

Options: force noop verbose

ln(old, new, options = {})

Creates a hard link new which points to old. If new already exists and it is a directory, creates a link +new/old+. If new already exists and it is not a directory, raises Errno::EEXIST. But if :force option is set, overwrite new.

  FileUtils.ln 'gcc', 'cc', :verbose => true
  FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs'

ln(list, destdir, options = {})

Creates several hard links in a directory, with each one pointing to the item in list. If destdir is not a directory, raises Errno::ENOTDIR.

  include FileUtils
  cd '/sbin'
  FileUtils.ln %w(cp mv mkdir), '/bin'   # Now /sbin/cp and /bin/cp are linked.
ln_s(src, dest, options = {})

Options: force noop verbose

ln_s(old, new, options = {})

Creates a symbolic link new which points to old. If new already exists and it is a directory, creates a symbolic link +new/old+. If new already exists and it is not a directory, raises Errno::EEXIST. But if :force option is set, overwrite new.

  FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
  FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true

ln_s(list, destdir, options = {})

Creates several symbolic links in a directory, with each one pointing to the item in list. If destdir is not a directory, raises Errno::ENOTDIR.

If destdir is not a directory, raises Errno::ENOTDIR.

  FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin'
ln_sf(src, dest, options = {})

Options: noop verbose

Same as

  #ln_s(src, dest, :force)
makedirs(list, options = {})

Alias for mkdir_p

mkdir(list, options = {})

Options: mode noop verbose

Creates one or more directories.

  FileUtils.mkdir 'test'
  FileUtils.mkdir %w( tmp data )
  FileUtils.mkdir 'notexist', :noop => true  # Does not really create.
  FileUtils.mkdir 'tmp', :mode => 0700
mkdir_p(list, options = {})

Options: mode noop verbose

Creates a directory and all its parent directories. For example,

  FileUtils.mkdir_p '/usr/local/lib/ruby'

causes to make following directories, if it does not exist.

    * /usr
    * /usr/local
    * /usr/local/lib
    * /usr/local/lib/ruby

You can pass several directories at a time in a list.

mkpath(list, options = {})

Alias for mkdir_p

move(src, dest, options = {})

Alias for mv

mv(src, dest, options = {})

Options: force noop verbose

Moves file(s) src to dest. If file and dest exist on the different disk partition, the file is copied instead.

  FileUtils.mv 'badname.rb', 'goodname.rb'
  FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true  # no error

  FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
  FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
pwd()

Options: (none)

Returns the name of the current directory.

remove(list, options = {})

Alias for rm

remove_dir(path, force = false)

Removes a directory dir and its contents recursively. This method ignores StandardError if force is true.

remove_entry(path, force = false)

This method removes a file system entry path. path might be a regular file, a directory, or something. If path is a directory, remove it recursively.

See also remove_entry_secure.

remove_entry_secure(path, force = false)

This method removes a file system entry path. path shall be a regular file, a directory, or something. If path is a directory, remove it recursively. This method is required to avoid TOCTTOU (time-of-check-to-time-of-use) local security vulnerability of rm_r. rm_r causes security hole when:

  * Parent directory is world writable (including /tmp).
  * Removing directory tree includes world writable directory.
  * The system has symbolic link.

To avoid this security hole, this method applies special preprocess. If path is a directory, this method chown(2) and chmod(2) all removing directories. This requires the current process is the owner of the removing whole directory tree, or is the super user (root).

WARNING: You must ensure that ALL parent directories are not world writable. Otherwise this method does not work. Only exception is temporary directory like /tmp and /var/tmp, whose permission is 1777.

WARNING: Only the owner of the removing directory tree, or Unix super user (root) should invoke this method. Otherwise this method does not work.

For details of this security vulnerability, see Perl‘s case:

  http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
  http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452

For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].

remove_file(path, force = false)

Removes a file path. This method ignores StandardError if force is true.

rm(list, options = {})

Options: force noop verbose

Remove file(s) specified in list. This method cannot remove directories. All StandardErrors are ignored when the :force option is set.

  FileUtils.rm %w( junk.txt dust.txt )
  FileUtils.rm Dir.glob('*.so')
  FileUtils.rm 'NotExistFile', :force => true   # never raises exception
rm_f(list, options = {})

Options: noop verbose

Equivalent to

  #rm(list, :force => true)
rm_r(list, options = {})

Options: force noop verbose secure

remove files list[0] list[1]… If list[n] is a directory, removes its all contents recursively. This method ignores StandardError when :force option is set.

  FileUtils.rm_r Dir.glob('/tmp/*')
  FileUtils.rm_r '/', :force => true          #  :-)

WARNING: This method causes local vulnerability if one of parent directories or removing directory tree are world writable (including /tmp, whose permission is 1777), and the current process has strong privilege such as Unix super user (root), and the system has symbolic link. For secure removing, read the documentation of remove_entry_secure carefully, and set :secure option to true. Default is :secure=>false.

NOTE: This method calls remove_entry_secure if :secure option is set. See also remove_entry_secure.

rm_rf(list, options = {})

Options: noop verbose secure

Equivalent to

  #rm_r(list, :force => true)

WARNING: This method causes local vulnerability. Read the documentation of rm_r first.

rmdir(list, options = {})

Options: noop, verbose

Removes one or more directories.

  FileUtils.rmdir 'somedir'
  FileUtils.rmdir %w(somedir anydir otherdir)
  # Does not really remove directory; outputs message.
  FileUtils.rmdir 'somedir', :verbose => true, :noop => true
rmtree(list, options = {})

Alias for rm_rf

safe_unlink(list, options = {})

Alias for rm_f

symlink(src, dest, options = {})

Alias for ln_s

touch(list, options = {})

Options: noop verbose

Updates modification time (mtime) and access time (atime) of file(s) in list. Files are created if they don‘t exist.

  FileUtils.touch 'timestamp'
  FileUtils.touch Dir.glob('*.c');  system 'make'
uptodate?(new, old_list, options = nil)

Options: (none)

Returns true if newer is newer than all old_list. Non-existent files are older than any file.

  FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or    #       system 'make hello.o'


Module: FileUtils::DryRun

Module | FileUtils::DryRun
In: | lib/fileutils.rb

This module has all methods of FileUtils module, but never changes files/directories, with printing message before acting. This equates to passing the :noop and :verbose flag to methods in FileUtils.

Included Modules

FileUtils


Module: FileUtils::NoWrite

Module | FileUtils::NoWrite
In: | lib/fileutils.rb

This module has all methods of FileUtils module, but never changes files/directories. This equates to passing the :noop flag to methods in FileUtils.

Included Modules

FileUtils


Module: FileUtils::StreamUtils_

Module | FileUtils::StreamUtils_
In: | lib/fileutils.rb


Module: FileUtils::Verbose

Module | FileUtils::Verbose
In: | lib/fileutils.rb

This module has all methods of FileUtils module, but it outputs messages before acting. This equates to passing the :verbose flag to methods in FileUtils.

Included Modules

FileUtils


Module: Finalizer

Module | Finalizer
In: | lib/finalize.rb

Usage:

add dependency R_method(obj, dependant)

  add(obj, dependant, method = :finalize, *opt)
  add_dependency(obj, dependant, method = :finalize, *opt)

delete dependency R_method(obj, dependant)

  delete(obj_or_id, dependant, method = :finalize)
  delete_dependency(obj_or_id, dependant, method = :finalize)

delete dependency R_*(obj, dependant)

  delete_all_dependency(obj_or_id, dependant)

delete dependency R_method(*, dependant)

  delete_by_dependant(dependant, method = :finalize)

delete dependency R_*(*, dependant)

  delete_all_by_dependant(dependant)

delete all dependency R_*(*, *)

  delete_all

finalize the dependant connected by dependency R_method(obj, dependtant).

  finalize(obj_or_id, dependant, method = :finalize)
  finalize_dependency(obj_or_id, dependant, method = :finalize)

finalize all dependants connected by dependency R_*(obj, dependtant).

  finalize_all_dependency(obj_or_id, dependant)

finalize the dependant connected by dependency R_method(*, dependtant).

  finalize_by_dependant(dependant, method = :finalize)

finalize all dependants connected by dependency R_*(*, dependant).

  finalize_all_by_dependant(dependant)

finalize all dependency registered to the Finalizer.

  finalize_all

stop invoking Finalizer on GC.

  safe{..}

Methods

add_dependency delete_all_by_dependant delete_all_dependency delete_by_dependant delete_dependency finalize_all finalize_all_by_dependant finalize_all_dependency finalize_by_dependant finalize_dependency safe

Constants

RCS_ID = '-$Id: finalize.rb,v 1.4 1998/02/27 05:34:33 keiju Exp keiju $-'

External Aliases

add_dependency | -> | add
delete_dependency | -> | delete
finalize_dependency | -> | finalize

Public Class methods

add_dependency(obj, dependant, method = :finalize, *opt)

add dependency R_method(obj, dependant)

delete_all_by_dependant(dependant)

delete dependency R_*(*, dependant)

delete_all_dependency(id, dependant)

delete dependency R_*(obj, dependant)

delete_by_dependant(dependant, method = :finalize)

delete dependency R_method(*, dependant)

delete_dependency(id, dependant, method = :finalize)

delete dependency R_method(obj, dependant)

finalize_all()

finalize all dependants registered to the Finalizer.

finalize_all_by_dependant(dependant)

finalize all dependants connected by dependency R_*(*, dependtant)

finalize_all_dependency(id, dependant)

finalize all dependants connected by dependency R_*(obj, dependtant)

finalize_by_dependant(dependant, method = :finalize)

finalize the dependant connected by dependency R_method(*, dependtant)

finalize_dependency(id, dependant, method = :finalize)

finalize the depandant connected by dependency R_method(obj, dependtant)

safe() {|| ...}

method to call finalize_* safely.


Module: Find

Module | Find
In: | lib/find.rb

The Find module supports the top-down traversal of a set of file paths.

For example, to total the size of all files under your home directory, ignoring anything in a "dot" directory (e.g. $HOME/.ssh):

  require 'find'

  total_size = 0

  Find.find(ENV["HOME"]) do |path|
    if FileTest.directory?(path)
      if File.basename(path)[0] == ?.
        Find.prune       # Don't look any further into this directory.
      else
        next
      end
    else
      total_size += FileTest.size(path)
    end
  end

Methods

find prune

Public Instance methods

find(*paths) {|path| ...}

Calls the associated block with the name of every file and directory listed as arguments, then recursively on their subdirectories, and so on.

See the Find module documentation for an example.

prune()

Skips the current file or directory, restarting the loop with the next entry. If the current file is a directory, that directory will not be recursively entered. Meaningful only within the block associated with Find::find.

See the Find module documentation for an example.


Class: Fixnum

Class | Fixnum
In: | numeric.c lib/mathn.rb lib/rational.rb lib/rexml/xpath_parser.rb
Parent: | Integer

A Fixnum holds Integer values that can be represented in a native machine word (minus 1 bit). If any operation on a Fixnum exceeds this range, the value is automatically converted to a Bignum.

Fixnum objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object. Assignment does not alias Fixnum objects. There is effectively only one Fixnum object instance for any given integer value, so, for example, you cannot add a singleton method to a Fixnum.

Methods

% & * ** ** + - -@ / / < << <= <=> == > >= >> [] ^ abs dclone div divmod id2name induced_from modulo power! quo quo rdiv rpower size to_f to_s to_sym zero? | ~

Included Modules

Precision

Public Class methods

Fixnum.induced_from(obj) => fixnum

Convert obj to a Fixnum. Works with numeric parameters. Also works with Symbols, but this is deprecated.

Public Instance methods

fix % other => Numeric
fix.modulo(other) => Numeric

Returns fix modulo other. See Numeric.divmod for more information.

fix & other => integer

Bitwise AND.

fix * numeric => numeric_result

Performs multiplication: the class of the resulting object depends on the class of numeric and on the magnitude of the result.

fix ** other => Numeric

Raises fix to the other power, which may be negative or fractional.

  2 ** 3      #=> 8
  2 ** -1     #=> 0.5
  2 ** 0.5    #=> 1.4142135623731
**(other)

Alias for rpower

fix + numeric => numeric_result

Performs addition: the class of the resulting object depends on the class of numeric and on the magnitude of the result.

fix - numeric => numeric_result

Performs subtraction: the class of the resulting object depends on the class of numeric and on the magnitude of the result.

-fix => integer

Negates fix (which might return a Bignum).

fix / numeric => numeric_result
fix.div(numeric) => numeric_result

Performs division: the class of the resulting object depends on the class of numeric and on the magnitude of the result.

/(p1)

Alias for quo

fix < other => true or false

Returns true if the value of fix is less than that of other.

fix << count => integer

Shifts fix left count positions (right if count is negative).

fix <= other => true or false

Returns true if the value of fix is less thanor equal to that of other.

fix <=> numeric => -1, 0, +1

Comparison—Returns -1, 0, or +1 depending on whether fix is less than, equal to, or greater than numeric. This is the basis for the tests in Comparable.

fix == other

Return true if fix equals other numerically.

  1 == 2      #=> false
  1 == 1.0    #=> true
fix > other => true or false

Returns true if the value of fix is greater than that of other.

fix >= other => true or false

Returns true if the value of fix is greater than or equal to that of other.

fix >> count => integer

Shifts fix right count positions (left if count is negative).

fix[n] => 0, 1

Bit Reference—Returns the nth bit in the binary representation of fix, where fix[0] is the least significant bit.

   a = 0b11001100101010
   30.downto(0) do |n| print a[n] end

produces:

   0000000000000000011001100101010
fix ^ other => integer

Bitwise EXCLUSIVE OR.

fix.abs → aFixnum

Returns the absolute value of fix.

   -12345.abs   #=> 12345
   12345.abs    #=> 12345
dclone()
fix / numeric => numeric_result
fix.div(numeric) => numeric_result

Performs division: the class of the resulting object depends on the class of numeric and on the magnitude of the result.

fix.divmod(numeric) => array

See Numeric#divmod.

fix.id2name → string or nil

Returns the name of the object whose symbol id is fix. If there is no symbol in the symbol table with this value, returns nil. id2name has nothing to do with the Object.id method. See also Fixnum#to_sym, String#intern, and class Symbol.

   symbol = :@inst_var    #=> :@inst_var
   id     = symbol.to_i   #=> 9818
   id.id2name             #=> "@inst_var"
fix % other => Numeric
fix.modulo(other) => Numeric

Returns fix modulo other. See Numeric.divmod for more information.

power!(p1)

Alias for #**

fix.quo(numeric) => float

Returns the floating point result of dividing fix by numeric.

   654321.quo(13731)      #=> 47.6528293642124
   654321.quo(13731.24)   #=> 47.6519964693647
quo(other)

If Rational is defined, returns a Rational number instead of a Fixnum.

rdiv(p1)

Alias for quo

rpower(other)

Returns a Rational number if the result is in fact rational (i.e. other < 0).

fix.size → fixnum

Returns the number of bytes in the machine representation of a Fixnum.

   1.size            #=> 4
   -1.size           #=> 4
   2147483647.size   #=> 4
fix.to_f → float

Converts fix to a Float.

fix.to_s( base=10 ) → aString

Returns a string containing the representation of fix radix base (between 2 and 36).

   12345.to_s       #=> "12345"
   12345.to_s(2)    #=> "11000000111001"
   12345.to_s(8)    #=> "30071"
   12345.to_s(10)   #=> "12345"
   12345.to_s(16)   #=> "3039"
   12345.to_s(36)   #=> "9ix"
fix.to_sym → aSymbol

Returns the symbol whose integer value is fix. See also Fixnum#id2name.

   fred = :fred.to_i
   fred.id2name   #=> "fred"
   fred.to_sym    #=> :fred
fix.zero? => true or false

Returns true if fix is zero.

fix | other => integer

Bitwise OR.

~fix => integer

One‘s complement: returns a number where each bit is flipped.


Class: FloatDomainError

Class | FloatDomainError
In: | numeric.c
Parent: | RangeError


Class: Foo

Class | Foo
In: | lib/drb/extserv.rb
Parent: | Object

Methods

hello new to_s

Included Modules

DRbUndumped

Public Class methods

new(str)

Public Instance methods

hello(it)
to_s()


Module: Forwardable

Module | Forwardable
In: | lib/forwardable.rb

The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.

For example, say you have a class RecordCollection which contains an array @records. You could provide the lookup method record_number(), which simply calls #[] on the @records array, like this:

  class RecordCollection
    extend Forwardable
    def_delegator :@records, :[], :record_number
  end

Further, if you wish to provide the methods size, #<<, and map, all of which delegate to @records, this is how you can do it:

  class RecordCollection
    # extend Forwardable, but we did that above
    def_delegators :@records, :size, :<<, :map
  end

Also see the example at forwardable.rb.

Methods

def_delegator def_delegators def_instance_delegator def_instance_delegators

Attributes

debug [RW] force Forwardable to show up in stack backtraces of delegated methods

Public Instance methods

def_delegator(accessor, method, ali = method)

Alias for def_instance_delegator

def_delegators(accessor, *methods)

Alias for def_instance_delegators

def_instance_delegator(accessor, method, ali = method)

Defines a method method which delegates to obj (i.e. it calls the method of the same name in obj). If new_name is provided, it is used as the name for the delegate method.

See the examples at Forwardable and forwardable.rb.

def_instance_delegators(accessor, *methods)

Shortcut for defining multiple delegator methods, but with no provision for using a different name. The following two code samples have the same effect:

  def_delegators :@records, :size, :<<, :map

  def_delegator :@records, :size
  def_delegator :@records, :<<
  def_delegator :@records, :map

See the examples at Forwardable and forwardable.rb.


Module: GC

Module | GC
In: | gc.c

The GC module provides an interface to Ruby‘s mark and sweep garbage collection mechanism. Some of the underlying methods are also available via the ObjectSpace module.

Methods

disable enable garbage_collect start

Public Class methods

GC.disable => true or false

Disables garbage collection, returning true if garbage collection was already disabled.

   GC.disable   #=> false
   GC.disable   #=> true
GC.enable => true or false

Enables garbage collection, returning true if garbage collection was previously disabled.

   GC.disable   #=> false
   GC.enable    #=> true
   GC.enable    #=> false
GC.start => nil
gc.garbage_collect => nil
ObjectSpace.garbage_collect => nil

Initiates garbage collection, unless manually disabled.

Public Instance methods

GC.start => nil
gc.garbage_collect => nil
ObjectSpace.garbage_collect => nil

Initiates garbage collection, unless manually disabled.


Class: GServer

Class | GServer
In: | lib/gserver.rb
Parent: | Object

GServer implements a generic server, featuring thread pool management, simple logging, and multi-server management. See HttpServer in xmlrpc/httpserver.rb in the Ruby standard library for an example of GServer in action.

Any kind of application-level server can be implemented using this class. It accepts multiple simultaneous connections from clients, up to an optional maximum number. Several services (i.e. one service per TCP port) can be run simultaneously, and stopped at any time through the class method GServer.stop(port). All the threading issues are handled, saving you the effort. All events are optionally logged, but you can provide your own event handlers if you wish.

Example

Using GServer is simple. Below we implement a simple time server, run it, query it, and shut it down. Try this code in irb:

  require 'gserver'

  #
  # A server that returns the time in seconds since 1970.
  #
  class TimeServer < GServer
    def initialize(port=10001, *args)
      super(port, *args)
    end
    def serve(io)
      io.puts(Time.now.to_i)
    end
  end

  # Run the server with logging enabled (it's a separate thread).
  server = TimeServer.new
  server.audit = true                  # Turn logging on.
  server.start

  # *** Now point your browser to http://localhost:10001 to see it working ***

  # See if it's still running.
  GServer.in_service?(10001)           # -> true
  server.stopped?                      # -> false

  # Shut the server down gracefully.
  server.shutdown

  # Alternatively, stop it immediately.
  GServer.stop(10001)
  # or, of course, "server.stop".

All the business of accepting connections and exception handling is taken care of. All we have to do is implement the method that actually serves the client.

Advanced

As the example above shows, the way to use GServer is to subclass it to create a specific server, overriding the serve method. You can override other methods as well if you wish, perhaps to collect statistics, or emit more detailed logging.

  connecting
  disconnecting
  starting
  stopping

The above methods are only called if auditing is enabled.

You can also override log and error if, for example, you wish to use a more sophisticated logging system.

Methods

connecting connections disconnecting error in_service? join log new serve shutdown start starting stop stop stopped? stopping

Constants

DEFAULT_HOST = "127.0.0.1"

Attributes

audit | [RW]
debug | [RW]
host | [R]
maxConnections | [R]
port | [R]
stdlog | [RW]

Public Class methods

in_service?(port, host = DEFAULT_HOST)
new(port, host = DEFAULT_HOST, maxConnections = 4, stdlog = $stderr, audit = false, debug = false)
stop(port, host = DEFAULT_HOST)

Public Instance methods

connections()
join()
serve(io)
shutdown()
start(maxConnections = -1)
stop()
stopped?()

Protected Instance methods

connecting(client)
disconnecting(clientPort)
error(detail)
log(msg)
starting()
stopping()


Class: Generator

Class | Generator
In: | lib/generator.rb
Parent: | Object

Generator converts an internal iterator (i.e. an Enumerable object) to an external iterator.

Note that it is not very fast since it is implemented using continuations, which are currently slow.

Example

  require 'generator'

  # Generator from an Enumerable object
  g = Generator.new(['A', 'B', 'C', 'Z'])

  while g.next?
    puts g.next
  end

  # Generator from a block
  g = Generator.new { |g|
    for i in 'A'..'C'
      g.yield i
    end

    g.yield 'Z'
  }

  # The same result as above
  while g.next?
    puts g.next
  end

Methods

current each end? index new next next? pos rewind yield

Included Modules

Enumerable

Public Class methods

new(enum = nil, &block)

Creates a new generator either from an Enumerable object or from a block.

In the former, block is ignored even if given.

In the latter, the given block is called with the generator itself, and expected to call the yield method for each element.

Public Instance methods

current()

Returns the element at the current position.

each() {|self.next| ...}

Rewinds the generator and enumerates the elements.

end?()

Returns true if the generator has reached the end.

index()

Returns the current index (position) counting from zero.

next()

Returns the element at the current position and moves forward.

next?()

Returns true if the generator has not reached the end yet.

pos()

Returns the current index (position) counting from zero.

rewind()

Rewinds the generator.

yield(value)

Yields an element to the generator.


Module: Generators

Module | Generators
In: | lib/rdoc/generators/html_generator.rb lib/rdoc/generators/ri_generator.rb lib/rdoc/generators/xml_generator.rb lib/rdoc/generators/chm_generator.rb

Classes and Modules

Module Generators::MarkUp
Class Generators::AllReferences
Class Generators::CHMGenerator
Class Generators::ContextUser
Class Generators::HTMLGenerator
Class Generators::HTMLGeneratorInOne
Class Generators::HtmlClass
Class Generators::HtmlFile
Class Generators::HtmlMethod
Class Generators::HyperlinkHtml
Class Generators::RIGenerator
Class Generators::XMLGenerator

Constants

FILE_DIR | = | "files" | Name of sub-direcories that hold file and class/module descriptions
CLASS_DIR | = | "classes"
CSS_NAME | = | "rdoc-style.css"


Class: Generators::AllReferences

Class | Generators::AllReferences
In: | lib/rdoc/generators/html_generator.rb
Parent: | Object

Build a hash of all items that can be cross-referenced. This is used when we output required and included names: if the names appear in this hash, we can generate an html cross reference to the appropriate description. We also use this when parsing comment blocks: any decorated words matching an entry in this list are hyperlinked.

Methods

[] add keys reset

Public Class methods

[](name)
add(name, html_class)
keys()
reset()


Class: Generators::CHMGenerator

Class | Generators::CHMGenerator
In: | lib/rdoc/generators/chm_generator.rb
Parent: | HTMLGenerator

Methods

check_for_html_help_workshop compile_project create_contents_and_index create_help_project create_project_file for generate new

Constants

HHC_PATH = "c:/Program Files/HTML Help Workshop/hhc.exe"

Public Class methods

for(options)

Standard generator factory

new(*args)

Public Instance methods

check_for_html_help_workshop()
compile_project()

Invoke the windows help compiler to compiler the project

create_contents_and_index()

The contents is a list of all files and modules. For each we include as sub-entries the list of methods they contain. As we build the contents we also build an index file

create_help_project()

The project contains the project file, a table of contents and an index

create_project_file()

The project file links together all the various files that go to make up the help.

generate(info)

Generate the html as normal, then wrap it in a help project


Class: Generators::ContextUser

Class | Generators::ContextUser
In: | lib/rdoc/generators/html_generator.rb
Parent: | Object

A Context is built by the parser to represent a container: contexts hold classes, modules, methods, require lists and include lists. ClassModule and TopLevel are the context objects we process here

Methods

add_table_of_sections aref_to as_href build_alias_summary_list build_class_list build_constants_summary_list build_include_list build_method_detail_list build_method_summary_list build_requires_list collect_methods diagram_reference document_self find_symbol href new potentially_referenced_list url

Included Modules

MarkUp

Attributes

context [R]

Public Class methods

new(context, options)

Public Instance methods

add_table_of_sections()

create table of contents if we contain sections

aref_to(target)
as_href(from_path)

return a reference to outselves to be used as an href= the form depends on whether we‘re all in one file or in multiple files

build_alias_summary_list(section)

Build a list of aliases for which we couldn‘t find a corresponding method

build_class_list(level, from, section, infile=nil)

Build the structured list of classes and modules contained in this context.

build_constants_summary_list(section)

Build a list of constants

build_include_list(context)
build_method_detail_list(section)

Build an array of arrays of method details. The outer array has up to six entries, public, private, and protected for both class methods, the other for instance methods. The inner arrays contain a hash for each method

build_method_summary_list(path_prefix="")

Build a summary list of all the methods in this context

build_requires_list(context)
collect_methods()

Create a list of HtmlMethod objects for each method in the corresponding context object. If the @options.show_all variable is set (corresponding to the —all option, we include all methods, otherwise just the public ones.

diagram_reference(diagram)
document_self()
find_symbol(symbol, method=nil)

Find a symbol in ourselves or our parent

href(link, cls, name)

convenience method to build a hyperlink

potentially_referenced_list(array) {|i.name| ...}

Build a list from an array of Htmlxxx items. Look up each in the AllReferences hash: if we find a corresponding entry, we generate a hyperlink to it, otherwise just output the name. However, some names potentially need massaging. For example, you may require a Ruby file without the .rb extension, but the file names we know about may have it. To deal with this, we pass in a block which performs the massaging, returning an array of alternative names to match

url(target)


Class: Generators::HTMLGenerator

Class | Generators::HTMLGenerator
In: | lib/rdoc/generators/html_generator.rb
Parent: | Object

Methods

for gen_url generate new

Included Modules

MarkUp

Public Class methods

for(options)

Generators may need to return specific subclasses depending on the options they are passed. Because of this we create them using a factory

gen_url(path, target)

convert a target url to one that is relative to a given path

new(options)

Set up a new HTML generator. Basically all we do here is load up the correct output temlate

Public Instance methods

generate(toplevels)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.


Class: Generators::HTMLGeneratorInOne

Class | Generators::HTMLGeneratorInOne
In: | lib/rdoc/generators/html_generator.rb
Parent: | HTMLGenerator

Methods

build_class_list build_indices gen_an_index gen_class_index gen_file_index gen_into gen_method_index generate generate_xml new

Public Class methods

new(*args)

Public Instance methods

build_class_list(from, html_file, class_dir)
build_indices()

Generate:

  • a list of HtmlFile objects for each TopLevel object.
  • a list of HtmlClass objects for each first level class or module in the TopLevel objects
  • a complete list of all hyperlinkable terms (file, class, module, and method names)
gen_an_index(collection, title)
gen_class_index()
gen_file_index()
gen_into(list)
gen_method_index()
generate(info)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

generate_xml()

Generate all the HTML. For the one-file case, we generate all the information in to one big hash


Class: Generators::HtmlClass

Class | Generators::HtmlClass
In: | lib/rdoc/generators/html_generator.rb
Parent: | ContextUser

Wrap a ClassModule context

Methods

<=> build_attribute_list class_attribute_values http_url index_name name new parent_name value_hash write_on

Attributes

path [R]

Public Class methods

new(context, html_file, prefix, options)

Public Instance methods

<=>(other)
build_attribute_list(section)
class_attribute_values()
http_url(full_name, prefix)

return the relative file name to store this class in, which is also its url

index_name()
name()
parent_name()
value_hash()
write_on(f)


Class: Generators::HtmlFile

Class | Generators::HtmlFile
In: | lib/rdoc/generators/html_generator.rb
Parent: | ContextUser

Handles the mapping of a file‘s information to HTML. In reality, a file corresponds to a TopLevel object, containing modules, classes, and top-level methods. In theory it could contain attributes and aliases, but we ignore these for now.

Methods

<=> file_attribute_values filename_to_label http_url index_name new parent_name value_hash write_on

Attributes

name | [R]
path | [R]

Public Class methods

new(context, options, file_dir)

Public Instance methods

<=>(other)
file_attribute_values()
filename_to_label()
http_url(file_dir)
index_name()
parent_name()
value_hash()
write_on(f)


Class: Generators::HtmlMethod

Class | Generators::HtmlMethod
In: | lib/rdoc/generators/html_generator.rb
Parent: | Object

Methods

<=> add_line_numbers aliases all_methods aref as_href call_seq create_source_code_file description document_self find_symbol index_name markup_code name new params parent_name path reset section singleton visibility

Included Modules

MarkUp

Attributes

context | [R]
img_url | [R]
source_code | [R]
src_url | [R]

Public Class methods

all_methods()
new(context, html_class, options)
reset()

Public Instance methods

<=>(other)
add_line_numbers(src)

we rely on the fact that the first line of a source code listing has

   # File xxxxx, line dddd
aliases()
aref()
as_href(from_path)

return a reference to outselves to be used as an href= the form depends on whether we‘re all in one file or in multiple files

call_seq()
create_source_code_file(code_body)
description()
document_self()
find_symbol(symbol, method=nil)
index_name()
markup_code(tokens)

Given a sequence of source tokens, mark up the source code to make it look purty.

name()
params()
parent_name()
path()
section()
singleton()
visibility()


Class: Generators::HyperlinkHtml

Class | Generators::HyperlinkHtml
In: | lib/rdoc/generators/html_generator.rb
Parent: | SM::ToHtml

Subclass of the SM::ToHtml class that supports looking up words in the AllReferences list. Those that are found (like AllReferences in this comment) will be hyperlinked

Methods

gen_url handle_special_CROSSREF handle_special_HYPERLINK handle_special_TIDYLINK new

Public Class methods

new(from_path, context)

We need to record the html path of our caller so we can generate correct relative paths for any hyperlinks that we find

Public Instance methods

gen_url(url, text)

Generate a hyperlink for url, labeled with text. Handle the special cases for img: and link: described under handle_special_HYPEDLINK

handle_special_CROSSREF(special)

We‘re invoked when any text matches the CROSSREF pattern (defined in MarkUp). If we fine the corresponding reference, generate a hyperlink. If the name we‘re looking for contains no punctuation, we look for it up the module/class chain. For example, HyperlinkHtml is found, even without the Generators:: prefix, because we look for it in module Generators first.

handle_special_HYPERLINK(special)

And we‘re invoked with a potential external hyperlink mailto: just gets inserted. http: links are checked to see if they reference an image. If so, that image gets inserted using an <img> tag. Otherwise a conventional <a href> is used. We also support a special type of hyperlink, link:, which is a reference to a local file whose path is relative to the —op directory.

handle_special_TIDYLINK(special)

HEre‘s a hypedlink where the label is different to the URL

 <label>[url]


Module: Generators::MarkUp

Module | Generators::MarkUp
In: | lib/rdoc/generators/html_generator.rb

Handle common markup tasks for the various Html classes

Methods

cvs_url markup style_url

Public Instance methods

cvs_url(url, full_path)

Build a webcvs URL with the given ‘url’ argument. URLs with a ’%s’ in them get the file‘s path sprintfed into them; otherwise they‘re just catenated together.

markup(str, remove_para=false)

Convert a string in markup format into HTML. We keep a cached SimpleMarkup object lying around after the first time we‘re called per object.

style_url(path, css_name=nil)

Qualify a stylesheet URL; if if css_name does not begin with ’/’ or ‘http[s]://’, prepend a prefix relative to path. Otherwise, return it unmodified.


Class: Generators::RIGenerator

Class | Generators::RIGenerator
In: | lib/rdoc/generators/ri_generator.rb
Parent: | Object

Methods

for generate generate_class_info generate_method_info new process_class

Public Class methods

for(options)

Generators may need to return specific subclasses depending on the options they are passed. Because of this we create them using a factory

new(options)

Set up a new HTML generator. Basically all we do here is load up the correct output temlate

Public Instance methods

generate(toplevels)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

generate_class_info(cls)
generate_method_info(cls_desc, method)
process_class(from_class)


Class: Generators::XMLGenerator

Class | Generators::XMLGenerator
In: | lib/rdoc/generators/xml_generator.rb
Parent: | HTMLGenerator

Generate XML output as one big file

Methods

build_class_list build_indices for gen_an_index gen_class_index gen_file_index gen_into gen_method_index generate generate_xml new

Public Class methods

for(options)

Standard generator factory

new(*args)

Public Instance methods

build_class_list(from, html_file, class_dir)
build_indices()

Generate:

  • a list of HtmlFile objects for each TopLevel object.
  • a list of HtmlClass objects for each first level class or module in the TopLevel objects
  • a complete list of all hyperlinkable terms (file, class, module, and method names)
gen_an_index(collection, title)
gen_class_index()
gen_file_index()
gen_into(list)
gen_method_index()
generate(info)

Build the initial indices and output objects based on an array of TopLevel objects containing the extracted information.

generate_xml()

Generate all the HTML. For the one-file case, we generate all the information in to one big hash


Class: GetoptLong

Class | GetoptLong
In: | lib/getoptlong.rb
Parent: | Object

The GetoptLong class allows you to parse command line options similarly to the GNU getopt_long() C library call. Note, however, that GetoptLong is a pure Ruby implementation.

GetoptLong allows for POSIX-style options like —file as well as single letter options like -f

The empty option — (two minus symbols) is used to end option processing. This can be particularly important if options have optional arguments.

Here is a simple example of usage:

    # == Synopsis
    #
    # hello: greets user, demonstrates command line parsing
    #
    # == Usage
    #
    # hello [OPTION] ... DIR
    #
    # -h, --help:
    #    show help
    #
    # --repeat x, -n x:
    #    repeat x times
    #
    # --name [name]:
    #    greet user by name, if name not supplied default is John
    #
    # DIR: The directory in which to issue the greeting.

    require 'getoptlong'
    require 'rdoc/usage'

    opts = GetoptLong.new(
      [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
      [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
    )

    dir = nil
    name = nil
    repetitions = 1
    opts.each do |opt, arg|
      case opt
        when '--help'
          RDoc::usage
        when '--repeat'
          repetitions = arg.to_i
        when '--name'
          if arg == ''
            name = 'John'
          else
            name = arg
          end
      end
    end

    if ARGV.length != 1
      puts "Missing dir argument (try --help)"
      exit 0
    end

    dir = ARGV.shift

    Dir.chdir(dir)
    for i in (1..repetitions)
      print "Hello"
      if name
        print ", #{name}"
      end
      puts
    end

Example command line:

    hello -n 6 --name -- /tmp

Methods

each each_option error_message get get_option new ordering= set_error set_options terminate terminated?

Classes and Modules

Class GetoptLong::AmbigousOption
Class GetoptLong::Error
Class GetoptLong::InvalidOption
Class GetoptLong::MissingArgument
Class GetoptLong::NeedlessArgument

Constants

ORDERINGS | = | [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2] | Orderings.
ARGUMENT_FLAGS | = | [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1, OPTIONAL_ARGUMENT = 2] | Argument flags.
STATUS_TERMINATED | = | 0, 1, 2

External Aliases

quiet | -> | quiet?
 | `quiet?’ is an alias of `quiet’.
error | -> | error?
 | `error?’ is an alias of `error’.

Attributes

error | [R] | Examine whether an option processing is failed.
ordering | [R] | Return ordering.
quiet | [W] | Set/Unset `quiet’ mode.
quiet | [R] | Return the flag of `quiet’ mode.

Public Class methods

new(*arguments)

Set up option processing.

The options to support are passed to new() as an array of arrays. Each sub-array contains any number of String option names which carry the same meaning, and one of the following flags:

GetoptLong::NO_ARGUMENT : | Option does not take an argument.
GetoptLong::REQUIRED_ARGUMENT : | Option always takes an argument.
GetoptLong::OPTIONAL_ARGUMENT : | Option may or may not take an argument.

The first option name is considered to be the preferred (canonical) name. Other than that, the elements of each sub-array can be in any order.

Public Instance methods

each() {|option_name, option_argument| ...}

Iterator version of `get’.

The block is called repeatedly with two arguments: The first is the option name. The second is the argument which followed it (if any). Example: (’—opt’, ‘value’)

The option name is always converted to the first (preferred) name given in the original options to GetoptLong.new.

each_option()

Alias for each

error_message()

Return the appropriate error message in POSIX-defined format. If no error has occurred, returns nil.

get()

Get next option name and its argument, as an Array of two elements.

The option name is always converted to the first (preferred) name given in the original options to GetoptLong.new.

Example: [’—option’, ‘value’]

Returns nil if the processing is complete (as determined by STATUS_TERMINATED).

get_option()

Alias for get

ordering=(ordering)

Set the handling of the ordering of options and arguments. A RuntimeError is raised if option processing has already started.

The supplied value must be a member of GetoptLong::ORDERINGS. It alters the processing of options as follows:

REQUIRE_ORDER :

Options are required to occur before non-options.

Processing of options ends as soon as a word is encountered that has not been preceded by an appropriate option flag.

For example, if -a and -b are options which do not take arguments, parsing command line arguments of ’-a one -b two’ would result in ‘one’, ’-b’, ‘two’ being left in ARGV, and only (’-a’, ’’) being processed as an option/arg pair.

This is the default ordering, if the environment variable POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.)

PERMUTE :

Options can occur anywhere in the command line parsed. This is the default behavior.

Every sequence of words which can be interpreted as an option (with or without argument) is treated as an option; non-option words are skipped.

For example, if -a does not require an argument and -b optionally takes an argument, parsing ’-a one -b two three’ would result in (’-a’,’’) and (’-b’, ‘two’) being processed as option/arg pairs, and ‘one’,’three’ being left in ARGV.

If the ordering is set to PERMUTE but the environment variable POSIXLY_CORRECT is set, REQUIRE_ORDER is used instead. This is for compatibility with GNU getopt_long.

RETURN_IN_ORDER :

All words on the command line are processed as options. Words not preceded by a short or long option flag are passed as arguments with an option of ’’ (empty string).

For example, if -a requires an argument but -b does not, a command line of ’-a one -b two three’ would result in option/arg pairs of (’-a’, ‘one’) (’-b’, ’’), (’’, ‘two’), (’’, ‘three’) being processed.

set_options(*arguments)

Set options. Takes the same argument as GetoptLong.new.

Raises a RuntimeError if option processing has already started.

terminate()

Explicitly terminate option processing.

terminated?()

Returns true if option processing has terminated, false otherwise.

Protected Instance methods

set_error(type, message)

Set an error (protected).


Class: GetoptLong::AmbigousOption

Class | GetoptLong::AmbigousOption
In: | lib/getoptlong.rb
Parent: | Error


Class: GetoptLong::Error

Class | GetoptLong::Error
In: | lib/getoptlong.rb
Parent: | StandardError

Error types.


Class: GetoptLong::InvalidOption

Class | GetoptLong::InvalidOption
In: | lib/getoptlong.rb
Parent: | Error


Class: GetoptLong::MissingArgument

Class | GetoptLong::MissingArgument
In: | lib/getoptlong.rb
Parent: | Error


Class: GetoptLong::NeedlessArgument

Class | GetoptLong::NeedlessArgument
In: | lib/getoptlong.rb
Parent: | Error


Module: IE_CONST

Module | IE_CONST
In: | ext/win32ole/sample/ieconst.rb


Class: IOError

Class | IOError
In: | io.c
Parent: | StandardError


Class: IPAddr

Class | IPAddr
In: | lib/ipaddr.rb
Parent: | Object

IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.

Example

  require 'ipaddr'

  ipaddr1 = IPAddr.new "3ffe:505:2::1"

  p ipaddr1                   #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>

  p ipaddr1.to_s              #=> "3ffe:505:2::1"

  ipaddr2 = ipaddr1.mask(48)  #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>

  p ipaddr2.to_s              #=> "3ffe:505:2::"

  ipaddr3 = IPAddr.new "192.168.2.0/24"

  p ipaddr3                   #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>

Methods

& << == === >> hton include? inspect ip6_arpa ip6_int ipv4? ipv4_compat ipv4_compat? ipv4_mapped ipv4_mapped? ipv6? mask mask! native new new_ntoh ntop reverse set to_i to_s to_string | ~

Constants

IN4MASK | = | 0xffffffff
IN6MASK | = | 0xffffffffffffffffffffffffffffffff
IN6FORMAT | = | (["%.4x"] * 8).join(':')

Attributes

family [R] Returns the address family of this IP address.

Public Class methods

new(addr = '::', family = Socket::AF_UNSPEC)

Creates a new ipaddr containing the given human readable form of an IP address. It also accepts `address/prefixlen’ and `address/mask’. When prefixlen or mask is specified, it returns a masked ipaddr. IPv6 address may beenclosed with `[’ and `]’.

Although an address family is determined automatically from a specified address, you can specify an address family explicitly by the optional second argument.

new_ntoh(addr)

Creates a new ipaddr containing the given network byte ordered string form of an IP address.

ntop(addr)

Convert a network byte ordered string form of an IP address into human readable form.

Public Instance methods

&(other)

Returns a new ipaddr built by bitwise AND.

<<(num)

Returns a new ipaddr built by bitwise left shift.

==(other)

Returns true if two ipaddr are equal.

===(other)

Alias for include?

>>(num)

Returns a new ipaddr built by bitwise right-shift.

hton()

Returns a network byte ordered string form of the IP address.

include?(other)

Returns true if the given ipaddr is in the range.

e.g.:

  require 'ipaddr'
  net1 = IPAddr.new("192.168.2.0/24")
  p net1.include?(IPAddr.new("192.168.2.0"))        #=> true
  p net1.include?(IPAddr.new("192.168.2.255"))      #=> true
  p net1.include?(IPAddr.new("192.168.3.0"))        #=> false
inspect()

Returns a string containing a human-readable representation of the ipaddr. ("#<IPAddr: family:address/mask>")

ip6_arpa()

Returns a string for DNS reverse lookup compatible with RFC3172.

ip6_int()

Returns a string for DNS reverse lookup compatible with RFC1886.

ipv4?()

Returns true if the ipaddr is an IPv4 address.

ipv4_compat()

Returns a new ipaddr built by converting the native IPv4 address into an IPv4-compatible IPv6 address.

ipv4_compat?()

Returns true if the ipaddr is an IPv4-compatible IPv6 address.

ipv4_mapped()

Returns a new ipaddr built by converting the native IPv4 address into an IPv4-mapped IPv6 address.

ipv4_mapped?()

Returns true if the ipaddr is an IPv4-mapped IPv6 address.

ipv6?()

Returns true if the ipaddr is an IPv6 address.

mask(prefixlen)

Returns a new ipaddr built by masking IP address with the given prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)

native()

Returns a new ipaddr built by converting the IPv6 address into a native IPv4 address. If the IP address is not an IPv4-mapped or IPv4-compatible IPv6 address, returns self.

reverse()

Returns a string for DNS reverse lookup. It returns a string in RFC3172 form for an IPv6 address.

to_i()

Returns the integer representation of the ipaddr.

to_s()

Returns a string containing the IP address representation.

to_string()

Returns a string containing the IP address representation in canonical form.

|(other)

Returns a new ipaddr built by bitwise OR.

~()

Returns a new ipaddr built by bitwise negation.

Protected Instance methods

mask!(mask)
set(addr, *family)


Class: IPSocket

Class | IPSocket
In: | ext/socket/socket.c
Parent: | BasicSocket

IPSocket is the parent of TCPSocket and UDPSocket and implements functionality common to them.

A number of APIs in IPSocket, Socket, and their descendants return an address as an array. The members of that array are:

  • address family: A string like "AF_INET" or "AF_INET6" if it is one of the commonly used families, the string "unknown:#" (where `#’ is the address family number) if it is not one of the common ones. The strings map to the Socket::AF_* constants.
  • port: The port number.
  • name: Either the canonical name from looking the address up in the DNS, or the address in presentation format
  • address: The address in presentation format (a dotted decimal string for IPv4, a hex string for IPv6).

The address and port can be used directly to create sockets and to bind or connect them to the address.


Module: IRB

Module | IRB
In: | lib/irb/input-method.rb lib/irb/slex.rb lib/irb/cmd/load.rb lib/irb/cmd/chws.rb lib/irb/cmd/fork.rb lib/irb/cmd/nop.rb lib/irb/cmd/pushws.rb lib/irb/cmd/subirb.rb lib/irb/cmd/help.rb lib/irb/ext/loader.rb lib/irb/ext/multi-irb.rb lib/irb/ext/workspaces.rb lib/irb/ext/use-loader.rb lib/irb/ext/history.rb lib/irb/ext/change-ws.rb lib/irb/ext/tracer.rb lib/irb/ext/math-mode.rb lib/irb/ext/save-history.rb lib/irb/init.rb lib/irb/context.rb lib/irb/version.rb lib/irb/notifier.rb lib/irb/output-method.rb lib/irb/lc/ja/error.rb lib/irb/lc/error.rb lib/irb/extend-command.rb lib/irb/frame.rb lib/irb/locale.rb lib/irb/help.rb lib/irb/completion.rb lib/irb/workspace.rb lib/irb.rb
  irb/workspace-binding.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Methods

CurrentContext CurrentContext JobManager conf delete_caller init_config init_error initialize_tracer irb irb_abort irb_exit load_modules parse_opts print_usage rc_file rc_file_generators run_config setup start version

Classes and Modules

Module IRB::ContextExtender
Module IRB::ExtendCommand
Module IRB::ExtendCommandBundle
Module IRB::HistorySavingAbility
Module IRB::InputCompletor
Module IRB::IrbLoader
Module IRB::MethodExtender
Module IRB::Notifier
Class IRB::Abort
Class IRB::Context
Class IRB::FileInputMethod
Class IRB::Frame
Class IRB::History
Class IRB::InputMethod
Class IRB::Irb
Class IRB::JobManager
Class IRB::LoadAbort
Class IRB::Locale
Class IRB::OutputMethod
Class IRB::ReadlineInputMethod
Class IRB::SLex
Class IRB::StdioInputMethod
Class IRB::StdioOutputMethod
Class IRB::WorkSpace

Constants

STDIN_FILE_NAME = "(line)" InputMethod
    StdioInputMethod
    FileInputMethod
    (ReadlineInputMethod)
FEATURE_IOPT_CHANGE_VERSION = "1.9.0"
IRBRC_EXT = "rc"

Public Class methods

CurrentContext()
CurrentContext()
JobManager()
conf()
delete_caller()
init_config(ap_path)

@CONF default setting

init_error()
initialize_tracer()

initialize tracing function

irb(file = nil, *main)

invoke multi-irb

irb_abort(irb, exception = Abort)
irb_exit(irb, ret)
load_modules()

loading modules

parse_opts()

option analyzing

print_usage()
rc_file(ext = IRBRC_EXT)
rc_file_generators() {|proc{|rc| rc == "rc" ? irbrc : irbrc+rc| ...}

enumerate possible rc-file base name generators

run_config()

running config

setup(ap_path)

initialize config

start(ap_path = nil)

initialize IRB and start TOP_LEVEL irb

version()

IRB version method


Class: IRB::Abort

Class | IRB::Abort
In: | lib/irb.rb
Parent: | Exception


Class: IRB::Context

Class | IRB::Context
In: | lib/irb/ext/workspaces.rb lib/irb/ext/use-loader.rb lib/irb/ext/history.rb lib/irb/ext/change-ws.rb lib/irb/ext/tracer.rb lib/irb/ext/math-mode.rb lib/irb/ext/save-history.rb lib/irb/context.rb
Parent: | Object

Methods

change_workspace debug? debug_level= eval_history= evaluate exit file_input? history_file history_file= home_workspace init_save_history inspect inspect? inspect? inspect_mode= irb_level main math_mode= new pop_workspace prompt_mode= prompting? push_workspace save_history save_history= set_last_value set_last_value to_s use_loader use_loader= use_loader? use_readline= use_tracer= verbose? workspaces

Constants

NOPRINTING_IVARS | = | ["@last_value"]
NO_INSPECTING_IVARS | = | ["@irb", "@io"]
IDNAME_IVARS | = | ["@prompt_mode"]

External Aliases

set_last_value | -> | _set_last_value
use_tracer | -> | use_tracer?
math_mode | -> | math?
use_readline | -> | use_readline?
rc | -> | rc?
ignore_sigint | -> | ignore_sigint?
ignore_eof | -> | ignore_eof?
echo | -> | echo?
exit | -> | __exit__
inspect | -> | __inspect__
to_s | -> | __to_s__

Attributes

ap_name | [RW]
auto_indent_mode | [RW]
back_trace_limit | [RW]
debug_level | [R]
echo | [RW]
eval_history | [R]
ignore_eof | [RW]
ignore_sigint | [RW]
inspect_mode | [R]
io | [RW]
irb | [RW]
irb_name | [RW]
irb_name | [R]
irb_path | [RW]
last_value | [R]
load_modules | [RW]
math_mode | [R]
prompt_c | [RW]
prompt_i | [RW]
prompt_mode | [R]
prompt_n | [RW]
prompt_s | [RW]
rc | [RW]
return_format | [RW]
thread | [R]
use_readline | [R]
use_tracer | [R]
verbose | [RW]
workspace | [RW]
workspace_home | [R]

Public Class methods

new(irb, workspace = nil, input_method = nil, output_method = nil)

Arguments:

  input_method: nil -- stdin or readline
                String -- File
                other -- using this as InputMethod

Public Instance methods

change_workspace(*_main)
debug?()
debug_level=(value)
eval_history=(no)
evaluate(line, line_no)
exit(ret = 0)
file_input?()
history_file()
history_file=(hist)
home_workspace()
init_save_history()
inspect()
inspect?()
inspect?()
inspect_mode=(opt)
irb_level()
main()
math_mode=(opt)
pop_workspace()
prompt_mode=(mode)
prompting?()
push_workspace(*_main)
save_history()
save_history=(val)
set_last_value(value)
set_last_value(value)
to_s()

Alias for inspect

use_loader()
use_loader=(opt)
use_loader?()

Alias for use_loader

use_readline=(opt)
use_tracer=(opt)
verbose?()
workspaces()


Module: IRB::ContextExtender

Module | IRB::ContextExtender
In: | lib/irb/extend-command.rb

extension support for Context

Methods

def_extend_command install_extend_commands

Constants

CE = ContextExtender

Public Class methods

def_extend_command(cmd_name, load_file, *aliases)
install_extend_commands()


Module: IRB::ExtendCommand

Module | IRB::ExtendCommand
In: | lib/irb/cmd/load.rb lib/irb/cmd/chws.rb lib/irb/cmd/fork.rb lib/irb/cmd/nop.rb lib/irb/cmd/pushws.rb lib/irb/cmd/subirb.rb lib/irb/cmd/help.rb

Classes and Modules

Module IRB::ExtendCommand::Help
Class IRB::ExtendCommand::ChangeWorkspace
Class IRB::ExtendCommand::CurrentWorkingWorkspace
Class IRB::ExtendCommand::Foreground
Class IRB::ExtendCommand::Fork
Class IRB::ExtendCommand::IrbCommand
Class IRB::ExtendCommand::Jobs
Class IRB::ExtendCommand::Kill
Class IRB::ExtendCommand::Load
Class IRB::ExtendCommand::Nop
Class IRB::ExtendCommand::PopWorkspace
Class IRB::ExtendCommand::PushWorkspace
Class IRB::ExtendCommand::Require
Class IRB::ExtendCommand::Source
Class IRB::ExtendCommand::Workspaces


Class: IRB::ExtendCommand::ChangeWorkspace

Class | IRB::ExtendCommand::ChangeWorkspace
In: | lib/irb/cmd/chws.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute(*obj)


Class: IRB::ExtendCommand::CurrentWorkingWorkspace

Class | IRB::ExtendCommand::CurrentWorkingWorkspace
In: | lib/irb/cmd/chws.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute(*obj)


Class: IRB::ExtendCommand::Foreground

Class | IRB::ExtendCommand::Foreground
In: | lib/irb/cmd/subirb.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute(key)


Class: IRB::ExtendCommand::Fork

Class | IRB::ExtendCommand::Fork
In: | lib/irb/cmd/fork.rb
Parent: | Nop

Methods

execute

External Aliases

ExtendCommand -> exit

Public Instance methods

execute() {|| ...}


Module: IRB::ExtendCommand::Help

Module | IRB::ExtendCommand::Help
In: | lib/irb/cmd/help.rb

Methods

execute

Public Class methods

execute(context, *names)


Class: IRB::ExtendCommand::IrbCommand

Class | IRB::ExtendCommand::IrbCommand
In: | lib/irb/cmd/subirb.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute(*obj)


Class: IRB::ExtendCommand::Jobs

Class | IRB::ExtendCommand::Jobs
In: | lib/irb/cmd/subirb.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute()


Class: IRB::ExtendCommand::Kill

Class | IRB::ExtendCommand::Kill
In: | lib/irb/cmd/subirb.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute(*keys)


Class: IRB::ExtendCommand::Load

Class | IRB::ExtendCommand::Load
In: | lib/irb/cmd/load.rb
Parent: | Nop

Methods

execute

Included Modules

IrbLoader

Public Instance methods

execute(file_name, priv = nil)


Class: IRB::ExtendCommand::Nop

Class | IRB::ExtendCommand::Nop
In: | lib/irb/cmd/nop.rb
Parent: | Object

Methods

execute execute irb new

Attributes

irb_context [R]

Public Class methods

execute(conf, *opts)
new(conf)

Public Instance methods

execute(*opts)
irb()


Class: IRB::ExtendCommand::PopWorkspace

Class | IRB::ExtendCommand::PopWorkspace
In: | lib/irb/cmd/pushws.rb
Parent: | Workspaces

Methods

execute

Public Instance methods

execute(*obj)


Class: IRB::ExtendCommand::PushWorkspace

Class | IRB::ExtendCommand::PushWorkspace
In: | lib/irb/cmd/pushws.rb
Parent: | Workspaces

Methods

execute

Public Instance methods

execute(*obj)


Class: IRB::ExtendCommand::Require

Class | IRB::ExtendCommand::Require
In: | lib/irb/cmd/load.rb
Parent: | Nop

Methods

execute

Included Modules

IrbLoader

Public Instance methods

execute(file_name)


Class: IRB::ExtendCommand::Source

Class | IRB::ExtendCommand::Source
In: | lib/irb/cmd/load.rb
Parent: | Nop

Methods

execute

Included Modules

IrbLoader

Public Instance methods

execute(file_name)


Class: IRB::ExtendCommand::Workspaces

Class | IRB::ExtendCommand::Workspaces
In: | lib/irb/cmd/pushws.rb
Parent: | Nop

Methods

execute

Public Instance methods

execute(*obj)


Module: IRB::ExtendCommandBundle

Module | IRB::ExtendCommandBundle
In: | lib/irb/ext/use-loader.rb lib/irb/extend-command.rb

IRB extended command

Methods

def_extend_command extend_object install_alias_method install_extend_commands irb_context irb_exit irb_load irb_original_method_name irb_require

Constants

EXCB | = | ExtendCommandBundle
NO_OVERRIDE | = | 0
OVERRIDE_PRIVATE_ONLY | = | 0x01
OVERRIDE_ALL | = | 0x02

Public Class methods

def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)

aliases = [commans_alias, flag], …

extend_object(obj)
install_extend_commands()
irb_original_method_name(method_name)

Public Instance methods

install_alias_method(to, from, override = NO_OVERRIDE)

override = {NO_OVERRIDE, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL}

irb_context()
irb_exit(ret = 0)
irb_load(*opts, &b)
irb_require(*opts, &b)


Class: IRB::FileInputMethod

Class | IRB::FileInputMethod
In: | lib/irb/input-method.rb
Parent: | InputMethod

Methods

eof? gets new

Attributes

file_name [R]

Public Class methods

new(file)

Public Instance methods

eof?()
gets()


Class: IRB::Frame

Class | IRB::Frame
In: | lib/irb/frame.rb
Parent: | Object

Methods

bottom bottom new sender top top trace_func

Constants

INIT_STACK_TIMES | = | 3
CALL_STACK_OFFSET | = | 3

Public Class methods

bottom(n = 0)

singleton functions

new()
sender()
top(n = 0)

Public Instance methods

bottom(n = 0)
top(n = 0)
trace_func(event, file, line, id, binding)


Class: IRB::History

Class | IRB::History
In: | lib/irb/ext/history.rb
Parent: | Object

Methods

[] inspect new push size

External Aliases

inspect -> real_inspect

Public Class methods

new(size = 16)

Public Instance methods

[](idx)
inspect()
push(no, val)
size(size)


Module: IRB::HistorySavingAbility

Module | IRB::HistorySavingAbility
In: | lib/irb/ext/save-history.rb

Methods

create_finalizer extended load_history

Included Modules

Readline

Public Class methods

create_finalizer()
extended(obj)

Public Instance methods

load_history()


Module: IRB::InputCompletor

Module | IRB::InputCompletor
In: | lib/irb/completion.rb

Methods

select_message

Constants

ReservedWords | = | [ "BEGIN", "END", "alias", "and", "begin", "break", "case", "class", "def", "defined", "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", ]
CompletionProc | = | proc { |input| bind = IRB.conf[:MAIN_CONTEXT].workspace.binding
Operators | = | ["%", "&", "*", "**", "+", "-", "/", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>", "[]", "[]=", "^",]

Public Class methods

select_message(receiver, message, candidates)


Class: IRB::InputMethod

Class | IRB::InputMethod
In: | lib/irb/input-method.rb
Parent: | Object

Methods

gets new readable_atfer_eof?

Attributes

file_name | [R]
prompt | [RW]

Public Class methods

new(file = STDIN_FILE_NAME)

Public Instance methods

gets()
readable_atfer_eof?()


Class: IRB::Irb

Class | IRB::Irb
In: | lib/irb/ext/multi-irb.rb lib/irb.rb
Parent: | Object

irb interpriter main routine

Methods

eval_input inspect new output_value prompt signal_handle signal_handle signal_status suspend_context suspend_input_method suspend_name suspend_workspace

Attributes

context | [R]
scanner | [RW]

Public Class methods

new(workspace = nil, input_method = nil, output_method = nil)

Public Instance methods

eval_input()
inspect()
output_value()
prompt(prompt, ltype, indent, line_no)
signal_handle()
signal_handle()
signal_status(status) {|if @signal_status == :IN_LOAD| ...}
suspend_context(context) {|back_context| ...}
suspend_input_method(input_method) {|back_io| ...}
suspend_name(path = nil, name = nil) {|back_path, back_name| ...}
suspend_workspace(workspace) {|back_workspace| ...}


Module: IRB::IrbLoader

Module | IRB::IrbLoader
In: | lib/irb/ext/loader.rb

Methods

irb_load load_file old search_file_from_ruby_path source_file

External Aliases

load | -> | ruby_load
require | -> | ruby_require

Public Instance methods

irb_load(fn, priv = nil)
load_file(path, priv = nil)
old()
search_file_from_ruby_path(fn)
source_file(path)


Class: IRB::JobManager

Class | IRB::JobManager
In: | lib/irb/ext/multi-irb.rb
Parent: | Object

job management class

Methods

delete insert inspect irb kill main_irb main_thread n_jobs new search switch thread

Attributes

current_job [RW]

Public Class methods

new()

Public Instance methods

delete(key)
insert(irb)
inspect()
irb(key)
kill(*keys)
main_irb()
main_thread()
n_jobs()
search(key)
switch(key)
thread(key)


Class: IRB::LoadAbort

Class | IRB::LoadAbort
In: | lib/irb/ext/loader.rb
Parent: | Exception


Class: IRB::Locale

Class | IRB::Locale
In: | lib/irb/locale.rb
Parent: | Object

Methods

String find format gets load new print printf puts readline require

Constants

JPDefaultLocale | = | "ja"
LOCALE_DIR | = | "/lc/"

External Aliases

load -> toplevel_load

Attributes

lang [R]

Public Class methods

new(locale = nil)

Public Instance methods

String(mes)
find(file , paths = $:)
format(*opts)
gets(*rs)
load(file, priv=nil)
print(*opts)
printf(*opts)
puts(*opts)
readline(*rs)
require(file, priv = nil)


Module: IRB::MethodExtender

Module | IRB::MethodExtender
In: | lib/irb/extend-command.rb

Methods

def_post_proc def_pre_proc new_alias_name

Public Instance methods

def_post_proc(base_method, extend_method)
def_pre_proc(base_method, extend_method)
new_alias_name(name, prefix = "__alias_of__", postfix = "__")

return #{prefix}#{name}#{postfix}<num>


Module: IRB::Notifier

Module | IRB::Notifier
In: | lib/irb/notifier.rb

Methods

def_notifier

Classes and Modules

Class IRB::Notifier::AbstructNotifier
Class IRB::Notifier::CompositeNotifier
Class IRB::Notifier::LeveledNotifier
Class IRB::Notifier::NoMsgNotifier

Constants

D_NOMSG = NoMsgNotifier.new

Public Instance methods

def_notifier(prefix = "", output_method = StdioOutputMethod.new)


Class: IRB::Notifier::AbstructNotifier

Class | IRB::Notifier::AbstructNotifier
In: | lib/irb/notifier.rb
Parent: | Object

Methods

exec_if new notify? pp ppx print printf printn puts

Attributes

prefix [R]

Public Class methods

new(prefix, base_notifier)

Public Instance methods

exec_if() {|@base_notifier| ...}
notify?()
pp(*objs)
ppx(prefix, *objs)
print(*opts)
printf(format, *opts)
printn(*opts)
puts(*objs)


Class: IRB::Notifier::CompositeNotifier

Class | IRB::Notifier::CompositeNotifier
In: | lib/irb/notifier.rb
Parent: | AbstructNotifier

Methods

def_notifier level= level_notifier= new

External Aliases

level_notifier -> level

Attributes

level_notifier | [R]
notifiers | [R]

Public Class methods

new(prefix, base_notifier)

Public Instance methods

def_notifier(level, prefix = "")
level=(value)

Alias for level_notifier=

level_notifier=(value)


Class: IRB::Notifier::LeveledNotifier

Class | IRB::Notifier::LeveledNotifier
In: | lib/irb/notifier.rb
Parent: | AbstructNotifier

Methods

<=> new notify?

Included Modules

Comparable

Attributes

level [R]

Public Class methods

new(base, level, prefix)

Public Instance methods

<=>(other)
notify?()


Class: IRB::Notifier::NoMsgNotifier

Class | IRB::Notifier::NoMsgNotifier
In: | lib/irb/notifier.rb
Parent: | LeveledNotifier

Methods

new notify?

Public Class methods

new()

Public Instance methods

notify?()


Class: IRB::OutputMethod

Class | IRB::OutputMethod
In: | lib/irb/output-method.rb
Parent: | Object

OutputMethod

  StdioOutputMethod

Methods

foo parse_printf_format pp ppx print printf printn puts

Public Instance methods

foo(format)
parse_printf_format(format, opts)

% <¥Õ¥é¥°> [0- +] <ºÇ¾®¥Õ¥£¡¼¥ë¥ÉÉý> (*|*[1-9][0-9]*\$|[1-9][0-9]*) <ÀºÅÙ>.(*|*[1-9][0-9]*\$|[1-9][0-9]*|)? #<Ä¹¤µ½¤ÀµÊ¸»ú>(hh|h|l|ll|L|q|j|z|t) <ÊÑ´¹½¤ÀµÊ¸»ú>[diouxXeEfgGcsb%]

pp(*objs)
ppx(prefix, *objs)
print(*opts)
printf(format, *opts)

extend printf

printn(*opts)
puts(*objs)


Class: IRB::ReadlineInputMethod

Class | IRB::ReadlineInputMethod
In: | lib/irb/input-method.rb
Parent: | InputMethod

Methods

eof? gets line new readable_atfer_eof?

Included Modules

Readline

Public Class methods

new()

Public Instance methods

eof?()
gets()
line(line_no)
readable_atfer_eof?()


Class: IRB::SLex

Class | IRB::SLex
In: | lib/irb/slex.rb
Parent: | Object

Methods

create def_rule def_rules inspect match new postproc preproc search

Classes and Modules

Class IRB::SLex::Node

Constants

DOUT | = | Notifier::def_notifier("SLex::")
D_WARN | = | DOUT::def_notifier(1, "Warn: ")
D_DEBUG | = | DOUT::def_notifier(2, "Debug: ")
D_DETAIL | = | DOUT::def_notifier(4, "Detail: ")

Public Class methods

new()

Public Instance methods

create(token, preproc = nil, postproc = nil)
def_rule(token, preproc = nil, postproc = nil, &block)
def_rules(*tokens, &block)
inspect()
match(token)
postproc(token)

$BMW%A%’%C%/(B?

preproc(token, proc)
search(token)


Class: IRB::SLex::Node

Class | IRB::SLex::Node
In: | lib/irb/slex.rb
Parent: | Object

Methods

create_subnode match match_io new search

Attributes

postproc | [RW]
preproc | [RW]

Public Class methods

new(preproc = nil, postproc = nil)

if postproc is nil, this node is an abstract node. if postproc is non-nil, this node is a real node.

Public Instance methods

create_subnode(chrs, preproc = nil, postproc = nil)
match(chrs, op = "")

chrs: String

      character array
      io must have getc()/ungetc(); and ungetc() must be
      able to be called arbitrary number of times.
match_io(io, op = "")
search(chrs, opt = nil)


Class: IRB::StdioInputMethod

Class | IRB::StdioInputMethod
In: | lib/irb/input-method.rb
Parent: | InputMethod

Methods

eof? gets line new readable_atfer_eof?

Public Class methods

new()

Public Instance methods

eof?()
gets()
line(line_no)
readable_atfer_eof?()


Class: IRB::StdioOutputMethod

Class | IRB::StdioOutputMethod
In: | lib/irb/output-method.rb
Parent: | OutputMethod

Methods

print

Public Instance methods

print(*opts)


Class: IRB::WorkSpace

Class | IRB::WorkSpace
In: | lib/irb/ext/tracer.rb lib/irb/workspace.rb
Parent: | Object

Methods

evaluate evaluate filter_backtrace new

External Aliases

evaluate -> __evaluate__

Attributes

binding | [R]
main | [R]

Public Class methods

new(*main)

create new workspace. set self to main if specified, otherwise inherit main from TOPLEVEL_BINDING.

Public Instance methods

evaluate(context, statements, file = nil, line = nil)
evaluate(context, statements, file = __FILE__, line = __LINE__)
filter_backtrace(bt)

error message manipulator


Module: IXMLDOMAttribute

Module | IXMLDOMAttribute
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild hasChildNodes insertBefore lastChild name namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified text text= transformNode transformNodeToObject value value= xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

name()

BSTR name get name of the attribute

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
value()

VARIANT value string value of the attribute

value=(arg0)

VOID value string value of the attribute

xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMCDATASection

Module | IXMLDOMCDATASection
In: | ext/win32ole/sample/xml.rb

Methods

appendChild appendData attributes baseName childNodes cloneNode data data= dataType dataType= definition deleteData firstChild hasChildNodes insertBefore insertData lastChild length namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild replaceData selectNodes selectSingleNode specified splitText substringData text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
appendData(arg0)

VOID appendData append string to value

  BSTR arg0 --- data [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
data()

BSTR data value of the node

data=(arg0)

VOID data value of the node

dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

deleteData(arg0, arg1)

VOID deleteData delete string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
insertData(arg0, arg1)

VOID insertData insert string into value

  I4 arg0 --- offset [IN]
  BSTR arg1 --- data [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

length()

I4 length number of characters in value

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
replaceData(arg0, arg1, arg2)

VOID replaceData replace string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
  BSTR arg2 --- data [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

splitText(arg0)

IXMLDOMText splitText split the text node into two text nodes at the position specified

  I4 arg0 --- offset [IN]
substringData(arg0, arg1)

BSTR substringData retrieve substring of value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMCharacterData

Module | IXMLDOMCharacterData
In: | ext/win32ole/sample/xml.rb

Methods

appendChild appendData attributes baseName childNodes cloneNode data data= dataType dataType= definition deleteData firstChild hasChildNodes insertBefore insertData lastChild length namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild replaceData selectNodes selectSingleNode specified substringData text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
appendData(arg0)

VOID appendData append string to value

  BSTR arg0 --- data [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
data()

BSTR data value of the node

data=(arg0)

VOID data value of the node

dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

deleteData(arg0, arg1)

VOID deleteData delete string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
insertData(arg0, arg1)

VOID insertData insert string into value

  I4 arg0 --- offset [IN]
  BSTR arg1 --- data [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

length()

I4 length number of characters in value

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
replaceData(arg0, arg1, arg2)

VOID replaceData replace string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
  BSTR arg2 --- data [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

substringData(arg0, arg1)

BSTR substringData retrieve substring of value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMComment

Module | IXMLDOMComment
In: | ext/win32ole/sample/xml.rb

Methods

appendChild appendData attributes baseName childNodes cloneNode data data= dataType dataType= definition deleteData firstChild hasChildNodes insertBefore insertData lastChild length namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild replaceData selectNodes selectSingleNode specified substringData text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
appendData(arg0)

VOID appendData append string to value

  BSTR arg0 --- data [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
data()

BSTR data value of the node

data=(arg0)

VOID data value of the node

dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

deleteData(arg0, arg1)

VOID deleteData delete string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
insertData(arg0, arg1)

VOID insertData insert string into value

  I4 arg0 --- offset [IN]
  BSTR arg1 --- data [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

length()

I4 length number of characters in value

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
replaceData(arg0, arg1, arg2)

VOID replaceData replace string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
  BSTR arg2 --- data [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

substringData(arg0, arg1)

BSTR substringData retrieve substring of value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMDocument

Module | IXMLDOMDocument
In: | ext/win32ole/sample/xml.rb

Methods

abort appendChild async async= attributes baseName childNodes cloneNode createAttribute createCDATASection createComment createDocumentFragment createElement createEntityReference createNode createProcessingInstruction createTextNode dataType dataType= definition doctype documentElement firstChild getElementsByTagName hasChildNodes implementation insertBefore lastChild load loadXML namespaceURI nextSibling nodeFromID nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ondataavailable= onreadystatechange= ontransformnode= ownerDocument parentNode parseError parsed prefix preserveWhiteSpace preserveWhiteSpace= previousSibling readyState removeChild replaceChild resolveExternals resolveExternals= save selectNodes selectSingleNode specified text text= transformNode transformNodeToObject url validateOnParse validateOnParse= xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

abort()

VOID abort abort an asynchronous download

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
async()

BOOL async flag for asynchronous download

async=(arg0)

VOID async flag for asynchronous download

attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
createAttribute(arg0)

IXMLDOMAttribute createAttribute create an attribute node

  BSTR arg0 --- name [IN]
createCDATASection(arg0)

IXMLDOMCDATASection createCDATASection create a CDATA section node

  BSTR arg0 --- data [IN]
createComment(arg0)

IXMLDOMComment createComment create a comment node

  BSTR arg0 --- data [IN]
createDocumentFragment()

IXMLDOMDocumentFragment createDocumentFragment create a DocumentFragment node

createElement(arg0)

IXMLDOMElement createElement create an Element node

  BSTR arg0 --- tagName [IN]
createEntityReference(arg0)

IXMLDOMEntityReference createEntityReference create an entity reference node

  BSTR arg0 --- name [IN]
createNode(arg0, arg1, arg2)

IXMLDOMNode createNode create a node of the specified node type and name

  VARIANT arg0 --- type [IN]
  BSTR arg1 --- name [IN]
  BSTR arg2 --- namespaceURI [IN]
createProcessingInstruction(arg0, arg1)

IXMLDOMProcessingInstruction createProcessingInstruction create a processing instruction node

  BSTR arg0 --- target [IN]
  BSTR arg1 --- data [IN]
createTextNode(arg0)

IXMLDOMText createTextNode create a text node

  BSTR arg0 --- data [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

doctype()

IXMLDOMDocumentType doctype node corresponding to the DOCTYPE

documentElement()

IXMLDOMElement documentElement the root of the tree

firstChild()

IXMLDOMNode firstChild first child of the node

getElementsByTagName(arg0)

IXMLDOMNodeList getElementsByTagName build a list of elements by name

  BSTR arg0 --- tagName [IN]
hasChildNodes()

BOOL hasChildNodes

implementation()

IXMLDOMImplementation implementation info on this DOM implementation

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

load(arg0)

BOOL load load document from the specified XML source

  VARIANT arg0 --- xmlSource [IN]
loadXML(arg0)

BOOL loadXML load the document from a string

  BSTR arg0 --- bstrXML [IN]
namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeFromID(arg0)

IXMLDOMNode nodeFromID retrieve node from it‘s ID

  BSTR arg0 --- idString [IN]
nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ondataavailable=(arg0)

VOID ondataavailable register an ondataavailable event handler

onreadystatechange=(arg0)

VOID onreadystatechange register a readystatechange event handler

ontransformnode=(arg0)

VOID ontransformnode register an ontransformnode event handler

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parseError()

IXMLDOMParseError parseError get the last parser error

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

preserveWhiteSpace()

BOOL preserveWhiteSpace indicates whether the parser preserves whitespace

preserveWhiteSpace=(arg0)

VOID preserveWhiteSpace indicates whether the parser preserves whitespace

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

readyState()

I4 readyState get the state of the XML document

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
resolveExternals()

BOOL resolveExternals indicates whether the parser resolves references to external DTD/Entities/Schema

resolveExternals=(arg0)

VOID resolveExternals indicates whether the parser resolves references to external DTD/Entities/Schema

save(arg0)

VOID save save the document to a specified desination

  VARIANT arg0 --- desination [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
url()

BSTR url get the URL for the loaded XML document

validateOnParse()

BOOL validateOnParse indicates whether the parser performs validation

validateOnParse=(arg0)

VOID validateOnParse indicates whether the parser performs validation

xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMDocumentFragment

Module | IXMLDOMDocumentFragment
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMDocumentType

Module | IXMLDOMDocumentType
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition entities firstChild hasChildNodes insertBefore lastChild name namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= notations ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

entities()

IXMLDOMNamedNodeMap entities a list of entities in the document

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

name()

BSTR name name of the document type (root of the tree)

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

notations()

IXMLDOMNamedNodeMap notations a list of notations in the document

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMElement

Module | IXMLDOMElement
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild getAttribute getAttributeNode getElementsByTagName hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= normalize ownerDocument parentNode parsed prefix previousSibling removeAttribute removeAttributeNode removeChild replaceChild selectNodes selectSingleNode setAttribute setAttributeNode specified tagName text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

getAttribute(arg0)

VARIANT getAttribute look up the string value of an attribute by name

  BSTR arg0 --- name [IN]
getAttributeNode(arg0)

IXMLDOMAttribute getAttributeNode look up the attribute node by name

  BSTR arg0 --- name [IN]
getElementsByTagName(arg0)

IXMLDOMNodeList getElementsByTagName build a list of elements by name

  BSTR arg0 --- tagName [IN]
hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

normalize()

VOID normalize collapse all adjacent text nodes in sub-tree

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeAttribute(arg0)

VOID removeAttribute remove an attribute by name

  BSTR arg0 --- name [IN]
removeAttributeNode(arg0)

IXMLDOMAttribute removeAttributeNode remove the specified attribute

  IXMLDOMAttribute arg0 --- DOMAttribute [IN]
removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
setAttribute(arg0, arg1)

VOID setAttribute set the string value of an attribute by name

  BSTR arg0 --- name [IN]
  VARIANT arg1 --- value [IN]
setAttributeNode(arg0)

IXMLDOMAttribute setAttributeNode set the specified attribute on the element

  IXMLDOMAttribute arg0 --- DOMAttribute [IN]
specified()

BOOL specified indicates whether node is a default value

tagName()

BSTR tagName get the tagName of the element

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMEntity

Module | IXMLDOMEntity
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= notationName ownerDocument parentNode parsed prefix previousSibling publicId removeChild replaceChild selectNodes selectSingleNode specified systemId text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

notationName()

BSTR notationName the name of the notation

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

publicId()

VARIANT publicId the public ID

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

systemId()

VARIANT systemId the system ID

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMEntityReference

Module | IXMLDOMEntityReference
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMImplementation

Module | IXMLDOMImplementation
In: | ext/win32ole/sample/xml.rb

Methods

hasFeature

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

hasFeature(arg0, arg1)

BOOL hasFeature

  BSTR arg0 --- feature [IN]
  BSTR arg1 --- version [IN]


Module: IXMLDOMNamedNodeMap

Module | IXMLDOMNamedNodeMap
In: | ext/win32ole/sample/xml.rb

Methods

getNamedItem getQualifiedItem item length nextNode removeNamedItem removeQualifiedItem reset setNamedItem

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

getNamedItem(arg0)

IXMLDOMNode getNamedItem lookup item by name

  BSTR arg0 --- name [IN]
getQualifiedItem(arg0, arg1)

IXMLDOMNode getQualifiedItem lookup the item by name and namespace

  BSTR arg0 --- baseName [IN]
  BSTR arg1 --- namespaceURI [IN]
item()

PTR item collection of nodes

  I4 arg0 --- index [IN]
length()

I4 length number of nodes in the collection

nextNode()

IXMLDOMNode nextNode get next node from iterator

removeNamedItem(arg0)

IXMLDOMNode removeNamedItem remove item by name

  BSTR arg0 --- name [IN]
removeQualifiedItem(arg0, arg1)

IXMLDOMNode removeQualifiedItem remove the item by name and namespace

  BSTR arg0 --- baseName [IN]
  BSTR arg1 --- namespaceURI [IN]
reset()

VOID reset reset the position of iterator

setNamedItem(arg0)

IXMLDOMNode setNamedItem set item by name

  IXMLDOMNode arg0 --- newItem [IN]


Module: IXMLDOMNode

Module | IXMLDOMNode
In: | ext/win32ole/sample/xml.rb

Core DOM node interface

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMNodeList

Module | IXMLDOMNodeList
In: | ext/win32ole/sample/xml.rb

Methods

item length nextNode reset

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

item()

PTR item collection of nodes

  I4 arg0 --- index [IN]
length()

I4 length number of nodes in the collection

nextNode()

IXMLDOMNode nextNode get next node from iterator

reset()

VOID reset reset the position of iterator


Module: IXMLDOMNotation

Module | IXMLDOMNotation
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode dataType dataType= definition firstChild hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling publicId removeChild replaceChild selectNodes selectSingleNode specified systemId text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

publicId()

VARIANT publicId the public ID

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

systemId()

VARIANT systemId the system ID

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMParseError

Module | IXMLDOMParseError
In: | ext/win32ole/sample/xml.rb

structure for reporting parser errors

Methods

errorCode filepos line linepos reason srcText url

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

errorCode()

I4 errorCode the error code

filepos()

I4 filepos the absolute file position in the XML document containing the error

line()

I4 line the line number in the XML document where the error occurred

linepos()

I4 linepos the character position in the line containing the error

reason()

BSTR reason the cause of the error

srcText()

BSTR srcText the data where the error occurred

url()

BSTR url the URL of the XML document containing the error


Module: IXMLDOMProcessingInstruction

Module | IXMLDOMProcessingInstruction
In: | ext/win32ole/sample/xml.rb

Methods

appendChild attributes baseName childNodes cloneNode data data= dataType dataType= definition firstChild hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified target text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
data()

BSTR data the data

data=(arg0)

VOID data the data

dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

target()

BSTR target the target

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLDOMText

Module | IXMLDOMText
In: | ext/win32ole/sample/xml.rb

Methods

appendChild appendData attributes baseName childNodes cloneNode data data= dataType dataType= definition deleteData firstChild hasChildNodes insertBefore insertData lastChild length namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild replaceData selectNodes selectSingleNode specified splitText substringData text text= transformNode transformNodeToObject xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
appendData(arg0)

VOID appendData append string to value

  BSTR arg0 --- data [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
data()

BSTR data value of the node

data=(arg0)

VOID data value of the node

dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

deleteData(arg0, arg1)

VOID deleteData delete string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
firstChild()

IXMLDOMNode firstChild first child of the node

hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
insertData(arg0, arg1)

VOID insertData insert string into value

  I4 arg0 --- offset [IN]
  BSTR arg1 --- data [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

length()

I4 length number of characters in value

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
replaceData(arg0, arg1, arg2)

VOID replaceData replace string within the value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
  BSTR arg2 --- data [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

splitText(arg0)

IXMLDOMText splitText split the text node into two text nodes at the position specified

  I4 arg0 --- offset [IN]
substringData(arg0, arg1)

BSTR substringData retrieve substring of value

  I4 arg0 --- offset [IN]
  I4 arg1 --- count [IN]
text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Module: IXMLHttpRequest

Module | IXMLHttpRequest
In: | ext/win32ole/sample/xml.rb

IXMLHttpRequest Interface

Methods

abort getAllResponseHeaders getResponseHeader onreadystatechange= open readyState responseBody responseStream responseText responseXML send setRequestHeader status statusText

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

abort()

VOID abort Abort HTTP request

getAllResponseHeaders()

BSTR getAllResponseHeaders Get all HTTP response headers

getResponseHeader(arg0)

BSTR getResponseHeader Get HTTP response header

  BSTR arg0 --- bstrHeader [IN]
onreadystatechange=(arg0)

VOID onreadystatechange Register a complete event handler

open(arg0, arg1, arg2=nil, arg3=nil, arg4=nil)

VOID open Open HTTP connection

  BSTR arg0 --- bstrMethod [IN]
  BSTR arg1 --- bstrUrl [IN]
  VARIANT arg2 --- varAsync [IN]
  VARIANT arg3 --- bstrUser [IN]
  VARIANT arg4 --- bstrPassword [IN]
readyState()

I4 readyState Get ready state

responseBody()

VARIANT responseBody Get response body

responseStream()

VARIANT responseStream Get response body

responseText()

BSTR responseText Get response body

responseXML()

DISPATCH responseXML Get response body

send(arg0=nil)

VOID send Send HTTP request

  VARIANT arg0 --- varBody [IN]
setRequestHeader(arg0, arg1)

VOID setRequestHeader Add HTTP request header

  BSTR arg0 --- bstrHeader [IN]
  BSTR arg1 --- bstrValue [IN]
status()

I4 status Get HTTP status code

statusText()

BSTR statusText Get HTTP status text


Module: IXTLRuntime

Module | IXTLRuntime
In: | ext/win32ole/sample/xml.rb

XTL runtime object

Methods

absoluteChildNumber ancestorChildNumber appendChild attributes baseName childNodes childNumber cloneNode dataType dataType= definition depth firstChild formatDate formatIndex formatNumber formatTime hasChildNodes insertBefore lastChild namespaceURI nextSibling nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ownerDocument parentNode parsed prefix previousSibling removeChild replaceChild selectNodes selectSingleNode specified text text= transformNode transformNodeToObject uniqueID xml

Included Modules

WIN32OLE::VARIANT

Attributes

lastargs [R]

Public Instance methods

absoluteChildNumber(arg0)

I4 absoluteChildNumber

  IXMLDOMNode arg0 --- pNode [IN]
ancestorChildNumber(arg0, arg1)

I4 ancestorChildNumber

  BSTR arg0 --- bstrNodeName [IN]
  IXMLDOMNode arg1 --- pNode [IN]
appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

childNumber(arg0)

I4 childNumber

  IXMLDOMNode arg0 --- pNode [IN]
cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

depth(arg0)

I4 depth

  IXMLDOMNode arg0 --- pNode [IN]
firstChild()

IXMLDOMNode firstChild first child of the node

formatDate(arg0, arg1, arg2=nil)

BSTR formatDate

  VARIANT arg0 --- varDate [IN]
  BSTR arg1 --- bstrFormat [IN]
  VARIANT arg2 --- varDestLocale [IN]
formatIndex(arg0, arg1)

BSTR formatIndex

  I4 arg0 --- lIndex [IN]
  BSTR arg1 --- bstrFormat [IN]
formatNumber(arg0, arg1)

BSTR formatNumber

  R8 arg0 --- dblNumber [IN]
  BSTR arg1 --- bstrFormat [IN]
formatTime(arg0, arg1, arg2=nil)

BSTR formatTime

  VARIANT arg0 --- varTime [IN]
  BSTR arg1 --- bstrFormat [IN]
  VARIANT arg2 --- varDestLocale [IN]
hasChildNodes()

BOOL hasChildNodes

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
uniqueID(arg0)

I4 uniqueID

  IXMLDOMNode arg0 --- pNode [IN]
xml()

BSTR xml return the XML source for the node and each of its descendants


Class: Iconv

Class | Iconv
In: | ext/iconv/iconv.c
Parent: | Data

Document-class: Iconv::BrokenLibrary

Detected a bug of underlying iconv(3) libray.

  • returns an error without setting errno properly

Methods

charset_map close conv iconv iconv new open

Classes and Modules

Module Iconv::Failure
Class Iconv::BrokenLibrary
Class Iconv::IllegalSequence
Class Iconv::InvalidCharacter
Class Iconv::InvalidEncoding
Class Iconv::OutOfRange

Public Class methods

Iconv.charset_map

Returns the map from canonical name to system dependent name.

Iconv.conv(to, from, str)

Document-method: Iconv::conv

Shorthand for

  Iconv.iconv(to, from, str).join

See Iconv.iconv.

Iconv.iconv(to, from, *strs)

Shorthand for

  Iconv.open(to, from) { |cd|
    (strs + [nil]).collect { |s| cd.iconv(s) }
  }

Parameters

to, from: | see Iconv.new
strs: | strings to be converted

Exceptions

Exceptions thrown by Iconv.new, Iconv.open and Iconv#iconv.

Iconv.new(to, from)

Creates new code converter from a coding-system designated with from to another one designated with to.

Parameters

to: | encoding name for destination
from: | encoding name for source

Exceptions

TypeError: | if to or from aren‘t String
InvalidEncoding: | if designated converter couldn‘t find out
SystemCallError: | if iconv_open(3) fails
Iconv.open(to, from) { |iconv| ... }

Equivalent to Iconv.new except that when it is called with a block, it yields with the new instance and closes it, and returns the result which returned from the block.

Public Instance methods

close()

Finishes conversion.

After calling this, calling Iconv#iconv will cause an exception, but multiple calls of close are guaranteed to end successfully.

Returns a string containing the byte sequence to change the output buffer to its initial shift state.

Iconv.iconv(to, from, *strs)

Shorthand for

  Iconv.open(to, from) { |cd|
    (strs + [nil]).collect { |s| cd.iconv(s) }
  }

Parameters

to, from: | see Iconv.new
strs: | strings to be converted

Exceptions

Exceptions thrown by Iconv.new, Iconv.open and Iconv#iconv.


Class: Iconv::BrokenLibrary

Class | Iconv::BrokenLibrary
In: | ext/iconv/iconv.c
Parent: | RuntimeError

Detected a bug of underlying iconv(3) libray.

  • returns an error without setting errno properly

Included Modules

Iconv::Failure


Module: Iconv::Failure

Module | Iconv::Failure
In: | ext/iconv/iconv.c

Base attributes for Iconv exceptions.

Methods

failed inspect new success

Public Class methods

Iconv.new(to, from)

Creates new code converter from a coding-system designated with from to another one designated with to.

Parameters

to: | encoding name for destination
from: | encoding name for source

Exceptions

TypeError: | if to or from aren‘t String
InvalidEncoding: | if designated converter couldn‘t find out
SystemCallError: | if iconv_open(3) fails

Public Instance methods

failed

Returns substring of the original string passed to Iconv that starts at the character caused the exception.

inspect

Returns inspected string like as: #<class: success, failed>

success

Returns string(s) translated successfully until the exception occurred.

  • In the case of failure occurred within Iconv.iconv, returned value is an array of strings translated successfully preceding failure and the last element is string on the way.


Class: Iconv::IllegalSequence

Class | Iconv::IllegalSequence
In: | ext/iconv/iconv.c
Parent: | ArgError

Input conversion stopped due to an input byte that does not belong to the input codeset, or the output codeset does not contain the character.

Included Modules

Iconv::Failure


Class: Iconv::InvalidCharacter

Class | Iconv::InvalidCharacter
In: | ext/iconv/iconv.c
Parent: | ArgError

Input conversion stopped due to an incomplete character or shift sequence at the end of the input buffer.

Included Modules

Iconv::Failure


Class: Iconv::InvalidEncoding

Class | Iconv::InvalidEncoding
In: | ext/iconv/iconv.c
Parent: | ArgError

Requested coding-system is not available on this system.

Included Modules

Iconv::Failure


Class: Iconv::OutOfRange

Class | Iconv::OutOfRange
In: | ext/iconv/iconv.c
Parent: | RuntimeError

Iconv library internal error. Must not occur.

Included Modules

Iconv::Failure


Class: IndexError

Class | IndexError
In: | error.c
Parent: | StandardError


Class: Interrupt

Class | Interrupt
In: | error.c
Parent: | SignalException


Class: InvalidArgument

Class | InvalidArgument
In: | lib/optparse.rb
Parent: | ParseError

Raises when the given argument does not match required format.


Class: InvalidOption

Class | InvalidOption
In: | lib/optparse.rb
Parent: | ParseError

Raises when switch is undefined.


Module: Kconv

Module | Kconv
In: | ext/nkf/lib/kconv.rb

Kanji Converter for Ruby.

Methods

guess guess_old iseuc issjis isutf8 kconv toeuc tojis tosjis toutf16 toutf8

Constants

AUTO | = | NKF::AUTO | Auto-Detect
JIS | = | NKF::JIS | ISO-2022-JP
EUC | = | NKF::EUC | EUC-JP
SJIS | = | NKF::SJIS | Shift_JIS
BINARY | = | NKF::BINARY | BINARY
NOCONV | = | NKF::NOCONV | NOCONV
ASCII | = | NKF::ASCII | ASCII
UTF8 | = | NKF::UTF8 | UTF-8
UTF16 | = | NKF::UTF16 | UTF-16
UTF32 | = | NKF::UTF32 | UTF-32
UNKNOWN | = | NKF::UNKNOWN | UNKNOWN
REVISION | = | %q$Revision: 11708 $ | Revision of kconv.rb
RegexpShiftjis | = | /\A(?: [\x00-\x7f\xa1-\xdf] | [\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc] )*\z/nx | Regexp of Shift_JIS string (private constant)
RegexpEucjp | = | /\A(?: [\x00-\x7f] | \x8e [\xa1-\xdf] | \x8f [\xa1-\xfe] [\xa1-\xfe] | [\xa1-\xfe] [\xa1-\xfe] )*\z/nx | Regexp of EUC-JP string (private constant)
RegexpUtf8 | = | /\A(?: [\x00-\x7f] | [\xc2-\xdf] [\x80-\xbf] | \xe0 [\xa0-\xbf] [\x80-\xbf] | [\xe1-\xef] [\x80-\xbf] [\x80-\xbf] | \xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] | [\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] | \xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf] )*\z/nx | Regexp of UTF-8 string (private constant)

Public Instance methods

Kconv.guess(str) → integer

Guess input encoding by NKF.guess2

Kconv.guess_old(str) → integer

Guess input encoding by NKF.guess1

Kconv.iseuc(str) → obj or nil

Returns whether input encoding is EUC-JP or not.

Note don‘t expect this return value is MatchData.

Kconv.issjis(str) → obj or nil

Returns whether input encoding is Shift_JIS or not.

Note don‘t expect this return value is MatchData.

Kconv.isutf8(str) → obj or nil

Returns whether input encoding is UTF-8 or not.

Note don‘t expect this return value is MatchData.

Kconv.kconv(str, out_code, in_code = Kconv::AUTO)

Convert str to out_code. out_code and in_code are given as constants of Kconv.

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want to decode them, use NKF.nkf.

Kconv.toeuc(str) → string

Convert str to EUC-JP

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-exm0’, str).

Kconv.tojis(str) → string

Convert str to ISO-2022-JP

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-jxm0’, str).

Kconv.tosjis(str) → string

Convert str to Shift_JIS

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-sxm0’, str).

Kconv.toutf16(str) → string

Convert str to UTF-16

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-w16xm0’, str).

Kconv.toutf8(str) → string

Convert str to UTF-8

Note This method decode MIME encoded string and convert halfwidth katakana to fullwidth katakana. If you don‘t want it, use NKF.nkf(’-wxm0’, str).


Class: List

Class | List
In: | lib/optparse.rb
Parent: | Object

Simple option list providing mapping from short and/or long option string to OptionParser::Switch and mapping from acceptable argument to matching pattern and converter pair. Also provides summary feature.

Methods

accept append complete each_option new prepend reject search summarize

Attributes

atype | [R] | Map from acceptable argument types to pattern and converter pairs.
list | [R] | List of all switches and summary string.
long | [R] | Map from long style option switches to actual switch objects.
short | [R] | Map from short style option switches to actual switch objects.

Public Class methods

new()

Just initializes all instance variables.

Public Instance methods

accept(t, pat = /.*/nm, &block)

See OptionParser.accept.

append(*args)

Appends switch at the tail of the list, and associates short, long and negated long options. Arguments are:

switch: | OptionParser::Switch instance to be inserted.
short_opts: | List of short style options.
long_opts: | List of long style options.
nolong_opts: | List of long style options with "no-" prefix.
  append(switch, short_opts, long_opts, nolong_opts)
complete(id, opt, icase = false, *pat, &block)

Searches list id for opt and the optional patterns for completion pat. If icase is true, the search is case insensitive. The result is returned or yielded if a block is given. If it isn‘t found, nil is returned.

each_option(&block)

Iterates over each option, passing the option to the block.

prepend(*args)

Inserts switch at the head of the list, and associates short, long and negated long options. Arguments are:

switch: | OptionParser::Switch instance to be inserted.
short_opts: | List of short style options.
long_opts: | List of long style options.
nolong_opts: | List of long style options with "no-" prefix.
  prepend(switch, short_opts, long_opts, nolong_opts)
reject(t)

See OptionParser.reject.

search(id, key) {|val| ...}

Searches key in id list. The result is returned or yielded if a block is given. If it isn‘t found, nil is returned.

summarize(*args) {|""| ...}

Creates the summary table, passing each line to the block (without newline). The arguments args are passed along to the summarize method which is called on every option.


Class: LoadError

Class | LoadError
In: | error.c
Parent: | ScriptError


Class: LocalJumpError

Class | LocalJumpError
In: | eval.c
Parent: | StandardError

Methods

exit_value reason

Public Instance methods

exit_value()

call_seq:

  local_jump_error.exit_value  => obj

Returns the exit value associated with this LocalJumpError.

local_jump_error.reason => symbol

The reason this block was terminated: :break, :redo, :retry, :next, :return, or :noreason.


Class: Logger

Class | Logger
In: | lib/logger.rb
Parent: | Object

Simple logging utility.

Author: | NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
Documentation: | NAKAMURA, Hiroshi and Gavin Sinclair
License: | You can redistribute it and/or modify it under the same terms of Ruby‘s license; either the dual license version in 2003, or any later version.
Revision: | $Id: logger.rb 11708 2007-02-12 23:01:19Z shyouhei $

Description

The Logger class provides a simple but sophisticated logging utility that anyone can use because it‘s included in the Ruby 1.8.x standard library.

The HOWTOs below give a code-based overview of Logger‘s usage, but the basic concept is as follows. You create a Logger object (output to a file or elsewhere), and use it to log messages. The messages will have varying levels (info, error, etc), reflecting their varying importance. The levels, and their meanings, are:

FATAL: | an unhandleable error that results in a program crash
ERROR: | a handleable error condition
WARN: | a warning
INFO: | generic (useful) information about system operation
DEBUG: | low-level information for developers

So each message has a level, and the Logger itself has a level, which acts as a filter, so you can control the amount of information emitted from the logger without having to remove actual messages.

For instance, in a production system, you may have your logger(s) set to INFO (or WARN if you don‘t want the log files growing large with repetitive information). When you are developing it, though, you probably want to know about the program‘s internal state, and would set them to DEBUG.

Example

A simple example demonstrates the above explanation:

  log = Logger.new(STDOUT)
  log.level = Logger::WARN

  log.debug("Created logger")
  log.info("Program started")
  log.warn("Nothing to do!")

  begin
    File.each_line(path) do |line|
      unless line =~ /^(\w+) = (.*)$/
        log.error("Line in wrong format: #{line}")
      end
    end
  rescue => err
    log.fatal("Caught exception; exiting")
    log.fatal(err)
  end

Because the Logger‘s level is set to WARN, only the warning, error, and fatal messages are recorded. The debug and info messages are silently discarded.

Features

There are several interesting features that Logger provides, like auto-rolling of log files, setting the format of log messages, and specifying a program name in conjunction with the message. The next section shows you how to achieve these things.

HOWTOs

How to create a logger

The options below give you various choices, in more or less increasing complexity.

  1. Create a logger which logs messages to STDERR/STDOUT.
      logger = Logger.new(STDERR)
  logger = Logger.new(STDOUT)
  2. Create a logger for the file which has the specified name.
      logger = Logger.new('logfile.log')
  3. Create a logger for the specified file.
      file = File.open('foo.log', File::WRONLY | File::APPEND)
  # To create new (and to remove old) logfile, add File::CREAT like;
  #   file = open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
  logger = Logger.new(file)
  4. Create a logger which ages logfile once it reaches a certain size. Leave 10 "old log files" and each file is about 1,024,000 bytes.
      logger = Logger.new('foo.log', 10, 1024000)
  5. Create a logger which ages logfile daily/weekly/monthly.
      logger = Logger.new('foo.log', 'daily')
  logger = Logger.new('foo.log', 'weekly')
  logger = Logger.new('foo.log', 'monthly')

How to log a message

Notice the different methods (fatal, error, info) being used to log messages of various levels. Other methods in this family are warn and debug. add is used below to log a message of an arbitrary (perhaps dynamic) level.

  1. Message in block.
      logger.fatal { "Argument 'foo' not given." }
  2. Message as a string.
      logger.error "Argument #{ @foo } mismatch."
  3. With progname.
      logger.info('initialize') { "Initializing..." }
  4. With severity.
      logger.add(Logger::FATAL) { 'Fatal error!' }

How to close a logger

     logger.close

Setting severity threshold

  1. Original interface.
      logger.sev_threshold = Logger::WARN
  2. Log4r (somewhat) compatible interface.
      logger.level = Logger::INFO

  DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN

Format

Log messages are rendered in the output stream in a certain format. The default format and a sample are shown below:

Log format:

  SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message

Log sample:

  I, [Wed Mar 03 02:34:24 JST 1999 895701 #19074]  INFO -- Main: info.

You may change the date and time format in this manner:

  logger.datetime_format = "%Y-%m-%d %H:%M:%S"
        # e.g. "2004-01-03 00:54:26"

There is currently no supported way to change the overall format, but you may have some luck hacking the Format constant.

Methods

<< add close datetime_format datetime_format= debug debug? error error? fatal fatal? info info? log new unknown warn warn?

Included Modules

Severity

Classes and Modules

Module Logger::Severity
Class Logger::Application
Class Logger::Error
Class Logger::Formatter
Class Logger::LogDevice
Class Logger::ShiftingError

Constants

VERSION | = | "1.2.6"
ProgName | = | "#{$1}/#{$2}"
SEV_LABEL | = | %w(DEBUG INFO WARN ERROR FATAL ANY) | Severity label for logging. (max 5 char)

External Aliases

level | -> | sev_threshold
level= | -> | sev_threshold=

Attributes

formatter | [RW] | Logging formatter. formatter#call is invoked with 4 arguments; severity, time, progname and msg for each log. Bear in mind that time is a Time and msg is an Object that user passed and it could not be a String. It is expected to return a logdev#write-able Object. Default formatter is used when no formatter is set.
level | [RW] | Logging severity threshold (e.g. Logger::INFO).
progname | [RW] | Logging program name.

Public Class methods

new(logdev, shift_age = 0, shift_size = 1048576)

Synopsis

  Logger.new(name, shift_age = 7, shift_size = 1048576)
  Logger.new(name, shift_age = 'weekly')

Args

logdev: | The log device. This is a filename (String) or IO object (typically STDOUT, STDERR, or an open file).
shift_age: | Number of old log files to keep, or frequency of rotation (daily, weekly or monthly).
shift_size: | Maximum logfile size (only applies when shift_age is a number).

Description

Create an instance.

Public Instance methods

<<(msg)

Dump given message to the log device without any formatting. If no log device exists, return nil.

add(severity, message = nil, progname = nil) {|| ...}

Synopsis

  Logger#add(severity, message = nil, progname = nil) { ... }

Args

severity: | Severity. Constants are defined in Logger namespace: DEBUG, INFO, WARN, ERROR, FATAL, or UNKNOWN.
message: | The log message. A String or Exception.
progname: | Program name string. Can be omitted. Treated as a message if no message and block are given.
block: | Can be omitted. Called to get a message string if message is nil.

Return

true if successful, false otherwise.

When the given severity is not high enough (for this particular logger), log no message, and return true.

Description

Log a message if the given severity is high enough. This is the generic logging method. Users will be more inclined to use debug, info, warn, error, and fatal.

Message format: message can be any object, but it has to be converted to a String in order to log it. Generally, inspect is used if the given object is not a String. A special case is an Exception object, which will be printed in detail, including message, class, and backtrace. See msg2str for the implementation if required.

Bugs

  • Logfile is not locked.
  • Append open does not need to lock file.
  • But on the OS which supports multi I/O, records possibly be mixed.
close()

Close the logging device.

datetime_format()
datetime_format=(datetime_format)

Logging date-time format (string passed to strftime).

debug(progname = nil, &block)

Log a DEBUG message.

See info for more information.

debug?()

Returns true iff the current severity level allows for the printing of DEBUG messages.

error(progname = nil, &block)

Log an ERROR message.

See info for more information.

error?()

Returns true iff the current severity level allows for the printing of ERROR messages.

fatal(progname = nil, &block)

Log a FATAL message.

See info for more information.

fatal?()

Returns true iff the current severity level allows for the printing of FATAL messages.

info(progname = nil, &block)

Log an INFO message.

The message can come either from the progname argument or the block. If both are provided, then the block is used as the message, and progname is used as the program name.

Examples

  logger.info("MainApp") { "Received connection from #{ip}" }
  # ...
  logger.info "Waiting for input from user"
  # ...
  logger.info { "User typed #{input}" }

You‘ll probably stick to the second form above, unless you want to provide a program name (which you can do with Logger#progname= as well).

Return

See add.

info?()

Returns true iff the current severity level allows for the printing of INFO messages.

log(severity, message = nil, progname = nil, &block)

Alias for add

unknown(progname = nil, &block)

Log an UNKNOWN message. This will be printed no matter what the logger level.

See info for more information.

warn(progname = nil, &block)

Log a WARN message.

See info for more information.

warn?()

Returns true iff the current severity level allows for the printing of WARN messages.


Class: Logger::Application

Class | Logger::Application
In: | lib/logger.rb
Parent: | Object

Description

Application — Add logging support to your application.

Usage

  1. Define your application class as a sub-class of this class.
  2. Override ‘run’ method in your class to do many things.
  3. Instantiate it and invoke ‘start’.

Example

  class FooApp < Application
    def initialize(foo_app, application_specific, arguments)
      super('FooApp') # Name of the application.
    end

    def run
      ...
      log(WARN, 'warning', 'my_method1')
      ...
      @log.error('my_method2') { 'Error!' }
      ...
    end
  end

  status = FooApp.new(....).start

Methods

level= log log= new set_log start

Included Modules

Logger::Severity

Attributes

appname | [R]
logdev | [R]

Public Class methods

new(appname = nil)

Synopsis

  Application.new(appname = '')

Args

appname: Name of the application.

Description

Create an instance. Log device is STDERR by default. This can be changed with set_log.

Public Instance methods

level=(level)

Set the logging threshold, just like Logger#level=.

log(severity, message = nil, &block)

See Logger#add. This application‘s appname is used.

log=(logdev)
set_log(logdev, shift_age = 0, shift_size = 1024000)

Sets the log device for this application. See the class Logger for an explanation of the arguments.

start()

Start the application. Return the status code.


Class: Logger::Error

Class | Logger::Error
In: | lib/logger.rb
Parent: | RuntimeError


Class: Logger::Formatter

Class | Logger::Formatter
In: | lib/logger.rb
Parent: | Object

Methods

call new

Constants

Format = "%s, [%s#%d] %5s -- %s: %s\n"

Attributes

datetime_format [RW]

Public Class methods

new()

Public Instance methods

call(severity, time, progname, msg)


Class: Logger::LogDevice

Class | Logger::LogDevice
In: | lib/logger.rb
Parent: | Object

Methods

close new write

Classes and Modules

Class Logger::LogDevice::LogDeviceMutex

Constants

SiD = 24 * 60 * 60

Attributes

dev | [R]
filename | [R]

Public Class methods

new(log = nil, opt = {})

Public Instance methods

close()
write(message)


Class: Logger::LogDevice::LogDeviceMutex

Class | Logger::LogDevice::LogDeviceMutex
In: | lib/logger.rb
Parent: | Object

Included Modules

MonitorMixin


Module: Logger::Severity

Module | Logger::Severity
In: | lib/logger.rb

Logging severity.

Constants

DEBUG | = | 0
INFO | = | 1
WARN | = | 2
ERROR | = | 3
FATAL | = | 4
UNKNOWN | = | 5


Class: Logger::ShiftingError

Class | Logger::ShiftingError
In: | lib/logger.rb
Parent: | Error


Module: Logging

Module | Logging
In: | lib/mkmf.rb

Methods

logfile message open postpone

Public Class methods

logfile(file)
message(*s)
open() {|| ...}
postpone() {|| ...}


Class: Mail

Class | Mail
In: | lib/mailread.rb
Parent: | Object

The Mail class represents an internet mail message (as per RFC822, RFC2822) with headers and a body.

Methods

[] body header new

Public Class methods

new(f)

Create a new Mail where f is either a stream which responds to gets(), or a path to a file. If f is a path it will be opened.

The whole message is read so it can be made available through the header, #[] and body methods.

The "From " line is ignored if the mail is in mbox format.

Public Instance methods

[](field)

Return the header corresponding to field.

Matching is case-insensitive.

body()

Return the message body as an Array of lines

header()

Return the headers as a Hash.


Module: Marshal

Module | Marshal
In: | marshal.c

The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted. Marshaled data has major and minor version numbers stored along with the object information. In normal use, marshaling can only load data written with the same major version number and an equal or lower minor version number. If Ruby‘s ``verbose’’ flag is set (normally using -d, -v, -w, or —verbose) the major and minor numbers must match exactly. Marshal versioning is independent of Ruby‘s version numbers. You can extract the version by reading the first two bytes of marshaled data.

    str = Marshal.dump("thing")
    RUBY_VERSION   #=> "1.8.0"
    str[0]         #=> 4
    str[1]         #=> 8

Some objects cannot be dumped: if the objects to be dumped include bindings, procedure or method objects, instances of class IO, or singleton objects, a TypeError will be raised. If your class has special serialization needs (for example, if you want to serialize in some specific format), or if it contains objects that would otherwise not be serializable, you can implement your own serialization strategy by defining two methods, _dump and _load: The instance method _dump should return a String object containing all the information necessary to reconstitute objects of this class and all referenced objects up to a maximum depth given as an integer parameter (a value of -1 implies that you should disable depth checking). The class method _load should take a String and return an object of this class.

Methods

dump load restore

Constants

MAJOR_VERSION | = | INT2FIX(MARSHAL_MAJOR)
MINOR_VERSION | = | INT2FIX(MARSHAL_MINOR)

Public Class methods

dump( obj [, anIO] , limit=--1 ) => anIO

Serializes obj and all descendent objects. If anIO is specified, the serialized data will be written to it, otherwise the data will be returned as a String. If limit is specified, the traversal of subobjects will be limited to that depth. If limit is negative, no checking of depth will be performed.

    class Klass
      def initialize(str)
        @str = str
      end
      def sayHello
        @str
      end
    end

(produces no output)

    o = Klass.new("hello\n")
    data = Marshal.dump(o)
    obj = Marshal.load(data)
    obj.sayHello   #=> "hello\n"
load( source [, proc] ) => obj
restore( source [, proc] ) => obj

Returns the result of converting the serialized data in source into a Ruby object (possibly with associated subordinate objects). source may be either an instance of IO or an object that responds to to_str. If proc is specified, it will be passed each object as it is deserialized.

load( source [, proc] ) => obj
restore( source [, proc] ) => obj

Returns the result of converting the serialized data in source into a Ruby object (possibly with associated subordinate objects). source may be either an instance of IO or an object that responds to to_str. If proc is specified, it will be passed each object as it is deserialized.


Class: MatchData

Class | MatchData
In: | re.c lib/pp.rb
Parent: | Object

MatchData is the type of the special variable $~, and is the type of the object returned by Regexp#match and Regexp#last_match. It encapsulates all the results of a pattern match, results normally accessed through the special variables $&, $’, $`, $1, $2, and so on. Matchdata is also known as MatchingData.

Methods

[] begin captures end inspect length offset post_match pre_match pretty_print select size string to_a to_s values_at

Public Instance methods

mtch[i] => obj
mtch[start, length] => array
mtch[range] => array

Match Reference—MatchData acts as an array, and may be accessed using the normal array indexing techniques. mtch[0] is equivalent to the special variable $&, and returns the entire matched string. mtch[1], mtch[2], and so on return the values of the matched backreferences (portions of the pattern between parentheses).

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m[0]       #=> "HX1138"
   m[1, 2]    #=> ["H", "X"]
   m[1..3]    #=> ["H", "X", "113"]
   m[-3, 2]   #=> ["X", "113"]
mtch.begin(n) => integer

Returns the offset of the start of the nth element of the match array in the string.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.begin(0)   #=> 1
   m.begin(2)   #=> 2
mtch.captures => array

Returns the array of captures; equivalent to mtch.to_a.

   f1,f2,f3,f4 = /(.)(.)(\d+)(\d)/.match("THX1138.").captures
   f1    #=> "H"
   f2    #=> "X"
   f3    #=> "113"
   f4    #=> "8"
mtch.end(n) => integer

Returns the offset of the character immediately following the end of the nth element of the match array in the string.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.end(0)   #=> 7
   m.end(2)   #=> 3
obj.to_s => string

Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘

mtch.length => integer
mtch.size => integer

Returns the number of elements in the match array.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.length   #=> 5
   m.size     #=> 5
mtch.offset(n) => array

Returns a two-element array containing the beginning and ending offsets of the nth match.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.offset(0)   #=> [1, 7]
   m.offset(4)   #=> [6, 7]
mtch.post_match => str

Returns the portion of the original string after the current match. Equivalent to the special variable $’.

   m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
   m.post_match   #=> ": The Movie"
mtch.pre_match => str

Returns the portion of the original string before the current match. Equivalent to the special variable $`.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.pre_match   #=> "T"
pretty_print(q)
mtch.select([index]*) => array

Uses each index to access the matching values, returning an array of the corresponding matches.

   m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
   m.to_a               #=> ["HX1138", "H", "X", "113", "8"]
   m.select(0, 2, -2)   #=> ["HX1138", "X", "113"]
mtch.length => integer
mtch.size => integer

Returns the number of elements in the match array.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.length   #=> 5
   m.size     #=> 5
mtch.string => str

Returns a frozen copy of the string passed in to match.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.string   #=> "THX1138."
mtch.to_a => anArray

Returns the array of matches.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.to_a   #=> ["HX1138", "H", "X", "113", "8"]

Because to_a is called when expanding *variable, there‘s a useful assignment shortcut for extracting matched fields. This is slightly slower than accessing the fields directly (as an intermediate array is generated).

   all,f1,f2,f3 = *(/(.)(.)(\d+)(\d)/.match("THX1138."))
   all   #=> "HX1138"
   f1    #=> "H"
   f2    #=> "X"
   f3    #=> "113"
mtch.to_s => str

Returns the entire matched string.

   m = /(.)(.)(\d+)(\d)/.match("THX1138.")
   m.to_s   #=> "HX1138"
mtch.select([index]*) => array

Uses each index to access the matching values, returning an array of the corresponding matches.

   m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
   m.to_a               #=> ["HX1138", "H", "X", "113", "8"]
   m.select(0, 2, -2)   #=> ["HX1138", "X", "113"]


Class: Matrix

Class | Matrix
In: | lib/matrix.rb
Parent: | Object

The Matrix class represents a mathematical matrix, and provides methods for creating special-case matrices (zero, identity, diagonal, singular, vector), operating on them arithmetically and algebraically, and determining their mathematical properties (trace, rank, inverse, determinant).

Note that although matrices should theoretically be rectangular, this is not enforced by the class.

Also note that the determinant of integer matrices may be incorrectly calculated unless you also require ‘mathn‘. This may be fixed in the future.

Method Catalogue

To create a matrix:

  • Matrix[*rows]
  • Matrix.[](*rows)
  • Matrix.rows(rows, copy = true)
  • Matrix.columns(columns)
  • Matrix.diagonal(*values)
  • Matrix.scalar(n, value)
  • Matrix.scalar(n, value)
  • Matrix.identity(n)
  • Matrix.unit(n)
  • Matrix.I(n)
  • Matrix.zero(n)
  • Matrix.row_vector(row)
  • Matrix.column_vector(column)

To access Matrix elements/columns/rows/submatrices/properties:

  • [](i, j)
  • row_size
  • column_size
  • row(i)
  • column(j)
  • collect
  • map
  • minor(*param)

Properties of a matrix:

  • regular?
  • singular?
  • square?

Matrix arithmetic:

  • *(m)
  • +(m)
  • -(m)
  • #/(m)
  • inverse
  • inv
  • **

Matrix functions:

  • determinant
  • det
  • rank
  • trace
  • tr
  • transpose
  • t

Conversion to other data types:

  • coerce(other)
  • row_vectors
  • column_vectors
  • to_a

String representations:

  • to_s
  • inspect

Methods

* ** + - / == [] [] clone coerce collect column column_size column_vector column_vectors columns compare_by_row_vectors det determinant diagonal eql? hash identity inspect inv inverse inverse_from map minor new rank regular? row row_size row_vector row_vectors rows scalar singular? square? t to_a to_s tr trace transpose zero

Included Modules

ExceptionForMatrix

External Aliases

identity | -> | unit
identity | -> | I

Public Class methods

[](*rows)

Creates a matrix where each argument is a row.

  Matrix[ [25, 93], [-1, 66] ]
     =>  25 93
         -1 66
column_vector(column)

Creates a single-column matrix where the values of that column are as given in column.

  Matrix.column_vector([4,5,6])
    => 4
       5
       6
columns(columns)

Creates a matrix using columns as an array of column vectors.

  Matrix.columns([[25, 93], [-1, 66]])
     =>  25 -1
         93 66
diagonal(*values)

Creates a matrix where the diagonal elements are composed of values.

  Matrix.diagonal(9, 5, -3)
    =>  9  0  0
        0  5  0
        0  0 -3
identity(n)

Creates an n by n identity matrix.

  Matrix.identity(2)
    => 1 0
       0 1
new(init_method, *argv)

This method is used by the other methods that create matrices, and is of no use to general users.

row_vector(row)

Creates a single-row matrix where the values of that row are as given in row.

  Matrix.row_vector([4,5,6])
    => 4 5 6
rows(rows, copy = true)

Creates a matrix where rows is an array of arrays, each of which is a row to the matrix. If the optional argument copy is false, use the given arrays as the internal structure of the matrix without copying.

  Matrix.rows([[25, 93], [-1, 66]])
     =>  25 93
         -1 66
scalar(n, value)

Creates an n by n diagonal matrix where each diagonal element is value.

  Matrix.scalar(2, 5)
    => 5 0
       0 5
zero(n)

Creates an n by n zero matrix.

  Matrix.zero(2)
    => 0 0
       0 0

Public Instance methods

*(m)

Matrix multiplication.

  Matrix[[2,4], [6,8]] * Matrix.identity(2)
    => 2 4
       6 8
**(other)

Matrix exponentiation. Defined for integer powers only. Equivalent to multiplying the matrix by itself N times.

  Matrix[[7,6], [3,9]] ** 2
    => 67 96
       48 99
+(m)

Matrix addition.

  Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
    =>  6  0
       -4 12
-(m)

Matrix subtraction.

  Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
    => -8  2
        8  1
/(other)

Matrix division (multiplication by the inverse).

  Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
    => -7  1
       -3 -6
==(other)

Returns true if and only if the two matrices contain equal elements.

[](i, j)

Returns element (i,j) of the matrix. That is: row i, column j.

clone()

Returns a clone of the matrix, so that the contents of each do not reference identical objects.

coerce(other)

FIXME: describe coerce.

collect( {|e| ...}

Returns a matrix that is the result of iteration of the given block over all elements of the matrix.

  Matrix[ [1,2], [3,4] ].collect { |i| i**2 }
    => 1  4
       9 16
column(j) {|e| ...}

Returns column vector number j of the matrix as a Vector (starting at 0 like an array). When a block is given, the elements of that vector are iterated.

column_size()

Returns the number of columns. Note that it is possible to construct a matrix with uneven columns (e.g. Matrix[ [1,2,3], [4,5] ]), but this is mathematically unsound. This method uses the first row to determine the result.

column_vectors()

Returns an array of the column vectors of the matrix. See Vector.

compare_by_row_vectors(rows)

Not really intended for general consumption.

det()

Alias for determinant

determinant()

Returns the determinant of the matrix. If the matrix is not square, the result is 0.

  Matrix[[7,6], [3,9]].determinant
    => 63
eql?(other)

Alias for #==

hash()

Returns a hash-code for the matrix.

inspect()

Overrides Object#inspect

inv()

Alias for inverse

inverse()

Returns the inverse of the matrix.

  Matrix[[1, 2], [2, 1]].inverse
    => -1  1
        0 -1
inverse_from(src)

Not for public consumption?

map(

Alias for collect

minor(*param)

Returns a section of the matrix. The parameters are either:

  • start_row, nrows, start_col, ncols; OR
  • col_range, row_range
  Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
    => 9 0 0
       0 5 0
rank()

Returns the rank of the matrix. Beware that using Float values, with their usual lack of precision, can affect the value returned by this method. Use Rational values instead if this is important to you.

  Matrix[[7,6], [3,9]].rank
    => 2
regular?()

Returns true if this is a regular matrix.

row(i) {|e| ...}

Returns row vector number i of the matrix as a Vector (starting at 0 like an array). When a block is given, the elements of that vector are iterated.

row_size()

Returns the number of rows.

row_vectors()

Returns an array of the row vectors of the matrix. See Vector.

singular?()

Returns true is this is a singular (i.e. non-regular) matrix.

square?()

Returns true is this is a square matrix. See note in column_size about this being unreliable, though.

t()

Alias for transpose

to_a()

Returns an array of arrays that describe the rows of the matrix.

to_s()

Overrides Object#to_s

tr()

Alias for trace

trace()

Returns the trace (sum of diagonal elements) of the matrix.

  Matrix[[7,6], [3,9]].trace
    => 16
transpose()

Returns the transpose of the matrix.

  Matrix[[1,2], [3,4], [5,6]]
    => 1 2
       3 4
       5 6
  Matrix[[1,2], [3,4], [5,6]].transpose
    => 1 3 5
       2 4 6


Class: Method

Class | Method
In: | eval.c
Parent: | Object

Methods

== [] arity call clone inspect to_proc to_s unbind

Public Instance methods

meth == other_meth => true or false

Two method objects are equal if that are bound to the same object and contain the same body.

meth.call(args, ...) => obj
meth[args, ...] => obj

Invokes the meth with the specified arguments, returning the method‘s return value.

   m = 12.method("+")
   m.call(3)    #=> 15
   m.call(20)   #=> 32
meth.arity => fixnum

Returns an indication of the number of arguments accepted by a method. Returns a nonnegative integer for methods that take a fixed number of arguments. For Ruby methods that take a variable number of arguments, returns -n-1, where n is the number of required arguments. For methods written in C, returns -1 if the call takes a variable number of arguments.

   class C
     def one;    end
     def two(a); end
     def three(*a);  end
     def four(a, b); end
     def five(a, b, *c);    end
     def six(a, b, *c, &d); end
   end
   c = C.new
   c.method(:one).arity     #=> 0
   c.method(:two).arity     #=> 1
   c.method(:three).arity   #=> -1
   c.method(:four).arity    #=> 2
   c.method(:five).arity    #=> -3
   c.method(:six).arity     #=> -3

   "cat".method(:size).arity      #=> 0
   "cat".method(:replace).arity   #=> 1
   "cat".method(:squeeze).arity   #=> -1
   "cat".method(:count).arity     #=> -1
meth.call(args, ...) => obj
meth[args, ...] => obj

Invokes the meth with the specified arguments, returning the method‘s return value.

   m = 12.method("+")
   m.call(3)    #=> 15
   m.call(20)   #=> 32
clone()

MISSING: documentation

meth.to_s => string
meth.inspect => string

Show the name of the underlying method.

  "cat".method(:count).inspect   #=> "#<Method: String#count>"
meth.to_proc => prc

Returns a Proc object corresponding to this method.

meth.to_s => string
meth.inspect => string

Show the name of the underlying method.

  "cat".method(:count).inspect   #=> "#<Method: String#count>"
meth.unbind => unbound_method

Dissociates meth from it‘s current receiver. The resulting UnboundMethod can subsequently be bound to a new object of the same class (see UnboundMethod).


Class: Microsoft_FreeThreadedXMLDOM_1_0

Class | Microsoft_FreeThreadedXMLDOM_1_0
In: | ext/win32ole/sample/xml.rb
Parent: | Object

W3C-DOM XML Document (Apartment)

Methods

abort appendChild async async= attributes baseName childNodes cloneNode createAttribute createCDATASection createComment createDocumentFragment createElement createEntityReference createNode createProcessingInstruction createTextNode dataType dataType= definition doctype documentElement firstChild getElementsByTagName hasChildNodes implementation insertBefore lastChild load loadXML method_missing namespaceURI new nextSibling nodeFromID nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ondataavailable ondataavailable= onreadystatechange onreadystatechange= ontransformnode= ownerDocument parentNode parseError parsed prefix preserveWhiteSpace preserveWhiteSpace= previousSibling readyState removeChild replaceChild resolveExternals resolveExternals= save selectNodes selectSingleNode specified text text= transformNode transformNodeToObject url validateOnParse validateOnParse= xml

Included Modules

WIN32OLE::VARIANT

Attributes

clsid | [R]
dispatch | [R]
lastargs | [R]
progid | [R]

Public Class methods

new(obj = nil)

Public Instance methods

abort()

VOID abort abort an asynchronous download

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
async()

BOOL async flag for asynchronous download

async=(arg0)

VOID async flag for asynchronous download

attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
createAttribute(arg0)

IXMLDOMAttribute createAttribute create an attribute node

  BSTR arg0 --- name [IN]
createCDATASection(arg0)

IXMLDOMCDATASection createCDATASection create a CDATA section node

  BSTR arg0 --- data [IN]
createComment(arg0)

IXMLDOMComment createComment create a comment node

  BSTR arg0 --- data [IN]
createDocumentFragment()

IXMLDOMDocumentFragment createDocumentFragment create a DocumentFragment node

createElement(arg0)

IXMLDOMElement createElement create an Element node

  BSTR arg0 --- tagName [IN]
createEntityReference(arg0)

IXMLDOMEntityReference createEntityReference create an entity reference node

  BSTR arg0 --- name [IN]
createNode(arg0, arg1, arg2)

IXMLDOMNode createNode create a node of the specified node type and name

  VARIANT arg0 --- type [IN]
  BSTR arg1 --- name [IN]
  BSTR arg2 --- namespaceURI [IN]
createProcessingInstruction(arg0, arg1)

IXMLDOMProcessingInstruction createProcessingInstruction create a processing instruction node

  BSTR arg0 --- target [IN]
  BSTR arg1 --- data [IN]
createTextNode(arg0)

IXMLDOMText createTextNode create a text node

  BSTR arg0 --- data [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

doctype()

IXMLDOMDocumentType doctype node corresponding to the DOCTYPE

documentElement()

IXMLDOMElement documentElement the root of the tree

firstChild()

IXMLDOMNode firstChild first child of the node

getElementsByTagName(arg0)

IXMLDOMNodeList getElementsByTagName build a list of elements by name

  BSTR arg0 --- tagName [IN]
hasChildNodes()

BOOL hasChildNodes

implementation()

IXMLDOMImplementation implementation info on this DOM implementation

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

load(arg0)

BOOL load load document from the specified XML source

  VARIANT arg0 --- xmlSource [IN]
loadXML(arg0)

BOOL loadXML load the document from a string

  BSTR arg0 --- bstrXML [IN]
method_missing(cmd, *arg)
namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeFromID(arg0)

IXMLDOMNode nodeFromID retrieve node from it‘s ID

  BSTR arg0 --- idString [IN]
nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ondataavailable()

HRESULT ondataavailable EVENT in XMLDOMDocumentEvents

ondataavailable=(arg0)

VOID ondataavailable register an ondataavailable event handler

onreadystatechange()

HRESULT onreadystatechange EVENT in XMLDOMDocumentEvents

onreadystatechange=(arg0)

VOID onreadystatechange register a readystatechange event handler

ontransformnode=(arg0)

VOID ontransformnode register an ontransformnode event handler

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parseError()

IXMLDOMParseError parseError get the last parser error

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

preserveWhiteSpace()

BOOL preserveWhiteSpace indicates whether the parser preserves whitespace

preserveWhiteSpace=(arg0)

VOID preserveWhiteSpace indicates whether the parser preserves whitespace

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

readyState()

I4 readyState get the state of the XML document

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
resolveExternals()

BOOL resolveExternals indicates whether the parser resolves references to external DTD/Entities/Schema

resolveExternals=(arg0)

VOID resolveExternals indicates whether the parser resolves references to external DTD/Entities/Schema

save(arg0)

VOID save save the document to a specified desination

  VARIANT arg0 --- desination [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
url()

BSTR url get the URL for the loaded XML document

validateOnParse()

BOOL validateOnParse indicates whether the parser performs validation

validateOnParse=(arg0)

VOID validateOnParse indicates whether the parser performs validation

xml()

BSTR xml return the XML source for the node and each of its descendants


Class: Microsoft_XMLDOM_1_0

Class | Microsoft_XMLDOM_1_0
In: | ext/win32ole/sample/xml.rb
Parent: | Object

W3C-DOM XML Document

Methods

abort appendChild async async= attributes baseName childNodes cloneNode createAttribute createCDATASection createComment createDocumentFragment createElement createEntityReference createNode createProcessingInstruction createTextNode dataType dataType= definition doctype documentElement firstChild getElementsByTagName hasChildNodes implementation insertBefore lastChild load loadXML method_missing namespaceURI new nextSibling nodeFromID nodeName nodeType nodeTypeString nodeTypedValue nodeTypedValue= nodeValue nodeValue= ondataavailable ondataavailable= onreadystatechange onreadystatechange= ontransformnode= ownerDocument parentNode parseError parsed prefix preserveWhiteSpace preserveWhiteSpace= previousSibling readyState removeChild replaceChild resolveExternals resolveExternals= save selectNodes selectSingleNode specified text text= transformNode transformNodeToObject url validateOnParse validateOnParse= xml

Included Modules

WIN32OLE::VARIANT

Attributes

clsid | [R]
dispatch | [R]
lastargs | [R]
progid | [R]

Public Class methods

new(obj = nil)

Public Instance methods

abort()

VOID abort abort an asynchronous download

appendChild(arg0)

IXMLDOMNode appendChild append a child node

  IXMLDOMNode arg0 --- newChild [IN]
async()

BOOL async flag for asynchronous download

async=(arg0)

VOID async flag for asynchronous download

attributes()

IXMLDOMNamedNodeMap attributes the collection of the node‘s attributes

baseName()

BSTR baseName the base name of the node (nodename with the prefix stripped off)

childNodes()

IXMLDOMNodeList childNodes the collection of the node‘s children

cloneNode(arg0)

IXMLDOMNode cloneNode

  BOOL arg0 --- deep [IN]
createAttribute(arg0)

IXMLDOMAttribute createAttribute create an attribute node

  BSTR arg0 --- name [IN]
createCDATASection(arg0)

IXMLDOMCDATASection createCDATASection create a CDATA section node

  BSTR arg0 --- data [IN]
createComment(arg0)

IXMLDOMComment createComment create a comment node

  BSTR arg0 --- data [IN]
createDocumentFragment()

IXMLDOMDocumentFragment createDocumentFragment create a DocumentFragment node

createElement(arg0)

IXMLDOMElement createElement create an Element node

  BSTR arg0 --- tagName [IN]
createEntityReference(arg0)

IXMLDOMEntityReference createEntityReference create an entity reference node

  BSTR arg0 --- name [IN]
createNode(arg0, arg1, arg2)

IXMLDOMNode createNode create a node of the specified node type and name

  VARIANT arg0 --- type [IN]
  BSTR arg1 --- name [IN]
  BSTR arg2 --- namespaceURI [IN]
createProcessingInstruction(arg0, arg1)

IXMLDOMProcessingInstruction createProcessingInstruction create a processing instruction node

  BSTR arg0 --- target [IN]
  BSTR arg1 --- data [IN]
createTextNode(arg0)

IXMLDOMText createTextNode create a text node

  BSTR arg0 --- data [IN]
dataType()

VARIANT dataType the data type of the node

dataType=(arg0)

VOID dataType the data type of the node

definition()

IXMLDOMNode definition pointer to the definition of the node in the DTD or schema

doctype()

IXMLDOMDocumentType doctype node corresponding to the DOCTYPE

documentElement()

IXMLDOMElement documentElement the root of the tree

firstChild()

IXMLDOMNode firstChild first child of the node

getElementsByTagName(arg0)

IXMLDOMNodeList getElementsByTagName build a list of elements by name

  BSTR arg0 --- tagName [IN]
hasChildNodes()

BOOL hasChildNodes

implementation()

IXMLDOMImplementation implementation info on this DOM implementation

insertBefore(arg0, arg1)

IXMLDOMNode insertBefore insert a child node

  IXMLDOMNode arg0 --- newChild [IN]
  VARIANT arg1 --- refChild [IN]
lastChild()

IXMLDOMNode lastChild first child of the node

load(arg0)

BOOL load load document from the specified XML source

  VARIANT arg0 --- xmlSource [IN]
loadXML(arg0)

BOOL loadXML load the document from a string

  BSTR arg0 --- bstrXML [IN]
method_missing(cmd, *arg)
namespaceURI()

BSTR namespaceURI the URI for the namespace applying to the node

nextSibling()

IXMLDOMNode nextSibling right sibling of the node

nodeFromID(arg0)

IXMLDOMNode nodeFromID retrieve node from it‘s ID

  BSTR arg0 --- idString [IN]
nodeName()

BSTR nodeName name of the node

nodeType()

DOMNodeType nodeType the node‘s type

nodeTypeString()

BSTR nodeTypeString the type of node in string form

nodeTypedValue()

VARIANT nodeTypedValue get the strongly typed value of the node

nodeTypedValue=(arg0)

VOID nodeTypedValue get the strongly typed value of the node

nodeValue()

VARIANT nodeValue value stored in the node

nodeValue=(arg0)

VOID nodeValue value stored in the node

ondataavailable()

HRESULT ondataavailable EVENT in XMLDOMDocumentEvents

ondataavailable=(arg0)

VOID ondataavailable register an ondataavailable event handler

onreadystatechange()

HRESULT onreadystatechange EVENT in XMLDOMDocumentEvents

onreadystatechange=(arg0)

VOID onreadystatechange register a readystatechange event handler

ontransformnode=(arg0)

VOID ontransformnode register an ontransformnode event handler

ownerDocument()

IXMLDOMDocument ownerDocument document that contains the node

parentNode()

IXMLDOMNode parentNode parent of the node

parseError()

IXMLDOMParseError parseError get the last parser error

parsed()

BOOL parsed has sub-tree been completely parsed

prefix()

BSTR prefix the prefix for the namespace applying to the node

preserveWhiteSpace()

BOOL preserveWhiteSpace indicates whether the parser preserves whitespace

preserveWhiteSpace=(arg0)

VOID preserveWhiteSpace indicates whether the parser preserves whitespace

previousSibling()

IXMLDOMNode previousSibling left sibling of the node

readyState()

I4 readyState get the state of the XML document

removeChild(arg0)

IXMLDOMNode removeChild remove a child node

  IXMLDOMNode arg0 --- childNode [IN]
replaceChild(arg0, arg1)

IXMLDOMNode replaceChild replace a child node

  IXMLDOMNode arg0 --- newChild [IN]
  IXMLDOMNode arg1 --- oldChild [IN]
resolveExternals()

BOOL resolveExternals indicates whether the parser resolves references to external DTD/Entities/Schema

resolveExternals=(arg0)

VOID resolveExternals indicates whether the parser resolves references to external DTD/Entities/Schema

save(arg0)

VOID save save the document to a specified desination

  VARIANT arg0 --- desination [IN]
selectNodes(arg0)

IXMLDOMNodeList selectNodes execute query on the subtree

  BSTR arg0 --- queryString [IN]
selectSingleNode(arg0)

IXMLDOMNode selectSingleNode execute query on the subtree

  BSTR arg0 --- queryString [IN]
specified()

BOOL specified indicates whether node is a default value

text()

BSTR text text content of the node and subtree

text=(arg0)

VOID text text content of the node and subtree

transformNode(arg0)

BSTR transformNode apply the stylesheet to the subtree

  IXMLDOMNode arg0 --- stylesheet [IN]
transformNodeToObject(arg0, arg1)

VOID transformNodeToObject apply the stylesheet to the subtree, returning the result through a document or a stream

  IXMLDOMNode arg0 --- stylesheet [IN]
  VARIANT arg1 --- outputObject [IN]
url()

BSTR url get the URL for the loaded XML document

validateOnParse()

BOOL validateOnParse indicates whether the parser performs validation

validateOnParse=(arg0)

VOID validateOnParse indicates whether the parser performs validation

xml()

BSTR xml return the XML source for the node and each of its descendants


Class: Microsoft_XMLDSO_1_0

Class | Microsoft_XMLDSO_1_0
In: | ext/win32ole/sample/xml.rb
Parent: | Object

XML Data Source Object

Methods

JavaDSOCompatible JavaDSOCompatible= XMLDocument XMLDocument= method_missing new readyState

Included Modules

WIN32OLE::VARIANT

Attributes

clsid | [R]
dispatch | [R]
lastargs | [R]
progid | [R]

Public Class methods

new(obj = nil)

Public Instance methods

JavaDSOCompatible()

I4 JavaDSOCompatible

JavaDSOCompatible=(arg0)

VOID JavaDSOCompatible

XMLDocument()

IXMLDOMDocument XMLDocument

XMLDocument=(arg0)

VOID XMLDocument

method_missing(cmd, *arg)
readyState()

I4 readyState


Class: Microsoft_XMLHTTP_1

Class | Microsoft_XMLHTTP_1
In: | ext/win32ole/sample/xml.rb
Parent: | Object

XML HTTP Request class.

Methods

abort getAllResponseHeaders getResponseHeader method_missing new onreadystatechange= open readyState responseBody responseStream responseText responseXML send setRequestHeader status statusText

Included Modules

WIN32OLE::VARIANT

Attributes

clsid | [R]
dispatch | [R]
lastargs | [R]
progid | [R]

Public Class methods

new(obj = nil)

Public Instance methods

abort()

VOID abort Abort HTTP request

getAllResponseHeaders()

BSTR getAllResponseHeaders Get all HTTP response headers

getResponseHeader(arg0)

BSTR getResponseHeader Get HTTP response header

  BSTR arg0 --- bstrHeader [IN]
method_missing(cmd, *arg)
onreadystatechange=(arg0)

VOID onreadystatechange Register a complete event handler

open(arg0, arg1, arg2=nil, arg3=nil, arg4=nil)

VOID open Open HTTP connection

  BSTR arg0 --- bstrMethod [IN]
  BSTR arg1 --- bstrUrl [IN]
  VARIANT arg2 --- varAsync [IN]
  VARIANT arg3 --- bstrUser [IN]
  VARIANT arg4 --- bstrPassword [IN]
readyState()

I4 readyState Get ready state

responseBody()

VARIANT responseBody Get response body

responseStream()

VARIANT responseStream Get response body

responseText()

BSTR responseText Get response body

responseXML()

DISPATCH responseXML Get response body

send(arg0=nil)

VOID send Send HTTP request

  VARIANT arg0 --- varBody [IN]
setRequestHeader(arg0, arg1)

VOID setRequestHeader Add HTTP request header

  BSTR arg0 --- bstrHeader [IN]
  BSTR arg1 --- bstrValue [IN]
status()

I4 status Get HTTP status code

statusText()

BSTR statusText Get HTTP status text


Class: MissingArgument

Class | MissingArgument
In: | lib/optparse.rb
Parent: | ParseError

Raises when a switch with mandatory argument has no argument.


Class: Monitor

Class | Monitor
In: | lib/monitor.rb
Parent: | Object

Monitors provide means of mutual exclusion for Thread programming. A critical region is created by means of the synchronize method, which takes a block. The condition variables (created with new_cond) may be used to control the execution of a monitor with signal and wait.

the Monitor class wraps MonitorMixin, and provides aliases

 alias try_enter try_mon_enter
 alias enter mon_enter
 alias exit mon_exit

to access its methods more concisely.

Included Modules

MonitorMixin

External Aliases

try_mon_enter | -> | try_enter
mon_enter | -> | enter
mon_exit | -> | exit


Module: MonitorMixin

Module | MonitorMixin
In: | lib/monitor.rb

Adds monitor functionality to an arbitrary object by mixing the module with include. For example:

   require 'monitor.rb'

   buf = []
   buf.extend(MonitorMixin)
   empty_cond = buf.new_cond

   # consumer
   Thread.start do
     loop do
       buf.synchronize do
         empty_cond.wait_while { buf.empty? }
         print buf.shift
       end
     end
   end

   # producer
   while line = ARGF.gets
     buf.synchronize do
       buf.push(line)
       empty_cond.signal
     end
   end

The consumer thread waits for the producer thread to push a line to buf while buf.empty?, and the producer thread (main thread) reads a line from ARGF and push it to buf, then call empty_cond.signal.

Methods

extend_object mon_enter mon_exit mon_synchronize mon_try_enter new new_cond synchronize try_mon_enter

Classes and Modules

Class MonitorMixin::ConditionVariable

Public Class methods

extend_object(obj)
new(*args)

Public Instance methods

mon_enter()

Enters exclusive section.

mon_exit()

Leaves exclusive section.

mon_synchronize() {|| ...}

Enters exclusive section and executes the block. Leaves the exclusive section automatically when the block exits. See example under MonitorMixin.

mon_try_enter()

Attempts to enter exclusive section. Returns false if lock fails.

new_cond()

FIXME: This isn‘t documented in Nutshell.

Create a new condition variable for this monitor. This facilitates control of the monitor with signal and wait.

synchronize()

Alias for mon_synchronize

try_mon_enter()

Alias for mon_try_enter


Class: MonitorMixin::ConditionVariable

Class | MonitorMixin::ConditionVariable
In: | lib/monitor.rb
Parent: | Object

FIXME: This isn‘t documented in Nutshell.

Since MonitorMixin.new_cond returns a ConditionVariable, and the example above calls while_wait and signal, this class should be documented.

Methods

broadcast count_waiters new signal wait wait_until wait_while

Classes and Modules

Class MonitorMixin::ConditionVariable::Timeout

Public Class methods

new(monitor)

Public Instance methods

broadcast()

Wake up all the waiters.

count_waiters()
signal()

Wake up and run the next waiter

wait(timeout = nil)

Create a new timer with the argument timeout, and add the current thread to the list of waiters. Then the thread is stopped. It will be resumed when a corresponding signal occurs.

wait_until()

call wait until the supplied block returns true.

wait_while()

call wait while the supplied block returns true.


Class: MonitorMixin::ConditionVariable::Timeout

Class | MonitorMixin::ConditionVariable::Timeout
In: | lib/monitor.rb
Parent: | Exception


Class: Msxml

Class | Msxml
In: | ext/win32ole/sample/xml.rb
Parent: | Object

XMLDocument extends IXML Document. It is obsolete. You should use DOMDocument. This object should not be confused with the XMLDocument property on the XML data island.

Methods

async async= charset charset= createElement doctype method_missing new readyState root url url= version

Included Modules

WIN32OLE::VARIANT

Attributes

clsid | [R]
dispatch | [R]
lastargs | [R]
progid | [R]

Public Class methods

new(obj = nil)

Public Instance methods

async()

HRESULT async get asynchronous loading flag.

  BOOL arg0 --- pf [OUT]
async=(arg0)

HRESULT async get asynchronous loading flag.

  BOOL arg0 --- pf [IN]
charset()

HRESULT charset get encoding.

  BSTR arg0 --- p [OUT]
charset=(arg0)

HRESULT charset get encoding.

  BSTR arg0 --- p [IN]
createElement(arg0, arg1=nil, arg2=nil)

HRESULT createElement create different types of IXMLElements.

  VARIANT arg0 --- vType [IN]
  VARIANT arg1 --- var1 [IN]
  IXMLElement2,IXMLElement2 arg2 --- ppElem [OUT]
doctype()

HRESULT doctype get document type.

  BSTR arg0 --- p [OUT]
method_missing(cmd, *arg)
readyState()

HRESULT readyState get ready state.

  I4 arg0 --- pl [OUT]
root()

HRESULT root get root IXMLElement of the XML document.

  IXMLElement2,IXMLElement2 arg0 --- p [OUT]
url()

HRESULT url set URL to load an XML document from the URL.

  BSTR arg0 --- p [OUT]
url=(arg0)

HRESULT url set URL to load an XML document from the URL.

  BSTR arg0 --- p [IN]
version()

HRESULT version get XML version number.

  BSTR arg0 --- p [OUT]


Class: Mutex

Class | Mutex
In: | lib/thread.rb
Parent: | Object

Mutex implements a simple semaphore that can be used to coordinate access to shared data from multiple concurrent threads.

Example:

  require 'thread'
  semaphore = Mutex.new

  a = Thread.new {
    semaphore.synchronize {
      # access shared resource
    }
  }

  b = Thread.new {
    semaphore.synchronize {
      # access shared resource
    }
  }

Methods

exclusive_unlock lock locked? new synchronize try_lock unlock

Public Class methods

new()

Creates a new Mutex

Public Instance methods

exclusive_unlock() {|| ...}

If the mutex is locked, unlocks the mutex, wakes one waiting thread, and yields in a critical section.

lock()

Attempts to grab the lock and waits if it isn‘t available.

locked?()

Returns true if this lock is currently held by some thread.

synchronize() {|| ...}

Obtains a lock, runs the block, and releases the lock when the block completes. See the example under Mutex.

try_lock()

Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.

unlock()

Releases the lock. Returns nil if ref wasn‘t locked.


Module: Mutex_m

Module | Mutex_m
In: | lib/mutex_m.rb

Usage

Extend an object and use it like a Mutex object:

  require "mutex_m.rb"
  obj = Object.new
  obj.extend Mutex_m
  # ...

Or, include Mutex_m in a class to have its instances behave like a Mutex object:

  class Foo
    include Mutex_m
    # ...
  end

  obj = Foo.new

Methods

append_features define_aliases extend_object mu_extended mu_lock mu_locked? mu_synchronize mu_try_lock mu_unlock new

Public Class methods

append_features(cl)
define_aliases(cl)
extend_object(obj)
new(*args)

Public Instance methods

mu_extended()
mu_lock()
mu_locked?()
mu_synchronize() {|| ...}

locking

mu_try_lock()
mu_unlock()


Class: MyExcel

Class | MyExcel
In: | ext/win32ole/tests/testWIN32OLE.rb
Parent: | WIN32OLE

a subclass of Win32OLE override new() and connect()

Methods

connect new

Public Class methods

connect()
new()


Module: NKF

Module | NKF
In: | ext/nkf/nkf.c

NKF - Ruby extension for Network Kanji Filter

Description

This is a Ruby Extension version of nkf (Netowrk Kanji Filter). It converts the first argument and return converted result. Conversion details are specified by flags as the first argument.

Nkf is a yet another kanji code converter among networks, hosts and terminals. It converts input kanji code to designated kanji code such as ISO-2022-JP, Shift_JIS, EUC-JP, UTF-8 or UTF-16.

One of the most unique faculty of nkf is the guess of the input kanji encodings. It currently recognizes ISO-2022-JP, Shift_JIS, EUC-JP, UTF-8 and UTF-16. So users needn‘t set the input kanji code explicitly.

By default, X0201 kana is converted into X0208 kana. For X0201 kana, SO/SI, SSO and ESC-(-I methods are supported. For automatic code detection, nkf assumes no X0201 kana in Shift_JIS. To accept X0201 in Shift_JIS, use -X, -x or -S.

Flags

-b -u

Output is buffered (DEFAULT), Output is unbuffered.

-j -s -e -w -w16

Output code is ISO-2022-JP (7bit JIS), Shift_JIS, EUC-JP, UTF-8N, UTF-16BE. Without this option and compile option, ISO-2022-JP is assumed.

-J -S -E -W -W16

Input assumption is JIS 7 bit, Shift_JIS, EUC-JP, UTF-8, UTF-16LE.

-J

Assume JIS input. It also accepts EUC-JP. This is the default. This flag does not exclude Shift_JIS.

-S

Assume Shift_JIS and X0201 kana input. It also accepts JIS. EUC-JP is recognized as X0201 kana. Without -x flag, X0201 kana (halfwidth kana) is converted into X0208.

-E

Assume EUC-JP input. It also accepts JIS. Same as -J.

-t

No conversion.

-i_

Output sequence to designate JIS-kanji. (DEFAULT B)

-o_

Output sequence to designate ASCII. (DEFAULT B)

-r

{de/en}crypt ROT13/47

-h[123] —hiragana —katakana —katakana-hiragana

-h1 —hiragana
Katakana to Hiragana conversion.
-h2 —katakana
Hiragana to Katakana conversion.
-h3 —katakana-hiragana
Katakana to Hiragana and Hiragana to Katakana conversion.

-T

Text mode output (MS-DOS)

-l

ISO8859-1 (Latin-1) support

-f[m [- n]]

Folding on m length with n margin in a line. Without this option, fold length is 60 and fold margin is 10.

-F

New line preserving line folding.

-Z[0-3]

Convert X0208 alphabet (Fullwidth Alphabets) to ASCII.

-Z -Z0
Convert X0208 alphabet to ASCII.
-Z1
Converts X0208 kankaku to single ASCII space.
-Z2
Converts X0208 kankaku to double ASCII spaces.
-Z3
Replacing Fullwidth >, <, ", & into ’&gt;’, ’&lt;’, ’&quot;’, ’&amp;’ as in HTML.

-X -x

Assume X0201 kana in MS-Kanji. With -X or without this option, X0201 is converted into X0208 Kana. With -x, try to preserve X0208 kana and do not convert X0201 kana to X0208. In JIS output, ESC-(-I is used. In EUC output, SSO is used.

-B[0-2]

Assume broken JIS-Kanji input, which lost ESC. Useful when your site is using old B-News Nihongo patch.

-B1
allows any char after ESC-( or ESC-$.
-B2
forces ASCII after NL.

-I

Replacing non iso-2022-jp char into a geta character (substitute character in Japanese).

-d -c

Delete \r in line feed, Add \r in line feed.

-m[BQN0]

MIME ISO-2022-JP/ISO8859-1 decode. (DEFAULT) To see ISO8859-1 (Latin-1) -l is necessary.

-mB
Decode MIME base64 encoded stream. Remove header or other part before

conversion.

-mQ
Decode MIME quoted stream. ‘_’ in quoted stream is converted to space.
-mN
Non-strict decoding.

It allows line break in the middle of the base64 encoding.

-m0
No MIME decode.

-M

MIME encode. Header style. All ASCII code and control characters are intact. Kanji conversion is performed before encoding, so this cannot be used as a picture encoder.

-MB
MIME encode Base64 stream.
-MQ
Perfome quoted encoding.

-l

Input and output code is ISO8859-1 (Latin-1) and ISO-2022-JP. -s, -e and -x are not compatible with this option.

-L[uwm]

new line mode Without this option, nkf doesn‘t convert line breaks.

-Lu
unix (LF)
-Lw
windows (CRLF)
-Lm
mac (CR)

—fj —unix —mac —msdos —windows

convert for these system

—jis —euc —sjis —mime —base64

convert for named code

—jis-input —euc-input —sjis-input —mime-input —base64-input

assume input system

—ic=input codeset —oc=output codeset

Set the input or output codeset. NKF supports following codesets and those codeset name are case insensitive.

ISO-2022-JP
a.k.a. RFC1468, 7bit JIS, JUNET
EUC-JP (eucJP-nkf)
a.k.a. AT&T JIS, Japanese EUC, UJIS
eucJP-ascii
a.k.a. x-eucjp-open-19970715-ascii
eucJP-ms
a.k.a. x-eucjp-open-19970715-ms
CP51932
Microsoft Version of EUC-JP.
Shift_JIS
SJIS, MS-Kanji
CP932
a.k.a. Windows-31J
UTF-8
same as UTF-8N
UTF-8N
UTF-8 without BOM
UTF-8-BOM
UTF-8 with BOM
UTF-16
same as UTF-16BE
UTF-16BE
UTF-16 Big Endian without BOM
UTF-16BE-BOM
UTF-16 Big Endian with BOM
UTF-16LE
UTF-16 Little Endian without BOM
UTF-16LE-BOM
UTF-16 Little Endian with BOM
UTF8-MAC
NKDed UTF-8, a.k.a. UTF8-NFD (input only)

—fb-{skip, html, xml, perl, java, subchar}

Specify the way that nkf handles unassigned characters. Without this option, —fb-skip is assumed.

—prefix= escape character target character ..

When nkf converts to Shift_JIS, nkf adds a specified escape character to specified 2nd byte of Shift_JIS characters. 1st byte of argument is the escape character and following bytes are target characters.

—disable-cp932ext

Handle the characters extended in CP932 as unassigned characters.

—cap-input

Decode hex encoded characters.

—url-input

Unescape percent escaped characters.

—

Ignore rest of -option.

Methods

guess1 guess2 nkf

Constants

AUTO | = | INT2FIX(_AUTO) | Auto-Detect
JIS | = | INT2FIX(_JIS) | ISO-2022-JP
EUC | = | INT2FIX(_EUC) | EUC-JP
SJIS | = | INT2FIX(_SJIS) | Shift_JIS
BINARY | = | INT2FIX(_BINARY) | BINARY
NOCONV | = | INT2FIX(_NOCONV) | No conversion
ASCII | = | INT2FIX(_ASCII) | ASCII
UTF8 | = | INT2FIX(_UTF8) | UTF-8
UTF16 | = | INT2FIX(_UTF16) | UTF-16
UTF32 | = | INT2FIX(_UTF32) | UTF-32
UNKNOWN | = | INT2FIX(_UNKNOWN) | UNKNOWN
VERSION | = | rb_str_new2(RUBY_NKF_VERSION) | Full version string of nkf
NKF_VERSION | = | rb_str_new2(NKF_VERSION) | Version of nkf
NKF_RELEASE_DATE | = | rb_str_new2(NKF_RELEASE_DATE) | Release date of nkf

External Aliases

guess2 -> guess

Public Class methods

NKF.guess1(str) → integer

Returns guessed encoding of str as integer.

Algorithm described in: Ken Lunde. `Understanding Japanese Information Processing’ Sebastopol, CA: O‘Reilly & Associates.

    case NKF.guess1(input)
    when NKF::JIS
      "ISO-2022-JP"
    when NKF::SJIS
      "Shift_JIS"
    when NKF::EUC
      "EUC-JP"
    when NKF::UNKNOWN
      "UNKNOWN(ASCII)"
    when NKF::BINARY
      "BINARY"
    end
NKF.guess2(str) → integer

Returns guessed encoding of str as integer by nkf routine.

   case NKF.guess(input)
   when NKF::ASCII
     "ASCII"
   when NKF::JIS
     "ISO-2022-JP"
   when NKF::SJIS
     "Shift_JIS"
   when NKF::EUC
     "EUC-JP"
   when NKF::UTF8
     "UTF-8"
   when NKF::UTF16
     "UTF-16"
   when NKF::UNKNOWN
     "UNKNOWN"
   when NKF::BINARY
     "BINARY"
   end
NKF.nkf(opt, str) → string

Convert str and return converted result. Conversion details are specified by opt as String.

   require 'nkf'
   output = NKF.nkf("-s", input)

Note By default, nkf decodes MIME encoded string. If you want not to decode input, use NKF.nkf with -m0 flag.


Class: NameDescriptor

Class | NameDescriptor
In: | lib/rdoc/ri/ri_util.rb
Parent: | Object

Break argument into its constituent class or module names, an optional method type, and a method name

Methods

full_class_name new

Attributes

class_names | [R] |
is_class_method | [R] | true and false have the obvious meaning. nil means we don‘t care
method_name | [R] |

Public Class methods

new(arg)

arg may be

  1. a class or module name (optionally qualified with other class or module names (Kernel, File::Stat etc)
  2. a method name
  3. a method name qualified by a optionally fully qualified class or module name

We‘re fairly casual about delimiters: folks can say Kernel::puts, Kernel.puts, or Kernel\puts for example. There‘s one exception: if you say IO::read, we look for a class method, but if you say IO.read, we look for an instance method

Public Instance methods

full_class_name()

Return the full class name (with ’::’ between the components) or "" if there‘s no class name


Class: NameError

Class | NameError
In: | error.c
Parent: | StandardError

Methods

name new to_s

Classes and Modules

Class NameError::message

Public Class methods

NameError.new(msg [, name]) => name_error

Construct a new NameError exception. If given the name parameter may subsequently be examined using the NameError.name method.

Public Instance methods

name_error.name => string or nil

Return the name associated with this NameError exception.

name_error.to_s => string

Produce a nicely-formated string representing the NameError.


Class: NameError::message

Class | NameError::message
In: | error.c
Parent: | Data


Class: NeedlessArgument

Class | NeedlessArgument
In: | lib/optparse.rb
Parent: | ParseError

Raises when there is an argument for a switch which takes no argument.


Class: NilClass

Class | NilClass
In: | object.c lib/yaml/rubytypes.rb
Parent: | Object

The class of the singleton object nil.

Methods

& ^ inspect nil? to_a to_f to_i to_s to_yaml |

Public Instance methods

false & obj => false
nil & obj => false

And—Returns false. obj is always evaluated as it is the argument to a method call—there is no short-circuit evaluation in this case.

false ^ obj => true or false
nil ^ obj => true or false

Exclusive Or—If obj is nil or false, returns false; otherwise, returns true.

nil.inspect => "nil"

Always returns the string "nil".

nil?()

call_seq:

  nil.nil?               => true

Only the object nil responds true to nil?.

nil.to_a => []

Always returns an empty array.

   nil.to_a   #=> []
nil.to_f => 0.0

Always returns zero.

   nil.to_f   #=> 0.0
nil.to_i => 0

Always returns zero.

   nil.to_i   #=> 0
nil.to_s => ""

Always returns the empty string.

   nil.to_s   #=> ""
to_yaml( opts = {} )
false | obj => true or false
nil | obj => true or false

Or—Returns false if obj is nil or false; true otherwise.


Class: NoMemoryError

Class | NoMemoryError
In: | error.c
Parent: | Exception


Class: NoMethodError

Class | NoMethodError
In: | error.c
Parent: | NameError

Methods

args new

Public Class methods

NoMethodError.new(msg, name [, args]) => no_method_error

Construct a NoMethodError exception for a method of the given name called with the given arguments. The name may be accessed using the name method on the resulting object, and the arguments using the args method.

Public Instance methods

no_method_error.args => obj

Return the arguments passed in as the third parameter to the constructor.


Class: NotImplementedError

Class | NotImplementedError
In: | error.c
Parent: | ScriptError


Class: OLEProperty

Class | OLEProperty
In: | ext/win32ole/lib/win32ole/property.rb
Parent: | Object

OLEProperty helper class of Property with arguments.

Methods

[] []= new

Public Class methods

new(obj, dispid, gettypes, settypes)

Public Instance methods

[](*args)
[]=(*args)


Module: OLESERVER

Module | OLESERVER
In: | ext/win32ole/tests/oleserver.rb

Constants

MS_EXCEL_TYPELIB | = | oletypelib_name(/^Microsoft Excel .* Object Library$/)
MS_XML_TYPELIB | = | oletypelib_name(/^Microsoft XML/)


Module: OLEtagDOMNodeType

Module | OLEtagDOMNodeType
In: | ext/win32ole/sample/xml.rb

Constants that define a node‘s type

Included Modules

WIN32OLE::VARIANT

Constants

NODE_INVALID | = | 0
NODE_ELEMENT | = | 1
NODE_ATTRIBUTE | = | 2
NODE_TEXT | = | 3
NODE_CDATA_SECTION | = | 4
NODE_ENTITY_REFERENCE | = | 5
NODE_ENTITY | = | 6
NODE_PROCESSING_INSTRUCTION | = | 7
NODE_COMMENT | = | 8
NODE_DOCUMENT | = | 9
NODE_DOCUMENT_TYPE | = | 10
NODE_DOCUMENT_FRAGMENT | = | 11
NODE_NOTATION | = | 12

Attributes

lastargs [R]


Module: OLEtagXMLEMEM_TYPE

Module | OLEtagXMLEMEM_TYPE
In: | ext/win32ole/sample/xml.rb

Constants that define types for IXMLElement.

Included Modules

WIN32OLE::VARIANT

Constants

XMLELEMTYPE_ELEMENT | = | 0
XMLELEMTYPE_TEXT | = | 1
XMLELEMTYPE_COMMENT | = | 2
XMLELEMTYPE_DOCUMENT | = | 3
XMLELEMTYPE_DTD | = | 4
XMLELEMTYPE_PI | = | 5
XMLELEMTYPE_OTHER | = | 6

Attributes

lastargs [R]


Module: ObjectSpace

Module | ObjectSpace
In: | gc.c

The ObjectSpace module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.

ObjectSpace also provides support for object finalizers, procs that will be called when a specific object is about to be destroyed by garbage collection.

   include ObjectSpace

   a = "A"
   b = "B"
   c = "C"

   define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
   define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
   define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })

produces:

   Finalizer three on 537763470
   Finalizer one on 537763480
   Finalizer two on 537763480

Methods

_id2ref add_finalizer call_finalizer define_finalizer each_object finalizers garbage_collect remove_finalizer undefine_finalizer

Public Class methods

ObjectSpace._id2ref(object_id) → an_object

Converts an object id to a reference to the object. May not be called on an object id passed as a parameter to a finalizer.

   s = "I am a string"                    #=> "I am a string"
   r = ObjectSpace._id2ref(s.object_id)   #=> "I am a string"
   r == s                                 #=> true
add_finalizer(p1)

deprecated

call_finalizer(p1)

deprecated

ObjectSpace.define_finalizer(obj, aProc=proc())

Adds aProc as a finalizer, to be called after obj was destroyed.

ObjectSpace.each_object([module]) {|obj| ... } => fixnum

Calls the block once for each living, nonimmediate object in this Ruby process. If module is specified, calls the block for only those classes or modules that match (or are a subclass of) module. Returns the number of objects found. Immediate objects (Fixnums, Symbols true, false, and nil) are never returned. In the example below, each_object returns both the numbers we defined and several constants defined in the Math module.

   a = 102.7
   b = 95       # Won't be returned
   c = 12345678987654321
   count = ObjectSpace.each_object(Numeric) {|x| p x }
   puts "Total count: #{count}"

produces:

   12345678987654321
   102.7
   2.71828182845905
   3.14159265358979
   2.22044604925031e-16
   1.7976931348623157e+308
   2.2250738585072e-308
   Total count: 7
finalizers()

deprecated

GC.start => nil
gc.garbage_collect => nil
ObjectSpace.garbage_collect => nil

Initiates garbage collection, unless manually disabled.

remove_finalizer(p1)

deprecated

ObjectSpace.undefine_finalizer(obj)

Removes all finalizers for obj.


Module: Observable

Module | Observable
In: | lib/observer.rb

Implements the Observable design pattern as a mixin so that other objects can be notified of changes in state. See observer.rb for details and an example.

Methods

add_observer changed changed? count_observers delete_observer delete_observers notify_observers

Public Instance methods

add_observer(observer)

Add observer as an observer on this object. observer will now receive notifications.

changed(state=true)

Set the changed state of this object. Notifications will be sent only if the changed state is true.

changed?()

Query the changed state of this object.

count_observers()

Return the number of observers associated with this object.

delete_observer(observer)

Delete observer as an observer on this object. It will no longer receive notifications.

delete_observers()

Delete all observers associated with this object.

notify_observers(*arg)

If this object‘s changed state is true, invoke the update method in each currently associated observer in turn, passing it the given arguments. The changed state is then set to false.


Module: Open3

Module | Open3
In: | lib/open3.rb

Open3 grants you access to stdin, stdout, and stderr when running another program. Example:

  require "open3"
  include Open3

  stdin, stdout, stderr = popen3('nroff -man')

Open3.popen3 can also take a block which will receive stdin, stdout and stderr as parameters. This ensures stdin, stdout and stderr are closed once the block exits. Example:

  require "open3"

  Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }

Methods

popen3

Public Instance methods

popen3(*cmd) {|| ...}

Open stdin, stdout, and stderr streams and start external executable. Non-block form:

  require 'open3'

  [stdin, stdout, stderr] = Open3.popen3(cmd)

Block form:

  require 'open3'

  Open3.popen3(cmd) { |stdin, stdout, stderr| ... }

The parameter cmd is passed directly to Kernel#exec.


Class: OpenStruct

Class | OpenStruct
In: | lib/ostruct.rb
Parent: | Object

OpenStruct allows you to create data objects and set arbitrary attributes. For example:

  require 'ostruct'

  record = OpenStruct.new
  record.name    = "John Smith"
  record.age     = 70
  record.pension = 300

  puts record.name     # -> "John Smith"
  puts record.address  # -> nil

It is like a hash with a different way to access the data. In fact, it is implemented with a hash, and you can initialize it with one.

  hash = { "country" => "Australia", :population => 20_000_000 }
  data = OpenStruct.new(hash)

  p data        # -> <OpenStruct country="Australia" population=20000000>

Methods

== delete_field initialize_copy inspect marshal_dump marshal_load new new_ostruct_member to_s

Public Class methods

new(hash=nil)

Create a new OpenStruct object. The optional hash, if given, will generate attributes and values. For example.

  require 'ostruct'
  hash = { "country" => "Australia", :population => 20_000_000 }
  data = OpenStruct.new(hash)

  p data        # -> <OpenStruct country="Australia" population=20000000>

By default, the resulting OpenStruct object will have no attributes.

Public Instance methods

==(other)

Compare this object and other for equality.

delete_field(name)

Remove the named field from the object.

initialize_copy(orig)

Duplicate an OpenStruct object members.

inspect()

Returns a string containing a detailed summary of the keys and values.

marshal_dump()
marshal_load(x)
new_ostruct_member(name)
to_s()

Alias for inspect


Module: OpenURI

Module | OpenURI
In: | lib/open-uri.rb
 OpenURI is an easy-to-use wrapper for net/http, net/https and net/ftp.

Example

 It is possible to open http/https/ftp URL as usual like opening a file:

   open("http://www.ruby-lang.org/") {|f|
     f.each_line {|line| p line}
   }

 The opened file has several methods for meta information as follows since
 it is extended by OpenURI::Meta.

   open("http://www.ruby-lang.org/en") {|f|
     f.each_line {|line| p line}
     p f.base_uri         # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/>
     p f.content_type     # "text/html"
     p f.charset          # "iso-8859-1"
     p f.content_encoding # []
     p f.last_modified    # Thu Dec 05 02:45:02 UTC 2002
   }

 Additional header fields can be specified by an optional hash argument.

   open("http://www.ruby-lang.org/en/",
     "User-Agent" => "Ruby/#{RUBY_VERSION}",
     "From" => "foo@bar.invalid",
     "Referer" => "http://www.ruby-lang.org/") {|f|
     # ...
   }

 The environment variables such as http_proxy, https_proxy and ftp_proxy
 are in effect by default.  :proxy => nil disables proxy.

   open("http://www.ruby-lang.org/en/raa.html", :proxy => nil) {|f|
     # ...
   }

 URI objects can be opened in a similar way.

   uri = URI.parse("http://www.ruby-lang.org/en/")
   uri.open {|f|
     # ...
   }

 URI objects can be read directly. The returned string is also extended by
 OpenURI::Meta.

   str = uri.read
   p str.base_uri

 Author:: Tanaka Akira <akr@m17n.org>

Classes and Modules

Module OpenURI::Meta
Module OpenURI::OpenRead
Class OpenURI::HTTPError

Constants

Options = { :proxy => true, :progress_proc => true, :content_length_proc => true, :http_basic_authentication => true, }


Class: OpenURI::HTTPError

Class | OpenURI::HTTPError
In: | lib/open-uri.rb
Parent: | StandardError

Methods

new

Attributes

io [R]

Public Class methods

new(message, io)


Module: OpenURI::Meta

Module | OpenURI::Meta
In: | lib/open-uri.rb

Mixin for holding meta-information.

Methods

charset content_encoding content_type last_modified

Constants

RE_LWS | = | /[\r\n\t ]+/n
RE_TOKEN | = | %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
RE_QUOTED_STRING | = | %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
RE_PARAMETERS | = | %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n

Attributes

base_uri | [RW] | returns a URI which is base of relative URIs in the data. It may differ from the URI supplied by a user because redirection.
meta | [R] | returns a Hash which represents header fields. The Hash keys are downcased for canonicalization.
status | [RW] | returns an Array which consists status code and message.

Public Instance methods

charset() {|| ...}

returns a charset parameter in Content-Type field. It is downcased for canonicalization.

If charset parameter is not given but a block is given, the block is called and its result is returned. It can be used to guess charset.

If charset parameter and block is not given, nil is returned except text type in HTTP. In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1.

content_encoding()

returns a list of encodings in Content-Encoding field as an Array of String. The encodings are downcased for canonicalization.

content_type()

returns "type/subtype" which is MIME Content-Type. It is downcased for canonicalization. Content-Type parameters are stripped.

last_modified()

returns a Time which represents Last-Modified field.


Module: OpenURI::OpenRead

Module | OpenURI::OpenRead
In: | lib/open-uri.rb

Mixin for HTTP and FTP URIs.

Methods

open read

Public Instance methods

open(*rest, &block)

OpenURI::OpenRead#open provides `open’ for URI::HTTP and URI::FTP.

OpenURI::OpenRead#open takes optional 3 arguments as: OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| … }]

`mode’, `perm’ is same as Kernel#open.

However, `mode’ must be read mode because OpenURI::OpenRead#open doesn‘t support write mode (yet). Also `perm’ is just ignored because it is meaningful only for file creation.

`options’ must be a hash.

Each pairs which key is a string in the hash specify a extra header field for HTTP. I.e. it is ignored for FTP without HTTP proxy.

The hash may include other options which key is a symbol:

:proxy
Synopsis:
  :proxy => "http://proxy.foo.com:8000/"
  :proxy => URI.parse("http://proxy.foo.com:8000/")
  :proxy => true
  :proxy => false
  :proxy => nil

If :proxy option is specified, the value should be String, URI, boolean or nil. When String or URI is given, it is treated as proxy URI. When true is given or the option itself is not specified, environment variable `scheme_proxy’ is examined. `scheme’ is replaced by `http’, `https’ or `ftp’. When false or nil is given, the environment variables are ignored and connection will be made to a server directly.

:http_basic_authentication
Synopsis:
  :http_basic_authentication=>[user, password]

If :http_basic_authentication is specified, the value should be an array which contains 2 strings: username and password. It is used for HTTP Basic authentication defined by RFC 2617.

:content_length_proc
Synopsis:
  :content_length_proc => lambda {|content_length| ... }

If :content_length_proc option is specified, the option value procedure is called before actual transfer is started. It takes one argument which is expected content length in bytes.

If two or more transfer is done by HTTP redirection, the procedure is called only one for a last transfer.

When expected content length is unknown, the procedure is called with nil. It is happen when HTTP response has no Content-Length header.

:progress_proc
Synopsis:
  :progress_proc => lambda {|size| ...}

If :progress_proc option is specified, the proc is called with one argument each time when `open’ gets content fragment from network. The argument `size’ `size’ is a accumulated transfered size in bytes.

If two or more transfer is done by HTTP redirection, the procedure is called only one for a last transfer.

:progress_proc and :content_length_proc are intended to be used for progress bar. For example, it can be implemented as follows using Ruby/ProgressBar.

  pbar = nil
  open("http://...",
    :content_length_proc => lambda {|t|
      if t && 0 < t
        pbar = ProgressBar.new("...", t)
        pbar.file_transfer_mode
      end
    },
    :progress_proc => lambda {|s|
      pbar.set s if pbar
    }) {|f| ... }

OpenURI::OpenRead#open returns an IO like object if block is not given. Otherwise it yields the IO object and return the value of the block. The IO object is extended with OpenURI::Meta.

read(options={})

OpenURI::OpenRead#read([options]) reads a content referenced by self and returns the content as string. The string is extended with OpenURI::Meta. The argument `options’ is same as OpenURI::OpenRead#open.


Class: OptionParser

Class | OptionParser
In: | lib/optparse.rb
Parent: | Object

Developer Documentation (not for RDoc output)

Class tree

  • OptionParser:: front end
  • OptionParser::Switch:: each switches
  • OptionParser::List:: options list
  • OptionParser::ParseError:: errors on parsing
    • OptionParser::AmbiguousOption
    • OptionParser::NeedlessArgument
    • OptionParser::MissingArgument
    • OptionParser::InvalidOption
    • OptionParser::InvalidArgument
      • OptionParser::AmbiguousArgument

Object relationship diagram

  +--------------+
  | OptionParser |<>-----+
  +--------------+       |                      +--------+
                         |                    ,-| Switch |
       on_head -------->+---------------+    /  +--------+
       accept/reject -->| List          |<|>-
                        |               |<|>-  +----------+
       on ------------->+---------------+    `-| argument |
                          :           :        |  class   |
                        +---------------+      |==========|
       on_tail -------->|               |      |pattern   |
                        +---------------+      |----------|
  OptionParser.accept ->| DefaultList   |      |converter |
               reject   |(shared between|      +----------+
                        | all instances)|
                        +---------------+

OptionParser

Introduction

OptionParser is a class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented solution.

Features

  1. The argument specification and the code to handle it are written in the same place.
  2. It can output an option summary; you don‘t need to maintain this string separately.
  3. Optional and mandatory arguments are specified very gracefully.
  4. Arguments can be automatically converted to a specified class.
  5. Arguments can be restricted to a certain set.

All of these features are demonstrated in the examples below.

Minimal example

  require 'optparse'

  options = {}
  OptionParser.new do |opts|
    opts.banner = "Usage: example.rb [options]"

    opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
      options[:verbose] = v
    end
  end.parse!

  p options
  p ARGV

Complete example

The following example is a complete Ruby program. You can run it and see the effect of specifying various options. This is probably the best way to learn the features of optparse.

  require 'optparse'
  require 'optparse/time'
  require 'ostruct'
  require 'pp'

  class OptparseExample

    CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
    CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }

    #
    # Return a structure describing the options.
    #
    def self.parse(args)
      # The options specified on the command line will be collected in *options*.
      # We set default values here.
      options = OpenStruct.new
      options.library = []
      options.inplace = false
      options.encoding = "utf8"
      options.transfer_type = :auto
      options.verbose = false

      opts = OptionParser.new do |opts|
        opts.banner = "Usage: example.rb [options]"

        opts.separator ""
        opts.separator "Specific options:"

        # Mandatory argument.
        opts.on("-r", "--require LIBRARY",
                "Require the LIBRARY before executing your script") do |lib|
          options.library << lib
        end

        # Optional argument; multi-line description.
        opts.on("-i", "--inplace [EXTENSION]",
                "Edit ARGV files in place",
                "  (make backup if EXTENSION supplied)") do |ext|
          options.inplace = true
          options.extension = ext || ''
          options.extension.sub!(/\A\.?(?=.)/, ".")  # Ensure extension begins with dot.
        end

        # Cast 'delay' argument to a Float.
        opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
          options.delay = n
        end

        # Cast 'time' argument to a Time object.
        opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
          options.time = time
        end

        # Cast to octal integer.
        opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
                "Specify record separator (default \\0)") do |rs|
          options.record_separator = rs
        end

        # List of arguments.
        opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
          options.list = list
        end

        # Keyword completion.  We are specifying a specific set of arguments (CODES
        # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
        # the shortest unambiguous text.
        code_list = (CODE_ALIASES.keys + CODES).join(',')
        opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
                "  (#{code_list})") do |encoding|
          options.encoding = encoding
        end

        # Optional argument with keyword completion.
        opts.on("--type [TYPE]", [:text, :binary, :auto],
                "Select transfer type (text, binary, auto)") do |t|
          options.transfer_type = t
        end

        # Boolean switch.
        opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
          options.verbose = v
        end

        opts.separator ""
        opts.separator "Common options:"

        # No argument, shows at tail.  This will print an options summary.
        # Try it and see!
        opts.on_tail("-h", "--help", "Show this message") do
          puts opts
          exit
        end

        # Another typical switch to print the version.
        opts.on_tail("--version", "Show version") do
          puts OptionParser::Version.join('.')
          exit
        end
      end

      opts.parse!(args)
      options
    end  # parse()

  end  # class OptparseExample

  options = OptparseExample.parse(ARGV)
  pp options

Further documentation

The above examples should be enough to learn how to use this class. If you have any questions, email me (gsinclair@soyabean.com.au) and I will update this document.

Methods

switch_name

Classes and Modules

Module OptionParser::Completion
Class OptionParser::NoArgument
Class OptionParser::OptionMap
Class OptionParser::OptionalArgument
Class OptionParser::PlacedArgument
Class OptionParser::RequiredArgument
Class OptionParser::Switch

Public Instance methods

switch_name()

Main name of the switch.


Module: OptionParser::Completion

Module | OptionParser::Completion
In: | lib/optparse.rb

Keyword completion module. This allows partial arguments to be specified and resolved against a list of acceptable values.

Methods

complete convert

Public Instance methods

complete(key, icase = false, pat = nil) {|key, *sw| ...}
convert(opt = nil, val = nil, *)


Class: OptionParser::NoArgument

Class | OptionParser::NoArgument
In: | lib/optparse.rb
Parent: | self

Switch that takes no arguments.

Methods

incompatible_argument_styles parse pattern

Public Class methods

incompatible_argument_styles(*)
pattern()

Public Instance methods

parse(arg, argv) {|NeedlessArgument, arg| ...}

Raises an exception if any arguments given.


Class: OptionParser::OptionMap

Class | OptionParser::OptionMap
In: | lib/optparse.rb
Parent: | Hash

Map from option/keyword string to object with completion.

Included Modules

Completion


Class: OptionParser::OptionalArgument

Class | OptionParser::OptionalArgument
In: | lib/optparse.rb
Parent: | self

Switch that can omit argument.

Methods

parse

Public Instance methods

parse(arg, argv, &error)

Parses argument if given, or uses default value.


Class: OptionParser::PlacedArgument

Class | OptionParser::PlacedArgument
In: | lib/optparse.rb
Parent: | self

Switch that takes an argument, which does not begin with ’-’.

Methods

parse

Public Instance methods

parse(arg, argv, &error)

Returns nil if argument is not present or begins with ’-’.


Class: OptionParser::RequiredArgument

Class | OptionParser::RequiredArgument
In: | lib/optparse.rb
Parent: | self

Switch that takes an argument.

Methods

parse

Public Instance methods

parse(arg, argv)

Raises an exception if argument is not present.


Class: OptionParser::Switch

Class | OptionParser::Switch
In: | lib/optparse.rb
Parent: | Object

Individual switch class. Not important to the user.

Defined within Switch are several Switch-derived classes: NoArgument, RequiredArgument, etc.

Methods

guess incompatible_argument_styles new pattern summarize

Attributes

arg | [R]
block | [R]
conv | [R]
desc | [R]
long | [R]
pattern | [R]
short | [R]

Public Class methods

guess(arg)

Guesses argument style from arg. Returns corresponding OptionParser::Switch class (OptionalArgument, etc.).

incompatible_argument_styles(arg, t)
new(pattern = nil, conv = nil, short = nil, long = nil, arg = nil, desc = ([] if short or long), block = Proc.new)
pattern()

Public Instance methods

summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "") {|indent + l| ...}

Produces the summary text. Each line of the summary is yielded to the block (without newline).

sdone: | Already summarized short style options keyed hash.
ldone: | Already summarized long style options keyed hash.
width: | Width of left side (option part). In other words, the right side (description part) starts after width columns.
max: | Maximum width of left side -> the options are filled within max columns.
indent: | Prefix string indents all summarized lines.


Class: Options

Class | Options
In: | lib/rdoc/options.rb
Parent: | Object

Methods

parse title title=

Included Modules

Singleton

Classes and Modules

Module Options::OptionList

Attributes

all_one_file | [R] | should the output be placed into a single file
charset | [R] | character-set
css | [R] | URL of stylesheet
diagram | [R] | should diagrams be drawn
exclude | [RW] | files matching this pattern will be excluded
extra_accessor_flags | [R] |
extra_accessors | [R] | pattern for additional attr_… style methods
fileboxes | [R] | should we draw fileboxes in diagrams
files | [R] | and the list of files to be processed
force_update | [R] | scan newer sources than the flag file if true.
generator | [RW] | description of the output generator (set with the -fmt option
image_format | [R] | image format for diagrams
include_line_numbers | [R] | include line numbers in the source listings
inline_source | [R] | should source code be included inline, or displayed in a popup
main_page | [RW] | name of the file, class or module to display in the initial index page (if not specified the first file we encounter is used)
merge | [R] | merge into classes of the name name when generating ri
op_dir | [RW] | the name of the output directory
op_name | [R] | the name to use for the output
promiscuous | [R] | Are we promiscuous about showing module contents across multiple files
quiet | [R] | Don‘t display progress as we process the files
rdoc_include | [R] | array of directories to search for files to satisfy an :include:
show_all | [RW] | include private and protected methods in the output
show_hash | [R] | include the ’#’ at the front of hyperlinked instance method names
tab_width | [R] | the number of columns in a tab
template | [R] | template to be used when generating output
webcvs | [R] | URL of web cvs frontend

Public Instance methods

parse(argv, generators)

Parse command line options. We‘re passed a hash containing output generators, keyed by the generator name

title()
title=(string)

Set the title, but only if not already set. This means that a title set from the command line trumps one set in a source file


Module: Options::OptionList

Module | Options::OptionList
In: | lib/rdoc/options.rb

Methods

error help_output options strip_output usage

Constants

OPTION_LIST = [ [ "--accessor", "-A", "accessorname[,..]", "comma separated list of additional class methods\n" + "that should be treated like 'attr_reader' and\n" + "friends. Option may be repeated. Each accessorname\n" + "may have '=text' appended, in which case that text\n" + "appears where the r/w/rw appears for normal accessors."], [ "--all", "-a", nil, "include all methods (not just public)\nin the output" ], [ "--charset", "-c", "charset", "specifies HTML character-set" ], [ "--debug", "-D", nil, "displays lots on internal stuff" ], [ "--diagram", "-d", nil, "Generate diagrams showing modules and classes.\n" + "You need dot V1.8.6 or later to use the --diagram\n" + "option correctly. Dot is available from\n"+ "http://www.research.att.com/sw/tools/graphviz/" ], [ "--exclude", "-x", "pattern", "do not process files or directories matching\n" + "pattern. Files given explicitly on the command\n" + "line will never be excluded." ], [ "--extension", "-E", "new=old", "Treat files ending with .new as if they ended with\n" + ".old. Using '-E cgi=rb' will cause xxx.cgi to be\n" + "parsed as a Ruby file"], [ "--fileboxes", "-F", nil, "classes are put in boxes which represents\n" + "files, where these classes reside. Classes\n" + "shared between more than one file are\n" + "shown with list of files that sharing them.\n" + "Silently discarded if --diagram is not given\n" + "Experimental." ], [ "--force-update", "-U", nil, "forces to scan all sources even if newer than\n" + "the flag file." ], [ "--fmt", "-f", "format name", "set the output formatter (see below)" ], [ "--help", "-h", nil, "you're looking at it" ], [ "--help-output", "-O", nil, "explain the various output options" ], [ "--image-format", "-I", "gif/png/jpg/jpeg", "Sets output image format for diagrams. Can\n" + "be png, gif, jpeg, jpg. If this option is\n" + "omitted, png is used. Requires --diagram." ], [ "--include", "-i", "dir[,dir...]", "set (or add to) the list of directories\n" + "to be searched when satisfying :include:\n" + "requests. Can be used more than once." ], [ "--inline-source", "-S", nil, "Show method source code inline, rather\n" + "than via a popup link" ], [ "--line-numbers", "-N", nil, "Include line numbers in the source code" ], [ "--main", "-m", "name", "'name' will be the initial page displayed" ], [ "--merge", "-M", nil, "when creating ri output, merge processed classes\n" + "into previously documented classes of the name name"], [ "--one-file", "-1", nil, "put all the output into a single file" ], [ "--op", "-o", "dir", "set the output directory" ], [ "--opname", "-n", "name", "Set the 'name' of the output. Has no\n" + "effect for HTML." ], [ "--promiscuous", "-p", nil, "When documenting a file that contains a module\n" + "or class also defined in other files, show\n" + "all stuff for that module/class in each files\n" + "page. By default, only show stuff defined in\n" + "that particular file." ], [ "--quiet", "-q", nil, "don't show progress as we parse" ], [ "--ri", "-r", nil, "generate output for use by 'ri.' The files are\n" + "stored in the '.rdoc' directory under your home\n"+ "directory unless overridden by a subsequent\n" + "--op parameter, so no special privileges are needed." ], [ "--ri-site", "-R", nil, "generate output for use by 'ri.' The files are\n" + "stored in a site-wide directory, making them accessible\n"+ "to others, so special privileges are needed." ], [ "--ri-system", "-Y", nil, "generate output for use by 'ri.' The files are\n" + "stored in a system-level directory, making them accessible\n"+ "to others, so special privileges are needed. This option\n"+ "is intended to be used during Ruby installations" ], [ "--show-hash", "-H", nil, "A name of the form #name in a comment\n" + "is a possible hyperlink to an instance\n" + "method name. When displayed, the '#' is\n" + "removed unless this option is specified" ], [ "--style", "-s", "stylesheet url", "specifies the URL of a separate stylesheet." ], [ "--tab-width", "-w", "n", "Set the width of tab characters (default 8)"], [ "--template", "-T", "template name", "Set the template used when generating output" ], [ "--title", "-t", "text", "Set 'txt' as the title for the output" ], [ "--version", "-v", nil, "display RDoc's version" ], [ "--webcvs", "-W", "url", "Specify a URL for linking to a web frontend\n" + "to CVS. If the URL contains a '\%s', the\n" + "name of the current file will be substituted;\n" + "if the URL doesn't contain a '\%s', the\n" + "filename will be appended to it." ], ]

Public Class methods

error(msg)

Show an error and exit

help_output()
options()
strip_output(text)
usage(generator_names)

Show usage and exit


Class: PP

Class | PP
In: | lib/pp.rb
Parent: | PrettyPrint

Methods

pp singleline_pp

Included Modules

PPMethods

Classes and Modules

Module PP::ObjectMixin
Module PP::PPMethods
Class PP::SingleLine

Attributes

sharing_detection [RW] Returns the sharing detection flag as a boolean value. It is false by default.

Public Class methods

pp(obj, out=$>, width=79)

Outputs obj to out in pretty printed format of width columns in width.

If out is omitted, +$>+ is assumed. If width is omitted, 79 is assumed.

PP.pp returns out.

singleline_pp(obj, out=$>)

Outputs obj to out like PP.pp but with no indent and newline.

PP.singleline_pp returns out.


Module: PP::ObjectMixin

Module | PP::ObjectMixin
In: | lib/pp.rb

Methods

pretty_print pretty_print_cycle pretty_print_inspect pretty_print_instance_variables

Public Instance methods

pretty_print(q)

A default pretty printing method for general objects. It calls pretty_print_instance_variables to list instance variables.

If self has a customized (redefined) inspect method, the result of self.inspect is used but it obviously has no line break hints.

This module provides predefined pretty_print methods for some of the most commonly used built-in classes for convenience.

pretty_print_cycle(q)

A default pretty printing method for general objects that are detected as part of a cycle.

pretty_print_inspect()

Is inspect implementation using pretty_print. If you implement pretty_print, it can be used as follows.

  alias inspect pretty_print_inspect

However, doing this requires that every class that inspect is called on implement pretty_print, or a RuntimeError will be raised.

pretty_print_instance_variables()

Returns a sorted array of instance variable names.

This method should return an array of names of instance variables as symbols or strings as: +[:@a, :@b]+.


Module: PP::PPMethods

Module | PP::PPMethods
In: | lib/pp.rb

Methods

comma_breakable guard_inspect_key object_address_group object_group pp pp_hash pp_object seplist

Constants

InspectKey = :__inspect_key__

Public Instance methods

comma_breakable()

A convenience method which is same as follows:

  text ','
  breakable
guard_inspect_key() {|| ...}
object_address_group(obj, &block)
object_group(obj) {|| ...}

A convenience method which is same as follows:

  group(1, '#<' + obj.class.name, '>') { ... }
pp(obj)

Adds obj to the pretty printing buffer using Object#pretty_print or Object#pretty_print_cycle.

Object#pretty_print_cycle is used when obj is already printed, a.k.a the object reference chain has a cycle.

pp_hash(obj)
pp_object(obj)
seplist(list, sep=nil, iter_method=:each) {|element| ...}

Adds a separated list. The list is separated by comma with breakable space, by default.

seplist iterates the list using iter_method. It yields each object to the block given for seplist. The procedure separator_proc is called between each yields.

If the iteration is zero times, separator_proc is not called at all.

If separator_proc is nil or not given, +lambda { comma_breakable }+ is used. If iter_method is not given, :each is used.

For example, following 3 code fragments has similar effect.

  q.seplist([1,2,3]) {|v| xxx v }

  q.seplist([1,2,3], lambda { comma_breakable }, :each) {|v| xxx v }

  xxx 1
  q.comma_breakable
  xxx 2
  q.comma_breakable
  xxx 3


Class: PP::SingleLine

Class | PP::SingleLine
In: | lib/pp.rb
Parent: | PrettyPrint::SingleLine

Included Modules

PPMethods


Class: PStore

Class | PStore
In: | lib/pstore.rb
Parent: | Object

PStore implements a file based persistance mechanism based on a Hash. User code can store hierarchies of Ruby objects (values) into the data store file by name (keys). An object hierarchy may be just a single object. User code may later read values back from the data store or even update data, as needed.

The transactional behavior ensures that any changes succeed or fail together. This can be used to ensure that the data store is not left in a transitory state, where some values were upated but others were not.

Behind the scenes, Ruby objects are stored to the data store file with Marshal. That carries the usual limitations. Proc objects cannot be marshalled, for example.

Usage example:

 require "pstore"

 # a mock wiki object...
 class WikiPage
   def initialize( page_name, author, contents )
     @page_name = page_name
     @revisions = Array.new

     add_revision(author, contents)
   end

   attr_reader :page_name

   def add_revision( author, contents )
     @revisions << { :created  => Time.now,
                     :author   => author,
                     :contents => contents }
   end

   def wiki_page_references
     [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
   end

   # ...
 end

 # create a new page...
 home_page = WikiPage.new( "HomePage", "James Edward Gray II",
                           "A page about the JoysOfDocumentation..." )

 # then we want to update page data and the index together, or not at all...
 wiki = PStore.new("wiki_pages.pstore")
 wiki.transaction do  # begin transaction; do all of this or none of it
   # store page...
   wiki[home_page.page_name] = home_page
   # ensure that an index has been created...
   wiki[:wiki_index] ||= Array.new
   # update wiki index...
   wiki[:wiki_index].push(*home_page.wiki_page_references)
 end                   # commit changes to wiki data store file

 ### Some time later... ###

 # read wiki data...
 wiki.transaction(true) do  # begin read-only transaction, no changes allowed
   wiki.roots.each do |data_root_name|
     p data_root_name
     p wiki[data_root_name]
   end
 end

Methods

[] []= abort commit delete fetch new path root? roots transaction

Classes and Modules

Class PStore::Error

Constants

RDWR_ACCESS | = | File::RDWR | File::CREAT | binmode
RD_ACCESS | = | File::RDONLY | binmode
WR_ACCESS | = | File::WRONLY | File::CREAT | File::TRUNC | binmode

Public Class methods

new(file)

To construct a PStore object, pass in the file path where you would like the data to be stored.

Public Instance methods

[](name)

Retrieves a value from the PStore file data, by name. The hierarchy of Ruby objects stored under that root name will be returned.

WARNING: This method is only valid in a PStore#transaction. It will raise PStore::Error if called at any other time.

[]=(name, value)

Stores an individual Ruby object or a hierarchy of Ruby objects in the data store file under the root name. Assigning to a name already in the data store clobbers the old data.

Example:

 require "pstore"

 store = PStore.new("data_file.pstore")
 store.transaction do  # begin transaction
   # load some data into the store...
   store[:single_object] = "My data..."
   store[:obj_heirarchy] = { "Kev Jackson" => ["rational.rb", "pstore.rb"],
                             "James Gray"  => ["erb.rb", "pstore.rb"] }
 end                   # commit changes to data store file

WARNING: This method is only valid in a PStore#transaction and it cannot be read-only. It will raise PStore::Error if called at any other time.

abort()

Ends the current PStore#transaction, discarding any changes to the data store.

Example:

 require "pstore"

 store = PStore.new("data_file.pstore")
 store.transaction do  # begin transaction
   store[:one] = 1     # this change is not applied, see below...
   store[:two] = 2     # this change is not applied, see below...

   store.abort         # end transaction here, discard all changes

   store[:three] = 3   # this change is never reached
 end

WARNING: This method is only valid in a PStore#transaction. It will raise PStore::Error if called at any other time.

commit()

Ends the current PStore#transaction, committing any changes to the data store immediately.

Example:

 require "pstore"

 store = PStore.new("data_file.pstore")
 store.transaction do  # begin transaction
   # load some data into the store...
   store[:one] = 1
   store[:two] = 2

   store.commit        # end transaction here, committing changes

   store[:three] = 3   # this change is never reached
 end

WARNING: This method is only valid in a PStore#transaction. It will raise PStore::Error if called at any other time.

delete(name)

Removes an object hierarchy from the data store, by name.

WARNING: This method is only valid in a PStore#transaction and it cannot be read-only. It will raise PStore::Error if called at any other time.

fetch(name, default=PStore::Error)

This method is just like PStore#[], save that you may also provide a default value for the object. In the event the specified name is not found in the data store, your default will be returned instead. If you do not specify a default, PStore::Error will be raised if the object is not found.

WARNING: This method is only valid in a PStore#transaction. It will raise PStore::Error if called at any other time.

path()

Returns the path to the data store file.

root?(name)

Returns true if the supplied name is currently in the data store.

WARNING: This method is only valid in a PStore#transaction. It will raise PStore::Error if called at any other time.

roots()

Returns the names of all object hierarchies currently in the store.

WARNING: This method is only valid in a PStore#transaction. It will raise PStore::Error if called at any other time.

transaction(read_only=false) {|pstore| ...}

Opens a new transaction for the data store. Code executed inside a block passed to this method may read and write data to and from the data store file.

At the end of the block, changes are committed to the data store automatically. You may exit the transaction early with a call to either PStore#commit or PStore#abort. See those methods for details about how changes are handled. Raising an uncaught Exception in the block is equivalent to calling PStore#abort.

If read_only is set to true, you will only be allowed to read from the data store during the transaction and any attempts to change the data will raise a PStore::Error.

Note that PStore does not support nested transactions.


Class: PStore::Error

Class | PStore::Error
In: | lib/pstore.rb
Parent: | StandardError

The error type thrown by all PStore methods.


Module: ParseDate

Module | ParseDate
In: | lib/parsedate.rb

Methods

parsedate

Public Instance methods

parsedate(str, comp=false)

Parse a string representation of a date into values. For example:

  require 'parsedate'

  ParseDate.parsedate "Tuesday, July 5th, 2007, 18:35:20 UTC"
  # => [2007, 7, 5, 18, 35, 20, "UTC", 2]

The order is of the form [year, month, day of month, hour, minute, second, timezone, day of week].

ParseDate.parsedate can also take a second argument, comp, which is a boolean telling the method to compensate for dates with years expressed as two digits. Example:

  require 'parsedate'

  ParseDate.parsedate "Mon Dec 25 00 06:53:24 UTC", true
  # => [2000, 12, 25, 6, 53, 24, "UTC", 1]


Class: ParseError

Class | ParseError
In: | lib/optparse.rb
Parent: | RuntimeError

Base class of exceptions from OptionParser.

Methods

inspect message new reason recover set_option to_s

Constants

Reason = 'parse error'.freeze Reason which caused the error.

Attributes

args | [R]
reason | [W]

Public Class methods

new(*args)

Public Instance methods

inspect()
message()

Default stringizing method to emit standard error message.

reason()

Returns error reason. Override this for I18N.

recover(argv)

Pushes back erred argument(s) to argv.

set_option(opt, eq)
to_s()

Alias for message


Class: Pathname

Class | Pathname
In: | lib/pathname.rb
Parent: | Object

Pathname

Pathname represents a pathname which locates a file in a filesystem. The pathname depends on OS: Unix, Windows, etc. Pathname library works with pathnames of local OS. However non-Unix pathnames are supported experimentally.

It does not represent the file itself. A Pathname can be relative or absolute. It‘s not until you try to reference the file that it even matters whether the file exists or not.

Pathname is immutable. It has no method for destructive update.

The value of this class is to manipulate file path information in a neater way than standard Ruby provides. The examples below demonstrate the difference. All functionality from File, FileTest, and some from Dir and FileUtils is included, in an unsurprising way. It is essentially a facade for all of these, and more.

Examples

Example 1: Using Pathname

  require 'pathname'
  p = Pathname.new("/usr/bin/ruby")
  size = p.size              # 27662
  isdir = p.directory?       # false
  dir  = p.dirname           # Pathname:/usr/bin
  base = p.basename          # Pathname:ruby
  dir, base = p.split        # [Pathname:/usr/bin, Pathname:ruby]
  data = p.read
  p.open { |f| _ }
  p.each_line { |line| _ }

Example 2: Using standard Ruby

  p = "/usr/bin/ruby"
  size = File.size(p)        # 27662
  isdir = File.directory?(p) # false
  dir  = File.dirname(p)     # "/usr/bin"
  base = File.basename(p)    # "ruby"
  dir, base = File.split(p)  # ["/usr/bin", "ruby"]
  data = File.read(p)
  File.open(p) { |f| _ }
  File.foreach(p) { |line| _ }

Example 3: Special features

  p1 = Pathname.new("/usr/lib")   # Pathname:/usr/lib
  p2 = p1 + "ruby/1.8"            # Pathname:/usr/lib/ruby/1.8
  p3 = p1.parent                  # Pathname:/usr
  p4 = p2.relative_path_from(p3)  # Pathname:lib/ruby/1.8
  pwd = Pathname.pwd              # Pathname:/home/gavin
  pwd.absolute?                   # true
  p5 = Pathname.new "."           # Pathname:.
  p5 = p5 + "music/../articles"   # Pathname:music/../articles
  p5.cleanpath                    # Pathname:articles
  p5.realpath                     # Pathname:/home/gavin/articles
  p5.children                     # [Pathname:/home/gavin/articles/linux, ...]

Breakdown of functionality

Core methods

These methods are effectively manipulating a String, because that‘s all a path is. Except for mountpoint?, children, and realpath, they don‘t access the filesystem.

  • +
  • join
  • parent
  • root?
  • absolute?
  • relative?
  • relative_path_from
  • each_filename
  • cleanpath
  • realpath
  • children
  • mountpoint?

File status predicate methods

These methods are a facade for FileTest:

  • blockdev?
  • chardev?
  • directory?
  • executable?
  • executable_real?
  • exist?
  • file?
  • grpowned?
  • owned?
  • pipe?
  • readable?
  • world_readable?
  • readable_real?
  • setgid?
  • setuid?
  • size
  • size?
  • socket?
  • sticky?
  • symlink?
  • writable?
  • world_writable?
  • writable_real?
  • zero?

File property and manipulation methods

These methods are a facade for File:

  • atime
  • ctime
  • mtime
  • chmod(mode)
  • lchmod(mode)
  • chown(owner, group)
  • lchown(owner, group)
  • fnmatch(pattern, *args)
  • fnmatch?(pattern, *args)
  • ftype
  • make_link(old)
  • open(*args, &block)
  • readlink
  • rename(to)
  • stat
  • lstat
  • make_symlink(old)
  • truncate(length)
  • utime(atime, mtime)
  • basename(*args)
  • dirname
  • extname
  • expand_path(*args)
  • split

Directory methods

These methods are a facade for Dir:

  • Pathname.glob(*args)
  • Pathname.getwd / Pathname.pwd
  • rmdir
  • entries
  • each_entry(&block)
  • mkdir(*args)
  • opendir(*args)

IO

These methods are a facade for IO:

  • each_line(*args, &block)
  • read(*args)
  • readlines(*args)
  • sysopen(*args)

Utilities

These methods are a mixture of Find, FileUtils, and others:

  • find(&block)
  • mkpath
  • rmtree
  • unlink / delete

Method documentation

As the above section shows, most of the methods in Pathname are facades. The documentation for these methods generally just says, for instance, "See FileTest.writable?", as you should be familiar with the original method anyway, and its documentation (e.g. through ri) will contain more information. In some cases, a brief description will follow.

Methods

+ <=> == === TO_PATH absolute? ascend atime basename blockdev? chardev? chdir children chmod chown chroot cleanpath ctime delete descend dir_foreach directory? dirname each_entry each_filename each_line entries eql? executable? executable_real? exist? expand_path extname file? find fnmatch fnmatch? foreach foreachline freeze ftype getwd glob grpowned? join lchmod lchown link lstat make_link make_symlink mkdir mkpath mountpoint? mtime new open opendir owned? parent pipe? read readable? readable_real? readlines readlink realpath relative? relative_path_from rename rmdir rmtree root? setgid? setuid? size size? socket? split stat sticky? sub symlink symlink? sysopen taint to_s truncate unlink untaint utime world_readable? world_writable? writable? writable_real? zero?

Constants

SEPARATOR_PAT | = | /[#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}]/
SEPARATOR_PAT | = | /#{Regexp.quote File::SEPARATOR}/

External Aliases

getwd -> pwd

Public Class methods

getwd()

See Dir.getwd. Returns the current working directory as a Pathname.

glob(*args) {|p| ...}

See Dir.glob. Returns or yields Pathname objects.

new(path)

Create a Pathname object from the given String (or String-like object). If path contains a NUL character (\0), an ArgumentError is raised.

Public Instance methods

+(other)

Pathname#+ appends a pathname fragment to this one to produce a new Pathname object.

  p1 = Pathname.new("/usr")      # Pathname:/usr
  p2 = p1 + "bin/ruby"           # Pathname:/usr/bin/ruby
  p3 = p1 + "/etc/passwd"        # Pathname:/etc/passwd

This method doesn‘t access the file system; it is pure string manipulation.

<=>(other)

Provides for comparing pathnames, case-sensitively.

==(other)

Compare this pathname with other. The comparison is string-based. Be aware that two different paths (foo.txt and ./foo.txt) can refer to the same file.

===(other)

Alias for #==

TO_PATH()

Alias for to_s

absolute?()

Predicate method for testing whether a path is absolute. It returns true if the pathname begins with a slash.

ascend() {|self| ...}

Iterates over and yields a new Pathname object for each element in the given path in ascending order.

 Pathname.new('/path/to/some/file.rb').ascend {|v| p v}
    #<Pathname:/path/to/some/file.rb>
    #<Pathname:/path/to/some>
    #<Pathname:/path/to>
    #<Pathname:/path>
    #<Pathname:/>

 Pathname.new('path/to/some/file.rb').ascend {|v| p v}
    #<Pathname:path/to/some/file.rb>
    #<Pathname:path/to/some>
    #<Pathname:path/to>
    #<Pathname:path>

It doesn‘t access actual filesystem.

This method is available since 1.8.5.

atime()

See File.atime. Returns last access time.

basename(*args)

See File.basename. Returns the last component of the path.

blockdev?()

See FileTest.blockdev?.

chardev?()

See FileTest.chardev?.

chdir(&block)

Pathname#chdir is obsoleted at 1.8.1.

children(with_directory=true)

Returns the children of the directory (files and subdirectories, not recursive) as an array of Pathname objects. By default, the returned pathnames will have enough information to access the files. If you set with_directory to false, then the returned pathnames will contain the filename only.

For example:

  p = Pathname("/usr/lib/ruby/1.8")
  p.children
      # -> [ Pathname:/usr/lib/ruby/1.8/English.rb,
             Pathname:/usr/lib/ruby/1.8/Env.rb,
             Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ]
  p.children(false)
      # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ]

Note that the result never contain the entries . and .. in the directory because they are not children.

This method has existed since 1.8.1.

chmod(mode)

See File.chmod. Changes permissions.

chown(owner, group)

See File.chown. Change owner and group of file.

chroot()

Pathname#chroot is obsoleted at 1.8.1.

cleanpath(consider_symlink=false)

Returns clean pathname of self with consecutive slashes and useless dots removed. The filesystem is not accessed.

If consider_symlink is true, then a more conservative algorithm is used to avoid breaking symbolic linkages. This may retain more .. entries than absolutely necessary, but without accessing the filesystem, this can‘t be avoided. See realpath.

ctime()

See File.ctime. Returns last (directory entry, not file) change time.

delete()

Alias for unlink

descend() {|v| ...}

Iterates over and yields a new Pathname object for each element in the given path in descending order.

 Pathname.new('/path/to/some/file.rb').descend {|v| p v}
    #<Pathname:/>
    #<Pathname:/path>
    #<Pathname:/path/to>
    #<Pathname:/path/to/some>
    #<Pathname:/path/to/some/file.rb>

 Pathname.new('path/to/some/file.rb').descend {|v| p v}
    #<Pathname:path>
    #<Pathname:path/to>
    #<Pathname:path/to/some>
    #<Pathname:path/to/some/file.rb>

It doesn‘t access actual filesystem.

This method is available since 1.8.5.

dir_foreach(*args, &block)

Pathname#dir_foreach is obsoleted at 1.8.1.

directory?()

See FileTest.directory?.

dirname()

See File.dirname. Returns all but the last component of the path.

each_entry() {|p| ...}

Iterates over the entries (files and subdirectories) in the directory. It yields a Pathname object for each entry.

This method has existed since 1.8.1.

each_filename( {|filename| ...}

Iterates over each component of the path.

  Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
    # yields "usr", "bin", and "ruby".
each_line(*args) {|line| ...}

each_line iterates over the line in the file. It yields a String object for each line.

This method has existed since 1.8.1.

entries()

Return the entries (files and subdirectories) in the directory, each as a Pathname object.

eql?(other)

Alias for #==

executable?()

See FileTest.executable?.

executable_real?()

See FileTest.executable_real?.

exist?()

See FileTest.exist?.

expand_path(*args)

See File.expand_path.

extname()

See File.extname. Returns the file‘s extension.

file?()

See FileTest.file?.

find() {|p| ...}

Pathname#find is an iterator to traverse a directory tree in a depth first manner. It yields a Pathname for each file under "this" directory.

Since it is implemented by find.rb, Find.prune can be used to control the traverse.

If self is ., yielded pathnames begin with a filename in the current directory, not ./.

fnmatch(pattern, *args)

See File.fnmatch. Return true if the receiver matches the given pattern.

fnmatch?(pattern, *args)

See File.fnmatch? (same as fnmatch).

foreach(*args, &block)

This method is obsoleted at 1.8.1. Use each_line or each_entry.

foreachline(*args, &block)

Pathname#foreachline is obsoleted at 1.8.1. Use each_line.

freeze()
ftype()

See File.ftype. Returns "type" of file ("file", "directory", etc).

grpowned?()

See FileTest.grpowned?.

join(*args)

Pathname#join joins pathnames.

path0.join(path1, …, pathN) is the same as path0 + path1 + … + pathN.

lchmod(mode)

See File.lchmod.

lchown(owner, group)

See File.lchown.

link(old)

Pathname#link is confusing and obsoleted because the receiver/argument order is inverted to corresponding system call.

lstat()

See File.lstat.

make_link(old)

See File.link. Creates a hard link.

make_symlink(old)

See File.symlink. Creates a symbolic link.

mkdir(*args)

See Dir.mkdir. Create the referenced directory.

mkpath()

See FileUtils.mkpath. Creates a full path, including any intermediate directories that don‘t yet exist.

mountpoint?()

mountpoint? returns true if self points to a mountpoint.

mtime()

See File.mtime. Returns last modification time.

open(*args) {|file| ...}

See File.open. Opens the file for reading or writing.

opendir() {|dir| ...}

See Dir.open.

owned?()

See FileTest.owned?.

parent()

parent returns the parent directory.

This is same as self + ’..’.

pipe?()

See FileTest.pipe?.

read(*args)

See IO.read. Returns all the bytes from the file, or the first N if specified.

readable?()

See FileTest.readable?.

readable_real?()

See FileTest.readable_real?.

readlines(*args)

See IO.readlines. Returns all the lines from the file.

readlink()

See File.readlink. Read symbolic link.

realpath()

Returns a real (absolute) pathname of self in the actual filesystem. The real pathname doesn‘t contain symlinks or useless dots.

No arguments should be given; the old behaviour is obsoleted.

relative?()

The opposite of absolute?

relative_path_from(base_directory)

relative_path_from returns a relative path from the argument to the receiver. If self is absolute, the argument must be absolute too. If self is relative, the argument must be relative too.

relative_path_from doesn‘t access the filesystem. It assumes no symlinks.

ArgumentError is raised when it cannot find a relative path.

This method has existed since 1.8.1.

rename(to)

See File.rename. Rename the file.

rmdir()

See Dir.rmdir. Remove the referenced directory.

rmtree()

See FileUtils.rm_r. Deletes a directory and all beneath it.

root?()

root? is a predicate for root directories. I.e. it returns true if the pathname consists of consecutive slashes.

It doesn‘t access actual filesystem. So it may return false for some pathnames which points to roots such as /usr/...

setgid?()

See FileTest.setgid?.

setuid?()

See FileTest.setuid?.

size()

See FileTest.size.

size?()

See FileTest.size?.

socket?()

See FileTest.socket?.

split()

See File.split. Returns the dirname and the basename in an Array.

stat()

See File.stat. Returns a File::Stat object.

sticky?()

See FileTest.sticky?.

sub(pattern, *rest, &block)

Return a pathname which is substituted by String#sub.

symlink(old)

Pathname#symlink is confusing and obsoleted because the receiver/argument order is inverted to corresponding system call.

symlink?()

See FileTest.symlink?.

sysopen(*args)

See IO.sysopen.

taint()
to_s()

Return the path as a String.

truncate(length)

See File.truncate. Truncate the file to length bytes.

unlink()

Removes a file or directory, using File.unlink or Dir.unlink as necessary.

untaint()
utime(atime, mtime)

See File.utime. Update the access and modification times.

world_readable?()

See FileTest.world_readable?.

world_writable?()

See FileTest.world_writable?.

writable?()

See FileTest.writable?.

writable_real?()

See FileTest.writable_real?.

zero?()

See FileTest.zero?.


Module: Ping

Module | Ping
In: | lib/ping.rb

Ping contains routines to test for the reachability of remote hosts. Currently the only routine implemented is pingecho().

Ping.pingecho uses a TCP echo (not an ICMP echo) to determine if the remote host is reachable. This is usually adequate to tell that a remote host is available to telnet, ftp, or ssh to.

Warning: Ping.pingecho may block for a long time if DNS resolution is slow. Requiring ‘resolv-replace’ allows non-blocking name resolution.

Usage:

  require 'ping'

  puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10)

Methods

pingecho

Public Instance methods

pingecho(host, timeout=5, service="echo")

Return true if we can open a connection to the hostname or IP address host on port service (which defaults to the "echo" port) waiting up to timeout seconds.

Example:

  require 'ping'

  Ping.pingecho "google.com", 10, 80


Module: Precision

Module | Precision
In: | prec.c

Precision is a mixin for concrete numeric classes with precision. Here, `precision’ means the fineness of approximation of a real number, so, this module should not be included into anything which is not a subset of Real (so it should not be included in classes such as Complex or Matrix).

Methods

included prec prec_f prec_i

Public Class methods

included(p1)

call_seq:

  included

When the Precision module is mixed-in to a class, this included method is used to add our default induced_from implementation to the host class.

Public Instance methods

num.prec(klass) => a_klass

Converts self into an instance of klass. By default, prec invokes

   klass.induced_from(num)

and returns its value. So, if klass.induced_from doesn‘t return an instance of klass, it will be necessary to reimplement prec.

num.prec_f => Float

Returns a Float converted from num. It is equivalent to prec(Float).

num.prec_i => Integer

Returns an Integer converted from num. It is equivalent to prec(Integer).


Class: PrettyPrint

Class | PrettyPrint
In: | lib/prettyprint.rb
Parent: | Object

This class implements a pretty printing algorithm. It finds line breaks and nice indentations for grouped structure.

By default, the class assumes that primitive elements are strings and each byte in the strings have single column in width. But it can be used for other situations by giving suitable arguments for some methods:

  • newline object and space generation block for PrettyPrint.new
  • optional width argument for PrettyPrint#text
  • PrettyPrint#breakable

There are several candidate uses:

  • text formatting using proportional fonts
  • multibyte characters which has columns different to number of bytes
  • non-string formatting

Bugs

  • Box based formatting?
  • Other (better) model/algorithm?

References

Christian Lindig, Strictly Pretty, March 2000, www.st.cs.uni-sb.de/~lindig/papers/#pretty

Philip Wadler, A prettier printer, March 1998, homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier

Author

Tanaka Akira <akr@m17n.org>

Methods

break_outmost_groups breakable current_group fill_breakable first? flush format group group_sub nest new singleline_format text

Classes and Modules

Class PrettyPrint::Breakable
Class PrettyPrint::Group
Class PrettyPrint::GroupQueue
Class PrettyPrint::SingleLine
Class PrettyPrint::Text

Attributes

genspace | [R]
group_queue | [R]
indent | [R]
maxwidth | [R]
newline | [R]
output | [R]

Public Class methods

format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n} {|q| ...}

This is a convenience method which is same as follows:

  begin
    q = PrettyPrint.new(output, maxwidth, newline, &genspace)
    ...
    q.flush
    output
  end
new(output='', maxwidth=79, newline="\n", &genspace)

Creates a buffer for pretty printing.

output is an output target. If it is not specified, ’’ is assumed. It should have a << method which accepts the first argument obj of PrettyPrint#text, the first argument sep of PrettyPrint#breakable, the first argument newline of PrettyPrint.new, and the result of a given block for PrettyPrint.new.

maxwidth specifies maximum line length. If it is not specified, 79 is assumed. However actual outputs may overflow maxwidth if long non-breakable texts are provided.

newline is used for line breaks. "\n" is used if it is not specified.

The block is used to generate spaces. {|width| ’ ’ * width} is used if it is not given.

singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil) {|q| ...}

This is similar to PrettyPrint::format but the result has no breaks.

maxwidth, newline and genspace are ignored.

The invocation of breakable in the block doesn‘t break a line and is treated as just an invocation of text.

Public Instance methods

break_outmost_groups()
breakable(sep=' ', width=sep.length)

This tells "you can break a line here if necessary", and a width\-column text sep is inserted if a line is not broken at the point.

If sep is not specified, " " is used.

If width is not specified, +sep.length+ is used. You will have to specify this when sep is a multibyte character, for example.

current_group()
fill_breakable(sep=' ', width=sep.length)
first?()

first? is a predicate to test the call is a first call to first? with current group.

It is useful to format comma separated values as:

  q.group(1, '[', ']') {
    xxx.each {|yyy|
      unless q.first?
        q.text ','
        q.breakable
      end
      ... pretty printing yyy ...
    }
  }

first? is obsoleted in 1.8.2.

flush()

outputs buffered data.

group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length) {|| ...}

Groups line break hints added in the block. The line break hints are all to be used or not.

If indent is specified, the method call is regarded as nested by nest(indent) { … }.

If open_obj is specified, text open_obj, open_width is called before grouping. If close_obj is specified, text close_obj, close_width is called after grouping.

group_sub() {|| ...}
nest(indent) {|| ...}

Increases left margin after newline with indent for line breaks added in the block.

text(obj, width=obj.length)

This adds obj as a text of width columns in width.

If width is not specified, obj.length is used.


Class: PrettyPrint::Breakable

Class | PrettyPrint::Breakable
In: | lib/prettyprint.rb
Parent: | Object

Methods

new output

Attributes

indent | [R]
obj | [R]
width | [R]

Public Class methods

new(sep, width, q)

Public Instance methods

output(out, output_width)


Class: PrettyPrint::Group

Class | PrettyPrint::Group
In: | lib/prettyprint.rb
Parent: | Object

Methods

break break? first? new

Attributes

breakables | [R]
depth | [R]

Public Class methods

new(depth)

Public Instance methods

break()
break?()
first?()


Class: PrettyPrint::GroupQueue

Class | PrettyPrint::GroupQueue
In: | lib/prettyprint.rb
Parent: | Object

Methods

delete deq enq new

Public Class methods

new(*groups)

Public Instance methods

delete(group)
deq()
enq(group)


Class: PrettyPrint::SingleLine

Class | PrettyPrint::SingleLine
In: | lib/prettyprint.rb
Parent: | Object

Methods

breakable first? flush group nest new text

Public Class methods

new(output, maxwidth=nil, newline=nil)

Public Instance methods

breakable(sep=' ', width=nil)
first?()
flush()
group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil) {|| ...}
nest(indent) {|| ...}
text(obj, width=nil)


Class: PrettyPrint::Text

Class | PrettyPrint::Text
In: | lib/prettyprint.rb
Parent: | Object

Methods

add new output

Attributes

width [R]

Public Class methods

new()

Public Instance methods

add(obj, width)
output(out, output_width)


Class: Prime

Class | Prime
In: | lib/mathn.rb
Parent: | Object

Methods

each new next succ

Included Modules

Enumerable

Public Class methods

new()

Public Instance methods

each() {|succ| ...}
next()

Alias for succ

succ()


Class: Proc

Class | Proc
In: | eval.c
Parent: | Object

Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.

   def gen_times(factor)
     return Proc.new {|n| n*factor }
   end

   times3 = gen_times(3)
   times5 = gen_times(5)

   times3.call(12)               #=> 36
   times5.call(5)                #=> 25
   times3.call(times5.call(4))   #=> 60

Methods

== [] arity binding call clone dup new to_proc to_s

Public Class methods

Proc.new {|...| block } => a_proc
Proc.new => a_proc

Creates a new Proc object, bound to the current context. Proc::new may be called without a block only within a method with an attached block, in which case that block is converted to the Proc object.

   def proc_from
     Proc.new
   end
   proc = proc_from { "hello" }
   proc.call   #=> "hello"

Public Instance methods

prc == other_proc => true or false

Return true if prc is the same object as other_proc, or if they are both procs with the same body.

prc.call(params,...) => obj
prc[params,...] => obj

Invokes the block, setting the block‘s parameters to the values in params using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array).

For procs created using Kernel.proc, generates an error if the wrong number of parameters are passed to a proc with multiple parameters. For procs created using Proc.new, extra parameters are silently discarded.

Returns the value of the last expression evaluated in the block. See also Proc#yield.

   a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
   a_proc.call(9, 1, 2, 3)   #=> [9, 18, 27]
   a_proc[9, 1, 2, 3]        #=> [9, 18, 27]
   a_proc = Proc.new {|a,b| a}
   a_proc.call(1,2,3)

produces:

   prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
    from prog.rb:4:in `call'
    from prog.rb:5
prc.arity → fixnum

Returns the number of arguments that would not be ignored. If the block is declared to take no arguments, returns 0. If the block is known to take exactly n arguments, returns n. If the block has optional arguments, return -n-1, where n is the number of mandatory arguments. A proc with no argument declarations is the same a block declaring || as its arguments.

   Proc.new {}.arity          #=>  0
   Proc.new {||}.arity        #=>  0
   Proc.new {|a|}.arity       #=>  1
   Proc.new {|a,b|}.arity     #=>  2
   Proc.new {|a,b,c|}.arity   #=>  3
   Proc.new {|*a|}.arity      #=> -1
   Proc.new {|a,*b|}.arity    #=> -2
prc.binding => binding

Returns the binding associated with prc. Note that Kernel#eval accepts either a Proc or a Binding object as its second parameter.

   def fred(param)
     proc {}
   end

   b = fred(99)
   eval("param", b.binding)   #=> 99
   eval("param", b)           #=> 99
prc.call(params,...) => obj
prc[params,...] => obj

Invokes the block, setting the block‘s parameters to the values in params using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array).

For procs created using Kernel.proc, generates an error if the wrong number of parameters are passed to a proc with multiple parameters. For procs created using Proc.new, extra parameters are silently discarded.

Returns the value of the last expression evaluated in the block. See also Proc#yield.

   a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
   a_proc.call(9, 1, 2, 3)   #=> [9, 18, 27]
   a_proc[9, 1, 2, 3]        #=> [9, 18, 27]
   a_proc = Proc.new {|a,b| a}
   a_proc.call(1,2,3)

produces:

   prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
    from prog.rb:4:in `call'
    from prog.rb:5
clone()

MISSING: documentation

dup()

MISSING: documentation

prc.to_proc → prc

Part of the protocol for converting objects to Proc objects. Instances of class Proc simply return themselves.

prc.to_s => string

Shows the unique identifier for this proc, along with an indication of where the proc was defined.


Module: Process

Module | Process
In: | process.c

The Process module is a collection of methods used to manipulate processes.

Methods

abort detach egid egid= euid euid= exit exit! fork getpgid getpriority getrlimit gid gid= groups groups= initgroups kill maxgroups maxgroups= pid ppid setpgid setpgrp setpriority setrlimit setsid times uid uid= wait wait2 waitall waitpid waitpid2

Classes and Modules

Module Process::GID
Module Process::Sys
Module Process::UID
Class Process::Status

Constants

WNOHANG | = | INT2FIX(WNOHANG)
WNOHANG | = | INT2FIX(0)
WUNTRACED | = | INT2FIX(WUNTRACED)
WUNTRACED | = | INT2FIX(0)
PRIO_PROCESS | = | INT2FIX(PRIO_PROCESS)
PRIO_PGRP | = | INT2FIX(PRIO_PGRP)
PRIO_USER | = | INT2FIX(PRIO_USER)
RLIM_INFINITY | = | RLIM2NUM(RLIM_INFINITY)
RLIM_SAVED_MAX | = | RLIM2NUM(RLIM_SAVED_MAX)
RLIM_SAVED_CUR | = | RLIM2NUM(RLIM_SAVED_CUR)
RLIMIT_CORE | = | INT2FIX(RLIMIT_CORE)
RLIMIT_CPU | = | INT2FIX(RLIMIT_CPU)
RLIMIT_DATA | = | INT2FIX(RLIMIT_DATA)
RLIMIT_FSIZE | = | INT2FIX(RLIMIT_FSIZE)
RLIMIT_NOFILE | = | INT2FIX(RLIMIT_NOFILE)
RLIMIT_STACK | = | INT2FIX(RLIMIT_STACK)
RLIMIT_AS | = | INT2FIX(RLIMIT_AS)
RLIMIT_MEMLOCK | = | INT2FIX(RLIMIT_MEMLOCK)
RLIMIT_NPROC | = | INT2FIX(RLIMIT_NPROC)
RLIMIT_RSS | = | INT2FIX(RLIMIT_RSS)
RLIMIT_SBSIZE | = | INT2FIX(RLIMIT_SBSIZE)

Public Class methods

abort
Kernel::abort
Process::abort

Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.

Process.detach(pid) => thread

Some operating systems retain the status of terminated child processes until the parent collects that status (normally using some variant of wait(). If the parent never collects this status, the child stays around as a zombie process. Process::detach prevents this by setting up a separate Ruby thread whose sole job is to reap the status of the process pid when it terminates. Use detach only when you do not intent to explicitly wait for the child to terminate. detach only checks the status periodically (currently once each second).

In this first example, we don‘t reap the first child process, so it appears as a zombie in the process status display.

   p1 = fork { sleep 0.1 }
   p2 = fork { sleep 0.2 }
   Process.waitpid(p2)
   sleep 2
   system("ps -ho pid,state -p #{p1}")

produces:

   27389 Z

In the next example, Process::detach is used to reap the child automatically.

   p1 = fork { sleep 0.1 }
   p2 = fork { sleep 0.2 }
   Process.detach(p1)
   Process.waitpid(p2)
   sleep 2
   system("ps -ho pid,state -p #{p1}")

(produces no output)

Process.egid => fixnum
Process::GID.eid => fixnum
Process::Sys.geteid => fixnum

Returns the effective group ID for this process. Not available on all platforms.

   Process.egid   #=> 500
Process.egid = fixnum => fixnum

Sets the effective group ID for this process. Not available on all platforms.

Process.euid => fixnum
Process::UID.eid => fixnum
Process::Sys.geteuid => fixnum

Returns the effective user ID for this process.

   Process.euid   #=> 501
Process.euid= integer

Sets the effective user ID for this process. Not available on all platforms.

exit(integer=0)
Kernel::exit(integer=0)
Process::exit(integer=0)

Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.

   begin
     exit
     puts "never get here"
   rescue SystemExit
     puts "rescued a SystemExit exception"
   end
   puts "after begin block"

produces:

   rescued a SystemExit exception
   after begin block

Just prior to termination, Ruby executes any at_exit functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer).

   at_exit { puts "at_exit function" }
   ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
   exit

produces:

   at_exit function
   in finalizer
Process.exit!(fixnum=-1)

Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.

   Process.exit!(0)
Kernel.fork [{ block }] => fixnum or nil
Process.fork [{ block }] => fixnum or nil

Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

The thread calling fork is the only thread in the created child process. fork doesn‘t copy other threads.

Process.getpgid(pid) => integer

Returns the process group ID for the given process id. Not available on all platforms.

   Process.getpgid(Process.ppid())   #=> 25527
Process.getpriority(kind, integer) => fixnum

Gets the scheduling priority for specified process, process group, or user. kind indicates the kind of entity to find: one of Process::PRIO_PGRP, Process::PRIO_USER, or Process::PRIO_PROCESS. integer is an id indicating the particular process, process group, or user (an id of 0 means current). Lower priorities are more favorable for scheduling. Not available on all platforms.

   Process.getpriority(Process::PRIO_USER, 0)      #=> 19
   Process.getpriority(Process::PRIO_PROCESS, 0)   #=> 19
Process.getrlimit(resource) => [cur_limit, max_limit]

Gets the resource limit of the process. cur_limit means current (soft) limit and max_limit means maximum (hard) limit.

resource indicates the kind of resource to limit: such as Process::RLIMIT_CORE, Process::RLIMIT_CPU, etc. See Process.setrlimit for details.

cur_limit and max_limit may be Process::RLIM_INFINITY, Process::RLIM_SAVED_MAX or Process::RLIM_SAVED_CUR. See Process.setrlimit and the system getrlimit(2) manual for details.

Process.gid => fixnum
Process::GID.rid => fixnum
Process::Sys.getgid => fixnum

Returns the (real) group ID for this process.

   Process.gid   #=> 500
Process.gid= fixnum => fixnum

Sets the group ID for this process.

Process.groups => array

Get an Array of the gids of groups in the supplemental group access list for this process.

   Process.groups   #=> [27, 6, 10, 11]
Process.groups= array => array

Set the supplemental group access list to the given Array of group IDs.

   Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
   Process.groups = [27, 6, 10, 11]   #=> [27, 6, 10, 11]
   Process.groups   #=> [27, 6, 10, 11]
Process.initgroups(username, gid) => array

Initializes the supplemental group access list by reading the system group database and using all groups of which the given user is a member. The group with the specified gid is also added to the list. Returns the resulting Array of the gids of all the groups in the supplementary group access list. Not available on all platforms.

   Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
   Process.initgroups( "mgranger", 30 )   #=> [30, 6, 10, 11]
   Process.groups   #=> [30, 6, 10, 11]
Process.kill(signal, pid, ...) => fixnum

Sends the given signal to the specified process id(s), or to the current process if pid is zero. signal may be an integer signal number or a POSIX signal name (either with or without a SIG prefix). If signal is negative (or starts with a minus sign), kills process groups instead of processes. Not all signals are available on all platforms.

   pid = fork do
      Signal.trap("HUP") { puts "Ouch!"; exit }
      # ... do some work ...
   end
   # ...
   Process.kill("HUP", pid)
   Process.wait

produces:

   Ouch!
Process.maxgroups => fixnum

Returns the maximum number of gids allowed in the supplemental group access list.

   Process.maxgroups   #=> 32
Process.maxgroups= fixnum => fixnum

Sets the maximum number of gids allowed in the supplemental group access list.

Process.pid => fixnum

Returns the process id of this process. Not available on all platforms.

   Process.pid   #=> 27415
Process.ppid => fixnum

Returns the process id of the parent of this process. Always returns 0 on NT. Not available on all platforms.

   puts "I am #{Process.pid}"
   Process.fork { puts "Dad is #{Process.ppid}" }

produces:

   I am 27417
   Dad is 27417
Process.setpgid(pid, integer) => 0

Sets the process group ID of pid (0 indicates this process) to integer. Not available on all platforms.

Process.setpgrp => 0

Equivalent to setpgid(0,0). Not available on all platforms.

Process.setpriority(kind, integer, priority) => 0

See Process#getpriority.

   Process.setpriority(Process::PRIO_USER, 0, 19)      #=> 0
   Process.setpriority(Process::PRIO_PROCESS, 0, 19)   #=> 0
   Process.getpriority(Process::PRIO_USER, 0)          #=> 19
   Process.getpriority(Process::PRIO_PROCESS, 0)       #=> 19
Process.setrlimit(resource, cur_limit, max_limit) => nil
Process.setrlimit(resource, cur_limit) => nil

Sets the resource limit of the process. cur_limit means current (soft) limit and max_limit means maximum (hard) limit.

If max_limit is not given, cur_limit is used.

resource indicates the kind of resource to limit. The list of resources are OS dependent. Ruby may support following resources.

Process::RLIMIT_CORE
core size (bytes) (SUSv3)
Process::RLIMIT_CPU
CPU time (seconds) (SUSv3)
Process::RLIMIT_DATA
data segment (bytes) (SUSv3)
Process::RLIMIT_FSIZE
file size (bytes) (SUSv3)
Process::RLIMIT_NOFILE
file descriptors (number) (SUSv3)
Process::RLIMIT_STACK
stack size (bytes) (SUSv3)
Process::RLIMIT_AS
total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD but 4.4BSD-Lite)
Process::RLIMIT_MEMLOCK
total size for mlock(2) (bytes) (4.4BSD, GNU/Linux)
Process::RLIMIT_NPROC
number of processes for the user (number) (4.4BSD, GNU/Linux)
Process::RLIMIT_RSS
resident memory size (bytes) (4.2BSD, GNU/Linux)
Process::RLIMIT_SBSIZE
all socket buffers (bytes) (NetBSD, FreeBSD)

Other Process::RLIMIT_??? constants may be defined.

cur_limit and max_limit may be Process::RLIM_INFINITY, which means that the resource is not limited. They may be Process::RLIM_SAVED_MAX or Process::RLIM_SAVED_CUR too. See system setrlimit(2) manual for details.

Process.setsid => fixnum

Establishes this process as a new session and process group leader, with no controlling tty. Returns the session id. Not available on all platforms.

   Process.setsid   #=> 27422
Process.times => aStructTms

Returns a Tms structure (see Struct::Tms on page 388) that contains user and system CPU times for this process.

   t = Process.times
   [ t.utime, t.stime ]   #=> [0.0, 0.02]
Process.uid => fixnum
Process::UID.rid => fixnum
Process::Sys.getuid => fixnum

Returns the (real) user ID of this process.

   Process.uid   #=> 501
Process.uid= integer => numeric

Sets the (integer) user ID for this process. Not available on all platforms.

Process.wait() => fixnum
Process.wait(pid=-1, flags=0) => fixnum
Process.waitpid(pid=-1, flags=0) => fixnum

Waits for a child process to exit, returns its process id, and sets $? to a Process::Status object containing information on that process. Which child it waits on depends on the value of pid:

> 0: | Waits for the child whose process ID equals pid.
0: | Waits for any child whose process group ID equals that of the calling process.
-1: | Waits for any child process (the default if no pid is given).
< -1: | Waits for any child whose process group ID equals the absolute value of pid.

The flags argument may be a logical or of the flag values Process::WNOHANG (do not block if no child available) or Process::WUNTRACED (return stopped children that haven‘t been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms.

Calling this method raises a SystemError if there are no child processes. Not available on all platforms.

   include Process
   fork { exit 99 }                 #=> 27429
   wait                             #=> 27429
   $?.exitstatus                    #=> 99

   pid = fork { sleep 3 }           #=> 27440
   Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
   waitpid(pid, Process::WNOHANG)   #=> nil
   Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
   waitpid(pid, 0)                  #=> 27440
   Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003
Process.wait2(pid=-1, flags=0) => [pid, status]
Process.waitpid2(pid=-1, flags=0) => [pid, status]

Waits for a child process to exit (see Process::waitpid for exact semantics) and returns an array containing the process id and the exit status (a Process::Status object) of that child. Raises a SystemError if there are no child processes.

   Process.fork { exit 99 }   #=> 27437
   pid, status = Process.wait2
   pid                        #=> 27437
   status.exitstatus          #=> 99
Process.waitall => [ [pid1,status1], ...]

Waits for all children, returning an array of pid/status pairs (where status is a Process::Status object).

   fork { sleep 0.2; exit 2 }   #=> 27432
   fork { sleep 0.1; exit 1 }   #=> 27433
   fork {            exit 0 }   #=> 27434
   p Process.waitall

produces:

   [[27434, #<Process::Status: pid=27434,exited(0)>],
    [27433, #<Process::Status: pid=27433,exited(1)>],
    [27432, #<Process::Status: pid=27432,exited(2)>]]
Process.wait() => fixnum
Process.wait(pid=-1, flags=0) => fixnum
Process.waitpid(pid=-1, flags=0) => fixnum

Waits for a child process to exit, returns its process id, and sets $? to a Process::Status object containing information on that process. Which child it waits on depends on the value of pid:

> 0: | Waits for the child whose process ID equals pid.
0: | Waits for any child whose process group ID equals that of the calling process.
-1: | Waits for any child process (the default if no pid is given).
< -1: | Waits for any child whose process group ID equals the absolute value of pid.

The flags argument may be a logical or of the flag values Process::WNOHANG (do not block if no child available) or Process::WUNTRACED (return stopped children that haven‘t been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms.

Calling this method raises a SystemError if there are no child processes. Not available on all platforms.

   include Process
   fork { exit 99 }                 #=> 27429
   wait                             #=> 27429
   $?.exitstatus                    #=> 99

   pid = fork { sleep 3 }           #=> 27440
   Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
   waitpid(pid, Process::WNOHANG)   #=> nil
   Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
   waitpid(pid, 0)                  #=> 27440
   Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003
Process.wait2(pid=-1, flags=0) => [pid, status]
Process.waitpid2(pid=-1, flags=0) => [pid, status]

Waits for a child process to exit (see Process::waitpid for exact semantics) and returns an array containing the process id and the exit status (a Process::Status object) of that child. Raises a SystemError if there are no child processes.

   Process.fork { exit 99 }   #=> 27437
   pid, status = Process.wait2
   pid                        #=> 27437
   status.exitstatus          #=> 99


Module: Process::GID

Module | Process::GID
In: | process.c

The Process::GID module contains a collection of module functions which can be used to portably get, set, and switch the current process‘s real, effective, and saved group IDs.

Methods

change_privilege eid grant_privilege re_exchange re_exchangeable? rid sid_available? switch

Public Class methods

Process::GID.change_privilege(integer) => fixnum

Change the current process‘s real and effective group ID to that specified by integer. Returns the new group ID. Not available on all platforms.

   [Process.gid, Process.egid]          #=> [0, 0]
   Process::GID.change_privilege(33)    #=> 33
   [Process.gid, Process.egid]          #=> [33, 33]
Process.egid => fixnum
Process::GID.eid => fixnum
Process::Sys.geteid => fixnum

Returns the effective group ID for this process. Not available on all platforms.

   Process.egid   #=> 500
Process::GID.grant_privilege(integer) => fixnum
Process::GID.eid = integer => fixnum

Set the effective group ID, and if possible, the saved group ID of the process to the given integer. Returns the new effective group ID. Not available on all platforms.

   [Process.gid, Process.egid]          #=> [0, 0]
   Process::GID.grant_privilege(31)     #=> 33
   [Process.gid, Process.egid]          #=> [0, 33]
Process::GID.re_exchange => fixnum

Exchange real and effective group IDs and return the new effective group ID. Not available on all platforms.

   [Process.gid, Process.egid]   #=> [0, 33]
   Process::GID.re_exchange      #=> 0
   [Process.gid, Process.egid]   #=> [33, 0]
Process::GID.re_exchangeable? => true or false

Returns true if the real and effective group IDs of a process may be exchanged on the current platform.

Process.gid => fixnum
Process::GID.rid => fixnum
Process::Sys.getgid => fixnum

Returns the (real) group ID for this process.

   Process.gid   #=> 500
Process::GID.sid_available? => true or false

Returns true if the current platform has saved group ID functionality.

Process::GID.switch => fixnum
Process::GID.switch {|| block} => object

Switch the effective and real group IDs of the current process. If a block is given, the group IDs will be switched back after the block is executed. Returns the new effective group ID if called without a block, and the return value of the block if one is given.


Class: Process::Status

Class | Process::Status
In: | process.c
Parent: | Object

Process::Status encapsulates the information on the status of a running or terminated system process. The built-in variable $? is either nil or a Process::Status object.

   fork { exit 99 }   #=> 26557
   Process.wait       #=> 26557
   $?.class           #=> Process::Status
   $?.to_i            #=> 25344
   $? >> 8            #=> 99
   $?.stopped?        #=> false
   $?.exited?         #=> true
   $?.exitstatus      #=> 99

Posix systems record information on processes using a 16-bit integer. The lower bits record the process status (stopped, exited, signaled) and the upper bits possibly contain additional information (for example the program‘s return code in the case of exited processes). Pre Ruby 1.8, these bits were exposed directly to the Ruby program. Ruby now encapsulates these in a Process::Status object. To maximize compatibility, however, these objects retain a bit-oriented interface. In the descriptions that follow, when we talk about the integer value of stat, we‘re referring to this 16 bit value.

Methods

& == >> coredump? exited? exitstatus inspect pid signaled? stopped? stopsig success? termsig to_i to_int to_s

Public Instance methods

stat & num => fixnum

Logical AND of the bits in stat with num.

   fork { exit 0x37 }
   Process.wait
   sprintf('%04x', $?.to_i)       #=> "3700"
   sprintf('%04x', $? & 0x1e00)   #=> "1600"
stat == other => true or false

Returns true if the integer value of stat equals other.

stat >> num => fixnum

Shift the bits in stat right num places.

   fork { exit 99 }   #=> 26563
   Process.wait       #=> 26563
   $?.to_i            #=> 25344
   $? >> 8            #=> 99
stat.coredump? => true or false

Returns true if stat generated a coredump when it terminated. Not available on all platforms.

stat.exited? => true or false

Returns true if stat exited normally (for example using an exit() call or finishing the program).

stat.exitstatus => fixnum or nil

Returns the least significant eight bits of the return code of stat. Only available if exited? is true.

   fork { }           #=> 26572
   Process.wait       #=> 26572
   $?.exited?         #=> true
   $?.exitstatus      #=> 0

   fork { exit 99 }   #=> 26573
   Process.wait       #=> 26573
   $?.exited?         #=> true
   $?.exitstatus      #=> 99
stat.inspect => string

Override the inspection method.

stat.pid => fixnum

Returns the process ID that this status object represents.

   fork { exit }   #=> 26569
   Process.wait    #=> 26569
   $?.pid          #=> 26569
stat.signaled? => true or false

Returns true if stat terminated because of an uncaught signal.

stat.stopped? => true or false

Returns true if this process is stopped. This is only returned if the corresponding wait call had the WUNTRACED flag set.

stat.stopsig => fixnum or nil

Returns the number of the signal that caused stat to stop (or nil if self is not stopped).

stat.success? => true, false or nil

Returns true if stat is successful, false if not. Returns nil if exited? is not true.

stat.termsig => fixnum or nil

Returns the number of the signal that caused stat to terminate (or nil if self was not terminated by an uncaught signal).

stat.to_i => fixnum
stat.to_int => fixnum

Returns the bits in stat as a Fixnum. Poking around in these bits is platform dependent.

   fork { exit 0xab }         #=> 26566
   Process.wait               #=> 26566
   sprintf('%04x', $?.to_i)   #=> "ab00"
stat.to_i => fixnum
stat.to_int => fixnum

Returns the bits in stat as a Fixnum. Poking around in these bits is platform dependent.

   fork { exit 0xab }         #=> 26566
   Process.wait               #=> 26566
   sprintf('%04x', $?.to_i)   #=> "ab00"
stat.to_s => string

Equivalent to stat.to_i.to_s.


Module: Process::Sys

Module | Process::Sys
In: | process.c

The Process::Sys module contains UID and GID functions which provide direct bindings to the system calls of the same names instead of the more-portable versions of the same functionality found in the Process, Process::UID, and Process::GID modules.

Methods

getegid geteuid getgid getuid issetugid setegid seteuid setgid setregid setresgid setresuid setreuid setrgid setruid setuid

Public Class methods

Process.egid => fixnum
Process::GID.eid => fixnum
Process::Sys.geteid => fixnum

Returns the effective group ID for this process. Not available on all platforms.

   Process.egid   #=> 500
Process.euid => fixnum
Process::UID.eid => fixnum
Process::Sys.geteuid => fixnum

Returns the effective user ID for this process.

   Process.euid   #=> 501
Process.gid => fixnum
Process::GID.rid => fixnum
Process::Sys.getgid => fixnum

Returns the (real) group ID for this process.

   Process.gid   #=> 500
Process.uid => fixnum
Process::UID.rid => fixnum
Process::Sys.getuid => fixnum

Returns the (real) user ID of this process.

   Process.uid   #=> 501
Process::Sys.issetugid => true or false

Returns true if the process was created as a result of an execve(2) system call which had either of the setuid or setgid bits set (and extra privileges were given as a result) or if it has changed any of its real, effective or saved user or group IDs since it began execution.

Process::Sys.setegid(integer) => nil

Set the effective group ID of the calling process to integer. Not available on all platforms.

Process::Sys.seteuid(integer) => nil

Set the effective user ID of the calling process to integer. Not available on all platforms.

Process::Sys.setgid(integer) => nil

Set the group ID of the current process to integer. Not available on all platforms.

Process::Sys.setregid(rid, eid) => nil

Sets the (integer) real and/or effective group IDs of the current process to rid and eid, respectively. A value of -1 for either means to leave that ID unchanged. Not available on all platforms.

Process::Sys.setresgid(rid, eid, sid) => nil

Sets the (integer) real, effective, and saved user IDs of the current process to rid, eid, and sid respectively. A value of -1 for any value means to leave that ID unchanged. Not available on all platforms.

Process::Sys.setresuid(rid, eid, sid) => nil

Sets the (integer) real, effective, and saved user IDs of the current process to rid, eid, and sid respectively. A value of -1 for any value means to leave that ID unchanged. Not available on all platforms.

Process::Sys.setreuid(rid, eid) => nil

Sets the (integer) real and/or effective user IDs of the current process to rid and eid, respectively. A value of -1 for either means to leave that ID unchanged. Not available on all platforms.

Process::Sys.setrgid(integer) => nil

Set the real group ID of the calling process to integer. Not available on all platforms.

Process::Sys.setruid(integer) => nil

Set the real user ID of the calling process to integer. Not available on all platforms.

Process::Sys.setuid(integer) => nil

Set the user ID of the current process to integer. Not available on all platforms.


Module: Process::UID

Module | Process::UID
In: | process.c

The Process::UID module contains a collection of module functions which can be used to portably get, set, and switch the current process‘s real, effective, and saved user IDs.

Methods

change_privilege eid grant_privilege re_exchange re_exchangeable? rid sid_available? switch

Public Class methods

Process::UID.change_privilege(integer) => fixnum

Change the current process‘s real and effective user ID to that specified by integer. Returns the new user ID. Not available on all platforms.

   [Process.uid, Process.euid]          #=> [0, 0]
   Process::UID.change_privilege(31)    #=> 31
   [Process.uid, Process.euid]          #=> [31, 31]
Process.euid => fixnum
Process::UID.eid => fixnum
Process::Sys.geteuid => fixnum

Returns the effective user ID for this process.

   Process.euid   #=> 501
Process::UID.grant_privilege(integer) => fixnum
Process::UID.eid= integer => fixnum

Set the effective user ID, and if possible, the saved user ID of the process to the given integer. Returns the new effective user ID. Not available on all platforms.

   [Process.uid, Process.euid]          #=> [0, 0]
   Process::UID.grant_privilege(31)     #=> 31
   [Process.uid, Process.euid]          #=> [0, 31]
Process::UID.re_exchange => fixnum

Exchange real and effective user IDs and return the new effective user ID. Not available on all platforms.

   [Process.uid, Process.euid]   #=> [0, 31]
   Process::UID.re_exchange      #=> 0
   [Process.uid, Process.euid]   #=> [31, 0]
Process::UID.re_exchangeable? => true or false

Returns true if the real and effective user IDs of a process may be exchanged on the current platform.

Process.uid => fixnum
Process::UID.rid => fixnum
Process::Sys.getuid => fixnum

Returns the (real) user ID of this process.

   Process.uid   #=> 501
Process::UID.sid_available? => true or false

Returns true if the current platform has saved user ID functionality.

Process::UID.switch => fixnum
Process::UID.switch {|| block} => object

Switch the effective and real user IDs of the current process. If a block is given, the user IDs will be switched back after the block is executed. Returns the new effective user ID if called without a block, and the return value of the block if one is given.


Module: Profiler__

Module | Profiler__
In: | lib/profiler.rb

Constants

PROFILE_PROC = proc{|event, file, line, id, binding, klass| case event


Class: Queue

Class | Queue
In: | lib/thread.rb
Parent: | Object

This class provides a way to synchronize communication between threads.

Example:

  require 'thread'

  queue = Queue.new

  producer = Thread.new do
    5.times do |i|
      sleep rand(i) # simulate expense
      queue << i
      puts "#{i} produced"
    end
  end

  consumer = Thread.new do
    5.times do |i|
      value = queue.pop
      sleep rand(i/2) # simulate expense
      puts "consumed #{value}"
    end
  end

  consumer.join

Methods

<< clear deq empty? enq length new num_waiting pop push shift size

Public Class methods

new()

Creates a new queue.

Public Instance methods

<<(obj)

Alias for push

clear()

Removes all objects from the queue.

deq(non_block=false)

Alias for pop

empty?()

Returns true is the queue is empty.

enq(obj)

Alias for push

length()

Returns the length of the queue.

num_waiting()

Returns the number of threads waiting on the queue.

pop(non_block=false)

Retrieves data from the queue. If the queue is empty, the calling thread is suspended until data is pushed onto the queue. If non_block is true, the thread isn‘t suspended, and an exception is raised.

push(obj)

Pushes obj to the queue.

shift(non_block=false)

Alias for pop

size()

Alias for length


Module: RDoc

Module | RDoc
In: | lib/rdoc/parsers/parse_f95.rb lib/rdoc/parsers/parse_c.rb lib/rdoc/parsers/parserfactory.rb lib/rdoc/parsers/parse_rb.rb lib/rdoc/parsers/parse_simple.rb lib/rdoc/code_objects.rb lib/rdoc/generators/template/xml/xml.rb lib/rdoc/generators/template/xml/rdf.rb lib/rdoc/generators/template/chm/chm.rb lib/rdoc/generators/template/html/one_page_html.rb lib/rdoc/generators/template/html/hefss.rb lib/rdoc/generators/template/html/old_html.rb lib/rdoc/generators/template/html/kilmer.rb lib/rdoc/generators/template/html/html.rb lib/rdoc/diagram.rb lib/rdoc/rdoc.rb lib/rdoc/usage.rb

We put rdoc stuff in the RDoc module to avoid namespace clutter.

ToDo: This isn‘t universally true.

RDOC - Ruby Documentation System

This package contains Rdoc and SimpleMarkup. Rdoc is an application that produces documentation for one or more Ruby source files. We work similarly to JavaDoc, parsing the source, and extracting the definition for classes, modules, and methods (along with includes and requires). We associate with these optional documentation contained in the immediately preceding comment block, and then render the result using a pluggable output formatter. (Currently, HTML is the only supported format. Markup is a library that converts plain text into various output formats. The Markup library is used to interpret the comment blocks that Rdoc uses to document methods, classes, and so on.

This library contains two packages, rdoc itself and a text markup library, ‘markup’.

Roadmap

  • If you want to use Rdoc to create documentation for your Ruby source files, read on.
  • If you want to include extensions written in C, see rdoc/parsers/parse_c.rb.
  • For information on the various markups available in comment blocks, see markup/simple_markup.rb.
  • If you want to drive Rdoc programatically, see RDoc::RDoc.
  • If you want to use the library to format text blocks into HTML, have a look at SM::SimpleMarkup.
  • If you want to try writing your own HTML output template, see RDoc::Page.

Summary

Once installed, you can create documentation using the ‘rdoc’ command (the command is ‘rdoc.bat’ under Windows)

  % rdoc [options]  [names...]

Type "rdoc —help" for an up-to-date option summary.

A typical use might be to generate documentation for a package of Ruby source (such as rdoc itself).

  % rdoc

This command generates documentation for all the Ruby and C source files in and below the current directory. These will be stored in a documentation tree starting in the subdirectory ‘doc’.

You can make this slightly more useful for your readers by having the index page contain the documentation for the primary file. In our case, we could type

  % rdoc --main rdoc/rdoc.rb

You‘ll find information on the various formatting tricks you can use in comment blocks in the documentation this generates.

RDoc uses file extensions to determine how to process each file. File names ending .rb and .rbw are assumed to be Ruby source. Files ending .c are parsed as C files. All other files are assumed to contain just SimpleMarkup-style markup (with or without leading ’#’ comment markers). If directory names are passed to RDoc, they are scanned recursively for C and Ruby source files only.

Credits

  • The Ruby parser in rdoc/parse.rb is based heavily on the outstanding work of Keiju ISHITSUKA of Nippon Rational Inc, who produced the Ruby parser for irb and the rtags package.
  • Code to diagram classes and modules was written by Sergey A Yanovitsky (Jah) of Enticla.
  • Charset patch from MoonWolf.
  • Rich Kilmer wrote the kilmer.rb output template.
  • Dan Brickley led the design of the RDF format.

License

RDoc is Copyright (c) 2001-2003 Dave Thomas, The Pragmatic Programmers. It is free software, and may be redistributed under the terms specified in the README file of the Ruby distribution.

Usage

RDoc is invoked from the command line using:

   % rdoc <options> [name...]

Files are parsed, and the information they contain collected, before any output is produced. This allows cross references between all files to be resolved. If a name is a directory, it is traversed. If no names are specified, all Ruby files in the current directory (and subdirectories) are processed.

Options are:

—accessor name
specifies the name(s) of additional methods that should be treated as if they were attr_xxx methods. Specifying "—accessor db_opt" means lines such as
     db_opt :name, :age

will get parsed and displayed in the documentation. Each name may have an optional "=flagtext" appended, in which case the given flagtext will appear where (for example) the ‘rw’ appears for attr_accessor.

—all
include protected and private methods in the output (by default only public methods are included)
—charset charset
Set the character set for the generated HTML.
—diagram
include diagrams showing modules and classes. This is currently an experimental feature, and may not be supported by all output templates. You need dot V1.8.6 or later to use the —diagram option correctly (www.research.att.com/sw/tools/graphviz/).
—exclude pattern
exclude files and directories matching this pattern from processing
—extension new=old
treat files ending .new as if they ended .old. Saying ’—extension cgi=rb’ causes RDoc to treat .cgi files as Ruby source.
fileboxes
Classes are put in boxes which represents files, where these classes reside. Classes shared between more than one file are shown with list of files that sharing them. Silently discarded if —diagram is not given Experimental.
—fmt fmt
generate output in a particular format.
—help
generate a usage summary.
—help-output
explain the various output options.
—image-format gif/png/jpg/jpeg
sets output image format for diagrams. Can be png, gif, jpeg, jpg. If this option is omitted, png is used. Requires —diagram.
—include dir,…
specify one or more directories to be searched when satisfying :include: directives. Multiple —include options may be given. The directory containing the file currently being processed is always searched.
—inline-source
By default, the source code of methods is shown in a popup. With this option, it‘s displayed inline.
line-numbers
include line numbers in the source code
—main name
the class of module name will appear on the index page. If you want to set a particular file as a main page (a README, for example) simply specifiy its name as the first on the command line.
—merge
when generating ri output, if classes being processed already exist in the destination directory, merge in the current details rather than overwrite them.
—one-file
place all the output into a single file
—op dir
set the output directory to dir (the default is the directory "doc")
—op-name name
set the name of the output. Has no effect for HTML. "doc")
—opname name
set the output name (has no effect for HTML).
—promiscuous
If a module or class is defined in more than one source file, and you click on a particular file‘s name in the top navigation pane, RDoc will normally only show you the inner classes and modules of that class that are defined in the particular file. Using this option makes it show all classes and modules defined in the class, regardless of the file they were defined in.
—quiet
do not display progress messages
—ri, —ri-site, and —ri-system
generate output than can be read by the ri command-line tool. By default —ri places its output in ~/.rdoc, —ri-site in $datadir/ri/<ver>/site, and —ri-system in $datadir/ri/<ver>/system. All can be overridden with a subsequent —op option. All default directories are in ri‘s default search path.
—show-hash
A name of the form name in a comment is a possible hyperlink to an instance method name. When displayed, the ’#’ is removed unless this option is specified
—style stylesheet url
specifies the URL of an external stylesheet to use (rather than generating one of our own)
tab-width n
set the width of tab characters (default 8)
—template name
specify an alternate template to use when generating output (the default is ‘standard’). This template should be in a directory accessible via $: as rdoc/generators/xxxx_template, where ‘xxxx’ depends on the output formatter.
—version
display RDoc‘s version
—webcvs url
Specify a URL for linking to a web frontend to CVS. If the URL contains a ’\%s’, the name of the current file will be substituted; if the URL doesn‘t contain a ’\%s’, the filename will be appended to it.

Example

A typical small Ruby program commented using RDoc might be as follows. You can see the formatted result in EXAMPLE.rb and Anagram.

      :include: EXAMPLE.rb

Markup

Comment blocks can be written fairly naturally, either using ’#’ on successive lines of the comment, or by including the comment in an =begin/=end block. If you use the latter form, the =begin line must be flagged with an RDoc tag:

  =begin rdoc
  Documentation to
  be processed by RDoc.
  =end

Paragraphs are lines that share the left margin. Text indented past this margin are formatted verbatim.

  1. Lists are typed as indented paragraphs with:
    • a ’*’ or ’-’ (for bullet lists)
    • a digit followed by a period for numbered lists
    • an upper or lower case letter followed by a period for alpha lists.

    For example, the input that produced the above paragraph looked like

        1. Lists are typed as indented
       paragraphs with:
       * a '*' or '-' (for bullet lists)
       * a digit followed by a period for
         numbered lists
       * an upper or lower case letter followed
         by a period for alpha lists.
  2. Labeled lists (sometimes called description lists) are typed using square brackets for the label.
       [cat]   small domestic animal
   [+cat+] command to copy standard input
  3. Labeled lists may also be produced by putting a double colon after the label. This sets the result in tabular form, so the descriptions all line up. This was used to create the ‘author’ block at the bottom of this description.
       cat::   small domestic animal
   +cat+:: command to copy standard input

    For both kinds of labeled lists, if the body text starts on the same line as the label, then the start of that text determines the block indent for the rest of the body. The text may also start on the line following the label, indented from the start of the label. This is often preferable if the label is long. Both the following are valid labeled list entries:

       <tt>--output</tt> <i>name [, name]</i>::
       specify the name of one or more output files. If multiple
       files are present, the first is used as the index.

   <tt>--quiet:</tt>:: do not output the names, sizes, byte counts,
                       index areas, or bit ratios of units as
                       they are processed.
  4. Headings are entered using equals signs
       = Level One Heading
   == Level Two Heading

    and so on

  5. Rules (horizontal lines) are entered using three or more hyphens.
  6. Non-verbatim text can be marked up:
    italic: _word_ or <em>text</em>
    bold: *word* or <b>text</b>
    typewriter: +word+ or <tt>text</tt>

    The first form only works around ‘words’, where a word is a sequence of upper and lower case letters and underscores. Putting a backslash before inline markup stops it being interpreted, which is how I created the table above:

      _italic_::     \_word_ or \<em>text</em>
  *bold*::       \*word* or \<b>text</b>
  +typewriter+:: \+word+ or \<tt>text</tt>
  7. Names of classes, source files, and any method names containing an underscore or preceded by a hash character are automatically hyperlinked from comment text to their description.
  8. Hyperlinks to the web starting http:, mailto:, ftp:, or www. are recognized. An HTTP url that references an external image file is converted into an inline <IMG..>. Hyperlinks starting ‘link:’ are assumed to refer to local files whose path is relative to the —op directory.

    Hyperlinks can also be of the form label[url], in which case the label is used in the displayed text, and url is used as the target. If label contains multiple words, put it in braces: {multi word label}[url].

  9. Method parameter lists are extracted and displayed with the method description. If a method calls yield, then the parameters passed to yield will also be displayed:
       def fred
     ...
     yield line, address

    This will get documented as

       fred() { |line, address| ... }

    You can override this using a comment containing ’:yields: …’ immediately after the method definition

       def fred      # :yields: index, position
     ...
     yield line, address

    which will get documented as

        fred() { |index, position| ... }
  10. ’:yields:’ is an example of a documentation modifier. These appear immediately after the start of the document element they are modifying. Other modifiers include
    :nodoc:[all]
    don‘t include this element in the documentation. For classes and modules, the methods, aliases, constants, and attributes directly within the affected class or module will also be omitted. By default, though, modules and classes within that class of module will be documented. This is turned off by adding the all modifier.
         module SM  #:nodoc:
       class Input
       end
     end
     module Markup #:nodoc: all
       class Output
       end
     end

    In the above code, only class SM::Input will be documented.

    :doc:
    force a method or attribute to be documented even if it wouldn‘t otherwise be. Useful if, for example, you want to include documentation of a particular private method.
    :notnew:
    only applicable to the initialize instance method. Normally RDoc assumes that the documentation and parameters for initialize are actually for the ::new method, and so fakes out a ::new for the class. THe :notnew: modifier stops this. Remember that initialize is protected, so you won‘t see the documentation unless you use the -a command line option.
  11. RDoc stops processing comments if it finds a comment line containing ‘#—’. This can be used to separate external from internal comments, or to stop a comment being associated with a method, class, or module. Commenting can be turned back on with a line that starts ‘#++’.
        # Extract the age and calculate the
    # date-of-birth.
    #--
    # FIXME: fails if the birthday falls on
    # February 29th
    #++
    # The DOB is returned as a Time object.

    def get_dob(person)
       ...
  12. Comment blocks can contain other directives:
    :section: title
    Starts a new section in the output. The title following
      <tt>:section:</tt> is used as the section heading, and the
  remainder of the comment containing the section is used as
  introductory text. Subsequent methods, aliases, attributes,
  and classes will be documented in this section. A :section:
  comment block may have one or more lines before the :section:
  directive. These will be removed, and any identical lines at
  the end of the block are also removed. This allows you to add
  visual cues such as

       # ----------------------------------------
     # :section: My Section
     # This is the section that I wrote.
     # See it glisten in the noon-day sun.
       # ----------------------------------------
    call-seq:
    lines up to the next blank line in the comment are treated as the method‘s calling sequence, overriding the default parsing of method parameters and yield arguments.
    :include:filename
    include the contents of the named file at this point. The file will be searched for in the directories listed by the —include option, or in the current directory by default. The contents of the file will be shifted to have the same indentation as the ’:’ at the start of the :include: directive.
    :title:text
    Sets the title for the document. Equivalent to the —title command line parameter. (The command line parameter overrides any :title: directive in the source).
    :enddoc:
    Document nothing further at the current level.
    :main:name
    Equivalent to the —main command line parameter.
    :stopdoc: / :startdoc:
    Stop and start adding new documentation elements to the current container. For example, if a class has a number of constants that you don‘t want to document, put a :stopdoc: before the first, and a :startdoc: after the last. If you don‘t specifiy a :startdoc: by the end of the container, disables documentation for the entire class or module.

See also markup/simple_markup.rb.

Other stuff

Author: | Dave Thomas <dave@pragmaticprogrammer.com>
Requires: | Ruby 1.8.1 or later
License: | Copyright (c) 2001-2003 Dave Thomas. Released under the same license as Ruby.

Warranty

This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose.

Methods

usage usage_no_exit

Classes and Modules

Module RDoc::Page
Module RDoc::ParserFactory
Class RDoc::Alias
Class RDoc::AnonClass
Class RDoc::AnyMethod
Class RDoc::Attr
Class RDoc::C_Parser
Class RDoc::ClassModule
Class RDoc::CodeObject
Class RDoc::Constant
Class RDoc::Context
Class RDoc::Diagram
Class RDoc::Fortran95parser
Class RDoc::Include
Class RDoc::NormalClass
Class RDoc::NormalModule
Class RDoc::RDoc
Class RDoc::RDocError
Class RDoc::Require
Class RDoc::RubyParser
Class RDoc::SimpleParser
Class RDoc::SingleClass
Class RDoc::Stats
Class RDoc::Token
Class RDoc::TopLevel

Constants

KNOWN_CLASSES = { "rb_cObject" => "Object", "rb_cArray" => "Array", "rb_cBignum" => "Bignum", "rb_cClass" => "Class", "rb_cDir" => "Dir", "rb_cData" => "Data", "rb_cFalseClass" => "FalseClass", "rb_cFile" => "File", "rb_cFixnum" => "Fixnum", "rb_cFloat" => "Float", "rb_cHash" => "Hash", "rb_cInteger" => "Integer", "rb_cIO" => "IO", "rb_cModule" => "Module", "rb_cNilClass" => "NilClass", "rb_cNumeric" => "Numeric", "rb_cProc" => "Proc", "rb_cRange" => "Range", "rb_cRegexp" => "Regexp", "rb_cString" => "String", "rb_cSymbol" => "Symbol", "rb_cThread" => "Thread", "rb_cTime" => "Time", "rb_cTrueClass" => "TrueClass", "rb_cStruct" => "Struct", "rb_eException" => "Exception", "rb_eStandardError" => "StandardError", "rb_eSystemExit" => "SystemExit", "rb_eInterrupt" => "Interrupt", "rb_eSignal" => "Signal", "rb_eFatal" => "Fatal", "rb_eArgError" => "ArgError", "rb_eEOFError" => "EOFError", "rb_eIndexError" => "IndexError", "rb_eRangeError" => "RangeError", "rb_eIOError" => "IOError", "rb_eRuntimeError" => "RuntimeError", "rb_eSecurityError" => "SecurityError", "rb_eSystemCallError" => "SystemCallError", "rb_eTypeError" => "TypeError", "rb_eZeroDivError" => "ZeroDivError", "rb_eNotImpError" => "NotImpError", "rb_eNoMemError" => "NoMemError", "rb_eFloatDomainError" => "FloatDomainError", "rb_eScriptError" => "ScriptError", "rb_eNameError" => "NameError", "rb_eSyntaxError" => "SyntaxError", "rb_eLoadError" => "LoadError", "rb_mKernel" => "Kernel", "rb_mComparable" => "Comparable", "rb_mEnumerable" => "Enumerable", "rb_mPrecision" => "Precision", "rb_mErrno" => "Errno", "rb_mFileTest" => "FileTest", "rb_mGC" => "GC", "rb_mMath" => "Math", "rb_mProcess" => "Process" Ruby‘s built-in classes.
GENERAL_MODIFIERS = [ 'nodoc' ].freeze
CLASS_MODIFIERS = GENERAL_MODIFIERS
ATTR_MODIFIERS = GENERAL_MODIFIERS
CONSTANT_MODIFIERS = GENERAL_MODIFIERS
METHOD_MODIFIERS = GENERAL_MODIFIERS + [ 'arg', 'args', 'yield', 'yields', 'notnew', 'not-new', 'not_new', 'doc' ]
DOT_DOC_FILENAME = ".document" Name of the dotfile that contains the description of files to be processed in the current directory

Public Class methods

usage(*args)

Display usage information from the comment at the top of the file. String arguments identify specific sections of the comment to display. An optional integer first argument specifies the exit status (defaults to 0)

usage_no_exit(*args)

Display usage


Class: RDoc::Alias

Class | RDoc::Alias
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

Represent an alias, which is an old_name/ new_name pair associated with a particular context

Methods

new to_s

Attributes

comment | [RW]
new_name | [RW]
old_name | [RW]
text | [RW]

Public Class methods

new(text, old_name, new_name, comment)

Public Instance methods

to_s()


Class: RDoc::AnonClass

Class | RDoc::AnonClass
In: | lib/rdoc/code_objects.rb
Parent: | ClassModule

Anonymous classes


Class: RDoc::AnyMethod

Class | RDoc::AnyMethod
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

AnyMethod is the base class for objects representing methods

Methods

<=> add_alias new param_seq to_s

Included Modules

TokenStream

Attributes

aliases | [R]
block_params | [RW]
call_seq | [RW]
dont_rename_initialize | [RW]
is_alias_for | [RW]
name | [RW]
singleton | [RW]
visibility | [RW]

Public Class methods

new(text, name)

Public Instance methods

<=>(other)
add_alias(method)
param_seq()
to_s()


Class: RDoc::Attr

Class | RDoc::Attr
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

Represent attributes

Methods

<=> new to_s

Attributes

name | [RW]
rw | [RW]
text | [RW]
visibility | [RW]

Public Class methods

new(text, name, rw, comment)

Public Instance methods

<=>(other)
to_s()


Class: RDoc::C_Parser

Class | RDoc::C_Parser
In: | lib/rdoc/parsers/parse_c.rb
Parent: | Object

We attempt to parse C extension files. Basically we look for the standard patterns that you find in extensions: rb_define_class, rb_define_method and so on. We also try to find the corresponding C source for the methods and extract comments, but if we fail we don‘t worry too much.

The comments associated with a Ruby method are extracted from the C comment block associated with the routine that implements that method, that is to say the method whose name is given in the rb_define_method call. For example, you might write:

 /*
  * 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(ary)
      VALUE ary;
  {
      ary = rb_obj_dup(ary);
      rb_ary_flatten_bang(ary);
      return ary;
  }

  ...

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

Here RDoc will determine from the rb_define_method line that there‘s a method called "flatten" in class Array, and will look for the implementation in the method rb_ary_flatten. It will then use the comment from that method in the HTML output. This method must be in the same source file as the rb_define_method.

C classes can be diagramed (see /tc/dl/ruby/ruby/error.c), and RDoc integrates C and Ruby source into one tree

The comment blocks may include special direcives:

Document-class: name
This comment block is documentation for the given class. Use this when the Init_xxx method is not named after the class.
Document-method: name
This comment documents the named method. Use when RDoc cannot automatically find the method from it‘s declaration
call-seq: text up to an empty line
Because C source doesn‘t give descripive names to Ruby-level parameters, you need to document the calling sequence explicitly

In additon, RDoc assumes by default that the C method implementing a Ruby function is in the same source file as the rb_define_method call. If this isn‘t the case, add the comment

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

As an example, we might have an extension that defines multiple classes in its Init_xxx method. We could document them using

 /*
  * 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.
  */

Methods

new scan

Attributes

progress [RW]

Public Class methods

new(top_level, file_name, body, options, stats)

prepare to parse a C file

Public Instance methods

scan()

Extract the classes/modules and methods from a C file and return the corresponding top-level object


Class: RDoc::ClassModule

Class | RDoc::ClassModule
In: | lib/rdoc/code_objects.rb
Parent: | Context

ClassModule is the base class for objects representing either a class or a module.

Methods

find_class_named full_name http_url is_module? new to_s

Attributes

diagram | [RW]
superclass | [R]

Public Class methods

new(name, superclass = nil)

Public Instance methods

find_class_named(name)
full_name()

Return the fully qualified name of this class or module

http_url(prefix)
is_module?()

Return true if this object represents a module

to_s()

to_s is simply for debugging


Class: RDoc::CodeObject

Class | RDoc::CodeObject
In: | lib/rdoc/code_objects.rb
Parent: | Object

We contain the common stuff for contexts (which are containers) and other elements (methods, attributes and so on)

Methods

attr_overridable comment= document_children= document_self= new remove_classes_and_modules remove_methods_etc start_doc stop_doc

Attributes

comment | [R] | Access the code object‘s comment
document_children | [R] | do we document ourselves and our children
document_self | [R] | do we document ourselves?
done_documenting | [RW] | are we done documenting (ie, did we come across a :enddoc:)?
force_documentation | [RW] | Do we force documentation, even is we wouldn‘t normally show the entity
parent | [RW] |
section | [RW] | Which section are we in
viewer | [RW] | We are the model of the code, but we know that at some point we will be worked on by viewers. By implementing the Viewable protocol, viewers can associated themselves with these objects.

Public Class methods

attr_overridable(name, *aliases)

There‘s a wee trick we pull. Comment blocks can have directives that override the stuff we extract during the parse. So, we have a special class method, attr_overridable, that lets code objects list those directives. Wehn a comment is assigned, we then extract out any matching directives and update our object

new()

Public Instance methods

comment=(comment)

Update the comment, but don‘t overwrite a real comment with an empty one

document_children=(val)
document_self=(val)
remove_classes_and_modules()

Default callbacks to nothing, but this is overridden for classes and modules

remove_methods_etc()
start_doc()

set and cleared by :startdoc: and :enddoc:, this is used to toggle the capturing of documentation

stop_doc()


Class: RDoc::Constant

Class | RDoc::Constant
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

Represent a constant

Methods

new

Attributes

name | [RW]
value | [RW]

Public Class methods

new(name, value, comment)


Class: RDoc::Context

Class | RDoc::Context
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

A Context is something that can hold modules, classes, methods, attributes, aliases, requires, and includes. Classes, modules, and files are all Contexts.

Methods

<=> add_alias add_attribute add_class add_class_or_module add_constant add_include add_method add_module add_require add_to classes defined_in? each_attribute each_classmodule each_constant each_method find_enclosing_module_named find_local_symbol find_module_named find_symbol initialize_classes_and_modules initialize_methods_etc modules new ongoing_visibility= record_location remove_classes_and_modules remove_methods_etc set_current_section set_visibility_for toplevel

Classes and Modules

Class RDoc::Context::Section

Attributes

aliases | [R]
attributes | [R]
constants | [R]
in_files | [R]
includes | [R]
method_list | [R]
name | [R]
requires | [R]
sections | [R]
visibility | [R]

Public Class methods

new()

Public Instance methods

<=>(other)

allow us to sort modules by name

add_alias(an_alias)
add_attribute(an_attribute)
add_class(class_type, name, superclass)
add_class_or_module(collection, class_type, name, superclass=nil)
add_constant(const)
add_include(an_include)
add_method(a_method)
add_module(class_type, name)
add_require(a_require)

Requires always get added to the top-level (file) context

add_to(array, thing)
classes()

map the class hash to an array externally

defined_in?(file)

Return true if at least part of this thing was defined in file

each_attribute() {|a| ...}
each_classmodule() {|m| ...}

Iterate over all the classes and modules in this object

each_constant() {|c| ...}
each_method() {|m| ...}
find_enclosing_module_named(name)

find a module at a higher scope

find_local_symbol(symbol)
find_module_named(name)

Find a named module

find_symbol(symbol, method=nil)

Look up the given symbol. If method is non-nil, then we assume the symbol references a module that contains that method

initialize_classes_and_modules()
initialize_methods_etc()
modules()

map the module hash to an array externally

ongoing_visibility=(vis)

Change the default visibility for new methods

record_location(toplevel)

Record the file that we happen to find it in

remove_classes_and_modules()

and remove classes and modules when we see a :nodoc: all

remove_methods_etc()

If a class‘s documentation is turned off after we‘ve started collecting methods etc., we need to remove the ones we have

set_current_section(title, comment)

Handle sections

set_visibility_for(methods, vis, singleton=false)

Given an array methods of method names, set the visibility of the corresponding AnyMethod object

toplevel()

Return the toplevel that owns us


Class: RDoc::Context::Section

Class | RDoc::Context::Section
In: | lib/rdoc/code_objects.rb
Parent: | Object

Contents

  • The title

Methods

new

Attributes

comment | [R]
sequence | [R]
title | [R]

Public Class methods

new(title, comment)

The title

remove lines up to the line containing :section:, and look for those lines again at the end and remove them. This lets us write

  # ---------------------
  # :SECTION: The title
  # The body
  # ---------------------


Class: RDoc::Diagram

Class | RDoc::Diagram
In: | lib/rdoc/diagram.rb
Parent: | Object

Draw a set of diagrams representing the modules and classes in the system. We draw one diagram for each file, and one for each toplevel class or module. This means there will be overlap. However, it also means that you‘ll get better context for objects.

To use, simply

  d = Diagram.new(info)   # pass in collection of top level infos
  d.draw

The results will be written to the dot subdirectory. The process also sets the diagram attribute in each object it graphs to the name of the file containing the image. This can be used by output generators to insert images.

Methods

draw new

Constants

FONT | = | "Arial"
DOT_PATH | = | "dot"

Public Class methods

new(info, options)

Pass in the set of top level objects. The method also creates the subdirectory to hold the images

Public Instance methods

draw()

Draw the diagrams. We traverse the files, drawing a diagram for each. We also traverse each top-level class and module in that file drawing a diagram for these too.


Class: RDoc::Fortran95parser

Class | RDoc::Fortran95parser
In: | lib/rdoc/parsers/parse_f95.rb
Parent: | Object

See rdoc/parsers/parse_f95.rb

Methods

new scan

Classes and Modules

Class RDoc::Fortran95parser::Fortran95Definition

Constants

COMMENTS_ARE_UPPER = false
"false": | Comments are below source code
"true" : | Comments are upper source code
INTERNAL_ALIAS_MES = "Alias for" Internal alias message
EXTERNAL_ALIAS_MES = "The entity is" External alias message

Public Class methods

new(top_level, file_name, body, options, stats)

prepare to parse a Fortran 95 file

Public Instance methods

scan()

devine code constructs


Class: RDoc::Fortran95parser::Fortran95Definition

Class | RDoc::Fortran95parser::Fortran95Definition
In: | lib/rdoc/parsers/parse_f95.rb
Parent: | Object

Information of arguments of subroutines and functions in Fortran95

Methods

include_attr? new to_s

Attributes

arraysuffix | [R] | Suffix of array
comment | [RW] | Comments
inivalue | [R] | Initial Value
nodoc | [RW] | Flag of non documentation
types | [R] | Types of variable
varname | [R] | Name of variable

Public Class methods

new(varname, types, inivalue, arraysuffix, comment, nodoc=false)

Public Instance methods

include_attr?(attr)

If attr is included, true is returned

to_s()


Class: RDoc::Include

Class | RDoc::Include
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

an included module

Methods

new

Attributes

name [RW]

Public Class methods

new(name, comment)


Class: RDoc::NormalClass

Class | RDoc::NormalClass
In: | lib/rdoc/code_objects.rb
Parent: | ClassModule

Normal classes


Class: RDoc::NormalModule

Class | RDoc::NormalModule
In: | lib/rdoc/code_objects.rb
Parent: | ClassModule

Module

Methods

is_module?

Public Instance methods

is_module?()


Module: RDoc::Page

Module | RDoc::Page
In: | lib/rdoc/generators/template/xml/xml.rb lib/rdoc/generators/template/xml/rdf.rb lib/rdoc/generators/template/chm/chm.rb lib/rdoc/generators/template/html/one_page_html.rb lib/rdoc/generators/template/html/hefss.rb lib/rdoc/generators/template/html/old_html.rb lib/rdoc/generators/template/html/kilmer.rb lib/rdoc/generators/template/html/html.rb

This is how you define the HTML that RDoc generates. Simply create a file in rdoc/generators/html_templates that creates the module RDoc::Page and populate it as described below. Then invoke rdoc using the —template <name of your file> option, and your template will be used.

The constants defining pages use a simple templating system:

  • The templating system is passed a hash. Keys in the hash correspond to tags on this page. The tag %abc% is looked up in the hash, and is replaced by the corresponding hash value.
  • Some tags are optional. You can detect this using IF/ENDIF
       IF: title
   The value of title is %title%
   ENDIF: title
  • Some entries in the hash have values that are arrays, where each entry in the array is itself a hash. These are used to generate lists using the START: construct. For example, given a hash containing
       { 'people' => [ { 'name' => 'Fred', 'age' => '12' },
                   { 'name' => 'Mary', 'age' => '21' } ]

    You could generate a simple table using

       <table>
   START:people
     <tr><td>%name%<td>%age%</tr>
   END:people
   </table>

    These lists can be nested to an arbitrary depth

  • the construct HREF:url:name: generates <a href="%url%">%name%</a> if url is defined in the hash, or %name% otherwise.

Your file must contain the following constants

FONTS
a list of fonts to be used
STYLE
a CSS section (without the <style> or comments). This is used to generate a style.css file
BODY
The main body of all non-index RDoc pages. BODY will contain two !INCLUDE!s. The first is used to include a document-type specific header (FILE_PAGE or CLASS_PAGE). The second include is for the method list (METHOD_LIST). THe body is passed:
%title%: the page‘s title
%style_url%: the url of a style sheet for this page
%diagram%: the optional URL of a diagram for this page
%description%: a (potentially multi-paragraph) string containing the description for th file/class/module.
%requires%: an optional list of %aref%/%name% pairs, one for each module required by this file.
%methods%: an optional list of %aref%/%name%, one for each method documented on this page. This is intended to be an index.
%attributes%: An optional list. For each attribute it contains:
%name%: the attribute name
%rw%: r/o, w/o, or r/w
%a_desc%: description of the attribute
%classlist%: An optional string containing an already-formatted list of classes and modules documented in this file

For FILE_PAGE entries, the body will be passed

%short_name%: The name of the file
%full_path%: The full path to the file
%dtm_modified%: The date/time the file was last changed

For class and module pages, the body will be passed

%classmod%: The name of the class or module
%files%: A list. For each file this class is defined in, it contains:
%full_path_url%: an (optional) URL of the RDoc page for this file
%full_path%: the name of the file
%par_url%: The (optional) URL of the RDoc page documenting this class‘s parent class
%parent%: The name of this class‘s parent.

For both files and classes, the body is passed the following information on includes and methods:

%includes%: Optional list of included modules. For each, it receives
%aref%: optional URL to RDoc page for the module
%name%: the name of the module
%method_list%: Optional list of methods of a particular class and category.

Each method list entry contains:

%type%: public/private/protected
%category%: instance/class
%methods%: a list of method descriptions

Each method description contains:

%aref%: a target aref, used when referencing this method description. You should code this as <a name="%aref%">
%codeurl%: the optional URL to the page containing this method‘s source code.
%name%: the method‘s name
%params%: the method‘s parameters
%callseq%: a full calling sequence
%m_desc%: the (potentially multi-paragraph) description of this method.
CLASS_PAGE
Header for pages documenting classes and modules. See BODY above for the available parameters.
FILE_PAGE
Header for pages documenting files. See BODY above for the available parameters.
METHOD_LIST
Controls the display of the listing of methods. See BODY for parameters.
INDEX
The top-level index page. For a browser-like environment define a frame set that includes the file, class, and method indices. Passed
%title%: title of page
%initial_page% : url of initial page to display
CLASS_INDEX
Individual files for the three indexes. Passed:
%index_url%: URL of main index page
%entries%: List of
%name%: name of an index entry
%href%: url of corresponding page
METHOD_INDEX
Same as CLASS_INDEX for methods
FILE_INDEX
Same as CLASS_INDEX for methods
FR_INDEX_BODY
A wrapper around CLASS_INDEX, METHOD_INDEX, and FILE_INDEX. If those index strings contain the complete HTML for the output, then FR_INDEX_BODY can simply be !INCLUDE!
SRC_PAGE
Page used to display source code. Passed %title% and %code%, the latter being a multi-line string of code.

Methods

write_extra_pages write_extra_pages

Constants

CONTENTS_XML = %{ IF:description <description> %description% </description> ENDIF:description <contents> IF:requires <required-file-list> START:requires <required-file name="%name%" IF:aref href="%aref%" ENDIF:aref /> END:requires </required-file-list> ENDIF:requires IF:attributes <attribute-list> START:attributes <attribute name="%name%"> IF:rw <attribute-rw>%rw%</attribute-rw> ENDIF:rw <description>%a_desc%</description> </attribute> END:attributes </attribute-list> ENDIF:attributes IF:includes <included-module-list> START:includes <included-module name="%name%" IF:aref href="%aref%" ENDIF:aref /> END:includes </included-module-list> ENDIF:includes IF:method_list <method-list> START:method_list IF:methods START:methods <method name="%name%" type="%type%" category="%category%" id="%aref%"> <parameters>%params%</parameters> IF:m_desc <description> %m_desc% </description> ENDIF:m_desc IF:sourcecode <source-code-listing> %sourcecode% </source-code-listing> ENDIF:sourcecode </method> END:methods ENDIF:methods END:method_list </method-list> ENDIF:method_list </contents> }
ONE_PAGE = %{<?xml version="1.0" encoding="utf-8"?> <rdoc> <file-list> START:files <file name="%short_name%" id="%href%"> <file-info> <path>%full_path%</path> <dtm-modified>%dtm_modified%</dtm-modified> </file-info> } + CONTENTS_XML + %{ </file> END:files </file-list> <class-module-list> START:classes <%classmod% name="%full_name%" id="%full_name%"> <classmod-info> IF:infiles <infiles> START:infiles <infile>HREF:full_path_url:full_path:</infile> END:infiles </infiles> ENDIF:infiles IF:parent <superclass>HREF:par_url:parent:</superclass> ENDIF:parent </classmod-info> } + CONTENTS_XML + %{ </%classmod%> END:classes </class-module-list> </rdoc> }
CONTENTS_RDF = %{ IF:description <description rd:parseType="Literal"> %description% </description> ENDIF:description IF:requires START:requires <rd:required-file rd:name="%name%" /> END:requires ENDIF:requires IF:attributes START:attributes <contents> <Attribute rd:name="%name%"> IF:rw <attribute-rw>%rw%</attribute-rw> ENDIF:rw <description rdf:parseType="Literal">%a_desc%</description> </Attribute> </contents> END:attributes ENDIF:attributes IF:includes <IncludedModuleList> START:includes <included-module rd:name="%name%" /> END:includes </IncludedModuleList> ENDIF:includes IF:method_list START:method_list IF:methods START:methods <contents> <Method rd:name="%name%" rd:visibility="%type%" rd:category="%category%" rd:id="%aref%"> <parameters>%params%</parameters> IF:m_desc <description rdf:parseType="Literal"> %m_desc% </description> ENDIF:m_desc IF:sourcecode <source-code-listing rdf:parseType="Literal"> %sourcecode% </source-code-listing> ENDIF:sourcecode </Method> </contents> END:methods ENDIF:methods END:method_list ENDIF:method_list <!-- end method list --> }
ONE_PAGE = %{<?xml version="1.0" encoding="utf-8"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://pragprog.com/rdoc/rdoc.rdf#" xmlns:rd="http://pragprog.com/rdoc/rdoc.rdf#"> <!-- RDoc --> START:files <rd:File rd:name="%short_name%" rd:id="%href%"> <path>%full_path%</path> <dtm-modified>%dtm_modified%</dtm-modified> } + CONTENTS_RDF + %{ </rd:File> END:files START:classes <%classmod% rd:name="%full_name%" rd:id="%full_name%"> <classmod-info> IF:infiles <InFiles> START:infiles <infile> <File rd:name="%full_path%" IF:full_path_url rdf:about="%full_path_url%" ENDIF:full_path_url /> </infile> END:infiles </InFiles> ENDIF:infiles IF:parent <superclass>HREF:par_url:parent:</superclass> ENDIF:parent </classmod-info> } + CONTENTS_RDF + %{ </%classmod%> END:classes <!-- /RDoc --> </rdf:RDF> }
HPP_FILE = %{ [OPTIONS] Auto Index = Yes Compatibility=1.1 or later Compiled file=%opname%.chm Contents file=contents.hhc Full-text search=Yes Index file=index.hhk Language=0x409 English(United States) Title=%title% [FILES] START:all_html_files %html_file_name% END:all_html_files }
CONTENTS = %{ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML> <HEAD> <meta name="GENERATOR" content="Microsoft&reg; HTML Help Workshop 4.1"> <!-- Sitemap 1.0 --> </HEAD><BODY> <OBJECT type="text/site properties"> <param name="Foreground" value="0x80"> <param name="Window Styles" value="0x800025"> <param name="ImageType" value="Folder"> </OBJECT> <UL> START:contents <LI> <OBJECT type="text/sitemap"> <param name="Name" value="%c_name%"> <param name="Local" value="%ref%"> </OBJECT> IF:methods <ul> START:methods <LI> <OBJECT type="text/sitemap"> <param name="Name" value="%name%"> <param name="Local" value="%aref%"> </OBJECT> END:methods </ul> ENDIF:methods </LI> END:contents </UL> </BODY></HTML> }
CHM_INDEX = %{ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML> <HEAD> <meta name="GENERATOR" content="Microsoft&reg; HTML Help Workshop 4.1"> <!-- Sitemap 1.0 --> </HEAD><BODY> <OBJECT type="text/site properties"> <param name="Foreground" value="0x80"> <param name="Window Styles" value="0x800025"> <param name="ImageType" value="Folder"> </OBJECT> <UL> START:index <LI> <OBJECT type="text/sitemap"> <param name="Name" value="%name%"> <param name="Local" value="%aref%"> </OBJECT> END:index </UL> </BODY></HTML> }
CONTENTS_XML = %{ IF:description %description% ENDIF:description IF:requires <h4>Requires:</h4> <ul> START:requires IF:aref <li><a href="%aref%">%name%</a></li> ENDIF:aref IFNOT:aref <li>%name%</li> ENDIF:aref END:requires </ul> ENDIF:requires IF:attributes <h4>Attributes</h4> <table> START:attributes <tr><td>%name%</td><td>%rw%</td><td>%a_desc%</td></tr> END:attributes </table> ENDIF:attributes IF:includes <h4>Includes</h4> <ul> START:includes IF:aref <li><a href="%aref%">%name%</a></li> ENDIF:aref IFNOT:aref <li>%name%</li> ENDIF:aref END:includes </ul> ENDIF:includes IF:method_list <h3>Methods</h3> START:method_list IF:methods START:methods <h4>%type% %category% method: IF:callseq <a name="%aref%">%callseq%</a> ENDIF:callseq IFNOT:callseq <a name="%aref%">%name%%params%</a></h4> ENDIF:callseq IF:m_desc %m_desc% ENDIF:m_desc IF:sourcecode <blockquote><pre> %sourcecode% </pre></blockquote> ENDIF:sourcecode END:methods ENDIF:methods END:method_list ENDIF:method_list } The following is used for the -1 option
ONE_PAGE = %{ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> </head> <body> START:files <h2>File: %short_name%</h2> <table> <tr><td>Path:</td><td>%full_path%</td></tr> <tr><td>Modified:</td><td>%dtm_modified%</td></tr> </table> } + CONTENTS_XML + %{ END:files IF:classes <h2>Classes</h2> START:classes IF:parent <h3>%classmod% %full_name% &lt; HREF:par_url:parent:</h3> ENDIF:parent IFNOT:parent <h3>%classmod% %full_name%</h3> ENDIF:parent IF:infiles (in files START:infiles HREF:full_path_url:full_path: END:infiles ) ENDIF:infiles } + CONTENTS_XML + %{ END:classes ENDIF:classes </body> </html> }
FONTS = "Verdana, Arial, Helvetica, sans-serif"
STYLE = %{ body,p { font-family: Verdana, Arial, Helvetica, sans-serif; color: #000040; background: #BBBBBB; } td { font-family: Verdana, Arial, Helvetica, sans-serif; color: #000040; } .attr-rw { font-size: small; color: #444488 } .title-row {color: #eeeeff; background: #BBBBDD; } .big-title-font { color: white; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: large; height: 50px} .small-title-font { color: purple; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; } .aqua { color: purple } .method-name, attr-name { font-family: monospace; font-weight: bold; } .tablesubtitle { width: 100%; margin-top: 1ex; margin-bottom: .5ex; padding: 5px 0px 5px 20px; font-size: large; color: purple; background: #BBBBCC; } .tablesubsubtitle { width: 100%; margin-top: 1ex; margin-bottom: .5ex; padding: 5px 0px 5px 20px; font-size: medium; color: white; background: #BBBBCC; } .name-list { font-family: monospace; margin-left: 40px; margin-bottom: 2ex; line-height: 140%; } .description { margin-left: 40px; margin-bottom: 2ex; line-height: 140%; } .methodtitle { font-size: medium; text_decoration: none; padding: 3px 3px 3px 20px; color: #0000AA; } .column-title { font-size: medium; font-weight: bold; text_decoration: none; padding: 3px 3px 3px 20px; color: #3333CC; } .variable-name { font-family: monospace; font-size: medium; text_decoration: none; padding: 3px 3px 3px 20px; color: #0000AA; } .row-name { font-size: medium; font-weight: medium; font-family: monospace; text_decoration: none; padding: 3px 3px 3px 20px; } .paramsig { font-size: small; } .srcbut { float: right } }
BODY = %{ <html><head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> <script type="text/javascript" language="JavaScript"> <!-- function popCode(url) { parent.frames.source.location = url } //--> </script> </head> <body bgcolor="#BBBBBB"> !INCLUDE! <!-- banner header --> IF:diagram <table width="100%"><tr><td align="center"> %diagram% </td></tr></table> ENDIF:diagram IF:description <div class="description">%description%</div> ENDIF:description IF:requires <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Required files</td></tr> </table><br /> <div class="name-list"> START:requires HREF:aref:name: END:requires ENDIF:requires </div> IF:methods <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Subroutines and Functions</td></tr> </table><br /> <div class="name-list"> START:methods HREF:aref:name:, END:methods </div> ENDIF:methods IF:attributes <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Arguments</td></tr> </table><br /> <table cellspacing="5"> START:attributes <tr valign="top"> IF:rw <td align="center" class="attr-rw">&nbsp;[%rw%]&nbsp;</td> ENDIF:rw IFNOT:rw <td></td> ENDIF:rw <td class="attr-name">%name%</td> <td>%a_desc%</td> </tr> END:attributes </table> ENDIF:attributes IF:classlist <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Modules</td></tr> </table><br /> %classlist%<br /> ENDIF:classlist !INCLUDE! <!-- method descriptions --> </body> </html> }
FILE_PAGE = <<_FILE_PAGE_ <table width="100%"> <tr class="title-row"> <td><table width="100%"><tr> <td class="big-title-font" colspan="2"><font size="-3"><b>File</b><br /></font>%short_name%</td> <td align="right"><table cellspacing="0" cellpadding="2"> <tr> <td class="small-title-font">Path:</td> <td class="small-title-font">%full_path% IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl </td> </tr> <tr> <td class="small-title-font">Modified:</td> <td class="small-title-font">%dtm_modified%</td> </tr> </table> </td></tr></table></td> </tr> </table><br /> _FILE_PAGE_
CLASS_PAGE = %{ <table width="100%" border="0" cellspacing="0"> <tr class="title-row"> <td class="big-title-font"> <font size="-3"><b>%classmod%</b><br /></font>%full_name% </td> <td align="right"> <table cellspacing="0" cellpadding="2"> <tr valign="top"> <td class="small-title-font">In:</td> <td class="small-title-font"> START:infiles HREF:full_path_url:full_path: IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl END:infiles </td> </tr> IF:parent <tr> <td class="small-title-font">Parent:</td> <td class="small-title-font"> IF:par_url <a href="%par_url%" class="cyan"> ENDIF:par_url %parent% IF:par_url </a> ENDIF:par_url </td> </tr> ENDIF:parent </table> </td> </tr> </table><br /> }
METHOD_LIST = %{ IF:includes <div class="tablesubsubtitle">Uses</div><br /> <div class="name-list"> START:includes <span class="method-name">HREF:aref:name:</span> END:includes </div> ENDIF:includes IF:method_list START:method_list IF:methods <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">%type% %category% methods</td></tr> </table> START:methods <table width="100%" cellspacing="0" cellpadding="5" border="0"> <tr><td class="methodtitle"> <a name="%aref%"> <b>%name%</b>%params% IF:codeurl <a href="%codeurl%" target="source" class="srclink">src</a> ENDIF:codeurl </a></td></tr> </table> IF:m_desc <div class="description"> %m_desc% </div> ENDIF:m_desc END:methods ENDIF:methods END:method_list ENDIF:method_list }
SRC_PAGE = %{ <html> <head><title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style type="text/css"> .kw { color: #3333FF; font-weight: bold } .cmt { color: green; font-style: italic } .str { color: #662222; font-style: italic } .re { color: #662222; } .ruby-comment { color: green; font-style: italic } .ruby-constant { color: #4433aa; font-weight: bold; } .ruby-identifier { color: #222222; } .ruby-ivar { color: #2233dd; } .ruby-keyword { color: #3333FF; font-weight: bold } .ruby-node { color: #777777; } .ruby-operator { color: #111111; } .ruby-regexp { color: #662222; } .ruby-value { color: #662222; font-style: italic } </style> </head> <body bgcolor="#BBBBBB"> <pre>%code%</pre> </body> </html> } Source code ##########################
FR_INDEX_BODY = %{ !INCLUDE! } Index ################################
FILE_INDEX = %{ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style type="text/css"> <!-- body { background-color: #bbbbbb; font-family: #{FONTS}; font-size: 11px; font-style: normal; line-height: 14px; color: #000040; } div.banner { background: #bbbbcc; color: white; padding: 1; margin: 0; font-size: 90%; font-weight: bold; line-height: 1.1; text-align: center; width: 100%; } --> </style> <base target="docwin"> </head> <body> <div class="banner">%list_title%</div> START:entries <a href="%href%">%name%</a><br /> END:entries </body></html> }
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{ <html> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> </head> <frameset cols="20%,*"> <frameset rows="15%,35%,50%"> <frame src="fr_file_index.html" title="Files" name="Files"> <frame src="fr_class_index.html" name="Modules"> <frame src="fr_method_index.html" name="Subroutines and Functions"> </frameset> <frameset rows="80%,20%"> <frame src="%initial_page%" name="docwin"> <frame src="blank.html" name="source"> </frameset> <noframes> <body bgcolor="#BBBBBB"> Click <a href="html/index.html">here</a> for a non-frames version of this page. </body> </noframes> </frameset> </html> }
BLANK = %{ <html><body bgcolor="#BBBBBB"></body></html> } and a blank page to use as a target
FONTS = "Verdana, Arial, Helvetica, sans-serif"
STYLE = %{ body,td,p { font-family: %fonts%; color: #000040; } .attr-rw { font-size: x-small; color: #444488 } .title-row { background: #0000aa; color: #eeeeff; } .big-title-font { color: white; font-family: %fonts%; font-size: large; height: 50px} .small-title-font { color: aqua; font-family: %fonts%; font-size: xx-small; } .aqua { color: aqua } .method-name, attr-name { font-family: monospace; font-weight: bold; } .tablesubtitle, .tablesubsubtitle { width: 100%; margin-top: 1ex; margin-bottom: .5ex; padding: 5px 0px 5px 20px; font-size: large; color: aqua; background: #3333cc; } .name-list { font-family: monospace; margin-left: 40px; margin-bottom: 2ex; line-height: 140%; } .description { margin-left: 40px; margin-top: -2ex; margin-bottom: 2ex; } .description p { line-height: 140%; } .aka { margin-left: 40px; margin-bottom: 2ex; line-height: 100%; font-size: small; color: #808080; } .methodtitle { font-size: medium; text-decoration: none; color: #0000AA; background: white; } .paramsig { font-size: small; } .srcbut { float: right } pre { font-size: 1.2em; } tt { font-size: 1.2em; } pre.source { border-style: groove; background-color: #ddddff; margin-left: 40px; padding: 1em 0em 1em 2em; } .classlist { margin-left: 40px; margin-bottom: 2ex; line-height: 140%; } li { display: list-item; margin-top: .6em; } .ruby-comment { color: green; font-style: italic } .ruby-constant { color: #4433aa; font-weight: bold; } .ruby-identifier { color: #222222; } .ruby-ivar { color: #2233dd; } .ruby-keyword { color: #3333FF; font-weight: bold } .ruby-node { color: #777777; } .ruby-operator { color: #111111; } .ruby-regexp { color: #662222; } .ruby-value { color: #662222; font-style: italic } }
HEADER = %{ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> <link rel=StyleSheet href="%style_url%" type="text/css" media="screen" /> <script type="text/javascript" language="JavaScript"> <!-- function popCode(url) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } //--> </script> </head> }
METHOD_LIST = %{ IF:includes <table summary="Included modules" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Included modules</td></tr> </table> <div class="name-list"> START:includes <span class="method-name">HREF:aref:name:</span> END:includes </div> ENDIF:includes IF:method_list START:method_list IF:methods <table summary="Method list" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">%type% %category% methods</td></tr> </table> START:methods <table summary="method" width="100%" cellspacing="0" cellpadding="5" border="0"> <tr><td class="methodtitle"> <a name="%aref%"></a> IF:codeurl <a href="%codeurl%" target="Code" class="methodtitle" onClick="popCode('%codeurl%');return false;"> ENDIF:codeurl IF:callseq <b>%callseq%</b> ENDIF:callseq IFNOT:callseq <b>%name%</b>%params% ENDIF:callseq IF:codeurl </a> ENDIF:codeurl </td></tr> </table> IF:m_desc <div class="description"> %m_desc% </div> ENDIF:m_desc IF:aka <div class="aka"> This method is also aliased as START:aka <a href="%aref%">%name%</a> END:aka </div> ENDIF:aka IF:sourcecode <pre class="source"> %sourcecode% </pre> ENDIF:sourcecode END:methods ENDIF:methods END:method_list ENDIF:method_list }
CONTEXT_CONTENT = %{ IF:diagram <table summary="Diagram of classes and modules" width="100%"> <tr><td align="center"> %diagram% </td></tr></table> ENDIF:diagram IF:description <div class="description">%description%</div> ENDIF:description IF:requires <table summary="Requires" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Required files</td></tr> </table> <div class="name-list"> START:requires HREF:aref:name:&nbsp; &nbsp; END:requires </div> ENDIF:requires IF:methods <table summary="Methods" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Methods</td></tr> </table> <div class="name-list"> START:methods HREF:aref:name:&nbsp; &nbsp; END:methods </div> ENDIF:methods IF:constants <table summary="Constants" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Constants</td></tr> </table> <table cellpadding="5"> START:constants <tr valign="top"><td>%name%</td><td>=</td><td>%value%</td></tr> IF:desc <tr><td></td><td></td><td>%desc%</td></tr> ENDIF:desc END:constants </table> ENDIF:constants IF:aliases <table summary="Aliases" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">External Aliases</td></tr> </table> <div class="name-list"> START:aliases %old_name% -> %new_name%<br /> END:aliases </div> ENDIF:aliases IF:attributes <table summary="Attributes" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Attributes</td></tr> </table> <table summary="Attribute details" cellspacing="5"> START:attributes <tr valign="top"> <td class="attr-name">%name%</td> IF:rw <td align="center" class="attr-rw">&nbsp;[%rw%]&nbsp;</td> ENDIF:rw IFNOT:rw <td></td> ENDIF:rw <td>%a_desc%</td> </tr> END:attributes </table> ENDIF:attributes IF:classlist <table summary="List of classes" cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Classes and Modules</td></tr> </table> <div class="classlist"> %classlist% </div> ENDIF:classlist }
BODY = HEADER + %{ <body bgcolor="white"> !INCLUDE! <!-- banner header --> } + CONTEXT_CONTENT + METHOD_LIST + %{ </body> </html> }
FILE_PAGE = <<_FILE_PAGE_ <table summary="Information on file" width="100%"> <tr class="title-row"> <td><table summary="layout" width="100%"><tr> <td class="big-title-font" colspan="2">%short_name%</td> <td align="right"><table summary="layout" cellspacing="0" cellpadding="2"> <tr> <td class="small-title-font">Path:</td> <td class="small-title-font">%full_path% IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl </td> </tr> <tr> <td class="small-title-font">Modified:</td> <td class="small-title-font">%dtm_modified%</td> </tr> </table> </td></tr></table></td> </tr> </table> _FILE_PAGE_
CLASS_PAGE = %{ <table summary="Information on class" width="100%" border="0" cellspacing="0"> <tr class="title-row"> <td class="big-title-font"> <sup><font color="aqua">%classmod%</font></sup> %full_name% </td> <td align="right"> <table summary="layout" cellspacing="0" cellpadding="2"> <tr valign="top"> <td class="small-title-font">In:</td> <td class="small-title-font"> START:infiles IF:full_path_url <a href="%full_path_url%" class="aqua"> ENDIF:full_path_url %full_path% IF:full_path_url </a> ENDIF:full_path_url IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl <br /> END:infiles </td> </tr> IF:parent <tr> <td class="small-title-font">Parent:</td> <td class="small-title-font"> IF:par_url <a href="%par_url%" class="aqua"> ENDIF:par_url %parent% IF:par_url </a> ENDIF:par_url </td> </tr> ENDIF:parent </table> </td> </tr> </table> }
SRC_PAGE = %{ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <title>%title%</title> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> </head> <body bgcolor="white"> <pre>%code%</pre> </body> </html> } Source code ##########################
FR_INDEX_BODY = %{ !INCLUDE! } Index ################################
FILE_INDEX = %{ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <title>%list_title%</title> <style type="text/css"> <!-- body { background-color: #ddddff; font-family: #{FONTS}; font-size: 11px; font-style: normal; line-height: 14px; color: #000040; } div.banner { background: #0000aa; color: white; padding: 1; margin: 0; font-size: 90%; font-weight: bold; line-height: 1.1; text-align: center; width: 100%; } A.xx { color: white; font-weight: bold; } --> </style> <base target="docwin"> </head> <body> <div class="banner"><a href="%index_url%" class="xx">%list_title%</a></div> START:entries <a href="%href%">%name%</a><br /> END:entries </body></html> }
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <title>%title%</title></head> <frameset rows="20%, 80%"> <frameset cols="25%,35%,45%"> <frame src="fr_file_index.html" title="Files" name="Files"> <frame src="fr_class_index.html" name="Classes"> <frame src="fr_method_index.html" name="Methods"> </frameset> <frame src="%initial_page%" name="docwin"> <noframes> <body bgcolor="white"> Sorry, RDoc currently only generates HTML using frames. </body> </noframes> </frameset> </html> }
CONTENTS_XML = %{ IF:description %description% ENDIF:description IF:requires <h4>Requires:</h4> <ul> START:requires IF:aref <li><a href="%aref%">%name%</a></li> ENDIF:aref IFNOT:aref <li>%name%</li> ENDIF:aref END:requires </ul> ENDIF:requires IF:attributes <h4>Attributes</h4> <table> START:attributes <tr><td>%name%</td><td>%rw%</td><td>%a_desc%</td></tr> END:attributes </table> ENDIF:attributes IF:includes <h4>Includes</h4> <ul> START:includes IF:aref <li><a href="%aref%">%name%</a></li> ENDIF:aref IFNOT:aref <li>%name%</li> ENDIF:aref END:includes </ul> ENDIF:includes IF:method_list <h3>Methods</h3> START:method_list IF:methods START:methods <h4>%type% %category% method: <a name="%aref%">%name%%params%</a></h4> IF:m_desc %m_desc% ENDIF:m_desc IF:sourcecode <blockquote><pre> %sourcecode% </pre></blockquote> ENDIF:sourcecode END:methods ENDIF:methods END:method_list ENDIF:method_list } The following is used for the -1 option
FONTS = "Verdana, Arial, Helvetica, sans-serif"
STYLE = %{ body,td,p { font-family: %fonts%; color: #000040; } .attr-rw { font-size: xx-small; color: #444488 } .title-row { background-color: #CCCCFF; color: #000010; } .big-title-font { color: black; font-weight: bold; font-family: %fonts%; font-size: large; height: 60px; padding: 10px 3px 10px 3px; } .small-title-font { color: black; font-family: %fonts%; font-size:10; } .aqua { color: black } .method-name, .attr-name { font-family: font-family: %fonts%; font-weight: bold; font-size: small; margin-left: 20px; color: #000033; } .tablesubtitle, .tablesubsubtitle { width: 100%; margin-top: 1ex; margin-bottom: .5ex; padding: 5px 0px 5px 3px; font-size: large; color: black; background-color: #CCCCFF; border: thin; } .name-list { margin-left: 5px; margin-bottom: 2ex; line-height: 105%; } .description { margin-left: 5px; margin-bottom: 2ex; line-height: 105%; font-size: small; } .methodtitle { font-size: small; font-weight: bold; text-decoration: none; color: #000033; background-color: white; } .srclink { font-size: small; font-weight: bold; text-decoration: none; color: #0000DD; background-color: white; } .paramsig { font-size: small; } .srcbut { float: right } }
BODY = %{ <html><head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> <script type="text/javascript" language="JavaScript"> <!-- function popCode(url) { parent.frames.source.location = url } //--> </script> </head> <body bgcolor="white"> !INCLUDE! <!-- banner header --> IF:diagram <table width="100%"><tr><td align="center"> %diagram% </td></tr></table> ENDIF:diagram IF:description <div class="description">%description%</div> ENDIF:description IF:requires <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Required files</td></tr> </table><br /> <div class="name-list"> START:requires HREF:aref:name: END:requires ENDIF:requires </div> IF:methods <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Methods</td></tr> </table><br /> <div class="name-list"> START:methods HREF:aref:name:, END:methods </div> ENDIF:methods START:sections <div id="section"> IF:sectitle <h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2> IF:seccomment <div class="section-comment"> %seccomment% </div> ENDIF:seccomment ENDIF:sectitle IF:attributes <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Attributes</td></tr> </table><br /> <table cellspacing="5"> START:attributes <tr valign="top"> IF:rw <td align="center" class="attr-rw">&nbsp;[%rw%]&nbsp;</td> ENDIF:rw IFNOT:rw <td></td> ENDIF:rw <td class="attr-name">%name%</td> <td>%a_desc%</td> </tr> END:attributes </table> ENDIF:attributes IF:classlist <table cellpadding="5" width="100%"> <tr><td class="tablesubtitle">Classes and Modules</td></tr> </table><br /> %classlist%<br /> ENDIF:classlist !INCLUDE! <!-- method descriptions --> END:sections </body> </html> }
FILE_PAGE = <<_FILE_PAGE_ <table width="100%"> <tr class="title-row"> <td><table width="100%"><tr> <td class="big-title-font" colspan="2"><font size="-3"><b>File</b><br /></font>%short_name%</td> <td align="right"><table cellspacing="0" cellpadding="2"> <tr> <td class="small-title-font">Path:</td> <td class="small-title-font">%full_path% IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl </td> </tr> <tr> <td class="small-title-font">Modified:</td> <td class="small-title-font">%dtm_modified%</td> </tr> </table> </td></tr></table></td> </tr> </table><br /> _FILE_PAGE_
CLASS_PAGE = %{ <table width="100%" border="0" cellspacing="0"> <tr class="title-row"> <td class="big-title-font"> <font size="-3"><b>%classmod%</b><br /></font>%full_name% </td> <td align="right"> <table cellspacing="0" cellpadding="2"> <tr valign="top"> <td class="small-title-font">In:</td> <td class="small-title-font"> START:infiles HREF:full_path_url:full_path: IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl END:infiles </td> </tr> IF:parent <tr> <td class="small-title-font">Parent:</td> <td class="small-title-font"> IF:par_url <a href="%par_url%" class="cyan"> ENDIF:par_url %parent% IF:par_url </a> ENDIF:par_url </td> </tr> ENDIF:parent </table> </td> </tr> </table><br /> }
METHOD_LIST = %{ IF:includes <div class="tablesubsubtitle">Included modules</div><br /> <div class="name-list"> START:includes <span class="method-name">HREF:aref:name:</span> END:includes </div> ENDIF:includes IF:method_list START:method_list IF:methods <table cellpadding=5 width="100%"> <tr><td class="tablesubtitle">%type% %category% methods</td></tr> </table> START:methods <table width="100%" cellspacing="0" cellpadding="5" border="0"> <tr><td class="methodtitle"> <a name="%aref%"> IF:callseq <b>%callseq%</b> ENDIF:callseq IFNOT:callseq <b>%name%</b>%params% ENDIF:callseq IF:codeurl <a href="%codeurl%" target="source" class="srclink">src</a> ENDIF:codeurl </a></td></tr> </table> IF:m_desc <div class="description"> %m_desc% </div> ENDIF:m_desc IF:aka <div class="aka"> This method is also aliased as START:aka <a href="%aref%">%name%</a> END:aka </div> ENDIF:aka IF:sourcecode <pre class="source"> %sourcecode% </pre> ENDIF:sourcecode END:methods ENDIF:methods END:method_list ENDIF:method_list }
SRC_PAGE = %{ <html> <head><title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style type="text/css"> .ruby-comment { color: green; font-style: italic } .ruby-constant { color: #4433aa; font-weight: bold; } .ruby-identifier { color: #222222; } .ruby-ivar { color: #2233dd; } .ruby-keyword { color: #3333FF; font-weight: bold } .ruby-node { color: #777777; } .ruby-operator { color: #111111; } .ruby-regexp { color: #662222; } .ruby-value { color: #662222; font-style: italic } .kw { color: #3333FF; font-weight: bold } .cmt { color: green; font-style: italic } .str { color: #662222; font-style: italic } .re { color: #662222; } </style> </head> <body bgcolor="white"> <pre>%code%</pre> </body> </html> } Source code ##########################
FR_INDEX_BODY = %{ !INCLUDE! } Index ################################
FILE_INDEX = %{ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style> <!-- body { background-color: #ddddff; font-family: #{FONTS}; font-size: 11px; font-style: normal; line-height: 14px; color: #000040; } div.banner { background: #0000aa; color: white; padding: 1; margin: 0; font-size: 90%; font-weight: bold; line-height: 1.1; text-align: center; width: 100%; } --> </style> <base target="docwin"> </head> <body> <div class="banner">%list_title%</div> START:entries <a href="%href%">%name%</a><br /> END:entries </body></html> }
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{ <html> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> </head> <frameset cols="20%,*"> <frameset rows="15%,35%,50%"> <frame src="fr_file_index.html" title="Files" name="Files"> <frame src="fr_class_index.html" name="Classes"> <frame src="fr_method_index.html" name="Methods"> </frameset> IF:inline_source <frame src="%initial_page%" name="docwin"> ENDIF:inline_source IFNOT:inline_source <frameset rows="80%,20%"> <frame src="%initial_page%" name="docwin"> <frame src="blank.html" name="source"> </frameset> ENDIF:inline_source <noframes> <body bgcolor="white"> Click <a href="html/index.html">here</a> for a non-frames version of this page. </body> </noframes> </frameset> </html> }
BLANK = %{ <html><body bgcolor="white"></body></html> } and a blank page to use as a target
FONTS = "Verdana,Arial,Helvetica,sans-serif"
STYLE = %{ body { font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 90%; margin: 0; margin-left: 40px; padding: 0; background: white; } h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; } h1 { font-size: 150%; } h2,h3,h4 { margin-top: 1em; } a { background: #eef; color: #039; text-decoration: none; } a:hover { background: #039; color: #eef; } /* Override the base stylesheet's Anchor inside a table cell */ td > a { background: transparent; color: #039; text-decoration: none; } /* and inside a section title */ .section-title > a { background: transparent; color: #eee; text-decoration: none; } /* === Structural elements =================================== */ div#index { margin: 0; margin-left: -40px; padding: 0; font-size: 90%; } div#index a { margin-left: 0.7em; } div#index .section-bar { margin-left: 0px; padding-left: 0.7em; background: #ccc; font-size: small; } div#classHeader, div#fileHeader { width: auto; color: white; padding: 0.5em 1.5em 0.5em 1.5em; margin: 0; margin-left: -40px; border-bottom: 3px solid #006; } div#classHeader a, div#fileHeader a { background: inherit; color: white; } div#classHeader td, div#fileHeader td { background: inherit; color: white; } div#fileHeader { background: #057; } div#classHeader { background: #048; } .class-name-in-header { font-size: 180%; font-weight: bold; } div#bodyContent { padding: 0 1.5em 0 1.5em; } div#description { padding: 0.5em 1.5em; background: #efefef; border: 1px dotted #999; } div#description h1,h2,h3,h4,h5,h6 { color: #125;; background: transparent; } div#validator-badges { text-align: center; } div#validator-badges img { border: 0; } div#copyright { color: #333; background: #efefef; font: 0.75em sans-serif; margin-top: 5em; margin-bottom: 0; padding: 0.5em 2em; } /* === Classes =================================== */ table.header-table { color: white; font-size: small; } .type-note { font-size: small; color: #DEDEDE; } .xxsection-bar { background: #eee; color: #333; padding: 3px; } .section-bar { color: #333; border-bottom: 1px solid #999; margin-left: -20px; } .section-title { background: #79a; color: #eee; padding: 3px; margin-top: 2em; margin-left: -30px; border: 1px solid #999; } .top-aligned-row { vertical-align: top } .bottom-aligned-row { vertical-align: bottom } /* --- Context section classes ----------------------- */ .context-row { } .context-item-name { font-family: monospace; font-weight: bold; color: black; } .context-item-value { font-size: small; color: #448; } .context-item-desc { color: #333; padding-left: 2em; } /* --- Method classes -------------------------- */ .method-detail { background: #efefef; padding: 0; margin-top: 0.5em; margin-bottom: 1em; border: 1px dotted #ccc; } .method-heading { color: black; background: #ccc; border-bottom: 1px solid #666; padding: 0.2em 0.5em 0 0.5em; } .method-signature { color: black; background: inherit; } .method-name { font-weight: bold; } .method-args { font-style: italic; } .method-description { padding: 0 0.5em 0 0.5em; } /* --- Source code sections -------------------- */ a.source-toggle { font-size: 90%; } div.method-source-code { background: #262626; color: #ffdead; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { color: #ffdead; overflow: hidden; } /* --- Ruby keyword styles --------------------- */ .standalone-code { background: #221111; color: #ffdead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; font-weight: bold; background: transparent; } .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } }
XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> } H E A D E R T E M P L A T E
HEADER = XHTML_PREAMBLE + %{ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\\"text/css\\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> }
CONTEXT_CONTENT = %{ } C O N T E X T C O N T E N T T E M P L A T E
FOOTER = %{ <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html> } F O O T E R T E M P L A T E
FILE_PAGE = %{ <div id="fileHeader"> <h1>%short_name%</h1> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Path:</strong></td> <td>%full_path% IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl </td> </tr> <tr class="top-aligned-row"> <td><strong>Last Update:</strong></td> <td>%dtm_modified%</td> </tr> </table> </div> } F I L E P A G E H E A D E R T E M P L A T E
CLASS_PAGE = %{ <div id="classHeader"> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>%classmod%</strong></td> <td class="class-name-in-header">%full_name%</td> </tr> <tr class="top-aligned-row"> <td><strong>In:</strong></td> <td> START:infiles IF:full_path_url <a href="%full_path_url%"> ENDIF:full_path_url %full_path% IF:full_path_url </a> ENDIF:full_path_url IF:cvsurl &nbsp;(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>) ENDIF:cvsurl <br /> END:infiles </td> </tr> IF:parent <tr class="top-aligned-row"> <td><strong>Parent:</strong></td> <td> IF:par_url <a href="%par_url%"> ENDIF:par_url %parent% IF:par_url </a> ENDIF:par_url </td> </tr> ENDIF:parent </table> </div> } C L A S S P A G E H E A D E R T E M P L A T E
METHOD_LIST = %{ <div id="contextContent"> IF:diagram <div id="diagram"> %diagram% </div> ENDIF:diagram IF:description <div id="description"> %description% </div> ENDIF:description IF:requires <div id="requires-list"> <h3 class="section-bar">Required files</h3> <div class="name-list"> START:requires HREF:aref:name:&nbsp;&nbsp; END:requires </div> </div> ENDIF:requires IF:toc <div id="contents-list"> <h3 class="section-bar">Contents</h3> <ul> START:toc <li><a href="#%href%">%secname%</a></li> END:toc </ul> ENDIF:toc </div> IF:methods <div id="method-list"> <h3 class="section-bar">Methods</h3> <div class="name-list"> START:methods HREF:aref:name:&nbsp;&nbsp; END:methods </div> </div> ENDIF:methods </div> <!-- if includes --> IF:includes <div id="includes"> <h3 class="section-bar">Included Modules</h3> <div id="includes-list"> START:includes <span class="include-name">HREF:aref:name:</span> END:includes </div> </div> ENDIF:includes START:sections <div id="section"> IF:sectitle <h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2> IF:seccomment <div class="section-comment"> %seccomment% </div> ENDIF:seccomment ENDIF:sectitle IF:classlist <div id="class-list"> <h3 class="section-bar">Classes and Modules</h3> %classlist% </div> ENDIF:classlist IF:constants <div id="constants-list"> <h3 class="section-bar">Constants</h3> <div class="name-list"> <table summary="Constants"> START:constants <tr class="top-aligned-row context-row"> <td class="context-item-name">%name%</td> <td>=</td> <td class="context-item-value">%value%</td> IF:desc <td width="3em">&nbsp;</td> <td class="context-item-desc">%desc%</td> ENDIF:desc </tr> END:constants </table> </div> </div> ENDIF:constants IF:aliases <div id="aliases-list"> <h3 class="section-bar">External Aliases</h3> <div class="name-list"> <table summary="aliases"> START:aliases <tr class="top-aligned-row context-row"> <td class="context-item-name">%old_name%</td> <td>-&gt;</td> <td class="context-item-value">%new_name%</td> </tr> IF:desc <tr class="top-aligned-row context-row"> <td>&nbsp;</td> <td colspan="2" class="context-item-desc">%desc%</td> </tr> ENDIF:desc END:aliases </table> </div> </div> ENDIF:aliases IF:attributes <div id="attribute-list"> <h3 class="section-bar">Attributes</h3> <div class="name-list"> <table> START:attributes <tr class="top-aligned-row context-row"> <td class="context-item-name">%name%</td> IF:rw <td class="context-item-value">&nbsp;[%rw%]&nbsp;</td> ENDIF:rw IFNOT:rw <td class="context-item-value">&nbsp;&nbsp;</td> ENDIF:rw <td class="context-item-desc">%a_desc%</td> </tr> END:attributes </table> </div> </div> ENDIF:attributes <!-- if method_list --> IF:method_list <div id="methods"> START:method_list IF:methods <h3 class="section-bar">%type% %category% methods</h3> START:methods <div id="method-%aref%" class="method-detail"> <a name="%aref%"></a> <div class="method-heading"> IF:codeurl <a href="%codeurl%" target="Code" class="method-signature" onclick="popupCode('%codeurl%');return false;"> ENDIF:codeurl IF:sourcecode <a href="#%aref%" class="method-signature"> ENDIF:sourcecode IF:callseq <span class="method-name">%callseq%</span> ENDIF:callseq IFNOT:callseq <span class="method-name">%name%</span><span class="method-args">%params%</span> ENDIF:callseq IF:codeurl </a> ENDIF:codeurl IF:sourcecode </a> ENDIF:sourcecode </div> <div class="method-description"> IF:m_desc %m_desc% ENDIF:m_desc IF:sourcecode <p><a class="source-toggle" href="#" onclick="toggleCode('%aref%-source');return false;">[Source]</a></p> <div class="method-source-code" id="%aref%-source"> <pre> %sourcecode% </pre> </div> ENDIF:sourcecode </div> </div> END:methods ENDIF:methods END:method_list </div> ENDIF:method_list END:sections } M E T H O D L I S T T E M P L A T E
BODY = HEADER + %{ !INCLUDE! <!-- banner header --> <div id="bodyContent"> } + METHOD_LIST + %{ </div> } + FOOTER B O D Y T E M P L A T E
SRC_PAGE = XHTML_PREAMBLE + %{ <html> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> </head> <body class="standalone-code"> <pre>%code%</pre> </body> </html> } S O U R C E C O D E T E M P L A T E
FR_INDEX_BODY = %{ !INCLUDE! } I N D E X F I L E T E M P L A T E S
FILE_INDEX = XHTML_PREAMBLE + %{ <!-- %list_title% --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>%list_title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> <link rel="stylesheet" href="%style_url%" type="text/css" /> <base target="docwin" /> </head> <body> <div id="index"> <h1 class="section-bar">%list_title%</h1> <div id="index-entries"> START:entries <a href="%href%">%name%</a><br /> END:entries </div> </div> </body> </html> }
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{<?xml version="1.0" encoding="%charset%"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <!-- %title% --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> </head> <frameset rows="20%, 80%"> <frameset cols="25%,35%,45%"> <frame src="fr_file_index.html" title="Files" name="Files" /> <frame src="fr_class_index.html" name="Classes" /> <frame src="fr_method_index.html" name="Methods" /> </frameset> <frame src="%initial_page%" name="docwin" /> </frameset> </html> }

Public Instance methods

write_extra_pages()
write_extra_pages()


Module: RDoc::ParserFactory

Module | RDoc::ParserFactory
In: | lib/rdoc/parsers/parserfactory.rb

A parser is simple a class that implements

  #initialize(file_name, body, options)

and

  #scan

The initialize method takes a file name to be used, the body of the file, and an RDoc::Options object. The scan method is then called to return an appropriately parsed TopLevel code object.

The ParseFactory is used to redirect to the correct parser given a filename extension. This magic works because individual parsers have to register themselves with us as they are loaded in. The do this using the following incantation

   require "rdoc/parsers/parsefactory"

   module RDoc

     class XyzParser
       extend ParseFactory                  <<<<
       parse_files_matching /\.xyz$/        <<<<

       def initialize(file_name, body, options)
         ...
       end

       def scan
         ...
       end
     end
   end

Just to make life interesting, if we suspect a plain text file, we also look for a shebang line just in case it‘s a potential shell script

Methods

alias_extension can_parse parse_files_matching parser_for

Constants

Parsers = Struct.new(:regexp, :parser)

Public Class methods

alias_extension(old_ext, new_ext)

Alias an extension to another extension. After this call, files ending "new_ext" will be parsed using the same parser as "old_ext"

can_parse(file_name)

Return a parser that can handle a particular extension

parser_for(top_level, file_name, body, options, stats)

Find the correct parser for a particular file name. Return a SimpleParser for ones that we don‘t know

Public Instance methods

parse_files_matching(regexp)

Record the fact that a particular class parses files that match a given extension


Class: RDoc::RDoc

Class | RDoc::RDoc
In: | lib/rdoc/rdoc.rb
Parent: | Object

Encapsulate the production of rdoc documentation. Basically you can use this as you would invoke rdoc from the command line:

   rdoc = RDoc::RDoc.new
   rdoc.document(args)

where args is an array of strings, each corresponding to an argument you‘d give rdoc on the command line. See rdoc/rdoc.rb for details.

Methods

document

Constants

Generator | = | Struct.new(:file_name, :class_name, :key) | This is the list of output generators that we support
GENERATORS | = | {}

Public Instance methods

document(argv)

Format up one or more files according to the given arguments. For simplicity, argv is an array of strings, equivalent to the strings that would be passed on the command line. (This isn‘t a coincidence, as we do pass in ARGV when running interactively). For a list of options, see rdoc/rdoc.rb. By default, output will be stored in a directory called doc below the current directory, so make sure you‘re somewhere writable before invoking.

Throws: RDocError on error


Class: RDoc::RDocError

Class | RDoc::RDocError
In: | lib/rdoc/rdoc.rb
Parent: | Exception

Exception thrown by any rdoc error. Only the message part is of use externally.


Class: RDoc::Require

Class | RDoc::Require
In: | lib/rdoc/code_objects.rb
Parent: | CodeObject

a required file

Methods

new

Attributes

name [RW]

Public Class methods

new(name, comment)


Class: RDoc::RubyParser

Class | RDoc::RubyParser
In: | lib/rdoc/parsers/parse_rb.rb
Parent: | Object

Methods

new scan

Included Modules

RubyToken TokenStream

Constants

NORMAL | = | "::"
SINGLE | = | "<<"

Public Class methods

new(top_level, file_name, content, options, stats)

Public Instance methods

scan()


Class: RDoc::SimpleParser

Class | RDoc::SimpleParser
In: | lib/rdoc/parsers/parse_simple.rb
Parent: | Object

See rdoc/parsers/parse_c.rb

Methods

new remove_private_comments scan

Public Class methods

new(top_level, file_name, body, options, stats)

prepare to parse a plain file

Public Instance methods

remove_private_comments(comment)
scan()

Extract the file contents and attach them to the toplevel as a comment


Class: RDoc::SingleClass

Class | RDoc::SingleClass
In: | lib/rdoc/code_objects.rb
Parent: | ClassModule

Singleton classes


Class: RDoc::Stats

Class | RDoc::Stats
In: | lib/rdoc/rdoc.rb
Parent: | Object

Simple stats collector

Methods

new print

Attributes

num_classes | [RW]
num_files | [RW]
num_methods | [RW]
num_modules | [RW]

Public Class methods

new()

Public Instance methods

print()


Class: RDoc::Token

Class | RDoc::Token
In: | lib/rdoc/parsers/parse_f95.rb
Parent: | Object

Methods

new set_text

Constants

NO_TEXT = "??".freeze

Attributes

char_no | [R]
line_no | [R]
text | [R]

Public Class methods

new(line_no, char_no)

Public Instance methods

set_text(text)

Because we‘re used in contexts that expect to return a token, we set the text string and then return ourselves


Class: RDoc::TopLevel

Class | RDoc::TopLevel
In: | lib/rdoc/code_objects.rb
Parent: | Context

A TopLevel context is a source file

Methods

add_class_or_module all_classes_and_modules find_class_named find_class_or_module_named find_local_symbol find_module_named full_name new reset

Attributes

diagram | [RW]
file_absolute_name | [RW]
file_relative_name | [RW]
file_stat | [RW]

Public Class methods

all_classes_and_modules()
find_class_named(name)
new(file_name)
reset()

Public Instance methods

add_class_or_module(collection, class_type, name, superclass)

Adding a class or module to a TopLevel is special, as we only want one copy of a particular top-level class. For example, if both file A and file B implement class C, we only want one ClassModule object for C. This code arranges to share classes and modules between files.

find_class_or_module_named(symbol)
find_local_symbol(symbol)
find_module_named(name)

Find a named module

full_name()


Module: REXML
In: lib/rexml/document.rb
lib/rexml/parsers/pullparser.rb
lib/rexml/parsers/streamparser.rb
lib/rexml/parsers/sax2parser.rb
lib/rexml/parsers/xpathparser.rb
lib/rexml/parsers/treeparser.rb
lib/rexml/parsers/lightparser.rb
lib/rexml/parsers/baseparser.rb
lib/rexml/parsers/ultralightparser.rb
lib/rexml/syncenumerator.rb
lib/rexml/functions.rb
lib/rexml/cdata.rb
lib/rexml/quickpath.rb
lib/rexml/output.rb
lib/rexml/namespace.rb
lib/rexml/dtd/entitydecl.rb
lib/rexml/dtd/elementdecl.rb
lib/rexml/dtd/dtd.rb
lib/rexml/dtd/notationdecl.rb
lib/rexml/dtd/attlistdecl.rb
lib/rexml/parseexception.rb
lib/rexml/attribute.rb
lib/rexml/comment.rb
lib/rexml/light/node.rb
lib/rexml/doctype.rb
lib/rexml/parent.rb
lib/rexml/element.rb
lib/rexml/xmldecl.rb
lib/rexml/rexml.rb
lib/rexml/entity.rb
lib/rexml/child.rb
lib/rexml/validation/validationexception.rb
lib/rexml/validation/validation.rb
lib/rexml/validation/relaxng.rb
lib/rexml/xmltokens.rb
lib/rexml/formatters/default.rb
lib/rexml/formatters/pretty.rb
lib/rexml/formatters/transitive.rb
lib/rexml/undefinednamespaceexception.rb
lib/rexml/sax2listener.rb
lib/rexml/instruction.rb
lib/rexml/streamlistener.rb
lib/rexml/xpath_parser.rb
lib/rexml/xpath.rb
lib/rexml/encoding.rb
lib/rexml/text.rb
lib/rexml/attlistdecl.rb
lib/rexml/node.rb
lib/rexml/source.rb
lib/rexml/encodings/EUC-JP.rb
lib/rexml/encodings/CP-1252.rb
lib/rexml/encodings/ISO-8859-1.rb
lib/rexml/encodings/UTF-8.rb
lib/rexml/encodings/UNILE.rb
lib/rexml/encodings/US-ASCII.rb
lib/rexml/encodings/ISO-8859-15.rb
lib/rexml/encodings/ICONV.rb
lib/rexml/encodings/SHIFT-JIS.rb
lib/rexml/encodings/UTF-16.rb

This class was contributed by Mikko Tiihonen mikko DOT tiihonen AT hut DOT fi

Classes and Modules

Module REXML::DTD
Module REXML::Encoding
Module REXML::EntityConst
Module REXML::Formatters
Module REXML::Functions
Module REXML::Light
Module REXML::Namespace
Module REXML::Node
Module REXML::Parsers
Module REXML::SAX2Listener
Module REXML::StreamListener
Module REXML::Validation
Module REXML::XMLTokens
Class REXML::AttlistDecl
Class REXML::Attribute
Class REXML::Attributes
Class REXML::CData
Class REXML::Child
Class REXML::Comment
Class REXML::Declaration
Class REXML::DocType
Class REXML::Document
Class REXML::Element
Class REXML::ElementDecl
Class REXML::Elements
Class REXML::Entity
Class REXML::ExternalEntity
Class REXML::IOSource
Class REXML::Instruction
Class REXML::NotationDecl
Class REXML::Output
Class REXML::Parent
Class REXML::ParseException
Class REXML::QuickPath
Class REXML::Source
Class REXML::SourceFactory
Class REXML::SyncEnumerator
Class REXML::Text
Class REXML::UndefinedNamespaceException
Class REXML::XMLDecl
Class REXML::XPath
Class REXML::XPathParser

Constants

COPYRIGHT | = | "Copyright \xC2\xA9 2001-2006 Sean Russell <ser@germane-software.com>"
VERSION | = | "3.1.7.2"
DATE | = | "2007/275"
REVISION | = | "$Revision: 13815 $".gsub(/\$Revision:|\$/,'').strip
Copyright | = | COPYRIGHT
Version | = | VERSION


Class: REXML::AttlistDecl

Class | REXML::AttlistDecl
In: | lib/rexml/attlistdecl.rb
Parent: | Child

This class needs:

  • Documentation
  • Work! Not all types of attlists are intelligently parsed, so we just

spew back out what we get in. This works, but it would be better if we formatted the output ourselves.

AttlistDecls provide just enough support to allow namespace declarations. If you need some sort of generalized support, or have an interesting idea about how to map the hideous, terrible design of DTD AttlistDecls onto an intuitive Ruby interface, let me know. I‘m desperate for anything to make DTDs more palateable.

Methods

[] each include? new node_type write

Included Modules

Enumerable

Attributes

element_name [R] What is this? Got me.

Public Class methods

new(source)

Create an AttlistDecl, pulling the information from a Source. Notice that this isn‘t very convenient; to create an AttlistDecl, you basically have to format it yourself, and then have the initializer parse it. Sorry, but for the forseeable future, DTD support in REXML is pretty weak on convenience. Have I mentioned how much I hate DTDs?

Public Instance methods

[](key)

Access the attlist attribute/value pairs.

 value = attlist_decl[ attribute_name ]
each(&block)

Itterate over the key/value pairs:

 attlist_decl.each { |attribute_name, attribute_value| ... }
include?(key)

Whether an attlist declaration includes the given attribute definition

 if attlist_decl.include? "xmlns:foobar"
node_type()
write(out, indent=-1)

Write out exactly what we got in.


Class: REXML::Attribute

Class | REXML::Attribute
In: | lib/rexml/attribute.rb
Parent: | Object

Defines an Element Attribute; IE, a attribute=value pair, as in: <element attribute="value"/>. Attributes can be in their own namespaces. General users of REXML will not interact with the Attribute class much.

Methods

== clone element= hash inspect namespace new node_type prefix remove to_s to_string value write xpath

Included Modules

Node Namespace

Constants

PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um

Attributes

element | [R] | The element to which this attribute belongs
normalized | [W] | The normalized value of this attribute. That is, the attribute with entities intact.

Public Class methods

new( first, second=nil, parent=nil )

Constructor. FIXME: The parser doesn‘t catch illegal characters in attributes

first: | Either: an Attribute, which this new attribute will become a clone of; or a String, which is the name of this attribute
second: | If first is an Attribute, then this may be an Element, or nil. If nil, then the Element parent of this attribute is the parent of the first Attribute. If the first argument is a String, then this must also be a String, and is the content of the attribute. If this is the content, it must be fully normalized (contain no illegal characters).
parent: | Ignored unless first is a String; otherwise, may be the Element parent of this attribute, or nil.
 Attribute.new( attribute_to_clone )
 Attribute.new( attribute_to_clone, parent_element )
 Attribute.new( "attr", "attr_value" )
 Attribute.new( "attr", "attr_value", parent_element )

Public Instance methods

==( other )

Returns true if other is an Attribute and has the same name and value, false otherwise.

clone()

Returns a copy of this attribute

element=( element )

Sets the element of which this object is an attribute. Normally, this is not directly called.

Returns this attribute

hash()

Creates (and returns) a hash from both the name and value

inspect()
namespace(arg=nil)

Returns the namespace URL, if defined, or nil otherwise

 e = Element.new("el")
 e.add_attributes({"xmlns:ns", "http://url"})
 e.namespace( "ns" )              # -> "http://url"
node_type()
prefix()

Returns the namespace of the attribute.

 e = Element.new( "elns:myelement" )
 e.add_attribute( "nsa:a", "aval" )
 e.add_attribute( "b", "bval" )
 e.attributes.get_attribute( "a" ).prefix   # -> "nsa"
 e.attributes.get_attribute( "b" ).prefix   # -> "elns"
 a = Attribute.new( "x", "y" )
 a.prefix                                   # -> ""
remove()

Removes this Attribute from the tree, and returns true if successfull

This method is usually not called directly.

to_s()

Returns the attribute value, with entities replaced

to_string()

Returns this attribute out as XML source, expanding the name

 a = Attribute.new( "x", "y" )
 a.to_string     # -> "x='y'"
 b = Attribute.new( "ns:x", "y" )
 b.to_string     # -> "ns:x='y'"
value()

Returns the UNNORMALIZED value of this attribute. That is, entities have been expanded to their values

write( output, indent=-1 )

Writes this attribute (EG, puts ‘key="value"’ to the output)

xpath()


Class: REXML::Attributes

Class | REXML::Attributes
In: | lib/rexml/element.rb
Parent: | Hash

A class that defines the set of Attributes of an Element and provides operations for accessing elements in that set.

Methods

<< [] []= add delete delete_all each each_attribute get_attribute get_attribute_ns length namespaces new prefixes size to_a

Public Class methods

new(element)

Constructor

element: the Element of which this is an Attribute

Public Instance methods

<<( attribute )

Alias for add

[](name)

Fetches an attribute value. If you want to get the Attribute itself, use get_attribute()

name: | an XPath attribute name. Namespaces are relevant here.
Returns: | the String value of the matching attribute, or nil if no matching attribute was found. This is the unnormalized value (with entities expanded).
 doc = Document.new "<a foo:att='1' bar:att='2' att='&lt;'/>"
 doc.root.attributes['att']         #-> '<'
 doc.root.attributes['bar:att']     #-> '2'
[]=( name, value )

Sets an attribute, overwriting any existing attribute value by the same name. Namespace is significant.

name: | the name of the attribute
value: | (optional) If supplied, the value of the attribute. If nil, any existing matching attribute is deleted.
Returns: | Owning element
 doc = Document.new "<a x:foo='1' foo='3'/>"
 doc.root.attributes['y:foo'] = '2'
 doc.root.attributes['foo'] = '4'
 doc.root.attributes['x:foo'] = nil
add( attribute )

Adds an attribute, overriding any existing attribute by the same name. Namespaces are significant.

attribute: An Attribute
delete( attribute )

Removes an attribute

attribute: | either a String, which is the name of the attribute to remove — namespaces are significant here — or the attribute to remove.
Returns: | the owning element
 doc = Document.new "<a y:foo='0' x:foo='1' foo='3' z:foo='4'/>"
 doc.root.attributes.delete 'foo'   #-> <a y:foo='0' x:foo='1' z:foo='4'/>"
 doc.root.attributes.delete 'x:foo' #-> <a y:foo='0' z:foo='4'/>"
 attr = doc.root.attributes.get_attribute('y:foo')
 doc.root.attributes.delete attr    #-> <a z:foo='4'/>"
delete_all( name )

Deletes all attributes matching a name. Namespaces are significant.

name: | A String; all attributes that match this path will be removed
Returns: | an Array of the Attributes that were removed
each() {|attr.expanded_name, attr.value| ...}

Itterates over each attribute of an Element, yielding the expanded name and value as a pair of Strings.

 doc = Document.new '<a x="1" y="2"/>'
 doc.root.attributes.each {|name, value| p name+" => "+value }
each_attribute( {|attribute| ...}

Itterates over the attributes of an Element. Yields actual Attribute nodes, not String values.

 doc = Document.new '<a x="1" y="2"/>'
 doc.root.attributes.each_attribute {|attr|
   p attr.expanded_name+" => "+attr.value
 }
get_attribute( name )

Fetches an attribute

name: | the name by which to search for the attribute. Can be a prefix:name namespace name.
Returns: | The first matching attribute, or nil if there was none. This

value is an Attribute node, not the String value of the attribute.

 doc = Document.new '<a x:foo="1" foo="2" bar="3"/>'
 doc.root.attributes.get_attribute("foo").value    #-> "2"
 doc.root.attributes.get_attribute("x:foo").value  #-> "1"
get_attribute_ns(namespace, name)

The get_attribute_ns method retrieves a method by its namespace and name. Thus it is possible to reliably identify an attribute even if an XML processor has changed the prefix.

Method contributed by Henrik Martensson

length()

Returns the number of attributes the owning Element contains.

 doc = Document "<a x='1' y='2' foo:x='3'/>"
 doc.root.attributes.length        #-> 3
namespaces()
prefixes()

Returns an array of Strings containing all of the prefixes declared by this set of # attributes. The array does not include the default namespace declaration, if one exists.

 doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' "+
       "z='glorp' p:k='gru'/>")
 prefixes = doc.root.attributes.prefixes    #-> ['x', 'y']
size()

Alias for length

to_a()


Class: REXML::CData

Class | REXML::CData
In: | lib/rexml/cdata.rb
Parent: | Text

Methods

clone new to_s value write

Constants

START | = | '<![CDATA['
STOP | = | ']]>'
ILLEGAL | = | /(\]\]>)/

Public Class methods

new( first, whitespace=true, parent=nil )
    Constructor.  CData is data between <![CDATA[ ... ]]>

Examples

 CData.new( source )
 CData.new( "Here is some CDATA" )
 CData.new( "Some unprocessed data", respect_whitespace_TF, parent_element )

Public Instance methods

clone()

Make a copy of this object

Examples

 c = CData.new( "Some text" )
 d = c.clone
 d.to_s        # -> "Some text"
to_s()

Returns the content of this CData object

Examples

 c = CData.new( "Some text" )
 c.to_s        # -> "Some text"
value()
write( output=$stdout, indent=-1, transitive=false, ie_hack=false )

DEPRECATED

See the rexml/formatters package

Generates XML output of this object

output: | Where to write the string. Defaults to $stdout
indent: | The amount to indent this node by
transitive: | Ignored
ie_hack: | Ignored

Examples

 c = CData.new( " Some text " )
 c.write( $stdout )     #->  <![CDATA[ Some text ]]>


Class: REXML::Child

Class | REXML::Child
In: | lib/rexml/child.rb
Parent: | Object

A Child object is something contained by a parent, and this class contains methods to support that. Most user code will not use this class directly.

Methods

bytes document new next_sibling= parent= previous_sibling= remove replace_with

Included Modules

Node

External Aliases

next_sibling_node | -> | next_sibling
previous_sibling_node | -> | previous_sibling

Attributes

parent [R]

Public Class methods

new( parent = nil )

Constructor. Any inheritors of this class should call super to make sure this method is called.

parent: if supplied, the parent of this child will be set to the supplied value, and self will be added to the parent

Public Instance methods

bytes()

This doesn‘t yet handle encodings

document()
Returns: the document this child belongs to, or nil if this child

belongs to no document

next_sibling=( other )

Sets the next sibling of this child. This can be used to insert a child after some other child.

 a = Element.new("a")
 b = a.add_element("b")
 c = Element.new("c")
 b.next_sibling = c
 # => <a><b/><c/></a>
parent=( other )

Sets the parent of this child to the supplied argument.

other: | Must be a Parent object. If this object is the same object as the existing parent of this child, no action is taken. Otherwise, this child is removed from the current parent (if one exists), and is added to the new parent.
Returns: | The parent added
previous_sibling=(other)

Sets the previous sibling of this child. This can be used to insert a child before some other child.

 a = Element.new("a")
 b = a.add_element("b")
 c = Element.new("c")
 b.previous_sibling = c
 # => <a><b/><c/></a>
remove()

Removes this child from the parent.

Returns: self
replace_with( child )

Replaces this object with another object. Basically, calls Parent.replace_child

Returns: self


Class: REXML::Comment

Class | REXML::Comment
In: | lib/rexml/comment.rb
Parent: | Child

Represents an XML comment; that is, text between <!— … —>

Methods

<=> == clone new node_type write

Included Modules

Comparable

Constants

START | = | "<!--"
STOP | = | "-->"

External Aliases

string -> to_s

Attributes

string [RW] The content text

Public Class methods

new( first, second = nil )

Constructor. The first argument can be one of three types: @param first If String, the contents of this comment are set to the argument. If Comment, the argument is duplicated. If Source, the argument is scanned for a comment. @param second If the first argument is a Source, this argument should be nil, not supplied, or a Parent to be set as the parent of this object

Public Instance methods

<=>(other)

Compares this Comment to another; the contents of the comment are used in the comparison.

==( other )

Compares this Comment to another; the contents of the comment are used in the comparison.

clone()
node_type()
write( output, indent=-1, transitive=false, ie_hack=false )

DEPRECATED

See REXML::Formatters

output: | Where to write the string
indent: | An integer. If -1, no indenting will be used; otherwise, the indentation will be this number of spaces, and children will be indented an additional amount.
transitive: | Ignored by this class. The contents of comments are never modified.
ie_hack: | Needed for conformity to the child API, but not used by this class.


Module: REXML::DTD

Module | REXML::DTD
In: | lib/rexml/dtd/entitydecl.rb lib/rexml/dtd/elementdecl.rb lib/rexml/dtd/dtd.rb lib/rexml/dtd/notationdecl.rb lib/rexml/dtd/attlistdecl.rb

Classes and Modules

Class REXML::DTD::AttlistDecl
Class REXML::DTD::ElementDecl
Class REXML::DTD::EntityDecl
Class REXML::DTD::NotationDecl
Class REXML::DTD::Parser


Class: REXML::DTD::AttlistDecl

Class | REXML::DTD::AttlistDecl
In: | lib/rexml/dtd/attlistdecl.rb
Parent: | Child

Constants

START | = | "<!ATTLIST"
START_RE | = | /^\s*#{START}/um
PATTERN_RE | = | /\s*(#{START}.*?>)/um


Class: REXML::DTD::ElementDecl

Class | REXML::DTD::ElementDecl
In: | lib/rexml/dtd/elementdecl.rb
Parent: | Child

Methods

new

Constants

START | = | "<!ELEMENT"
START_RE | = | /^\s*#{START}/um
PATTERN_RE | = | /^\s*(#{START}.*?)>/um
PATTERN_RE | = | /^\s*#{START}\s+((?:[:\w_][-\.\w_]*:)?[-!\*\.\w_]*)(.*?)>/

Public Class methods

new(match)

\">s*((((["']).*?\5)|*)*?)(\/)?>/um, true)


Class: REXML::DTD::EntityDecl

Class | REXML::DTD::EntityDecl
In: | lib/rexml/dtd/entitydecl.rb
Parent: | Child

Methods

new parse_source to_s write

Constants

START | = | "<!ENTITY"
START_RE | = | /^\s*#{START}/um
PUBLIC | = | /^\s*#{START}\s+(?:%\s+)?(\w+)\s+PUBLIC\s+((["']).*?\3)\s+((["']).*?\5)\s*>/um
SYSTEM | = | /^\s*#{START}\s+(?:%\s+)?(\w+)\s+SYSTEM\s+((["']).*?\3)(?:\s+NDATA\s+\w+)?\s*>/um
PLAIN | = | /^\s*#{START}\s+(\w+)\s+((["']).*?\3)\s*>/um
PERCENT | = | /^\s*#{START}\s+%\s+(\w+)\s+((["']).*?\3)\s*>/um

Public Class methods

new(src)

<!ENTITY name SYSTEM "…"> <!ENTITY name "…">

parse_source(source, listener)

Public Instance methods

to_s()
write( output, indent )


Class: REXML::DTD::NotationDecl

Class | REXML::DTD::NotationDecl
In: | lib/rexml/dtd/notationdecl.rb
Parent: | Child

Methods

new parse_source to_s write

Constants

START | = | "<!NOTATION"
START_RE | = | /^\s*#{START}/um
PUBLIC | = | /^\s*#{START}\s+(\w[\w-]*)\s+(PUBLIC)\s+((["']).*?\4)\s*>/um
SYSTEM | = | /^\s*#{START}\s+(\w[\w-]*)\s+(SYSTEM)\s+((["']).*?\4)\s*>/um

Public Class methods

new(src)
parse_source(source, listener)

Public Instance methods

to_s()
write( output, indent )


Class: REXML::DTD::Parser

Class | REXML::DTD::Parser
In: | lib/rexml/dtd/dtd.rb
Parent: | Object

Methods

parse parse_helper

Public Class methods

parse( input )
parse_helper( input )

Takes a String and parses it out


Class: REXML::Declaration

Class | REXML::Declaration
In: | lib/rexml/doctype.rb
Parent: | Child

This is an abstract class. You never use this directly; it serves as a parent class for the specific declarations.

Methods

new to_s write

Public Class methods

new(src)

Public Instance methods

to_s()
write( output, indent )

DEPRECATED

See REXML::Formatters


Class: REXML::DocType

Class | REXML::DocType
In: | lib/rexml/doctype.rb
Parent: | Parent

Represents an XML DOCTYPE declaration; that is, the contents of <!DOCTYPE … >. DOCTYPES can be used to declare the DTD of a document, as well as being used to declare entities used in the document.

Methods

add attribute_of attributes_of clone context entity new node_type notation notations public system write

Included Modules

XMLTokens

Constants

START | = | "<!DOCTYPE"
STOP | = | ">"
SYSTEM | = | "SYSTEM"
PUBLIC | = | "PUBLIC"
DEFAULT_ENTITIES | = | { 'gt'=>EntityConst::GT, 'lt'=>EntityConst::LT, 'quot'=>EntityConst::QUOT, "apos"=>EntityConst::APOS

Attributes

entities | [R] | name is the name of the doctype external_id is the referenced DTD, if given
external_id | [R] | name is the name of the doctype external_id is the referenced DTD, if given
name | [R] | name is the name of the doctype external_id is the referenced DTD, if given
namespaces | [R] | name is the name of the doctype external_id is the referenced DTD, if given

Public Class methods

new( first, parent=nil )

Constructor

  dt = DocType.new( 'foo', '-//I/Hate/External/IDs' )
  # <!DOCTYPE foo '-//I/Hate/External/IDs'>
  dt = DocType.new( doctype_to_clone )
  # Incomplete.  Shallow clone of doctype

Note that the constructor:

 Doctype.new( Source.new( "<!DOCTYPE foo 'bar'>" ) )

is deprecated. Do not use it. It will probably disappear.

Public Instance methods

add(child)
attribute_of(element, attribute)
attributes_of(element)
clone()
context()
entity( name )
node_type()
notation(name)

Retrieves a named notation. Only notations declared in the internal DTD subset can be retrieved.

Method contributed by Henrik Martensson

notations()

This method returns a list of notations that have been declared in the internal DTD subset. Notations in the external DTD subset are not listed.

Method contributed by Henrik Martensson

public()

This method retrieves the public identifier identifying the document‘s DTD.

Method contributed by Henrik Martensson

system()

This method retrieves the system identifier identifying the document‘s DTD

Method contributed by Henrik Martensson

write( output, indent=0, transitive=false, ie_hack=false )
output: | Where to write the string
indent: | An integer. If -1, no indentation will be used; otherwise, the indentation will be this number of spaces, and children will be indented an additional amount.
transitive: | Ignored
ie_hack: | Ignored


Class: REXML::Document

Class | REXML::Document
In: | lib/rexml/document.rb
Parent: | Element

Represents a full XML document, including PIs, a doctype, etc. A Document has a single child that can be accessed by root(). Note that if you want to have an XML declaration written for a document you create, you must add one; REXML documents do not write a default declaration for you. See |DECLARATION| and |write|.

Methods

<< add add_element clone doctype encoding expanded_name name new node_type parse_stream root stand_alone? version write xml_decl

Constants

DECLARATION = XMLDecl.default A convenient default XML declaration. If you want an XML declaration, the easiest way to add one is mydoc << Document::DECLARATION DEPRECATED Use: mydoc << XMLDecl.default

Public Class methods

new( source = nil, context = {} )

Constructor @param source if supplied, must be a Document, String, or IO. Documents have their context and Element attributes cloned. Strings are expected to be valid XML documents. IOs are expected to be sources of valid XML documents. @param context if supplied, contains the context of the document; this should be a Hash.

parse_stream( source, listener )

Public Instance methods

<<( child )

Alias for add

add( child )

We override this, because XMLDecls and DocTypes must go at the start of the document

add_element(arg=nil, arg2=nil)
clone()

Should be obvious

doctype()

@return the DocType child of the document, if one exists, and nil otherwise.

encoding()

@return the XMLDecl encoding of this document as a String. If no XMLDecl has been set, returns the default encoding.

expanded_name()

According to the XML spec, a root node has no expanded name

name()

Alias for expanded_name

node_type()
root()

@return the root Element of the document, or nil if this document has no children.

stand_alone?()

@return the XMLDecl standalone value of this document as a String. If no XMLDecl has been set, returns the default setting.

version()

@return the XMLDecl version of this document as a String. If no XMLDecl has been set, returns the default version.

write( output=$stdout, indent=-1, trans=false, ie_hack=false )

Write the XML tree out, optionally with indent. This writes out the entire XML document, including XML declarations, doctype declarations, and processing instructions (if any are given).

A controversial point is whether Document should always write the XML declaration (<?xml version=‘1.0’?>) whether or not one is given by the user (or source document). REXML does not write one if one was not specified, because it adds unneccessary bandwidth to applications such as XML-RPC.

See also the classes in the rexml/formatters package for the proper way to change the default formatting of XML output

Examples

  Document.new("<a><b/></a>").serialize

  output_string = ""
  tr = Transitive.new( output_string )
  Document.new("<a><b/></a>").serialize( tr )
output: output an object which supports ’<< string’; this is where the
  document will be written.

indent: | An integer. If -1, no indenting will be used; otherwise, the indentation will be twice this number of spaces, and children will be indented an additional amount. For a value of 3, every item will be indented 3 more levels, or 6 more spaces (2 * 3). Defaults to -1
trans: | If transitive is true and indent is >= 0, then the output will be pretty-printed in such a way that the added whitespace does not affect the absolute value of the document — that is, it leaves the value and number of Text nodes in the document unchanged.
ie_hack: | Internet Explorer is the worst piece of crap to have ever been written, with the possible exception of Windows itself. Since IE is unable to parse proper XML, we have to provide a hack to generate XML that IE‘s limited abilities can handle. This hack inserts a space before the /> on empty tags. Defaults to false
xml_decl()

@return the XMLDecl of this document; if no XMLDecl has been set, the default declaration is returned.


Class: REXML::Element

Class | REXML::Element
In: | lib/rexml/element.rb
Parent: | Parent

Represents a tagged XML element. Elements are characterized by having children, attributes, and names, and can themselves be children.

Methods

add_attribute add_attributes add_element add_namespace add_text attribute cdatas clone comments delete_attribute delete_element delete_namespace document each_element each_element_with_attribute each_element_with_text get_elements get_text has_attributes? has_elements? has_text? ignore_whitespace_nodes inspect instructions namespace namespaces new next_element node_type prefixes previous_element raw root root_node text text= texts whitespace write xpath

Included Modules

Namespace

Constants

UNDEFINED = "UNDEFINED";

Attributes

attributes | [R] | Mechanisms for accessing attributes and child elements of this element.
context | [RW] | The context holds information about the processing environment, such as whitespace handling.
elements | [R] | Mechanisms for accessing attributes and child elements of this element.

Public Class methods

new( arg = UNDEFINED, parent=nil, context=nil )

Constructor

arg: | if not supplied, will be set to the default value. If a String, the name of this object will be set to the argument. If an Element, the object will be shallowly cloned; name, attributes, and namespaces will be copied. Children will not be copied.
parent: | if supplied, must be a Parent, and will be used as the parent of this object.
context: | If supplied, must be a hash containing context items. Context items include:
  • :respect_whitespace the value of this is :all or an array of strings being the names of the elements to respect whitespace for. Defaults to :all.
  • :compress_whitespace the value can be :all or an array of strings being the names of the elements to ignore whitespace on. Overrides :respect_whitespace.
  • :ignore_whitespace_nodes the value can be :all or an array of strings being the names of the elements in which to ignore whitespace-only nodes. If this is set, Text nodes which contain only whitespace will not be added to the document tree.
  • :raw can be :all, or an array of strings being the names of the elements to process in raw mode. In raw mode, special characters in text is not converted to or from entities.

Public Instance methods

add_attribute( key, value=nil )

Adds an attribute to this element, overwriting any existing attribute by the same name.

key: | can be either an Attribute or a String. If an Attribute, the attribute is added to the list of Element attributes. If String, the argument is used as the name of the new attribute, and the value parameter must be supplied.
value: | Required if key is a String, and ignored if the first argument is an Attribute. This is a String, and is used as the value of the new Attribute. This should be the unnormalized value of the attribute (without entities).
Returns: | the Attribute added
 e = Element.new 'e'
 e.add_attribute( 'a', 'b' )               #-> <e a='b'/>
 e.add_attribute( 'x:a', 'c' )             #-> <e a='b' x:a='c'/>
 e.add_attribute Attribute.new('b', 'd')   #-> <e a='b' x:a='c' b='d'/>
add_attributes(hash)

Add multiple attributes to this element.

hash: is either a hash, or array of arrays
 el.add_attributes( {"name1"=>"value1", "name2"=>"value2"} )
 el.add_attributes( [ ["name1","value1"], ["name2"=>"value2"] ] )
add_element(element, attrs=nil)

Adds a child to this element, optionally setting attributes in the element.

element: | optional. If Element, the element is added. Otherwise, a new Element is constructed with the argument (see Element.initialize).
attrs: | If supplied, must be a Hash containing String name,value pairs, which will be used to set the attributes of the new Element.
Returns: | the Element that was added
 el = doc.add_element 'my-tag'
 el = doc.add_element 'my-tag', {'attr1'=>'val1', 'attr2'=>'val2'}
 el = Element.new 'my-tag'
 doc.add_element el
add_namespace( prefix, uri=nil )

Adds a namespace to this element.

prefix: | the prefix string, or the namespace URI if uri is not supplied
uri: | the namespace URI. May be nil, in which prefix is used as the URI

Evaluates to: this Element

 a = Element.new("a")
 a.add_namespace("xmlns:foo", "bar" )
 a.add_namespace("foo", "bar")  # shorthand for previous line
 a.add_namespace("twiddle")
 puts a   #-> <a xmlns:foo='bar' xmlns='twiddle'/>
add_text( text )

A helper method to add a Text child. Actual Text instances can be added with regular Parent methods, such as add() and <<()

text: | if a String, a new Text instance is created and added to the parent. If Text, the object is added directly.
Returns: | this Element
 e = Element.new('a')          #-> <e/>
 e.add_text 'foo'              #-> <e>foo</e>
 e.add_text Text.new(' bar')    #-> <e>foo bar</e>

Note that at the end of this example, the branch has 3 nodes; the ‘e’ element and 2 Text node children.

attribute( name, namespace=nil )

Attributes #

cdatas()

Get an array of all CData children. IMMUTABLE

clone()

Creates a shallow copy of self.

  d = Document.new "<a><b/><b/><c><d/></c></a>"
  new_a = d.root.clone
  puts new_a  # => "<a/>"
comments()

Get an array of all Comment children. IMMUTABLE

delete_attribute(key)

Removes an attribute

key: | either an Attribute or a String. In either case, the attribute is found by matching the attribute name to the argument, and then removed. If no attribute is found, no action is taken.
Returns: | the attribute removed, or nil if this Element did not contain a matching attribute
 e = Element.new('E')
 e.add_attribute( 'name', 'Sean' )             #-> <E name='Sean'/>
 r = e.add_attribute( 'sur:name', 'Russell' )  #-> <E name='Sean' sur:name='Russell'/>
 e.delete_attribute( 'name' )                  #-> <E sur:name='Russell'/>
 e.delete_attribute( r )                       #-> <E/>
delete_element(element)

Deletes a child element.

element: | Must be an Element, String, or Integer. If Element, the element is removed. If String, the element is found (via XPath) and removed. <em>This means that any parent can remove any descendant.<em> If Integer, the Element indexed by that number will be removed.
Returns: | the element that was removed.
 doc.delete_element "/a/b/c[@id='4']"
 doc.delete_element doc.elements["//k"]
 doc.delete_element 1
delete_namespace(namespace="xmlns")

Removes a namespace from this node. This only works if the namespace is actually declared in this node. If no argument is passed, deletes the default namespace.

Evaluates to: this element

 doc = Document.new "<a xmlns:foo='bar' xmlns='twiddle'/>"
 doc.root.delete_namespace
 puts doc     # -> <a xmlns:foo='bar'/>
 doc.root.delete_namespace 'foo'
 puts doc     # -> <a/>
document()

Evaluates to the document to which this element belongs, or nil if this element doesn‘t belong to a document.

each_element( xpath=nil ) {|Element| ...}

Synonym for Element.elements.each

each_element_with_attribute( key, value=nil, max=0, name=nil ) {|Element| ...}

Iterates through the child elements, yielding for each Element that has a particular attribute set.

key: | the name of the attribute to search for
value: | the value of the attribute
max: | (optional) causes this method to return after yielding for this number of matching children
name: | (optional) if supplied, this is an XPath that filters the children to check.
 doc = Document.new "<a><b @id='1'/><c @id='2'/><d @id='1'/><e/></a>"
 # Yields b, c, d
 doc.root.each_element_with_attribute( 'id' ) {|e| p e}
 # Yields b, d
 doc.root.each_element_with_attribute( 'id', '1' ) {|e| p e}
 # Yields b
 doc.root.each_element_with_attribute( 'id', '1', 1 ) {|e| p e}
 # Yields d
 doc.root.each_element_with_attribute( 'id', '1', 0, 'd' ) {|e| p e}
each_element_with_text( text=nil, max=0, name=nil ) {|Element| ...}

Iterates through the children, yielding for each Element that has a particular text set.

text: | the text to search for. If nil, or not supplied, will itterate over all Element children that contain at least one Text node.
max: | (optional) causes this method to return after yielding for this number of matching children
name: | (optional) if supplied, this is an XPath that filters the children to check.
 doc = Document.new '<a><b>b</b><c>b</c><d>d</d><e/></a>'
 # Yields b, c, d
 doc.each_element_with_text {|e|p e}
 # Yields b, c
 doc.each_element_with_text('b'){|e|p e}
 # Yields b
 doc.each_element_with_text('b', 1){|e|p e}
 # Yields d
 doc.each_element_with_text(nil, 0, 'd'){|e|p e}
get_elements( xpath )

Synonym for Element.to_a This is a little slower than calling elements.each directly.

xpath: | any XPath by which to search for elements in the tree
Returns: | an array of Elements that match the supplied path
get_text(path = nil)

Returns the first child Text node, if any, or nil otherwise. This method returns the actual Text node, rather than the String content.

 doc = Document.new "<p>some text <b>this is bold!</b> more text</p>"
 # The element 'p' has two text elements, "some text " and " more text".
 doc.root.get_text.value            #-> "some text "
has_attributes?()

Evaluates to true if this element has any attributes set, false otherwise.

has_elements?()

Evaluates to true if this element has at least one child Element

 doc = Document.new "<a><b/><c>Text</c></a>"
 doc.root.has_elements               # -> true
 doc.elements["/a/b"].has_elements   # -> false
 doc.elements["/a/c"].has_elements   # -> false
has_text?()

Evaluates to true if this element has at least one Text child

ignore_whitespace_nodes()
inspect()
instructions()

Get an array of all Instruction children. IMMUTABLE

namespace(prefix=nil)

Evalutas to the URI for a prefix, or the empty string if no such namespace is declared for this element. Evaluates recursively for ancestors. Returns the default namespace, if there is one.

prefix: | the prefix to search for. If not supplied, returns the default namespace if one exists
Returns: | the namespace URI as a String, or nil if no such namespace exists. If the namespace is undefined, returns an empty string
 doc = Document.new("<a xmlns='1' xmlns:y='2'><b/><c xmlns:z='3'/></a>")
 b = doc.elements['//b']
 b.namespace           # -> '1'
 b.namespace("y")      # -> '2'
namespaces()
next_element()

Returns the next sibling that is an element, or nil if there is no Element sibling after this one

 doc = Document.new '<a><b/>text<c/></a>'
 doc.root.elements['b'].next_element          #-> <c/>
 doc.root.elements['c'].next_element          #-> nil
node_type()
prefixes()

Evaluates to an Array containing the prefixes (names) of all defined namespaces at this context node.

 doc = Document.new("<a xmlns:x='1' xmlns:y='2'><b/><c xmlns:z='3'/></a>")
 doc.elements['//b'].prefixes # -> ['x', 'y']
previous_element()

Returns the previous sibling that is an element, or nil if there is no Element sibling prior to this one

 doc = Document.new '<a><b/>text<c/></a>'
 doc.root.elements['c'].previous_element          #-> <b/>
 doc.root.elements['b'].previous_element          #-> nil
raw()

Evaluates to true if raw mode is set for this element. This is the case if the context has :raw set to :all or an array containing the name of this element.

The evaluation is tested against expanded_name, and so is namespace sensitive.

root()
root_node()

Evaluates to the root node of the document that this element belongs to. If this element doesn‘t belong to a document, but does belong to another Element, the parent‘s root will be returned, until the earliest ancestor is found.

Note that this is not the same as the document element. In the following example, <a> is the document element, and the root node is the parent node of the document element. You may ask yourself why the root node is useful: consider the doctype and XML declaration, and any processing instructions before the document element… they are children of the root node, or siblings of the document element. The only time this isn‘t true is when an Element is created that is not part of any Document. In this case, the ancestor that has no parent acts as the root node.

 d = Document.new '<a><b><c/></b></a>'
 a = d[1] ; c = a[1][1]
 d.root_node == d   # TRUE
 a.root_node        # namely, d
 c.root_node        # again, d
text( path = nil )

A convenience method which returns the String value of the first child text element, if one exists, and nil otherwise.

Note that an element may have multiple Text elements, perhaps separated by other children. Be aware that this method only returns the first Text node.

This method returns the value of the first text child node, which ignores the raw setting, so always returns normalized text. See the Text::value documentation.

 doc = Document.new "<p>some text <b>this is bold!</b> more text</p>"
 # The element 'p' has two text elements, "some text " and " more text".
 doc.root.text              #-> "some text "
text=( text )

Sets the first Text child of this object. See text() for a discussion about Text children.

If a Text child already exists, the child is replaced by this content. This means that Text content can be deleted by calling this method with a nil argument. In this case, the next Text child becomes the first Text child. In no case is the order of any siblings disturbed.

text: | If a String, a new Text child is created and added to this Element as the first Text child. If Text, the text is set as the first Child element. If nil, then any existing first Text child is removed.
Returns: | this Element.
 doc = Document.new '<a><b/></a>'
 doc.root.text = 'Sean'      #-> '<a><b/>Sean</a>'
 doc.root.text = 'Elliott'   #-> '<a><b/>Elliott</a>'
 doc.root.add_element 'c'    #-> '<a><b/>Elliott<c/></a>'
 doc.root.text = 'Russell'   #-> '<a><b/>Russell<c/></a>'
 doc.root.text = nil         #-> '<a><b/><c/></a>'
texts()

Get an array of all Text children. IMMUTABLE

whitespace()

Evaluates to true if whitespace is respected for this element. This is the case if:

  1. Neither :respect_whitespace nor :compress_whitespace has any value
  2. The context has :respect_whitespace set to :all or an array containing the name of this element, and :compress_whitespace isn‘t set to :all or an array containing the name of this element.

The evaluation is tested against expanded_name, and so is namespace sensitive.

write(writer=$stdout, indent=-1, transitive=false, ie_hack=false)

DEPRECATED

See REXML::Formatters

Writes out this element, and recursively, all children.

output: output an object which supports ’<< string’; this is where the
  document will be written.

indent: | An integer. If -1, no indenting will be used; otherwise, the indentation will be this number of spaces, and children will be indented an additional amount. Defaults to -1
transitive: | If transitive is true and indent is >= 0, then the output will be pretty-printed in such a way that the added whitespace does not affect the parse tree of the document
ie_hack: | Internet Explorer is the worst piece of crap to have ever been written, with the possible exception of Windows itself. Since IE is unable to parse proper XML, we have to provide a hack to generate XML that IE‘s limited abilities can handle. This hack inserts a space before the /> on empty tags. Defaults to false
 out = ''
 doc.write( out )     #-> doc is written to the string 'out'
 doc.write( $stdout ) #-> doc written to the console
xpath()


Class: REXML::ElementDecl

Class | REXML::ElementDecl
In: | lib/rexml/doctype.rb
Parent: | Declaration

Methods

new

Public Class methods

new( src )


Class: REXML::Elements

Class | REXML::Elements
In: | lib/rexml/element.rb
Parent: | Object

A class which provides filtering of children for Elements, and XPath search support. You are expected to only encounter this class as the element.elements object. Therefore, you are not expected to instantiate this yourself.

Methods

<< [] []= add collect delete delete_all each empty? index inject new size to_a

Included Modules

Enumerable

Public Class methods

new(parent)

Constructor

parent: the parent Element

Public Instance methods

<<(element=nil)

Alias for add

[]( index, name=nil)

Fetches a child element. Filters only Element children, regardless of the XPath match.

index: | the search parameter. This is either an Integer, which will be used to find the index‘th child Element, or an XPath, which will be used to search for the Element. Because of the nature of XPath searches, any element in the connected XML document can be fetched through any other element. The Integer index is 1-based, not 0-based. This means that the first child element is at index 1, not 0, and the +n+th element is at index n, not n-1. This is because XPath indexes element children starting from 1, not 0, and the indexes should be the same.
name: | optional, and only used in the first argument is an Integer. In that case, the index‘th child Element that has the supplied name will be returned. Note again that the indexes start at 1.
Returns: | the first matching Element, or nil if no child matched
 doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>'
 doc.root.elements[1]       #-> <b/>
 doc.root.elements['c']     #-> <c id="1"/>
 doc.root.elements[2,'c']   #-> <c id="2"/>
[]=( index, element )

Sets an element, replacing any previous matching element. If no existing element is found ,the element is added.

index: | Used to find a matching element to replace. See []().
element: | The element to replace the existing element with the previous element
Returns: | nil if no previous element was found.
 doc = Document.new '<a/>'
 doc.root.elements[10] = Element.new('b')    #-> <a><b/></a>
 doc.root.elements[1]                        #-> <b/>
 doc.root.elements[1] = Element.new('c')     #-> <a><c/></a>
 doc.root.elements['c'] = Element.new('d')   #-> <a><d/></a>
add(element=nil)

Adds an element

element: | if supplied, is either an Element, String, or Source (see Element.initialize). If not supplied or nil, a new, default Element will be constructed
Returns: | the added Element
 a = Element.new('a')
 a.elements.add(Element.new('b'))  #-> <a><b/></a>
 a.elements.add('c')               #-> <a><b/><c/></a>
collect( xpath=nil ) {|e| ...}
delete(element)

Deletes a child Element

element: | Either an Element, which is removed directly; an xpath, where the first matching child is removed; or an Integer, where the n‘th Element is removed.
Returns: | the removed child
 doc = Document.new '<a><b/><c/><c id="1"/></a>'
 b = doc.root.elements[1]
 doc.root.elements.delete b           #-> <a><c/><c id="1"/></a>
 doc.elements.delete("a/c[@id='1']")  #-> <a><c/></a>
 doc.root.elements.delete 1           #-> <a/>
delete_all( xpath )

Removes multiple elements. Filters for Element children, regardless of XPath matching.

xpath: | all elements matching this String path are removed.
Returns: | an Array of Elements that have been removed
 doc = Document.new '<a><c/><c/><c/><c/></a>'
 deleted = doc.elements.delete_all 'a/c' #-> [<c/>, <c/>, <c/>, <c/>]
each( xpath=nil) {|e if e.kind_of? Element| ...}

Iterates through all of the child Elements, optionally filtering them by a given XPath

xpath: optional. If supplied, this is a String XPath, and is used to filter the children, so that only matching children are yielded. Note that XPaths are automatically filtered for Elements, so that non-Element children will not be yielded
 doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>'
 doc.root.each {|e|p e}       #-> Yields b, c, d, b, c, d elements
 doc.root.each('b') {|e|p e}  #-> Yields b, b elements
 doc.root.each('child::node()')  {|e|p e}
 #-> Yields <b/>, <c/>, <d/>, <b/>, <c/>, <d/>
 XPath.each(doc.root, 'child::node()', &block)
 #-> Yields <b/>, <c/>, <d/>, sean, <b/>, <c/>, <d/>
empty?()

Returns true if there are no Element children, false otherwise

index(element)

Returns the index of the supplied child (starting at 1), or -1 if the element is not a child

element: an Element child
inject( xpath=nil, initial=nil ) {|initial, e| ...}
size()

Returns the number of Element children of the parent object.

 doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>'
 doc.root.size            #-> 6, 3 element and 3 text nodes
 doc.root.elements.size   #-> 3
to_a( xpath=nil )

Returns an Array of Element children. An XPath may be supplied to filter the children. Only Element children are returned, even if the supplied XPath matches non-Element children.

 doc = Document.new '<a>sean<b/>elliott<c/></a>'
 doc.root.elements.to_a                  #-> [ <b/>, <c/> ]
 doc.root.elements.to_a("child::node()") #-> [ <b/>, <c/> ]
 XPath.match(doc.root, "child::node()")  #-> [ sean, <b/>, elliott, <c/> ]


Module: REXML::Encoding

Module | REXML::Encoding
In: | lib/rexml/encoding.rb lib/rexml/encodings/EUC-JP.rb lib/rexml/encodings/CP-1252.rb lib/rexml/encodings/ISO-8859-1.rb lib/rexml/encodings/UTF-8.rb lib/rexml/encodings/UNILE.rb lib/rexml/encodings/US-ASCII.rb lib/rexml/encodings/ISO-8859-15.rb lib/rexml/encodings/ICONV.rb lib/rexml/encodings/SHIFT-JIS.rb lib/rexml/encodings/UTF-16.rb

Methods

apply check_encoding decode_ascii decode_cp1252 decode_eucjp decode_eucjp decode_iconv decode_sjis decode_sjis decode_unile decode_utf16 decode_utf8 encode_ascii encode_cp1252 encode_eucjp encode_eucjp encode_iconv encode_sjis encode_sjis encode_unile encode_utf16 encode_utf8 encoding= encoding_method from_iso_8859_15 register to_iso_8859_15

Constants

UTF_8 | = | 'UTF-8' | Native, default format is UTF-8, so it is declared here rather than in an encodings/ definition.
UTF_16 | = | 'UTF-16'
UNILE | = | 'UNILE'
EUCTOU8 | = | '-Ewm0'
U8TOEUC | = | '-Wem0'
SJISTOU8 | = | '-Swm0'
U8TOSJIS | = | '-Wsm0'

External Aliases

to_iso_8859_15 | -> | encode
from_iso_8859_15 | -> | decode

Attributes

encoding [R] ID —> Encoding name

Public Class methods

apply(obj, enc)
encoding_method(enc)
register(enc, &block)

Public Instance methods

check_encoding(str)
decode_ascii(str)

Convert to UTF-8

decode_cp1252(str)

Convert to UTF-8

decode_eucjp(str)
decode_eucjp(str)
decode_iconv(str)
decode_sjis(str)
decode_sjis(content)
decode_unile(str)
decode_utf16(str)
decode_utf8(str)
encode_ascii(content)

Convert from UTF-8

encode_cp1252(content)

Convert from UTF-8

encode_eucjp(content)
encode_eucjp(content)
encode_iconv(content)
encode_sjis(content)
encode_sjis(str)
encode_unile(content)
encode_utf16(content)
encode_utf8(content)
encoding=( enc )
from_iso_8859_15(str)

Convert to UTF-8

to_iso_8859_15(content)

Convert from UTF-8


Class: REXML::Entity

Class | REXML::Entity
In: | lib/rexml/entity.rb
Parent: | Child

God, I hate DTDs. I really do. Why this idiot standard still plagues us is beyond me.

Methods

matches? new normalized to_s unnormalized value write

Included Modules

XMLTokens

Constants

PUBIDCHAR | = | "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
SYSTEMLITERAL | = | %Q{((?:"[^"]*")|(?:'[^']*'))}
PUBIDLITERAL | = | %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
EXTERNALID | = | "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
NDATADECL | = | "\\s+NDATA\\s+#{NAME}"
PEREFERENCE | = | "%#{NAME};"
ENTITYVALUE | = | %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
PEDEF | = | "(?:#{ENTITYVALUE}|#{EXTERNALID})"
ENTITYDEF | = | "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
PEDECL | = | "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
GEDECL | = | "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
ENTITYDECL | = | /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
PEREFERENCE_RE | = | /#{PEREFERENCE}/um

Attributes

external | [R]
name | [R]
ndata | [R]
pubid | [R]
ref | [R]

Public Class methods

matches?(string)

Evaluates whether the given string matchs an entity definition, returning true if so, and false otherwise.

new(stream, value=nil, parent=nil, reference=false)

Create a new entity. Simple entities can be constructed by passing a name, value to the constructor; this creates a generic, plain entity reference. For anything more complicated, you have to pass a Source to the constructor with the entity definiton, or use the accessor methods. WARNING: There is no validation of entity state except when the entity is read from a stream. If you start poking around with the accessors, you can easily create a non-conformant Entity. The best thing to do is dump the stupid DTDs and use XMLSchema instead.

 e = Entity.new( 'amp', '&' )

Public Instance methods

normalized()

Returns the value of this entity unprocessed — raw. This is the normalized value; that is, with all %ent; and &ent; entities intact

to_s()

Returns this entity as a string. See write().

unnormalized()

Evaluates to the unnormalized value of this entity; that is, replacing all entities — both %ent; and &ent; entities. This differs from +value()+ in that value only replaces %ent; entities.

value()

Returns the value of this entity. At the moment, only internal entities are processed. If the value contains internal references (IE, %blah;), those are replaced with their values. IE, if the doctype contains:

 <!ENTITY % foo "bar">
 <!ENTITY yada "nanoo %foo; nanoo>

then:

 doctype.entity('yada').value   #-> "nanoo bar nanoo"
write(out, indent=-1)

Write out a fully formed, correct entity definition (assuming the Entity object itself is valid.)

out: | An object implementing <TT>&lt;&lt;<TT> to which the entity will be output
indent: | DEPRECATED and ignored


Module: REXML::EntityConst

Module | REXML::EntityConst
In: | lib/rexml/entity.rb

This is a set of entity constants — the ones defined in the XML specification. These are gt, lt, amp, quot and apos.

Constants

GT | = | Entity.new( 'gt', '>' ) | +>+
LT | = | Entity.new( 'lt', '<' ) | +<+
AMP | = | Entity.new( 'amp', '&' ) | +&+
QUOT | = | Entity.new( 'quot', '"' ) | +"+
APOS | = | Entity.new( 'apos', "'" ) | +’+


Class: REXML::ExternalEntity

Class | REXML::ExternalEntity
In: | lib/rexml/doctype.rb
Parent: | Child

Methods

new to_s write

Public Class methods

new( src )

Public Instance methods

to_s()
write( output, indent )


Module: REXML::Formatters

Module | REXML::Formatters
In: | lib/rexml/formatters/default.rb lib/rexml/formatters/pretty.rb lib/rexml/formatters/transitive.rb

Classes and Modules

Class REXML::Formatters::Default
Class REXML::Formatters::Pretty
Class REXML::Formatters::Transitive


Class: REXML::Formatters::Default

Class | REXML::Formatters::Default
In: | lib/rexml/formatters/default.rb
Parent: | Object

Methods

new write write_cdata write_comment write_document write_element write_instruction write_text

Public Class methods

new( ie_hack=false )

Prints out the XML document with no formatting — except if id_hack is set.

ie_hack: If set to true, then inserts whitespace before the close of an empty tag, so that IE‘s bad XML parser doesn‘t choke.

Public Instance methods

write( node, output )

Writes the node to some output.

node: | The node to write
output: | A class implementing &lt;&lt;. Pass in an Output object to change the output encoding.

Protected Instance methods

write_cdata( node, output )
write_comment( node, output )
write_document( node, output )
write_element( node, output )
write_instruction( node, output )
write_text( node, output )


Class: REXML::Formatters::Pretty

Class | REXML::Formatters::Pretty
In: | lib/rexml/formatters/pretty.rb
Parent: | Default

Pretty-prints an XML document. This destroys whitespace in text nodes and will insert carriage returns and indentations.

TODO: Add an option to print attributes on new lines

Methods

new write_cdata write_comment write_document write_element write_text

Attributes

compact | [RW] | If compact is set to true, then the formatter will attempt to use as little space as possible
width | [RW] | The width of a page. Used for formatting text

Public Class methods

new( indentation=2, ie_hack=false )

Create a new pretty printer.

output: | An object implementing ’<<(String)’, to which the output will be written.
indentation: | An integer greater than 0. The indentation of each level will be this number of spaces. If this is < 1, the behavior of this object is undefined. Defaults to 2.
ie_hack: | If true, the printer will insert whitespace before closing empty tags, thereby allowing Internet Explorer‘s feeble XML parser to function. Defaults to false.

Protected Instance methods

write_cdata( node, output)
write_comment( node, output)
write_document( node, output )
write_element(node, output)
write_text( node, output )


Class: REXML::Formatters::Transitive

Class | REXML::Formatters::Transitive
In: | lib/rexml/formatters/transitive.rb
Parent: | Default

The Transitive formatter writes an XML document that parses to an identical document as the source document. This means that no extra whitespace nodes are inserted, and whitespace within text nodes is preserved. Within these constraints, the document is pretty-printed, with whitespace inserted into the metadata to introduce formatting.

Note that this is only useful if the original XML is not already formatted. Since this formatter does not alter whitespace nodes, the results of formatting already formatted XML will be odd.

Methods

new write_element write_text

Public Class methods

new( indentation=2 )

Protected Instance methods

write_element( node, output )
write_text( node, output )


Module: REXML::Functions

Module | REXML::Functions
In: | lib/rexml/functions.rb

If you add a method, keep in mind two things: (1) the first argument will always be a list of nodes from which to filter. In the case of context methods (such as position), the function should return an array with a value for each child in the array. (2) all method calls from XML will have "-" replaced with "_". Therefore, in XML, "local-name()" is identical (and actually becomes) "local_name()"

Methods

boolean ceiling compare_language concat contains context= count false floor get_namespace id lang last local_name method_missing name namespace_context namespace_context= namespace_uri normalize_space not number position processing_instruction round starts_with string string_length string_value substring substring_after substring_before sum text translate true variables variables=

Public Class methods

boolean( object=nil )

UNTESTED

ceiling( number )
compare_language(lang1, lang2)
concat( *objects )

UNTESTED

contains( string, test )

Fixed by Mike Stok

context=(value)
count( node_set )
false( )

UNTESTED

floor( number )
get_namespace( node_set = nil ) {|@@context[:node] if defined? @@context[:node].namespace| ...}

Helper method.

id( object )

Since REXML is non-validating, this method is not implemented as it requires a DTD

lang( language )

UNTESTED

last( )
local_name( node_set=nil )

UNTESTED

method_missing( id )
name( node_set=nil )
namespace_context()
namespace_context=(x)
namespace_uri( node_set=nil )
normalize_space( string=nil )

UNTESTED

not( object )

UNTESTED

number( object=nil )

a string that consists of optional whitespace followed by an optional minus sign followed by a Number followed by whitespace is converted to the IEEE 754 number that is nearest (according to the IEEE 754 round-to-nearest rule) to the mathematical value represented by the string; any other string is converted to NaN

boolean true is converted to 1; boolean false is converted to 0

a node-set is first converted to a string as if by a call to the string function and then converted in the same way as a string argument

an object of a type other than the four basic types is converted to a number in a way that is dependent on that type

position( )
processing_instruction( node )
round( number )
starts_with( string, test )

Fixed by Mike Stok

string( object=nil )

A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

A number is converted to a string as follows

NaN is converted to the string NaN

positive zero is converted to the string 0

negative zero is converted to the string 0

positive infinity is converted to the string Infinity

negative infinity is converted to the string -Infinity

if the number is an integer, the number is represented in decimal form as a Number with no decimal point and no leading zeros, preceded by a minus sign (-) if the number is negative

otherwise, the number is represented in decimal form as a Number including a decimal point with at least one digit before the decimal point and at least one digit after the decimal point, preceded by a minus sign (-) if the number is negative; there must be no leading zeros before the decimal point apart possibly from the one required digit immediately before the decimal point; beyond the one required digit after the decimal point there must be as many, but only as many, more digits as are needed to uniquely distinguish the number from all other IEEE 754 numeric values.

The boolean false value is converted to the string false. The boolean true value is converted to the string true.

An object of a type other than the four basic types is converted to a string in a way that is dependent on that type.

string_length( string )

UNTESTED

string_value( o )
substring( string, start, length=nil )

Take equal portions of Mike Stok and Sean Russell; mix vigorously, and pour into a tall, chilled glass. Serves 10,000.

substring_after( string, test )

Kouhei fixed this too

substring_before( string, test )

Kouhei fixed this

sum( nodes )
text( )
translate( string, tr1, tr2 )

This is entirely Mike Stok‘s beast

true( )

UNTESTED

variables()
variables=(x)


Class: REXML::IOSource

Class | REXML::IOSource
In: | lib/rexml/source.rb
Parent: | Source

A Source that wraps an IO. See the Source class for method documentation

Methods

consume current_line empty? match new position read scan

Public Class methods

new(arg, block_size=500, encoding=nil)

block_size has been deprecated

Public Instance methods

consume( pattern )
current_line()

@return the current line in the source

empty?()
match( pattern, cons=false )
position()
read()
scan(pattern, cons=false)


Class: REXML::Instruction

Class | REXML::Instruction
In: | lib/rexml/instruction.rb
Parent: | Child

Represents an XML Instruction; IE, <? … ?> TODO: Add parent arg (3rd arg) to constructor

Methods

== clone inspect new node_type write

Constants

START | = | '<\?'
STOP | = | '\?>'

Attributes

content | [RW] | target is the "name" of the Instruction; IE, the "tag" in <?tag …?> content is everything else.
target | [RW] | target is the "name" of the Instruction; IE, the "tag" in <?tag …?> content is everything else.

Public Class methods

new(target, content=nil)

Constructs a new Instruction @param target can be one of a number of things. If String, then the target of this instruction is set to this. If an Instruction, then the Instruction is shallowly cloned (target and content are copied). If a Source, then the source is scanned and parsed for an Instruction declaration. @param content Must be either a String, or a Parent. Can only be a Parent if the target argument is a Source. Otherwise, this String is set as the content of this instruction.

Public Instance methods

==( other )

@return true if other is an Instruction, and the content and target of the other matches the target and content of this object.

clone()
inspect()
node_type()
write(writer, indent=-1, transitive=false, ie_hack=false)

DEPRECATED

See the rexml/formatters package


Module: REXML::Light

Module | REXML::Light
In: | lib/rexml/light/node.rb

Classes and Modules

Class REXML::Light::Node


Class: REXML::Light::Node

Class | REXML::Light::Node
In: | lib/rexml/light/node.rb
Parent: | Object

Represents a tagged XML element. Elements are characterized by having children, attributes, and names, and can themselves be children.

Methods

<< =~ [] []= children each has_name? local_name local_name= name name= namespace namespace= new node_type parent parent= prefix root size text= to_s

Constants

NAMESPLIT | = | /^(?:(#{XMLTokens::NCNAME_STR}):)?(#{XMLTokens::NCNAME_STR})/u
PARENTS | = | [ :element, :document, :doctype ]

Public Class methods

new(node=nil)

Create a new element.

Public Instance methods

<<(element)

Append a child to this element, optionally under a provided namespace. The namespace argument is ignored if the element argument is an Element object. Otherwise, the element argument is a string, the namespace (if provided) is the namespace the element is created in.

=~( path )
[]( reference, ns=nil )
[]=( reference, ns, value=nil )

Doesn‘t handle namespaces yet

children()
each( ) {|at(x+4 )| ...}
has_name?( name, namespace = '' )
local_name()
local_name=( name_str )
name()
name=( name_str, ns=nil )
namespace( prefix=prefix() )
namespace=( namespace )
node_type()
parent()
parent=( node )
prefix( namespace=nil )
root()
size()
text=( foo )
to_s()


Module: REXML::Namespace

Module | REXML::Namespace
In: | lib/rexml/namespace.rb

Adds named attributes to an object.

Methods

fully_expanded_name has_name? name=

Included Modules

XMLTokens

Constants

NAMESPLIT = /^(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})/u

External Aliases

name -> local_name

Attributes

expanded_name | [R] | The name of the object, valid if set
name | [R] | The name of the object, valid if set
prefix | [RW] | The expanded name of the object, valid if name is set

Public Instance methods

fully_expanded_name()

Fully expand the name, even if the prefix wasn‘t specified in the source file.

has_name?( other, ns=nil )

Compares names optionally WITH namespaces

name=( name )

Sets the name and the expanded name


Module: REXML::Node

Module | REXML::Node
In: | lib/rexml/node.rb

Represents a node in the tree. Nodes are never encountered except as superclasses of other objects. Nodes have siblings.

Methods

each_recursive find_first_recursive indent index_in_parent next_sibling_node parent? previous_sibling_node to_s

Public Instance methods

each_recursive() {|node| ...}

Visit all subnodes of self recursively

find_first_recursive() {|node| ...}

Find (and return) first subnode (recursively) for which the block evaluates to true. Returns nil if none was found.

indent(to, ind)
index_in_parent()

Returns the position that self holds in its parent‘s array, indexed from 1.

next_sibling_node()

@return the next sibling (nil if unset)

parent?()
previous_sibling_node()

@return the previous sibling (nil if unset)

to_s(indent=nil)
indent: DEPRECATED This parameter is now ignored. See the formatters in the REXML::Formatters package for changing the output style.


Class: REXML::NotationDecl

Class | REXML::NotationDecl
In: | lib/rexml/doctype.rb
Parent: | Child

Methods

name new to_s write

Attributes

public | [RW]
system | [RW]

Public Class methods

new(name, middle, pub, sys)

Public Instance methods

name()

This method retrieves the name of the notation.

Method contributed by Henrik Martensson

to_s()
write( output, indent=-1 )


Class: REXML::Output

Class | REXML::Output
In: | lib/rexml/output.rb
Parent: | Object

Methods

<< new to_s

Included Modules

Encoding

Attributes

encoding [R]

Public Class methods

new(real_IO, encd="iso-8859-1")

Public Instance methods

<<( content )
to_s()


Class: REXML::Parent

Class | REXML::Parent
In: | lib/rexml/parent.rb
Parent: | Child

A parent has children, and has methods for accessing them. The Parent class is never encountered except as the superclass for some other object.

Methods

<< [] []= add children deep_clone delete delete_at delete_if each each_child each_index index insert_after insert_before length new parent? push replace_child size to_a unshift

Included Modules

Enumerable

Public Class methods

new(parent=nil)

Constructor @param parent if supplied, will be set as the parent of this object

Public Instance methods

<<( object )

Alias for push

[]( index )

Fetches a child at a given index @param index the Integer index of the child to fetch

[]=( *args )

Set an index entry. See Array.[]= @param index the index of the element to set @param opt either the object to set, or an Integer length @param child if opt is an Integer, this is the child to set @return the parent (self)

add( object )
children()

Alias for to_a

deep_clone()

Deeply clones this object. This creates a complete duplicate of this Parent, including all descendants.

delete( object )
delete_at( index )
delete_if( &block )
each(&block)
each_child(&block)

Alias for each

each_index( &block )
index( child )

Fetches the index of a given child @param child the child to get the index of @return the index of the child, or nil if the object is not a child of this parent.

insert_after( child1, child2 )

Inserts an child after another child @param child1 this is either an xpath or an Element. If an Element, child2 will be inserted after child1 in the child list of the parent. If an xpath, child2 will be inserted after the first child to match the xpath. @param child2 the child to insert @return the parent (self)

insert_before( child1, child2 )

Inserts an child before another child @param child1 this is either an xpath or an Element. If an Element, child2 will be inserted before child1 in the child list of the parent. If an xpath, child2 will be inserted before the first child to match the xpath. @param child2 the child to insert @return the parent (self)

length()

Alias for size

parent?()
push( object )

Alias for add

replace_child( to_replace, replacement )

Replaces one child with another, making sure the nodelist is correct @param to_replace the child to replace (must be a Child) @param replacement the child to insert into the nodelist (must be a Child)

size()

@return the number of children of this parent

to_a()
unshift( object )


Class: REXML::ParseException

Class | REXML::ParseException
In: | lib/rexml/parseexception.rb
Parent: | RuntimeError

Methods

context line new position to_s

Attributes

continued_exception | [RW]
parser | [RW]
source | [RW]

Public Class methods

new( message, source=nil, parser=nil, exception=nil )

Public Instance methods

context()
line()
position()
to_s()


Module: REXML::Parsers

Module | REXML::Parsers
In: | lib/rexml/parsers/pullparser.rb lib/rexml/parsers/streamparser.rb lib/rexml/parsers/sax2parser.rb lib/rexml/parsers/xpathparser.rb lib/rexml/parsers/treeparser.rb lib/rexml/parsers/lightparser.rb lib/rexml/parsers/baseparser.rb lib/rexml/parsers/ultralightparser.rb

Classes and Modules

Class REXML::Parsers::BaseParser
Class REXML::Parsers::LightParser
Class REXML::Parsers::PullEvent
Class REXML::Parsers::PullParser
Class REXML::Parsers::SAX2Parser
Class REXML::Parsers::StreamParser
Class REXML::Parsers::TreeParser
Class REXML::Parsers::UltraLightParser
Class REXML::Parsers::XPathParser


Class: REXML::Parsers::BaseParser

Class | REXML::Parsers::BaseParser
In: | lib/rexml/parsers/baseparser.rb
Parent: | Object

Using the Pull Parser

This API is experimental, and subject to change.

 parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
 while parser.has_next?
   res = parser.next
   puts res[1]['att'] if res.start_tag? and res[0] == 'b'
 end

See the PullEvent class for information on the content of the results. The data is identical to the arguments passed for the various events to the StreamListener API.

Notice that:

 parser = PullParser.new( "<a>BAD DOCUMENT" )
 while parser.has_next?
   res = parser.next
   raise res[1] if res.error?
 end

Nat Price gave me some good ideas for the API.

Methods

add_listener empty? entity has_next? new normalize peek position pull stream= unnormalize unshift

Constants

NCNAME_STR | = | '[\w:][\-\w\d.]*'
NAME_STR | = | "(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})"
UNAME_STR | = | "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
NAMECHAR | = | '[\-\w\d\.:]'
NAME | = | "([\\w:]#{NAMECHAR}*)"
NMTOKEN | = | "(?:#{NAMECHAR})+"
NMTOKENS | = | "#{NMTOKEN}(\\s+#{NMTOKEN})*"
REFERENCE | = | "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"
REFERENCE_RE | = | /#{REFERENCE}/
DOCTYPE_START | = | /\A\s*<!DOCTYPE\s/um
DOCTYPE_PATTERN | = | /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
ATTRIBUTE_PATTERN | = | /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\4/um
COMMENT_START | = | /\A<!--/u
COMMENT_PATTERN | = | /<!--(.*?)-->/um
CDATA_START | = | /\A<!\[CDATA\[/u
CDATA_END | = | /^\s*\]\s*>/um
CDATA_PATTERN | = | /<!\[CDATA\[(.*?)\]\]>/um
XMLDECL_START | = | /\A<\?xml\s/u;
XMLDECL_PATTERN | = | /<\?xml\s+(.*?)\?>/um
INSTRUCTION_START | = | /\A<\?/u
INSTRUCTION_PATTERN | = | /<\?(.*?)(\s+.*?)?\?>/um
TAG_MATCH | = | /^<((?>#{NAME_STR}))\s*((?>\s+#{UNAME_STR}\s*=\s*(["']).*?\5)*)\s*(\/)?>/um
CLOSE_MATCH | = | /^\s*<\/(#{NAME_STR})\s*>/um
VERSION | = | /\bversion\s*=\s*["'](.*?)['"]/um
ENCODING | = | /\bencoding\s*=\s*["'](.*?)['"]/um
STANDALONE | = | /\bstandalone\s*=\s["'](.*?)['"]/um
ENTITY_START | = | /^\s*<!ENTITY/
IDENTITY | = | /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'](.*?)['"])?(\s+['"](.*?)["'])?/u
ELEMENTDECL_START | = | /^\s*<!ELEMENT/um
ELEMENTDECL_PATTERN | = | /^\s*(<!ELEMENT.*?)>/um
SYSTEMENTITY | = | /^\s*(%.*?;)\s*$/um
ENUMERATION | = | "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
NOTATIONTYPE | = | "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
ENUMERATEDTYPE | = | "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
ATTTYPE | = | "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
ATTVALUE | = | "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
DEFAULTDECL | = | "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
ATTDEF | = | "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
ATTDEF_RE | = | /#{ATTDEF}/
ATTLISTDECL_START | = | /^\s*<!ATTLIST/um
ATTLISTDECL_PATTERN | = | /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um
NOTATIONDECL_START | = | /^\s*<!NOTATION/um
PUBLIC | = | /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+(["'])(.*?)\3(?:\s+(["'])(.*?)\5)?\s*>/um
SYSTEM | = | /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+(["'])(.*?)\3\s*>/um
TEXT_PATTERN | = | /\A([^<]*)/um
PUBIDCHAR | = | "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#" | Entity constants
SYSTEMLITERAL | = | %Q{((?:"[^"]*")|(?:'[^']*'))}
PUBIDLITERAL | = | %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
EXTERNALID | = | "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
NDATADECL | = | "\\s+NDATA\\s+#{NAME}"
PEREFERENCE | = | "%#{NAME};"
ENTITYVALUE | = | %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
PEDEF | = | "(?:#{ENTITYVALUE}|#{EXTERNALID})"
ENTITYDEF | = | "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
PEDECL | = | "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
GEDECL | = | "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
ENTITYDECL | = | /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
EREFERENCE | = | /&(?!#{NAME};)/
DEFAULT_ENTITIES | = | { 'gt' => [/&gt;/, '&gt;', '>', />/], 'lt' => [/&lt;/, '&lt;', '<', /</], 'quot' => [/&quot;/, '&quot;', '"', /"/], "apos" => [/&apos;/, "&apos;", "'", /'/]
MISSING_ATTRIBUTE_QUOTES | = | /^<#{NAME_STR}\s+#{NAME_STR}\s*=\s*[^"']/um | These are patterns to identify common markup errors, to make the error messages more informative.

Attributes

source [R]

Public Class methods

new( source )

Public Instance methods

add_listener( listener )
empty?()

Returns true if there are no more events

entity( reference, entities )
has_next?()

Returns true if there are more events. Synonymous with !empty?

normalize( input, entities=nil, entity_filter=nil )

Escapes all possible entities

peek(depth=0)

Peek at the depth event in the stack. The first element on the stack is at depth 0. If depth is -1, will parse to the end of the input stream and return the last event, which is always :end_document. Be aware that this causes the stream to be parsed up to the depth event, so you can effectively pre-parse the entire document (pull the entire thing into memory) using this method.

position()
pull()

Returns the next event. This is a PullEvent object.

stream=( source )
unnormalize( string, entities=nil, filter=nil )

Unescapes all possible entities

unshift(token)

Push an event back on the head of the stream. This method has (theoretically) infinite depth.


Class: REXML::Parsers::LightParser

Class | REXML::Parsers::LightParser
In: | lib/rexml/parsers/lightparser.rb
Parent: | Object

Methods

add_listener new parse rewind

Public Class methods

new(stream)

Public Instance methods

add_listener( listener )
parse()
rewind()


Class: REXML::Parsers::PullEvent

Class | REXML::Parsers::PullEvent
In: | lib/rexml/parsers/pullparser.rb
Parent: | Object

A parsing event. The contents of the event are accessed as an +Array?, and the type is given either by the …? methods, or by accessing the type accessor. The contents of this object vary from event to event, but are identical to the arguments passed to +StreamListener+s for each event.

Methods

[] attlistdecl? cdata? comment? doctype? elementdecl? end_element? entity? entitydecl? error? event_type inspect instruction? new notationdecl? start_element? text? xmldecl?

Public Class methods

new(arg)

The type of this event. Will be one of :tag_start, :tag_end, :text, :processing_instruction, :comment, :doctype, :attlistdecl, :entitydecl, :notationdecl, :entity, :cdata, :xmldecl, or :error.

Public Instance methods

[]( start, endd=nil)
attlistdecl?()

Content: [ String text ]

cdata?()

Content: [ String text ]

comment?()

Content: [ String text ]

doctype?()

Content: [ String name, String pub_sys, String long_name, String uri ]

elementdecl?()

Content: [ String text ]

end_element?()

Content: [ String tag_name ]

entity?()

Content: [ String text ]

entitydecl?()

Due to the wonders of DTDs, an entity declaration can be just about anything. There‘s no way to normalize it; you‘ll have to interpret the content yourself. However, the following is true:

  • If the entity declaration is an internal entity: [ String name, String value ]

Content: [ String text ]

error?()
event_type()
inspect()
instruction?()

Content: [ String text ]

notationdecl?()

Content: [ String text ]

start_element?()

Content: [ String tag_name, Hash attributes ]

text?()

Content: [ String raw_text, String unnormalized_text ]

xmldecl?()

Content: [ String version, String encoding, String standalone ]


Class: REXML::Parsers::PullParser

Class | REXML::Parsers::PullParser
In: | lib/rexml/parsers/pullparser.rb
Parent: | Object

Using the Pull Parser

This API is experimental, and subject to change.

 parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
 while parser.has_next?
   res = parser.next
   puts res[1]['att'] if res.start_tag? and res[0] == 'b'
 end

See the PullEvent class for information on the content of the results. The data is identical to the arguments passed for the various events to the StreamListener API.

Notice that:

 parser = PullParser.new( "<a>BAD DOCUMENT" )
 while parser.has_next?
   res = parser.next
   raise res[1] if res.error?
 end

Nat Price gave me some good ideas for the API.

Methods

add_listener each new peek pull unshift

Included Modules

XMLTokens

Public Class methods

new(stream)

Public Instance methods

add_listener( listener )
each() {|self.pull| ...}
peek(depth=0)
pull()
unshift(token)


Class: REXML::Parsers::SAX2Parser

Class | REXML::Parsers::SAX2Parser
In: | lib/rexml/parsers/sax2parser.rb
Parent: | Object

SAX2Parser

Methods

add_listener deafen listen new parse source

Public Class methods

new(source)

Public Instance methods

add_listener( listener )
deafen( listener=nil, &blok )
listen( *args, &blok )

Listen arguments:

Symbol, Array, Block

   Listen to Symbol events on Array elements

Symbol, Block

  Listen to Symbol events

Array, Listener

   Listen to all events on Array elements

Array, Block

   Listen to :start_element events on Array elements

Listener

   Listen to All events

Symbol can be one of: :start_element, :end_element, :start_prefix_mapping, :end_prefix_mapping, :characters, :processing_instruction, :doctype, :attlistdecl, :elementdecl, :entitydecl, :notationdecl, :cdata, :xmldecl, :comment

There is an additional symbol that can be listened for: :progress. This will be called for every event generated, passing in the current stream position.

Array contains regular expressions or strings which will be matched against fully qualified element names.

Listener must implement the methods in SAX2Listener

Block will be passed the same arguments as a SAX2Listener method would be, where the method name is the same as the matched Symbol. See the SAX2Listener for more information.

parse()
source()


Class: REXML::Parsers::StreamParser

Class | REXML::Parsers::StreamParser
In: | lib/rexml/parsers/streamparser.rb
Parent: | Object

Methods

add_listener new parse

Public Class methods

new(source, listener)

Public Instance methods

add_listener( listener )
parse()


Class: REXML::Parsers::TreeParser

Class | REXML::Parsers::TreeParser
In: | lib/rexml/parsers/treeparser.rb
Parent: | Object

Methods

add_listener new parse

Public Class methods

new( source, build_context = Document.new )

Public Instance methods

add_listener( listener )
parse()


Class: REXML::Parsers::UltraLightParser

Class | REXML::Parsers::UltraLightParser
In: | lib/rexml/parsers/ultralightparser.rb
Parent: | Object

Methods

add_listener new parse rewind

Public Class methods

new(stream)

Public Instance methods

add_listener( listener )
parse()
rewind()


Class: REXML::Parsers::XPathParser

Class | REXML::Parsers::XPathParser
In: | lib/rexml/parsers/xpathparser.rb
Parent: | Object

You don‘t want to use this class. Really. Use XPath, which is a wrapper for this class. Believe me. You don‘t want to poke around in here. There is strange, dark magic at work in this code. Beware. Go back! Go back while you still can!

Methods

abbreviate expand namespaces= parse predicate predicate_to_string

Included Modules

XMLTokens

Constants

LITERAL = /^'([^']*)'|^"([^"]*)"/u
AXIS = /^(ancestor|ancestor-or-self|attribute|child|descendant|descendant-or-self|following|following-sibling|namespace|parent|preceding|preceding-sibling|self)::/ RelativeLocationPath
  |                                                    Step
    | (AXIS_NAME '::' | '@' | '')                     AxisSpecifier
      NodeTest
        Predicate
    | '.' | '..'                                      AbbreviatedStep
  |  RelativeLocationPath '/' Step
  | RelativeLocationPath '//' Step
NCNAMETEST = /^(#{NCNAME_STR}):\*/u
 Returns a 1-1 map of the nodeset
 The contents of the resulting array are either:
   true/false, if a positive match
   String, if a name match
NodeTest
  | ('*' | NCNAME ':' '*' | QNAME)                NameTest
  | NODE_TYPE '(' ')'                              NodeType
  | PI '(' LITERAL ')'                            PI
    | '[' expr ']'                                Predicate
QNAME = Namespace::NAMESPLIT
NODE_TYPE = /^(comment|text|node)\(\s*\)/m
PI = /^processing-instruction\(/
VARIABLE_REFERENCE = /^\$(#{NAME_STR})/u | VARIABLE_REFERENCE | ’(’ expr ’)’ | LITERAL | NUMBER | FunctionCall
NUMBER = /^(\d*\.?\d+)/
NT = /^comment|text|processing-instruction|node$/

Public Instance methods

abbreviate( path )
expand( path )
namespaces=( namespaces )
parse(path)
predicate(path)
predicate_to_string( path ) {|path| ...}


Class: REXML::QuickPath

Class | REXML::QuickPath
In: | lib/rexml/quickpath.rb
Parent: | Object

Methods

attribute axe each filter first function match method_missing name parse_args predicate

Included Modules

Functions XMLTokens

Constants

EMPTY_HASH = {}

Public Class methods

attribute( name )
axe( elements, axe_name, rest )
each(element, path, namespaces=EMPTY_HASH, &block)
filter(elements, path)

Given an array of nodes it filters the array based on the path. The result is that when this method returns, the array will contain elements which match the path

first(element, path, namespaces=EMPTY_HASH)
function( elements, fname, rest )
match(element, path, namespaces=EMPTY_HASH)
method_missing( id, *args )
name()
parse_args( element, string )
predicate( elements, path )

A predicate filters a node-set with respect to an axis to produce a new node-set. For each node in the node-set to be filtered, the PredicateExpr is evaluated with that node as the context node, with the number of nodes in the node-set as the context size, and with the proximity position of the node in the node-set with respect to the axis as the context position; if PredicateExpr evaluates to true for that node, the node is included in the new node-set; otherwise, it is not included.

A PredicateExpr is evaluated by evaluating the Expr and converting the result to a boolean. If the result is a number, the result will be converted to true if the number is equal to the context position and will be converted to false otherwise; if the result is not a number, then the result will be converted as if by a call to the boolean function. Thus a location path para[3] is equivalent to para[position()=3].


Module: REXML::SAX2Listener

Module | REXML::SAX2Listener
In: | lib/rexml/sax2listener.rb

A template for stream parser listeners. Note that the declarations (attlistdecl, elementdecl, etc) are trivially processed; REXML doesn‘t yet handle doctype entity declarations, so you have to parse them out yourself.

Missing methods from SAX2

 ignorable_whitespace

Methods extending SAX2

WARNING These methods are certainly going to change, until DTDs are fully supported. Be aware of this.

 start_document
 end_document
 doctype
 elementdecl
 attlistdecl
 entitydecl
 notationdecl
 cdata
 xmldecl
 comment

Methods

attlistdecl cdata characters comment doctype elementdecl end_document end_element end_prefix_mapping entitydecl notationdecl processing_instruction progress start_document start_element start_prefix_mapping xmldecl

Public Instance methods

attlistdecl(element, pairs, contents)

If a doctype includes an ATTLIST declaration, it will cause this method to be called. The content is the declaration itself, unparsed. EG, <!ATTLIST el attr CDATA REQUIRED> will come to this method as "el attr CDATA REQUIRED". This is the same for all of the .*decl methods.

cdata(content)

Called when <![CDATA[ … ]]> is encountered in a document. @p content "…"

characters(text)
comment(comment)

Called when a comment is encountered. @p comment The content of the comment

doctype(name, pub_sys, long_name, uri)

Handles a doctype declaration. Any attributes of the doctype which are not supplied will be nil. # EG, <!DOCTYPE me PUBLIC "foo" "bar"> @p name the name of the doctype; EG, "me" @p pub_sys "PUBLIC", "SYSTEM", or nil. EG, "PUBLIC" @p long_name the supplied long name, or nil. EG, "foo" @p uri the uri of the doctype, or nil. EG, "bar"

elementdecl(content)

<!ELEMENT …>

end_document()
end_element(uri, localname, qname)
end_prefix_mapping(prefix)
entitydecl(name, decl)

<!ENTITY …> The argument passed to this method is an array of the entity declaration. It can be in a number of formats, but in general it returns (example, result):

 <!ENTITY % YN '"Yes"'>
 ["%", "YN", "'\"Yes\"'", "\""]
 <!ENTITY % YN 'Yes'>
 ["%", "YN", "'Yes'", "s"]
 <!ENTITY WhatHeSaid "He said %YN;">
 ["WhatHeSaid", "\"He said %YN;\"", "YN"]
 <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">
 ["open-hatch", "SYSTEM", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
 <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml">
 ["open-hatch", "PUBLIC", "\"-//Textuality//TEXT Standard open-hatch boilerplate//EN\"", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
 <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif>
 ["hatch-pic", "SYSTEM", "\"../grafix/OpenHatch.gif\"", "\n\t\t\t\t\t\t\tNDATA gif", "gif"]
notationdecl(content)

<!NOTATION …>

processing_instruction(target, data)
progress(position)
start_document()
start_element(uri, localname, qname, attributes)
start_prefix_mapping(prefix, uri)
xmldecl(version, encoding, standalone)

Called when an XML PI is encountered in the document. EG: <?xml version="1.0" encoding="utf"?> @p version the version attribute value. EG, "1.0" @p encoding the encoding attribute value, or nil. EG, "utf" @p standalone the standalone attribute value, or nil. EG, nil @p spaced the declaration is followed by a line break


Class: REXML::Source

Class | REXML::Source
In: | lib/rexml/source.rb
Parent: | Object

A Source can be searched for patterns, and wraps buffers and other objects and provides consumption of text

Methods

consume current_line empty? encoding= match match_to match_to_consume new position read scan

Included Modules

Encoding

Attributes

buffer | [R] | The current buffer (what we‘re going to read next)
encoding | [R] |
line | [R] | The line number of the last consumed text

Public Class methods

new(arg, encoding=nil)

Constructor @param arg must be a String, and should be a valid XML document @param encoding if non-null, sets the encoding of the source to this value, overriding all encoding detection

Public Instance methods

consume( pattern )
current_line()

@return the current line in the source

empty?()

@return true if the Source is exhausted

encoding=(enc)

Inherited from Encoding Overridden to support optimized en/decoding

match(pattern, cons=false)
match_to( char, pattern )
match_to_consume( char, pattern )
position()
read()
scan(pattern, cons=false)

Scans the source for a given pattern. Note, that this is not your usual scan() method. For one thing, the pattern argument has some requirements; for another, the source can be consumed. You can easily confuse this method. Originally, the patterns were easier to construct and this method more robust, because this method generated search regexes on the fly; however, this was computationally expensive and slowed down the entire REXML package considerably, since this is by far the most commonly called method. @param pattern must be a Regexp, and must be in the form of /^\s*(#{your pattern, with no groups})(.*)/. The first group will be returned; the second group is used if the consume flag is set. @param consume if true, the pattern returned will be consumed, leaving everything after it in the Source. @return the pattern, if found, or nil if the Source is empty or the pattern is not found.


Class: REXML::SourceFactory

Class | REXML::SourceFactory
In: | lib/rexml/source.rb
Parent: | Object

Generates Source-s. USE THIS CLASS.

Methods

create_from

Public Class methods

create_from(arg)

Generates a Source object @param arg Either a String, or an IO @return a Source, or nil if a bad argument was given


Module: REXML::StreamListener

Module | REXML::StreamListener
In: | lib/rexml/streamlistener.rb

A template for stream parser listeners. Note that the declarations (attlistdecl, elementdecl, etc) are trivially processed; REXML doesn‘t yet handle doctype entity declarations, so you have to parse them out yourself.

Methods

attlistdecl cdata comment doctype doctype_end elementdecl entity entitydecl instruction notationdecl tag_end tag_start text xmldecl

Public Instance methods

attlistdecl(element_name, attributes, raw_content)

If a doctype includes an ATTLIST declaration, it will cause this method to be called. The content is the declaration itself, unparsed. EG, <!ATTLIST el attr CDATA REQUIRED> will come to this method as "el attr CDATA REQUIRED". This is the same for all of the .*decl methods.

cdata(content)

Called when <![CDATA[ … ]]> is encountered in a document. @p content "…"

comment(comment)

Called when a comment is encountered. @p comment The content of the comment

doctype(name, pub_sys, long_name, uri)

Handles a doctype declaration. Any attributes of the doctype which are not supplied will be nil. # EG, <!DOCTYPE me PUBLIC "foo" "bar"> @p name the name of the doctype; EG, "me" @p pub_sys "PUBLIC", "SYSTEM", or nil. EG, "PUBLIC" @p long_name the supplied long name, or nil. EG, "foo" @p uri the uri of the doctype, or nil. EG, "bar"

doctype_end()

Called when the doctype is done

elementdecl(content)

<!ELEMENT …>

entity(content)

Called when %foo; is encountered in a doctype declaration. @p content "foo"

entitydecl(content)

<!ENTITY …> The argument passed to this method is an array of the entity declaration. It can be in a number of formats, but in general it returns (example, result):

 <!ENTITY % YN '"Yes"'>
 ["%", "YN", "'\"Yes\"'", "\""]
 <!ENTITY % YN 'Yes'>
 ["%", "YN", "'Yes'", "s"]
 <!ENTITY WhatHeSaid "He said %YN;">
 ["WhatHeSaid", "\"He said %YN;\"", "YN"]
 <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">
 ["open-hatch", "SYSTEM", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
 <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml">
 ["open-hatch", "PUBLIC", "\"-//Textuality//TEXT Standard open-hatch boilerplate//EN\"", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
 <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif>
 ["hatch-pic", "SYSTEM", "\"../grafix/OpenHatch.gif\"", "\n\t\t\t\t\t\t\tNDATA gif", "gif"]
instruction(name, instruction)

Called when an instruction is encountered. EG: <?xsl sheet=‘foo’?> @p name the instruction name; in the example, "xsl" @p instruction the rest of the instruction. In the example, "sheet=‘foo’"

notationdecl(content)

<!NOTATION …>

tag_end(name)

Called when the end tag is reached. In the case of <tag/>, tag_end will be called immidiately after tag_start @p the name of the tag

tag_start(name, attrs)

Called when a tag is encountered. @p name the tag name @p attrs an array of arrays of attribute/value pairs, suitable for use with assoc or rassoc. IE, <tag attr1="value1" attr2="value2"> will result in tag_start( "tag", # [["attr1","value1"],["attr2","value2"]])

text(text)

Called when text is encountered in the document @p text the text content.

xmldecl(version, encoding, standalone)

Called when an XML PI is encountered in the document. EG: <?xml version="1.0" encoding="utf"?> @p version the version attribute value. EG, "1.0" @p encoding the encoding attribute value, or nil. EG, "utf" @p standalone the standalone attribute value, or nil. EG, nil


Class: REXML::SyncEnumerator

Class | REXML::SyncEnumerator
In: | lib/rexml/syncenumerator.rb
Parent: | Object

Methods

each length new size

Included Modules

Enumerable

Public Class methods

new(*enums)

Creates a new SyncEnumerator which enumerates rows of given Enumerable objects.

Public Instance methods

each() {|*a[1..-1]| ...}

Enumerates rows of the Enumerable objects.

length()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.

size()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.


Class: REXML::Text

Class | REXML::Text
In: | lib/rexml/text.rb
Parent: | Child

Represents text nodes in an XML document

Methods

<< <=> clone empty? indent_text inspect new node_type normalize read_with_substitution to_s unnormalize value value= wrap write write_with_substitution xpath

Included Modules

Comparable

Constants

SPECIALS | = | [ /&(?!#?[\w-]+;)/u, /</u, />/u, /"/u, /'/u, /\r/u ] | The order in which the substitutions occur
SUBSTITUTES | = | ['&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#13;']
SLAICEPS | = | [ '<', '>', '"', "'", '&' ] | Characters which are substituted in written strings
SETUTITSBUS | = | [ /&lt;/u, /&gt;/u, /&quot;/u, /&apos;/u, /&amp;/u ]
ILLEGAL | = | /(<|&(?!(#{Entity::NAME})|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));))/um
NUMERICENTITY | = | /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/
REFERENCE | = | /#{Entity::REFERENCE}/
EREFERENCE | = | /&(?!#{Entity::NAME};)/

Attributes

raw [RW] If raw is true, then REXML leaves the value alone

Public Class methods

new(arg, respect_whitespace=false, parent=nil, raw=nil, entity_filter=nil, illegal=ILLEGAL )

Constructor arg if a String, the content is set to the String. If a Text, the object is shallowly cloned.

respect_whitespace (boolean, false) if true, whitespace is respected

parent (nil) if this is a Parent object, the parent will be set to this.

raw (nil) This argument can be given three values. If true, then the value of used to construct this object is expected to contain no unescaped XML markup, and REXML will not change the text. If this value is false, the string may contain any characters, and REXML will escape any and all defined entities whose values are contained in the text. If this value is nil (the default), then the raw value of the parent will be used as the raw value for this node. If there is no raw value for the parent, and no value is supplied, the default is false. Use this field if you have entities defined for some text, and you don‘t want REXML to escape that text in output.

  Text.new( "<&", false, nil, false ) #-> "&lt;&amp;"
  Text.new( "&lt;&amp;", false, nil, false ) #-> "&amp;lt;&amp;amp;"
  Text.new( "<&", false, nil, true )  #-> Parse exception
  Text.new( "&lt;&amp;", false, nil, true )  #-> "&lt;&amp;"
  # Assume that the entity "s" is defined to be "sean"
  # and that the entity    "r" is defined to be "russell"
  Text.new( "sean russell" )          #-> "&s; &r;"
  Text.new( "sean russell", false, nil, true ) #-> "sean russell"

entity_filter (nil) This can be an array of entities to match in the supplied text. This argument is only useful if raw is set to false.

  Text.new( "sean russell", false, nil, false, ["s"] ) #-> "&s; russell"
  Text.new( "sean russell", false, nil, true, ["s"] ) #-> "sean russell"

In the last example, the entity_filter argument is ignored.

pattern INTERNAL USE ONLY

normalize( input, doctype=nil, entity_filter=nil )

Escapes all possible entities

read_with_substitution( input, illegal=nil )

Reads text, substituting entities

unnormalize( string, doctype=nil, filter=nil, illegal=nil )

Unescapes all possible entities

Public Instance methods

<<( to_append )

Appends text to this text node. The text is appended in the raw mode of this text node.

<=>( other )

other a String or a Text returns the result of (to_s <=> arg.to_s)

clone()
empty?()
indent_text(string, level=1, style="\t", indentfirstline=true)
inspect()
node_type()
to_s()

Returns the string value of this text node. This string is always escaped, meaning that it is a valid XML text node string, and all entities that can be escaped, have been inserted. This method respects the entity filter set in the constructor.

  # Assume that the entity "s" is defined to be "sean", and that the
  # entity "r" is defined to be "russell"
  t = Text.new( "< & sean russell", false, nil, false, ['s'] )
  t.to_s   #-> "&lt; &amp; &s; russell"
  t = Text.new( "< & &s; russell", false, nil, false )
  t.to_s   #-> "&lt; &amp; &s; russell"
  u = Text.new( "sean russell", false, nil, true )
  u.to_s   #-> "sean russell"
value()

Returns the string value of this text. This is the text without entities, as it might be used programmatically, or printed to the console. This ignores the ‘raw’ attribute setting, and any entity_filter.

  # Assume that the entity "s" is defined to be "sean", and that the
  # entity "r" is defined to be "russell"
  t = Text.new( "< & sean russell", false, nil, false, ['s'] )
  t.value   #-> "< & sean russell"
  t = Text.new( "< & &s; russell", false, nil, false )
  t.value   #-> "< & sean russell"
  u = Text.new( "sean russell", false, nil, true )
  u.value   #-> "sean russell"
value=( val )

Sets the contents of this text node. This expects the text to be unnormalized. It returns self.

  e = Element.new( "a" )
  e.add_text( "foo" )   # <a>foo</a>
  e[0].value = "bar"    # <a>bar</a>
  e[0].value = "<a>"    # <a>&lt;a&gt;</a>
wrap(string, width, addnewline=false)
write( writer, indent=-1, transitive=false, ie_hack=false )

DEPRECATED

See REXML::Formatters

write_with_substitution(out, input)

Writes out text, substituting special characters beforehand. out A String, IO, or any other object supporting <<( String ) input the text to substitute and the write out

  z=utf8.unpack("U*")
  ascOut=""
  z.each{|r|
    if r <  0x100
      ascOut.concat(r.chr)
    else
      ascOut.concat(sprintf("&#x%x;", r))
    end
  }
  puts ascOut
xpath()

FIXME This probably won‘t work properly


Class: REXML::UndefinedNamespaceException

Class | REXML::UndefinedNamespaceException
In: | lib/rexml/undefinednamespaceexception.rb
Parent: | ParseException

Methods

new

Public Class methods

new( prefix, source, parser )


Module: REXML::Validation

Module | REXML::Validation
In: | lib/rexml/validation/validationexception.rb lib/rexml/validation/validation.rb lib/rexml/validation/relaxng.rb

Classes and Modules

Module REXML::Validation::Validator
Class REXML::Validation::Choice
Class REXML::Validation::Event
Class REXML::Validation::Interleave
Class REXML::Validation::OneOrMore
Class REXML::Validation::Optional
Class REXML::Validation::Ref
Class REXML::Validation::RelaxNG
Class REXML::Validation::Sequence
Class REXML::Validation::State
Class REXML::Validation::ValidationException
Class REXML::Validation::ZeroOrMore


Class: REXML::Validation::Choice

Class | REXML::Validation::Choice
In: | lib/rexml/validation/relaxng.rb
Parent: | State

Methods

<< add_event_to_arry expected inspect matches? new next reset

Public Class methods

new(context)

Public Instance methods

<<( event )
expected()
inspect()
matches?( event )
next( event )
reset()

Protected Instance methods

add_event_to_arry( arry, evt )


Class: REXML::Validation::Event

Class | REXML::Validation::Event
In: | lib/rexml/validation/validation.rb
Parent: | Object

Methods

== done? inspect matches? new single? to_s

Attributes

event_arg | [RW]
event_type | [R]

Public Class methods

new(event_type, event_arg=nil )

Public Instance methods

==( other )
done?()
inspect()
matches?( event )
single?()
to_s()


Class: REXML::Validation::Interleave

Class | REXML::Validation::Interleave
In: | lib/rexml/validation/relaxng.rb
Parent: | Choice

Methods

expected inspect matches? new next next_current reset

Public Class methods

new(context)

Public Instance methods

expected()
inspect()
matches?( event )
next( event )
next_current( event )
reset()


Class: REXML::Validation::OneOrMore

Class | REXML::Validation::OneOrMore
In: | lib/rexml/validation/relaxng.rb
Parent: | State

Methods

expected matches? new next reset

Public Class methods

new(context)

Public Instance methods

expected()
matches?( event )
next( event )
reset()


Class: REXML::Validation::Optional

Class | REXML::Validation::Optional
In: | lib/rexml/validation/relaxng.rb
Parent: | State

Methods

expected matches? next

Public Instance methods

expected()
matches?(event)
next( event )


Class: REXML::Validation::Ref

Class | REXML::Validation::Ref
In: | lib/rexml/validation/relaxng.rb
Parent: | Object

Methods

inspect new to_s

Public Class methods

new(value)

Public Instance methods

inspect()
to_s()


Class: REXML::Validation::RelaxNG

Class | REXML::Validation::RelaxNG
In: | lib/rexml/validation/relaxng.rb
Parent: | Object

Implemented:

  • empty
  • element
  • attribute
  • text
  • optional
  • choice
  • oneOrMore
  • zeroOrMore
  • group
  • value
  • interleave
  • mixed
  • ref
  • grammar
  • start
  • define

Not implemented:

  • data
  • param
  • include
  • externalRef
  • notAllowed
  • anyName
  • nsName
  • except
  • name

Methods

new receive

Included Modules

Validator

Constants

INFINITY | = | 1.0 / 0.0
EMPTY | = | Event.new( nil )
TEXT | = | [:start_element, "text"]

Attributes

count | [RW]
current | [RW]
references | [R]

Public Class methods

new(source)

FIXME: Namespaces

Public Instance methods

receive(event)


Class: REXML::Validation::Sequence

Class | REXML::Validation::Sequence
In: | lib/rexml/validation/relaxng.rb
Parent: | State

Methods

matches?

Public Instance methods

matches?(event)


Class: REXML::Validation::State

Class | REXML::Validation::State
In: | lib/rexml/validation/relaxng.rb
Parent: | Object

Methods

<< add_event_to_arry expand_ref_in expected generate_event inspect new next previous= reset to_s

Public Class methods

new( context )

Public Instance methods

<<( event )
expected()
inspect()
next( event )
previous=( previous )
reset()
to_s()

Protected Instance methods

add_event_to_arry( arry, evt )
expand_ref_in( arry, ind )
generate_event( event )


Class: REXML::Validation::ValidationException

Class | REXML::Validation::ValidationException
In: | lib/rexml/validation/validationexception.rb
Parent: | RuntimeError

Methods

new

Public Class methods

new(msg)


Module: REXML::Validation::Validator

Module | REXML::Validation::Validator
In: | lib/rexml/validation/validation.rb

Methods

dump reset validate

Constants

NILEVENT = [ nil ]

Public Instance methods

dump()
reset()
validate( event )


Class: REXML::Validation::ZeroOrMore

Class | REXML::Validation::ZeroOrMore
In: | lib/rexml/validation/relaxng.rb
Parent: | Optional

Methods

expected next

Public Instance methods

expected()
next( event )


Class: REXML::XMLDecl

Class | REXML::XMLDecl
In: | lib/rexml/xmldecl.rb
Parent: | Child

NEEDS DOCUMENTATION

Methods

== clone default dowrite encoding= inspect new node_type nowrite write xmldecl

Included Modules

Encoding

Constants

DEFAULT_VERSION | = | "1.0";
DEFAULT_ENCODING | = | "UTF-8";
DEFAULT_STANDALONE | = | "no";
START | = | '<\?xml';
STOP | = | '\?>';

External Aliases

standalone | -> | stand_alone?
encoding= | -> | old_enc=

Attributes

standalone | [RW]
version | [RW]
writeencoding | [R]
writethis | [R]

Public Class methods

default()

Only use this if you do not want the XML declaration to be written; this object is ignored by the XML writer. Otherwise, instantiate your own XMLDecl and add it to the document.

Note that XML 1.1 documents must include an XML declaration

new(version=DEFAULT_VERSION, encoding=nil, standalone=nil)

Public Instance methods

==( other )
clone()
dowrite()
encoding=( enc )
inspect()
node_type()
nowrite()
write(writer, indent=-1, transitive=false, ie_hack=false)
indent: | Ignored. There must be no whitespace before an XML declaration
transitive: | Ignored
ie_hack: | Ignored
xmldecl(version, encoding, standalone)


Module: REXML::XMLTokens

Module | REXML::XMLTokens
In: | lib/rexml/xmltokens.rb

Defines a number of tokens used for parsing XML. Not for general consumption.

Constants

NCNAME_STR | = | '[\w:][\-\w\d.]*'
NAME_STR | = | "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
NAMECHAR | = | '[\-\w\d\.:]'
NAME | = | "([\\w:]#{NAMECHAR}*)"
NMTOKEN | = | "(?:#{NAMECHAR})+"
NMTOKENS | = | "#{NMTOKEN}(\\s+#{NMTOKEN})*"
REFERENCE | = | "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"


Class: REXML::XPath

Class | REXML::XPath
In: | lib/rexml/xpath.rb
Parent: | Object

Wrapper class. Use this class to access the XPath functions.

Methods

each first match

Included Modules

Functions

Constants

EMPTY_HASH = {}

Public Class methods

each(element, path=nil, namespaces=nil, variables={})

Itterates over nodes that match the given path, calling the supplied block with the match.

element: | The context element
path: | The xpath to search for. If not supplied or nil, defaults to ’*’
namespaces: | If supplied, a Hash which defines a namespace mapping
 XPath.each( node ) { |el| ... }
 XPath.each( node, '/*[@attr='v']' ) { |el| ... }
 XPath.each( node, 'ancestor::x' ) { |el| ... }
first(element, path=nil, namespaces=nil, variables={})

Finds and returns the first node that matches the supplied xpath.

element: | The context element
path: | The xpath to search for. If not supplied or nil, returns the first node matching ’*’.
namespaces: | If supplied, a Hash which defines a namespace mapping.
 XPath.first( node )
 XPath.first( doc, "//b"} )
 XPath.first( node, "a/x:b", { "x"=>"http://doofus" } )
match(element, path=nil, namespaces=nil, variables={})

Returns an array of nodes matching a given XPath.


Class: REXML::XPathParser

Class | REXML::XPathParser
In: | lib/rexml/xpath_parser.rb
Parent: | Object

You don‘t want to use this class. Really. Use XPath, which is a wrapper for this class. Believe me. You don‘t want to poke around in here. There is strange, dark magic at work in this code. Beware. Go back! Go back while you still can!

Methods

[]= first get_first match namespaces= new parse predicate variables=

Included Modules

XMLTokens

Constants

LITERAL | = | /^'([^']*)'|^"([^"]*)"/u
ALL | = | [ :attribute, :element, :text, :processing_instruction, :comment ] | Expr takes a stack of path elements and a set of nodes (either a Parent or an Array and returns an Array of matching nodes
ELEMENTS | = | [ :element ]

Public Class methods

new( )

Public Instance methods

[]=( variable_name, value )
first( path_stack, node )

Performs a depth-first (document order) XPath search, and returns the first match. This is the fastest, lightest way to return a single result.

FIXME: This method is incomplete!

get_first(path, nodeset)
match( path_stack, nodeset )
namespaces=( namespaces={} )
parse(path, nodeset)
predicate(path, nodeset)
variables=( vars={} )


Module: RI

Module | RI
In: | lib/rdoc/ri/ri_formatter.rb lib/rdoc/ri/ri_writer.rb lib/rdoc/ri/ri_paths.rb lib/rdoc/ri/ri_descriptions.rb lib/rdoc/ri/ri_cache.rb lib/rdoc/ri/ri_options.rb lib/rdoc/ri/ri_reader.rb

We handle the parsing of options, and subsequently as a singleton object to be queried for option values

Classes and Modules

Class RI::AliasName
Class RI::AnsiFormatter
Class RI::Attribute
Class RI::AttributeFormatter
Class RI::ClassDescription
Class RI::ClassEntry
Class RI::Constant
Class RI::Description
Class RI::HtmlFormatter
Class RI::IncludedModule
Class RI::MethodDescription
Class RI::MethodEntry
Class RI::MethodSummary
Class RI::ModuleDescription
Class RI::NamedThing
Class RI::Options
Class RI::OverstrikeFormatter
Class RI::RiCache
Class RI::RiReader
Class RI::RiWriter
Class RI::SimpleFormatter
Class RI::TextFormatter
Class RI::TopLevelEntry

Constants

VERSION_STRING = "ri v1.0.1 - 20041108"


Class: RI::AliasName

Class | RI::AliasName
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Alias = Struct.new(:old_name, :new_name)


Class: RI::AnsiFormatter

Class | RI::AnsiFormatter
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | AttributeFormatter

This formatter uses ANSI escape sequences to colorize stuff works with pages such as man and less.

Methods

bold_print display_heading new write_attribute_text

Constants

HEADINGS | = | { 1 => [ "\033[1;32m", "\033[m" ] , 2 => ["\033[4;32m", "\033[m" ], 3 => ["\033[32m", "\033[m" ]
ATTR_MAP | = | { BOLD => "1", ITALIC => "33", CODE => "36"

Public Class methods

new(*args)

Public Instance methods

bold_print(txt)
display_heading(text, level, indent)
write_attribute_text(prefix, line)


Class: RI::Attribute

Class | RI::Attribute
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Methods

new

Attributes

comment | [R]
rw | [R]

Public Class methods

new(name, rw, comment)


Class: RI::AttributeFormatter

Class | RI::AttributeFormatter
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | TextFormatter

Handle text with attributes. We‘re a base class: there are different presentation classes (one, for example, uses overstrikes to handle bold and underlining, while another using ANSI escape sequences

Methods

bold_print wrap write_attribute_text

Classes and Modules

Class RI::AttributeFormatter::AttrChar
Class RI::AttributeFormatter::AttributeString

Constants

BOLD | = | 1
ITALIC | = | 2
CODE | = | 4
ATTR_MAP | = | { "b" => BOLD, "code" => CODE, "em" => ITALIC, "i" => ITALIC, "tt" => CODE

Public Instance methods

wrap(txt, prefix=@indent, linelen=@width)

overrides base class. Looks for … etc sequences and generates an array of AttrChars. This array is then used as the basis for the split

Protected Instance methods

bold_print(txt)

again, overridden

write_attribute_text(prefix, line)

overridden in specific formatters


Class: RI::AttributeFormatter::AttrChar

Class | RI::AttributeFormatter::AttrChar
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | Object

TODO: struct?

Methods

new

Attributes

attr | [R]
char | [R]

Public Class methods

new(char, attr)


Class: RI::AttributeFormatter::AttributeString

Class | RI::AttributeFormatter::AttributeString
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | Object

Methods

<< empty? new next_word

Attributes

txt [R]

Public Class methods

new()

Public Instance methods

<<(char)
empty?()
next_word()

accept non space, then all following spaces


Class: RI::ClassDescription

Class | RI::ClassDescription
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | ModuleDescription

Methods

display_name superclass_string

Attributes

superclass [RW]

Public Instance methods

display_name()
superclass_string()


Class: RI::ClassEntry

Class | RI::ClassEntry
In: | lib/rdoc/ri/ri_cache.rb
Parent: | Object

Methods

add_path all_method_names classes_and_modules contained_class_named contained_modules_matching full_name load_from methods_matching new recursively_find_methods_matching

Attributes

name | [R]
path_names | [R]

Public Class methods

new(path_name, name, in_class)

Public Instance methods

add_path(path)

We found this class in more tha one place, so add in the name from there.

all_method_names()

Return a list of all out method names

classes_and_modules()
contained_class_named(name)

Return an exact match to a particular name

contained_modules_matching(name)

Return a list of any classes or modules that we contain that match a given string

full_name()

Return our full name

load_from(dir)

read in our methods and any classes and modules in our namespace. Methods are stored in files called name-c|i.yaml, where the ‘name’ portion is the external form of the method name and the c|i is a class|instance flag

methods_matching(name, is_class_method)

return the list of local methods matching name We‘re split into two because we need distinct behavior when called from the toplevel

recursively_find_methods_matching(name, is_class_method)

Find methods matching ‘name’ in ourselves and in any classes we contain


Class: RI::Constant

Class | RI::Constant
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Methods

new

Attributes

comment | [R]
value | [R]

Public Class methods

new(name, value, comment)


Class: RI::Description

Class | RI::Description
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | Object

Methods

<=> deserialize serialize

Attributes

comment | [RW]
full_name | [RW]
name | [RW]

Public Class methods

deserialize(from)

Public Instance methods

<=>(other)
serialize()


Class: RI::HtmlFormatter

Class | RI::HtmlFormatter
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | AttributeFormatter

This formatter uses HTML.

Methods

blankline bold_print break_to_newline display_heading display_list display_verbatim_flow_item draw_line new write_attribute_text

Constants

ATTR_MAP = { BOLD => "b>", ITALIC => "i>", CODE => "tt>"

Public Class methods

new(*args)

Public Instance methods

blankline()
bold_print(txt)
break_to_newline()
display_heading(text, level, indent)
display_list(list)
display_verbatim_flow_item(item, prefix=@indent)
draw_line(label=nil)
write_attribute_text(prefix, line)


Class: RI::IncludedModule

Class | RI::IncludedModule
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | NamedThing


Class: RI::MethodDescription

Class | RI::MethodDescription
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | Description

Attributes

aliases | [RW]
block_params | [RW]
is_alias_for | [RW]
is_class_method | [RW]
is_singleton | [RW]
params | [RW]
visibility | [RW]


Class: RI::MethodEntry

Class | RI::MethodEntry
In: | lib/rdoc/ri/ri_cache.rb
Parent: | Object

Methods

full_name new

Attributes

name | [R]
path_name | [R]

Public Class methods

new(path_name, name, is_class_method, in_class)

Public Instance methods

full_name()


Class: RI::MethodSummary

Class | RI::MethodSummary
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | NamedThing

Methods

new

Public Class methods

new(name="")


Class: RI::ModuleDescription

Class | RI::ModuleDescription
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | Description

Methods

display_name merge_in superclass_string

Attributes

attributes | [RW]
class_methods | [RW]
constants | [RW]
includes | [RW]
instance_methods | [RW]

Public Instance methods

display_name()
merge_in(old)

merge in another class desscription into this one

superclass_string()

the ‘ClassDescription’ subclass overrides this to format up the name of a parent


Class: RI::NamedThing

Class | RI::NamedThing
In: | lib/rdoc/ri/ri_descriptions.rb
Parent: | Object

Methods

<=> eql? hash new

Attributes

name [R]

Public Class methods

new(name)

Public Instance methods

<=>(other)
eql?(other)
hash()


Class: RI::Options

Class | RI::Options
In: | lib/rdoc/ri/ri_options.rb
Parent: | Object

Methods

displayer new parse path raw_path show_version

Included Modules

Singleton

Classes and Modules

Module RI::Options::OptionList

Attributes

doc_dir | [R] | the directory we search for original documentation
formatter | [R] | the formatting we apply to the output
list_classes | [R] | should we just display a class list and exit
list_names | [R] | should we display a list of all names
use_stdout | [RW] | No not use a pager. Writable, because ri sets it if it can‘t find a pager
width | [R] | The width of the output line

Public Class methods

new()

Public Instance methods

displayer()

Return an instance of the displayer (the thing that actually writes the information). This allows us to load in new displayer classes at runtime (for example to help with IDE integration)

parse(args)

Parse command line options.

path()

Return the selected documentation directories.

raw_path()
show_version()

Show the version and exit


Module: RI::Options::OptionList

Module | RI::Options::OptionList
In: | lib/rdoc/ri/ri_options.rb

Methods

error options strip_output usage

Constants

OPTION_LIST = [ [ "--help", "-h", nil, "you're looking at it" ], [ "--classes", "-c", nil, "Display the names of classes and modules we\n" + "know about"], [ "--doc-dir", "-d", "<dirname>", "A directory to search for documentation. If not\n" + "specified, we search the standard rdoc/ri directories.\n" + "May be repeated."], [ "--system", nil, nil, "Include documentation from Ruby's standard library:\n " + RI::Paths::SYSDIR ], [ "--site", nil, nil, "Include documentation from libraries installed in site_lib:\n " + RI::Paths::SITEDIR ], [ "--home", nil, nil, "Include documentation stored in ~/.rdoc:\n " + (RI::Paths::HOMEDIR || "No ~/.rdoc found") ], [ "--gems", nil, nil, "Include documentation from Rubygems:\n " + (RI::Paths::GEMDIRS ? "#{Gem.path}/doc/*/ri" : "No Rubygems ri found.") ], [ "--format", "-f", "<name>", "Format to use when displaying output:\n" + " " + RI::TextFormatter.list + "\n" + "Use 'bs' (backspace) with most pager programs.\n" + "To use ANSI, either also use the -T option, or\n" + "tell your pager to allow control characters\n" + "(for example using the -R option to less)"], [ "--list-names", "-l", nil, "List all the names known to RDoc, one per line"

Public Class methods

error(msg)

Show an error and exit

options()
strip_output(text)
usage(short_form=false)

Show usage and exit


Class: RI::OverstrikeFormatter

Class | RI::OverstrikeFormatter
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | AttributeFormatter

This formatter generates overstrike-style formatting, which works with pagers such as man and less.

Methods

bold_print write_attribute_text

Constants

BS = "\C-h"

Public Instance methods

bold_print(text)

draw a string in bold

write_attribute_text(prefix, line)


Class: RI::RiCache

Class | RI::RiCache
In: | lib/rdoc/ri/ri_cache.rb
Parent: | Object

We represent everything know about all ‘ri’ files accessible to this program

Methods

new

Attributes

toplevel [R]

Public Class methods

new(dirs)


Class: RI::RiReader

Class | RI::RiReader
In: | lib/rdoc/ri/ri_reader.rb
Parent: | Object

Methods

all_names find_class_by_name find_methods full_class_names get_class get_method lookup_namespace_in new top_level_namespace

Public Class methods

new(ri_cache)

Public Instance methods

all_names()

return a list of all classes, modules, and methods

find_class_by_name(full_name)
find_methods(name, is_class_method, namespaces)
full_class_names()

return the names of all classes and modules

get_class(class_entry)

Return a class description

get_method(method_entry)

return the MethodDescription for a given MethodEntry by deserializing the YAML

lookup_namespace_in(target, namespaces)
top_level_namespace()


Class: RI::RiWriter

Class | RI::RiWriter
In: | lib/rdoc/ri/ri_writer.rb
Parent: | Object

Methods

add_class add_method class_desc_path external_to_internal internal_to_external new remove_class

Public Class methods

class_desc_path(dir, class_desc)
external_to_internal(name)

And the reverse operation

internal_to_external(name)

Convert a name from internal form (containing punctuation) to an external form (where punctuation is replaced by %xx)

new(base_dir)

Public Instance methods

add_class(class_desc)
add_method(class_desc, method_desc)
remove_class(class_desc)


Class: RI::SimpleFormatter

Class | RI::SimpleFormatter
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | TextFormatter

This formatter reduces extra lines for a simpler output. It improves way output looks for tools like IRC bots.

Methods

blankline display_heading draw_line

Public Instance methods

blankline()

No extra blank lines

display_heading(text, level, indent)

Place heading level indicators inline with heading.

draw_line(label=nil)

Display labels only, no lines


Class: RI::TextFormatter

Class | RI::TextFormatter
In: | lib/rdoc/ri/ri_formatter.rb
Parent: | Object

Finally, fill in the list of known formatters

Methods

blankline bold_print break_to_newline conv_html conv_markup display_flow display_flow_item display_heading display_list display_verbatim_flow_item draw_line for list new raw_print_line strip_attributes wrap

Constants

FORMATTERS = { "ansi" => AnsiFormatter, "bs" => OverstrikeFormatter, "html" => HtmlFormatter, "plain" => TextFormatter, "simple" => SimpleFormatter, }

Attributes

indent [R]

Public Class methods

for(name)
list()
new(options, indent)

Public Instance methods

blankline()
bold_print(txt)
break_to_newline()

called when we want to ensure a nbew ‘wrap’ starts on a newline Only needed for HtmlFormatter, because the rest do their own line breaking

conv_html(txt)

convert HTML entities back to ASCII

conv_markup(txt)

convert markup into display form

display_flow(flow)
display_flow_item(item, prefix=@indent)
display_heading(text, level, indent)
display_list(list)
display_verbatim_flow_item(item, prefix=@indent)
draw_line(label=nil)
raw_print_line(txt)
strip_attributes(txt)
wrap(txt, prefix=@indent, linelen=@width)


Class: RI::TopLevelEntry

Class | RI::TopLevelEntry
In: | lib/rdoc/ri/ri_cache.rb
Parent: | ClassEntry

A TopLevelEntry is like a class entry, but when asked to search for methods searches all classes, not just itself

Methods

full_name methods_matching module_named

Public Instance methods

full_name()
methods_matching(name, is_class_method)
module_named(name)


Module: RSS

Module | RSS
In: | lib/rss/xmlparser.rb lib/rss/syndication.rb lib/rss/maker/syndication.rb lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/2.0.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/content.rb lib/rss/maker/base.rb lib/rss/maker/0.9.rb lib/rss/maker/1.0.rb lib/rss/taxonomy.rb lib/rss/rss.rb lib/rss/trackback.rb lib/rss/xml-stylesheet.rb lib/rss/2.0.rb lib/rss/dublincore.rb lib/rss/image.rb lib/rss/rexmlparser.rb lib/rss/content.rb lib/rss/xmlscanner.rb lib/rss/0.9.rb lib/rss/utils.rb lib/rss/maker.rb lib/rss/parser.rb lib/rss/1.0.rb lib/rss/converter.rb

Classes and Modules

Module RSS::BaseDublinCoreModel
Module RSS::BaseModel
Module RSS::BaseTrackBackModel
Module RSS::ContentModel
Module RSS::DublinCoreModel
Module RSS::ImageFaviconModel
Module RSS::ImageItemModel
Module RSS::ImageModelUtils
Module RSS::ListenerMixin
Module RSS::Maker
Module RSS::RSS09
Module RSS::RSS10
Module RSS::RootElementMixin
Module RSS::SyndicationModel
Module RSS::TaxonomyTopicModel
Module RSS::TaxonomyTopicsModel
Module RSS::TrackBackModel10
Module RSS::TrackBackModel20
Module RSS::TrackBackUtils
Module RSS::Utils
Module RSS::XMLStyleSheetMixin
Class RSS::BaseListener
Class RSS::BaseParser
Class RSS::ConversionError
Class RSS::Converter
Class RSS::Element
Class RSS::Error
Class RSS::InvalidRSSError
Class RSS::MissingAttributeError
Class RSS::MissingTagError
Class RSS::NSError
Class RSS::NotAvailableValueError
Class RSS::NotExpectedTagError
Class RSS::NotSetError
Class RSS::NotValidXMLParser
Class RSS::NotWellFormedError
Class RSS::OverlappedPrefixError
Class RSS::Parser
Class RSS::RDF
Class RSS::REXMLLikeXMLParser
Class RSS::REXMLListener
Class RSS::REXMLParser
Class RSS::Rss
Class RSS::TooMuchTagError
Class RSS::UnknownConversionMethodError
Class RSS::UnknownTagError
Class RSS::XMLParserListener
Class RSS::XMLParserNotFound
Class RSS::XMLParserParser
Class RSS::XMLScanListener
Class RSS::XMLScanParser
Class RSS::XMLStyleSheet

Constants

SY_PREFIX | = | 'sy'
SY_URI | = | "http://purl.org/rss/1.0/modules/syndication/"
TAXO_PREFIX | = | "taxo"
TAXO_URI | = | "http://purl.org/rss/1.0/modules/taxonomy/"
TAXO_ELEMENTS | = | []
VERSION | = | "0.1.6"
URI | = | "http://purl.org/rss/1.0/"
DEBUG | = | false
NotExceptedTagError | = | NotExpectedTagError | For backward compatibility :X
UnknownConvertMethod | = | UnknownConversionMethodError | for backward compatibility
TRACKBACK_PREFIX | = | 'trackback'
TRACKBACK_URI | = | 'http://madskills.com/public/xml/rss/module/trackback/'
DC_PREFIX | = | 'dc'
DC_URI | = | "http://purl.org/dc/elements/1.1/"
DublincoreModel | = | DublinCoreModel | For backward compatibility
IMAGE_PREFIX | = | 'image'
IMAGE_URI | = | 'http://web.resource.org/rss/1.0/modules/image/'
IMAGE_ELEMENTS | = | []
CONTENT_PREFIX | = | 'content'
CONTENT_URI | = | "http://purl.org/rss/1.0/modules/content/"
AVAILABLE_PARSER_LIBRARIES | = | [ ["rss/xmlparser", :XMLParserParser], ["rss/xmlscanner", :XMLScanParser], ["rss/rexmlparser", :REXMLParser], ]
AVAILABLE_PARSERS | = | []


Module: RSS::BaseDublinCoreModel

Module | RSS::BaseDublinCoreModel
In: | lib/rss/dublincore.rb

Methods

append_features

Public Instance methods

append_features(klass)


Class: RSS::BaseListener

Class | RSS::BaseListener
In: | lib/rss/parser.rb
Parent: | Object

Methods

available_tags class_name install_class_name install_get_text_element raise_for_undefined_entity? register_uri setter uri_registered?

Public Class methods

available_tags(uri)

return the tag_names for setters associated with uri

class_name(uri, tag_name)

retrieve class_name for the supplied uri and tag_name If it doesn‘t exist, capitalize the tag_name

install_class_name(uri, tag_name, class_name)

record class_name for the supplied uri and tag_name

install_get_text_element(uri, name, setter)
raise_for_undefined_entity?()
register_uri(uri, name)

register uri against this name.

setter(uri, tag_name)

return the setter for the uri, tag_name pair, or nil.

uri_registered?(uri, name)

test if this uri is registered against this name


Module: RSS::BaseModel

Module | RSS::BaseModel
In: | lib/rss/rss.rb

Methods

install_date_element install_have_attribute_element install_have_child_element install_have_children_element install_text_element

Included Modules

Utils

Public Instance methods

install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil)
install_have_attribute_element(tag_name, uri, occurs, name=nil)

Alias for install_have_child_element

install_have_child_element(tag_name, uri, occurs, name=nil)
install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil)
install_text_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil)


Class: RSS::BaseParser

Class | RSS::BaseParser
In: | lib/rss/parser.rb
Parent: | Object

Methods

do_validate do_validate= ignore_unknown_element ignore_unknown_element= new parse raise_for_undefined_entity? rss

Public Class methods

new(rss)
raise_for_undefined_entity?()

Public Instance methods

do_validate()
do_validate=(new_value)
ignore_unknown_element()
ignore_unknown_element=(new_value)
parse()
rss()


Module: RSS::BaseTrackBackModel

Module | RSS::BaseTrackBackModel
In: | lib/rss/trackback.rb

Methods

append_features

Included Modules

TrackBackUtils

Constants

ELEMENTS = %w(ping about)

Public Instance methods

append_features(klass)


Module: RSS::ContentModel

Module | RSS::ContentModel
In: | lib/rss/content.rb

Methods

append_features

Constants

ELEMENTS = []

Public Class methods

append_features(klass)


Class: RSS::ConversionError

Class | RSS::ConversionError
In: | lib/rss/rss.rb
Parent: | Error

Methods

new

Attributes

from | [R]
string | [R]
to | [R]

Public Class methods

new(string, to, from)


Class: RSS::Converter

Class | RSS::Converter
In: | lib/rss/converter.rb
Parent: | Object

Methods

convert def_convert def_else_enc def_iconv_convert def_same_enc def_to_euc_jp_from_iso_2022_jp def_to_euc_jp_from_shift_jis def_to_euc_jp_from_utf_8 def_to_iso_2022_jp_from_euc_jp def_to_iso_8859_1_from_utf_8 def_to_shift_jis_from_euc_jp def_to_shift_jis_from_utf_8 def_to_utf_8_from_euc_jp def_to_utf_8_from_iso_8859_1 def_to_utf_8_from_shift_jis def_uconv_convert_if_can new

Included Modules

Utils

Public Class methods

new(to_enc, from_enc=nil)

Public Instance methods

convert(value)
def_convert(depth=0)
def_else_enc(to_enc, from_enc)
def_iconv_convert(to_enc, from_enc, depth=0)
def_same_enc()
def_to_euc_jp_from_iso_2022_jp()
def_to_euc_jp_from_shift_jis()
def_to_euc_jp_from_utf_8()
def_to_iso_2022_jp_from_euc_jp()
def_to_iso_8859_1_from_utf_8()
def_to_shift_jis_from_euc_jp()
def_to_shift_jis_from_utf_8()
def_to_utf_8_from_euc_jp()
def_to_utf_8_from_iso_8859_1()
def_to_utf_8_from_shift_jis()
def_uconv_convert_if_can(meth, to_enc, from_enc, nkf_arg)


Module: RSS::DublinCoreModel

Module | RSS::DublinCoreModel
In: | lib/rss/dublincore.rb

Constants

TEXT_ELEMENTS | = | { "title" => nil, "description" => nil, "creator" => nil, "subject" => nil, "publisher" => nil, "contributor" => nil, "type" => nil, "format" => nil, "identifier" => nil, "source" => nil, "language" => nil, "relation" => nil, "coverage" => nil, "rights" => "rightses"
DATE_ELEMENTS | = | { "date" => "w3cdtf", }
ELEMENT_NAME_INFOS | = | DublinCoreModel::TEXT_ELEMENTS.to_a
ELEMENTS | = | TEXT_ELEMENTS.keys + DATE_ELEMENTS.keys


Class: RSS::Element

Class | RSS::Element
In: | lib/rss/rss.rb
Parent: | Object

Methods

convert converter= full_name get_attributes have_children_elements inherited install_ns models must_call_validators need_initialize_variables new plural_forms required_prefix required_uri setup_maker tag_name tag_name to_element_methods to_s validate validate_for_stream

Included Modules

Utils

Constants

INDENT | = | " "
MUST_CALL_VALIDATORS | = | {}
MODELS | = | []
GET_ATTRIBUTES | = | []
HAVE_CHILDREN_ELEMENTS | = | []
TO_ELEMENT_METHODS | = | []
NEED_INITIALIZE_VARIABLES | = | []
PLURAL_FORMS | = | {}

Attributes

do_validate [RW]

Public Class methods

get_attributes()
have_children_elements()
inherited(klass)
install_ns(prefix, uri)
models()
must_call_validators()
need_initialize_variables()
new(do_validate=true, attrs={})
plural_forms()
required_prefix()
required_uri()
tag_name()
to_element_methods()

Public Instance methods

convert(value)
converter=(converter)
full_name()
setup_maker(maker)
tag_name()
to_s(need_convert=true, indent='')
validate(ignore_unknown_element=true)
validate_for_stream(tags, ignore_unknown_element=true)


Class: RSS::Error

Class | RSS::Error
In: | lib/rss/rss.rb
Parent: | StandardError


Module: RSS::ImageFaviconModel

Module | RSS::ImageFaviconModel
In: | lib/rss/image.rb

Methods

append_features

Included Modules

ImageModelUtils

Classes and Modules

Class RSS::ImageFaviconModel::ImageFavicon

Public Class methods

append_features(klass)


Class: RSS::ImageFaviconModel::ImageFavicon

Class | RSS::ImageFaviconModel::ImageFavicon
In: | lib/rss/image.rb
Parent: | Element

Methods

full_name image_size= new required_prefix required_uri size=

Included Modules

RSS10 DublinCoreModel

Constants

AVAILABLE_SIZES = %w(small medium large)

External Aliases

size= | -> | _size=
size | -> | image_size

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()
image_size=(new_value)

Alias for size=

size=(new_value)


Module: RSS::ImageItemModel

Module | RSS::ImageItemModel
In: | lib/rss/image.rb

Methods

append_features

Included Modules

ImageModelUtils

Classes and Modules

Class RSS::ImageItemModel::ImageItem

Public Class methods

append_features(klass)


Class: RSS::ImageItemModel::ImageItem

Class | RSS::ImageItemModel::ImageItem
In: | lib/rss/image.rb
Parent: | Element

Methods

full_name new required_prefix required_uri

Included Modules

RSS10 DublinCoreModel

External Aliases

image_width= | -> | width=
image_width | -> | width
image_height= | -> | height=
image_height | -> | height

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()


Module: RSS::ImageModelUtils

Module | RSS::ImageModelUtils
In: | lib/rss/image.rb

Methods

validate_one_tag_name

Public Instance methods

validate_one_tag_name(ignore_unknown_element, name, tags)


Class: RSS::InvalidRSSError

Class | RSS::InvalidRSSError
In: | lib/rss/rss.rb
Parent: | Error


Module: RSS::ListenerMixin

Module | RSS::ListenerMixin
In: | lib/rss/0.9.rb lib/rss/parser.rb lib/rss/1.0.rb

Methods

instruction new tag_end tag_start text xmldecl

Constants

CONTENT_PATTERN | = | /\s*([^=]+)=(["'])([^\2]+?)\2/
NAMESPLIT | = | /^(?:([\w:][-\w\d.]*):)?([\w:][-\w\d.]*)/

Attributes

do_validate | [RW]
ignore_unknown_element | [RW]
rss | [R]

Public Class methods

new()

Public Instance methods

instruction(name, content)
tag_end(name)
tag_start(name, attributes)
text(data)
xmldecl(version, encoding, standalone)

set instance vars for version, encoding, standalone


Module: RSS::Maker

Module | RSS::Maker
In: | lib/rss/maker/syndication.rb lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/2.0.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/content.rb lib/rss/maker/base.rb lib/rss/maker/0.9.rb lib/rss/maker/1.0.rb lib/rss/maker.rb

Methods

add_maker filename_to_version make maker

Classes and Modules

Module RSS::Maker::Base
Module RSS::Maker::ContentModel
Module RSS::Maker::DublinCoreModel
Module RSS::Maker::ImageFaviconModel
Module RSS::Maker::ImageItemModel
Module RSS::Maker::SyndicationModel
Module RSS::Maker::TaxonomyTopicModel
Module RSS::Maker::TaxonomyTopicsModel
Module RSS::Maker::TrackBackModel
Class RSS::Maker::ChannelBase
Class RSS::Maker::ImageBase
Class RSS::Maker::ItemsBase
Class RSS::Maker::RSS09
Class RSS::Maker::RSS10
Class RSS::Maker::RSS20
Class RSS::Maker::RSSBase
Class RSS::Maker::TextinputBase
Class RSS::Maker::XMLStyleSheets

Constants

MAKERS = {}

Public Class methods

add_maker(version, maker)
filename_to_version(filename)
make(version, &block)
maker(version)


Module: RSS::Maker::Base

Module | RSS::Maker::Base
In: | lib/rss/maker/base.rb

Methods

append_features have_required_values? new

Public Class methods

append_features(klass)
new(maker)

Public Instance methods

have_required_values?()


Class: RSS::Maker::ChannelBase

Class | RSS::Maker::ChannelBase
In: | lib/rss/maker/syndication.rb lib/rss/maker/taxonomy.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

SyndicationModel TaxonomyTopicsModel DublinCoreModel Maker::ImageFaviconModel Base

Classes and Modules

Class RSS::Maker::ChannelBase::CategoriesBase
Class RSS::Maker::ChannelBase::CloudBase
Class RSS::Maker::ChannelBase::SkipDaysBase
Class RSS::Maker::ChannelBase::SkipHoursBase

External Aliases

dc_date | -> | date
dc_date= | -> | date=
date | -> | pubDate
date= | -> | pubDate=

Public Instance methods

current_element(rss)


Class: RSS::Maker::ChannelBase::CategoriesBase

Class | RSS::Maker::ChannelBase::CategoriesBase
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

new_category

Included Modules

Base

Classes and Modules

Class RSS::Maker::ChannelBase::CategoriesBase::CategoryBase

Public Instance methods

new_category() {|category| ...}


Class: RSS::Maker::ChannelBase::CategoriesBase::CategoryBase

Class | RSS::Maker::ChannelBase::CategoriesBase::CategoryBase
In: | lib/rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::ChannelBase::CloudBase

Class | RSS::Maker::ChannelBase::CloudBase
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

Base

Public Instance methods

current_element(rss)


Class: RSS::Maker::ChannelBase::SkipDaysBase

Class | RSS::Maker::ChannelBase::SkipDaysBase
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

current_element new_day

Included Modules

Base

Classes and Modules

Class RSS::Maker::ChannelBase::SkipDaysBase::DayBase

Public Instance methods

current_element(rss)
new_day() {|day| ...}


Class: RSS::Maker::ChannelBase::SkipDaysBase::DayBase

Class | RSS::Maker::ChannelBase::SkipDaysBase::DayBase
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

Base

Public Instance methods

current_element(rss)


Class: RSS::Maker::ChannelBase::SkipHoursBase

Class | RSS::Maker::ChannelBase::SkipHoursBase
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

current_element new_hour

Included Modules

Base

Classes and Modules

Class RSS::Maker::ChannelBase::SkipHoursBase::HourBase

Public Instance methods

current_element(rss)
new_hour() {|hour| ...}


Class: RSS::Maker::ChannelBase::SkipHoursBase::HourBase

Class | RSS::Maker::ChannelBase::SkipHoursBase::HourBase
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

Base

Public Instance methods

current_element(rss)


Module: RSS::Maker::ContentModel

Module | RSS::Maker::ContentModel
In: | lib/rss/maker/content.rb

Methods

append_features

Public Class methods

append_features(klass)


Module: RSS::Maker::DublinCoreModel

Module | RSS::Maker::DublinCoreModel
In: | lib/rss/maker/dublincore.rb

Methods

append_features install_dublin_core

Public Class methods

append_features(klass)
install_dublin_core(klass)


Class: RSS::Maker::ImageBase

Class | RSS::Maker::ImageBase
In: | lib/rss/maker/dublincore.rb lib/rss/maker/base.rb
Parent: | Object

Methods

current_element link

Included Modules

DublinCoreModel Base

Public Instance methods

current_element(rss)
link()


Module: RSS::Maker::ImageFaviconModel

Module | RSS::Maker::ImageFaviconModel
In: | lib/rss/maker/image.rb

Methods

append_features

Classes and Modules

Class RSS::Maker::ImageFaviconModel::ImageFaviconBase

Public Class methods

append_features(klass)


Class: RSS::Maker::ImageFaviconModel::ImageFaviconBase

Class | RSS::Maker::ImageFaviconModel::ImageFaviconBase
In: | lib/rss/maker/image.rb
Parent: | Object

Methods

have_required_values?

Included Modules

Base Maker::DublinCoreModel

External Aliases

image_size | -> | size
image_size= | -> | size=

Attributes

about | [RW]
image_size | [RW]

Public Instance methods

have_required_values?()


Module: RSS::Maker::ImageItemModel

Module | RSS::Maker::ImageItemModel
In: | lib/rss/maker/image.rb

Methods

append_features

Classes and Modules

Class RSS::Maker::ImageItemModel::ImageItemBase

Public Class methods

append_features(klass)


Class: RSS::Maker::ImageItemModel::ImageItemBase

Class | RSS::Maker::ImageItemModel::ImageItemBase
In: | lib/rss/maker/image.rb
Parent: | Object

Methods

have_required_values?

Included Modules

Base Maker::DublinCoreModel

External Aliases

image_width= | -> | width=
image_width | -> | width
image_height= | -> | height=
image_height | -> | height

Attributes

about | [RW]
image_height | [RW]
image_width | [RW]
resource | [RW]

Public Instance methods

have_required_values?()


Class: RSS::Maker::ItemsBase

Class | RSS::Maker::ItemsBase
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/content.rb lib/rss/maker/base.rb
Parent: | Object

Methods

current_element new new_item normalize

Included Modules

Base

Classes and Modules

Class RSS::Maker::ItemsBase::ItemBase

Attributes

do_sort | [RW]
max_size | [RW]

Public Class methods

new(maker)

Public Instance methods

current_element(rss)
new_item() {|item| ...}
normalize()


Class: RSS::Maker::ItemsBase::ItemBase

Class | RSS::Maker::ItemsBase::ItemBase
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/content.rb lib/rss/maker/base.rb
Parent: | Object

Methods

<=> current_element

Included Modules

TaxonomyTopicsModel TrackBackModel DublinCoreModel Maker::ImageItemModel ContentModel Base

Classes and Modules

Class RSS::Maker::ItemsBase::ItemBase::EnclosureBase
Class RSS::Maker::ItemsBase::ItemBase::GuidBase
Class RSS::Maker::ItemsBase::ItemBase::SourceBase

Constants

CategoriesBase = ChannelBase::CategoriesBase

External Aliases

dc_date | -> | date
dc_date= | -> | date=
date | -> | pubDate
date= | -> | pubDate=

Public Instance methods

<=>(other)
current_element(rss)


Class: RSS::Maker::ItemsBase::ItemBase::EnclosureBase

Class | RSS::Maker::ItemsBase::ItemBase::EnclosureBase
In: | lib/rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::ItemsBase::ItemBase::GuidBase

Class | RSS::Maker::ItemsBase::ItemBase::GuidBase
In: | lib/rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::ItemsBase::ItemBase::SourceBase

Class | RSS::Maker::ItemsBase::ItemBase::SourceBase
In: | lib/rss/maker/base.rb
Parent: | Object

Included Modules

Base


Class: RSS::Maker::RSS09

Class | RSS::Maker::RSS09
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/0.9.rb
Parent: | Object

Methods

new

Classes and Modules

Class RSS::Maker::RSS09::Channel
Class RSS::Maker::RSS09::Image
Class RSS::Maker::RSS09::Items
Class RSS::Maker::RSS09::Textinput

Public Class methods

new(rss_version="0.91")


Class: RSS::Maker::RSS09::Channel

Class | RSS::Maker::RSS09::Channel
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/0.9.rb
Parent: | Object

Methods

have_required_values? to_rss

Classes and Modules

Class RSS::Maker::RSS09::Channel::Categories
Class RSS::Maker::RSS09::Channel::Cloud
Class RSS::Maker::RSS09::Channel::ImageFavicon
Class RSS::Maker::RSS09::Channel::SkipDays
Class RSS::Maker::RSS09::Channel::SkipHours

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::Maker::RSS09::Channel::Categories

Class | RSS::Maker::RSS09::Channel::Categories
In: | lib/rss/maker/0.9.rb
Parent: | CategoriesBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Channel::Categories::Category

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Channel::Categories::Category

Class | RSS::Maker::RSS09::Channel::Categories::Category
In: | lib/rss/maker/0.9.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS09::Channel::Cloud

Class | RSS::Maker::RSS09::Channel::Cloud
In: | lib/rss/maker/0.9.rb
Parent: | CloudBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Channel::ImageFavicon

Class | RSS::Maker::RSS09::Channel::ImageFavicon
In: | lib/rss/maker/image.rb
Parent: | ImageFaviconBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Channel::SkipDays

Class | RSS::Maker::RSS09::Channel::SkipDays
In: | lib/rss/maker/0.9.rb
Parent: | SkipDaysBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Channel::SkipDays::Day

Public Instance methods

to_rss(rss, channel)


Class: RSS::Maker::RSS09::Channel::SkipDays::Day

Class | RSS::Maker::RSS09::Channel::SkipDays::Day
In: | lib/rss/maker/0.9.rb
Parent: | DayBase

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, days)


Class: RSS::Maker::RSS09::Channel::SkipHours

Class | RSS::Maker::RSS09::Channel::SkipHours
In: | lib/rss/maker/0.9.rb
Parent: | SkipHoursBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Channel::SkipHours::Hour

Public Instance methods

to_rss(rss, channel)


Class: RSS::Maker::RSS09::Channel::SkipHours::Hour

Class | RSS::Maker::RSS09::Channel::SkipHours::Hour
In: | lib/rss/maker/0.9.rb
Parent: | HourBase

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, hours)


Class: RSS::Maker::RSS09::Image

Class | RSS::Maker::RSS09::Image
In: | lib/rss/maker/dublincore.rb lib/rss/maker/0.9.rb
Parent: | Object

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::Maker::RSS09::Items

Class | RSS::Maker::RSS09::Items
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/0.9.rb
Parent: | Object

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Items::Item

Public Instance methods

to_rss(rss)


Class: RSS::Maker::RSS09::Items::Item

Class | RSS::Maker::RSS09::Items::Item
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/0.9.rb
Parent: | Object

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Items::Item::Categories
Class RSS::Maker::RSS09::Items::Item::Enclosure
Class RSS::Maker::RSS09::Items::Item::Guid
Class RSS::Maker::RSS09::Items::Item::ImageItem
Class RSS::Maker::RSS09::Items::Item::Source
Class RSS::Maker::RSS09::Items::Item::TrackBackAbouts

Public Instance methods

to_rss(rss)


Class: RSS::Maker::RSS09::Items::Item::Categories

Class | RSS::Maker::RSS09::Items::Item::Categories
In: | lib/rss/maker/0.9.rb
Parent: | CategoriesBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Items::Item::Categories::Category

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Items::Item::Categories::Category

Class | RSS::Maker::RSS09::Items::Item::Categories::Category
In: | lib/rss/maker/0.9.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS09::Items::Item::Enclosure

Class | RSS::Maker::RSS09::Items::Item::Enclosure
In: | lib/rss/maker/0.9.rb
Parent: | EnclosureBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Items::Item::Guid

Class | RSS::Maker::RSS09::Items::Item::Guid
In: | lib/rss/maker/0.9.rb
Parent: | GuidBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Items::Item::ImageItem

Class | RSS::Maker::RSS09::Items::Item::ImageItem
In: | lib/rss/maker/image.rb
Parent: | ImageItemBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Items::Item::Source

Class | RSS::Maker::RSS09::Items::Item::Source
In: | lib/rss/maker/0.9.rb
Parent: | SourceBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Items::Item::TrackBackAbouts

Class | RSS::Maker::RSS09::Items::Item::TrackBackAbouts
In: | lib/rss/maker/trackback.rb
Parent: | TrackBackAboutsBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS09::Items::Item::TrackBackAbouts::TrackBackAbout

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS09::Items::Item::TrackBackAbouts::TrackBackAbout

Class | RSS::Maker::RSS09::Items::Item::TrackBackAbouts::TrackBackAbout
In: | lib/rss/maker/trackback.rb
Parent: | TrackBackAboutBase


Class: RSS::Maker::RSS09::Textinput

Class | RSS::Maker::RSS09::Textinput
In: | lib/rss/maker/dublincore.rb lib/rss/maker/0.9.rb
Parent: | Object

Methods

to_rss

Public Instance methods

to_rss(rss)


Class: RSS::Maker::RSS10

Class | RSS::Maker::RSS10
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/1.0.rb
Parent: | Object

Methods

new

Classes and Modules

Class RSS::Maker::RSS10::Channel
Class RSS::Maker::RSS10::Image
Class RSS::Maker::RSS10::Items
Class RSS::Maker::RSS10::Textinput

Public Class methods

new()


Class: RSS::Maker::RSS10::Channel

Class | RSS::Maker::RSS10::Channel
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/1.0.rb
Parent: | Object

Methods

have_required_values? to_rss

Classes and Modules

Class RSS::Maker::RSS10::Channel::Categories
Class RSS::Maker::RSS10::Channel::Cloud
Class RSS::Maker::RSS10::Channel::ImageFavicon
Class RSS::Maker::RSS10::Channel::SkipDays
Class RSS::Maker::RSS10::Channel::SkipHours

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::Maker::RSS10::Channel::Categories

Class | RSS::Maker::RSS10::Channel::Categories
In: | lib/rss/maker/1.0.rb
Parent: | CategoriesBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS10::Channel::Categories::Category

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Channel::Categories::Category

Class | RSS::Maker::RSS10::Channel::Categories::Category
In: | lib/rss/maker/1.0.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS10::Channel::Cloud

Class | RSS::Maker::RSS10::Channel::Cloud
In: | lib/rss/maker/1.0.rb
Parent: | CloudBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Channel::ImageFavicon

Class | RSS::Maker::RSS10::Channel::ImageFavicon
In: | lib/rss/maker/image.rb
Parent: | ImageFaviconBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)


Class: RSS::Maker::RSS10::Channel::SkipDays

Class | RSS::Maker::RSS10::Channel::SkipDays
In: | lib/rss/maker/1.0.rb
Parent: | SkipDaysBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS10::Channel::SkipDays::Day

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Channel::SkipDays::Day

Class | RSS::Maker::RSS10::Channel::SkipDays::Day
In: | lib/rss/maker/1.0.rb
Parent: | DayBase


Class: RSS::Maker::RSS10::Channel::SkipHours

Class | RSS::Maker::RSS10::Channel::SkipHours
In: | lib/rss/maker/1.0.rb
Parent: | SkipHoursBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS10::Channel::SkipHours::Hour

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Channel::SkipHours::Hour

Class | RSS::Maker::RSS10::Channel::SkipHours::Hour
In: | lib/rss/maker/1.0.rb
Parent: | HourBase


Class: RSS::Maker::RSS10::Image

Class | RSS::Maker::RSS10::Image
In: | lib/rss/maker/dublincore.rb lib/rss/maker/1.0.rb
Parent: | Object

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::Maker::RSS10::Items

Class | RSS::Maker::RSS10::Items
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/1.0.rb
Parent: | Object

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS10::Items::Item

Public Instance methods

to_rss(rss)


Class: RSS::Maker::RSS10::Items::Item

Class | RSS::Maker::RSS10::Items::Item
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/trackback.rb lib/rss/maker/dublincore.rb lib/rss/maker/image.rb lib/rss/maker/1.0.rb
Parent: | Object

Methods

have_required_values? to_rss

Classes and Modules

Class RSS::Maker::RSS10::Items::Item::Categories
Class RSS::Maker::RSS10::Items::Item::Enclosure
Class RSS::Maker::RSS10::Items::Item::Guid
Class RSS::Maker::RSS10::Items::Item::ImageItem
Class RSS::Maker::RSS10::Items::Item::Source
Class RSS::Maker::RSS10::Items::Item::TrackBackAbouts

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::Maker::RSS10::Items::Item::Categories

Class | RSS::Maker::RSS10::Items::Item::Categories
In: | lib/rss/maker/1.0.rb
Parent: | CategoriesBase

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS10::Items::Item::Categories::Category

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Items::Item::Categories::Category

Class | RSS::Maker::RSS10::Items::Item::Categories::Category
In: | lib/rss/maker/1.0.rb
Parent: | CategoryBase


Class: RSS::Maker::RSS10::Items::Item::Enclosure

Class | RSS::Maker::RSS10::Items::Item::Enclosure
In: | lib/rss/maker/1.0.rb
Parent: | EnclosureBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Items::Item::Guid

Class | RSS::Maker::RSS10::Items::Item::Guid
In: | lib/rss/maker/1.0.rb
Parent: | GuidBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Items::Item::ImageItem

Class | RSS::Maker::RSS10::Items::Item::ImageItem
In: | lib/rss/maker/image.rb
Parent: | ImageItemBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)


Class: RSS::Maker::RSS10::Items::Item::Source

Class | RSS::Maker::RSS10::Items::Item::Source
In: | lib/rss/maker/1.0.rb
Parent: | SourceBase

Methods

to_rss

Public Instance methods

to_rss(*args)


Class: RSS::Maker::RSS10::Items::Item::TrackBackAbouts

Class | RSS::Maker::RSS10::Items::Item::TrackBackAbouts
In: | lib/rss/maker/trackback.rb
Parent: | TrackBackAboutsBase

Classes and Modules

Class RSS::Maker::RSS10::Items::Item::TrackBackAbouts::TrackBackAbout


Class: RSS::Maker::RSS10::Items::Item::TrackBackAbouts::TrackBackAbout

Class | RSS::Maker::RSS10::Items::Item::TrackBackAbouts::TrackBackAbout
In: | lib/rss/maker/trackback.rb
Parent: | TrackBackAboutBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)


Class: RSS::Maker::RSS10::Textinput

Class | RSS::Maker::RSS10::Textinput
In: | lib/rss/maker/dublincore.rb lib/rss/maker/1.0.rb
Parent: | Object

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::Maker::RSS20

Class | RSS::Maker::RSS20
In: | lib/rss/maker/trackback.rb lib/rss/maker/2.0.rb
Parent: | Object

Methods

new

Classes and Modules

Class RSS::Maker::RSS20::Channel
Class RSS::Maker::RSS20::Image
Class RSS::Maker::RSS20::Items
Class RSS::Maker::RSS20::Textinput

Public Class methods

new(rss_version="2.0")


Class: RSS::Maker::RSS20::Channel

Class | RSS::Maker::RSS20::Channel
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel

Methods

have_required_values? required_variable_names

Classes and Modules

Class RSS::Maker::RSS20::Channel::Categories
Class RSS::Maker::RSS20::Channel::Cloud
Class RSS::Maker::RSS20::Channel::SkipDays
Class RSS::Maker::RSS20::Channel::SkipHours

Public Instance methods

have_required_values?()
required_variable_names()


Class: RSS::Maker::RSS20::Channel::Categories

Class | RSS::Maker::RSS20::Channel::Categories
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::Categories

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS20::Channel::Categories::Category

Public Instance methods

to_rss(rss, channel)


Class: RSS::Maker::RSS20::Channel::Categories::Category

Class | RSS::Maker::RSS20::Channel::Categories::Category
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::Categories::Category

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, channel)


Class: RSS::Maker::RSS20::Channel::Cloud

Class | RSS::Maker::RSS20::Channel::Cloud
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::Cloud

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, channel)


Class: RSS::Maker::RSS20::Channel::SkipDays

Class | RSS::Maker::RSS20::Channel::SkipDays
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::SkipDays

Classes and Modules

Class RSS::Maker::RSS20::Channel::SkipDays::Day


Class: RSS::Maker::RSS20::Channel::SkipDays::Day

Class | RSS::Maker::RSS20::Channel::SkipDays::Day
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::SkipDays::Day


Class: RSS::Maker::RSS20::Channel::SkipHours

Class | RSS::Maker::RSS20::Channel::SkipHours
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::SkipHours

Classes and Modules

Class RSS::Maker::RSS20::Channel::SkipHours::Hour


Class: RSS::Maker::RSS20::Channel::SkipHours::Hour

Class | RSS::Maker::RSS20::Channel::SkipHours::Hour
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Channel::SkipHours::Hour


Class: RSS::Maker::RSS20::Image

Class | RSS::Maker::RSS20::Image
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Image


Class: RSS::Maker::RSS20::Items

Class | RSS::Maker::RSS20::Items
In: | lib/rss/maker/trackback.rb lib/rss/maker/2.0.rb
Parent: | Object

Classes and Modules

Class RSS::Maker::RSS20::Items::Item


Class: RSS::Maker::RSS20::Items::Item

Class | RSS::Maker::RSS20::Items::Item
In: | lib/rss/maker/trackback.rb lib/rss/maker/2.0.rb
Parent: | Object

Methods

have_required_values?

Classes and Modules

Class RSS::Maker::RSS20::Items::Item::Categories
Class RSS::Maker::RSS20::Items::Item::Enclosure
Class RSS::Maker::RSS20::Items::Item::Guid
Class RSS::Maker::RSS20::Items::Item::Source
Class RSS::Maker::RSS20::Items::Item::TrackBackAbouts

Public Instance methods

have_required_values?()


Class: RSS::Maker::RSS20::Items::Item::Categories

Class | RSS::Maker::RSS20::Items::Item::Categories
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Categories

Methods

to_rss

Classes and Modules

Class RSS::Maker::RSS20::Items::Item::Categories::Category

Public Instance methods

to_rss(rss, item)


Class: RSS::Maker::RSS20::Items::Item::Categories::Category

Class | RSS::Maker::RSS20::Items::Item::Categories::Category
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Categories::Category

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, item)


Class: RSS::Maker::RSS20::Items::Item::Enclosure

Class | RSS::Maker::RSS20::Items::Item::Enclosure
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Enclosure

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, item)


Class: RSS::Maker::RSS20::Items::Item::Guid

Class | RSS::Maker::RSS20::Items::Item::Guid
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Guid

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, item)


Class: RSS::Maker::RSS20::Items::Item::Source

Class | RSS::Maker::RSS20::Items::Item::Source
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Items::Item::Source

Methods

have_required_values? to_rss

Public Instance methods

have_required_values?()
to_rss(rss, item)


Class: RSS::Maker::RSS20::Items::Item::TrackBackAbouts

Class | RSS::Maker::RSS20::Items::Item::TrackBackAbouts
In: | lib/rss/maker/trackback.rb
Parent: | TrackBackAboutsBase

Classes and Modules

Class RSS::Maker::RSS20::Items::Item::TrackBackAbouts::TrackBackAbout


Class: RSS::Maker::RSS20::Items::Item::TrackBackAbouts::TrackBackAbout

Class | RSS::Maker::RSS20::Items::Item::TrackBackAbouts::TrackBackAbout
In: | lib/rss/maker/trackback.rb
Parent: | TrackBackAboutBase

Methods

to_rss

Public Instance methods

to_rss(rss, current)


Class: RSS::Maker::RSS20::Textinput

Class | RSS::Maker::RSS20::Textinput
In: | lib/rss/maker/2.0.rb
Parent: | RSS09::Textinput


Class: RSS::Maker::RSSBase

Class | RSS::Maker::RSSBase
In: | lib/rss/maker/taxonomy.rb lib/rss/maker/base.rb
Parent: | Object

Methods

make make new to_rss

Included Modules

TaxonomyTopicModel Base

Attributes

encoding | [RW]
rss_version | [R]
standalone | [RW]
version | [RW]

Public Class methods

make(&block)
new(rss_version)

Public Instance methods

make() {|self| ...}
to_rss()


Module: RSS::Maker::SyndicationModel

Module | RSS::Maker::SyndicationModel
In: | lib/rss/maker/syndication.rb

Methods

append_features

Public Class methods

append_features(klass)


Module: RSS::Maker::TaxonomyTopicModel

Module | RSS::Maker::TaxonomyTopicModel
In: | lib/rss/maker/taxonomy.rb

Methods

append_features install_taxo_topic

Classes and Modules

Class RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase

Public Class methods

append_features(klass)
install_taxo_topic(klass)


Class: RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase

Class | RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase
In: | lib/rss/maker/taxonomy.rb
Parent: | Object

Methods

new_taxo_topic to_rss

Included Modules

Base

Classes and Modules

Class RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase::TaxonomyTopicBase

Public Instance methods

new_taxo_topic() {|taxo_topic| ...}
to_rss(rss, current)


Class: RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase::TaxonomyTopicBase

Class | RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase::TaxonomyTopicBase
In: | lib/rss/maker/taxonomy.rb
Parent: | Object

Methods

have_required_values?

Included Modules

Base DublinCoreModel TaxonomyTopicsModel

External Aliases

value | -> | taxo_link
value= | -> | taxo_link=

Attributes

value [RW]

Public Instance methods

have_required_values?()


Module: RSS::Maker::TaxonomyTopicsModel

Module | RSS::Maker::TaxonomyTopicsModel
In: | lib/rss/maker/taxonomy.rb

Methods

append_features install_taxo_topics

Classes and Modules

Class RSS::Maker::TaxonomyTopicsModel::TaxonomyTopicsBase

Public Class methods

append_features(klass)
install_taxo_topics(klass)


Class: RSS::Maker::TaxonomyTopicsModel::TaxonomyTopicsBase

Class | RSS::Maker::TaxonomyTopicsModel::TaxonomyTopicsBase
In: | lib/rss/maker/taxonomy.rb
Parent: | Object

Included Modules

Base

Attributes

resources [R]


Class: RSS::Maker::TextinputBase

Class | RSS::Maker::TextinputBase
In: | lib/rss/maker/dublincore.rb lib/rss/maker/base.rb
Parent: | Object

Methods

current_element

Included Modules

DublinCoreModel Base

Public Instance methods

current_element(rss)


Module: RSS::Maker::TrackBackModel

Module | RSS::Maker::TrackBackModel
In: | lib/rss/maker/trackback.rb

Methods

append_features

Classes and Modules

Class RSS::Maker::TrackBackModel::TrackBackAboutsBase

Public Class methods

append_features(klass)


Class: RSS::Maker::TrackBackModel::TrackBackAboutsBase

Class | RSS::Maker::TrackBackModel::TrackBackAboutsBase
In: | lib/rss/maker/trackback.rb
Parent: | Object

Methods

new_about to_rss

Included Modules

Base

Classes and Modules

Class RSS::Maker::TrackBackModel::TrackBackAboutsBase::TrackBackAboutBase

Public Instance methods

new_about() {|about| ...}
to_rss(rss, current)


Class: RSS::Maker::TrackBackModel::TrackBackAboutsBase::TrackBackAboutBase

Class | RSS::Maker::TrackBackModel::TrackBackAboutsBase::TrackBackAboutBase
In: | lib/rss/maker/trackback.rb
Parent: | Object

Methods

have_required_values?

Included Modules

Base

External Aliases

value | -> | resource
value= | -> | resource=
value | -> | content
value= | -> | content=

Attributes

value [RW]

Public Instance methods

have_required_values?()


Class: RSS::Maker::XMLStyleSheets

Class | RSS::Maker::XMLStyleSheets
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

new_xml_stylesheet to_rss

Included Modules

Base

Classes and Modules

Class RSS::Maker::XMLStyleSheets::XMLStyleSheet

Public Instance methods

new_xml_stylesheet() {|xss| ...}
to_rss(rss)


Class: RSS::Maker::XMLStyleSheets::XMLStyleSheet

Class | RSS::Maker::XMLStyleSheets::XMLStyleSheet
In: | lib/rss/maker/base.rb
Parent: | Object

Methods

have_required_values? to_rss

Included Modules

Base

Public Instance methods

have_required_values?()
to_rss(rss)


Class: RSS::MissingAttributeError

Class | RSS::MissingAttributeError
In: | lib/rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

attribute | [R]
tag | [R]

Public Class methods

new(tag, attribute)


Class: RSS::MissingTagError

Class | RSS::MissingTagError
In: | lib/rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

parent | [R]
tag | [R]

Public Class methods

new(tag, parent)


Class: RSS::NSError

Class | RSS::NSError
In: | lib/rss/parser.rb
Parent: | InvalidRSSError

Methods

new

Attributes

prefix | [R]
tag | [R]
uri | [R]

Public Class methods

new(tag, prefix, require_uri)


Class: RSS::NotAvailableValueError

Class | RSS::NotAvailableValueError
In: | lib/rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

attribute | [R]
tag | [R]
value | [R]

Public Class methods

new(tag, value, attribute=nil)


Class: RSS::NotExpectedTagError

Class | RSS::NotExpectedTagError
In: | lib/rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

parent | [R]
tag | [R]
uri | [R]

Public Class methods

new(tag, uri, parent)


Class: RSS::NotSetError

Class | RSS::NotSetError
In: | lib/rss/rss.rb
Parent: | Error

Methods

new

Attributes

name | [R]
variables | [R]

Public Class methods

new(name, variables)


Class: RSS::NotValidXMLParser

Class | RSS::NotValidXMLParser
In: | lib/rss/parser.rb
Parent: | Error

Methods

new

Public Class methods

new(parser)


Class: RSS::NotWellFormedError

Class | RSS::NotWellFormedError
In: | lib/rss/parser.rb
Parent: | Error

Methods

new

Attributes

element | [R]
line | [R]

Public Class methods

new(line=nil, element=nil)

Create a new NotWellFormedError for an error at line in element. If a block is given the return value of the block ends up in the error message.


Class: RSS::OverlappedPrefixError

Class | RSS::OverlappedPrefixError
In: | lib/rss/rss.rb
Parent: | Error

Methods

new

Attributes

prefix [R]

Public Class methods

new(prefix)


Class: RSS::Parser

Class | RSS::Parser
In: | lib/rss/parser.rb
Parent: | Object

Methods

default_parser default_parser= new parse

Public Class methods

default_parser()
default_parser=(new_value)

Set @@default_parser to new_value if it is one of the available parsers. Else raise NotValidXMLParser error.

new(rss, parser_class=self.class.default_parser)
parse(rss, do_validate=true, ignore_unknown_element=true, parser_class=default_parser)


Class: RSS::RDF

Class | RSS::RDF
In: | lib/rss/syndication.rb lib/rss/taxonomy.rb lib/rss/trackback.rb lib/rss/dublincore.rb lib/rss/image.rb lib/rss/content.rb lib/rss/1.0.rb
Parent: | Object

Methods

full_name new required_uri

Included Modules

TaxonomyTopicModel RSS10 RootElementMixin

Classes and Modules

Class RSS::RDF::Bag
Class RSS::RDF::Channel
Class RSS::RDF::Image
Class RSS::RDF::Item
Class RSS::RDF::Li
Class RSS::RDF::Seq
Class RSS::RDF::Textinput

Constants

PREFIX | = | 'rdf'
URI | = | "http://www.w3.org/1999/02/22-rdf-syntax-ns#"

Attributes

encoding | [RW]
rss_version | [RW]
standalone | [RW]
version | [RW]

Public Class methods

new(version=nil, encoding=nil, standalone=nil)
required_uri()

Public Instance methods

full_name()


Class: RSS::RDF::Bag

Class | RSS::RDF::Bag
In: | lib/rss/1.0.rb
Parent: | Element

Methods

full_name new required_uri setup_maker

Included Modules

RSS10

Constants

Li = ::RSS::RDF::Li

Public Class methods

new(*args)
required_uri()

Public Instance methods

full_name()
setup_maker(target)


Class: RSS::RDF::Channel

Class | RSS::RDF::Channel
In: | lib/rss/syndication.rb lib/rss/taxonomy.rb lib/rss/dublincore.rb lib/rss/image.rb lib/rss/1.0.rb
Parent: | Object

Methods

new required_uri

Included Modules

SyndicationModel TaxonomyTopicsModel DublinCoreModel ImageFaviconModel RSS10

Classes and Modules

Class RSS::RDF::Channel::Image
Class RSS::RDF::Channel::Items
Class RSS::RDF::Channel::Textinput

Public Class methods

new(*args)
required_uri()


Class: RSS::RDF::Channel::Image

Class | RSS::RDF::Channel::Image
In: | lib/rss/1.0.rb
Parent: | Element

Methods

new required_uri

Included Modules

RSS10

Public Class methods

new(*args)
required_uri()


Class: RSS::RDF::Channel::Items

Class | RSS::RDF::Channel::Items
In: | lib/rss/1.0.rb
Parent: | Element

Methods

new required_uri resources

Included Modules

RSS10

Constants

Seq | = | ::RSS::RDF::Seq
Seq | = | args[0]

Public Class methods

new(*args)
required_uri()

Public Instance methods

resources()


Class: RSS::RDF::Channel::Textinput

Class | RSS::RDF::Channel::Textinput
In: | lib/rss/1.0.rb
Parent: | Element

Methods

new required_uri

Included Modules

RSS10

Public Class methods

new(*args)
required_uri()


Class: RSS::RDF::Image

Class | RSS::RDF::Image
In: | lib/rss/dublincore.rb lib/rss/1.0.rb
Parent: | Object

Methods

new required_uri

Included Modules

DublinCoreModel RSS10

Public Class methods

new(*args)
required_uri()


Class: RSS::RDF::Item

Class | RSS::RDF::Item
In: | lib/rss/taxonomy.rb lib/rss/trackback.rb lib/rss/dublincore.rb lib/rss/image.rb lib/rss/content.rb lib/rss/1.0.rb
Parent: | Object

Methods

new required_uri

Included Modules

TaxonomyTopicsModel TrackBackModel10 DublinCoreModel ImageItemModel ContentModel RSS10

Public Class methods

new(*args)
required_uri()


Class: RSS::RDF::Li

Class | RSS::RDF::Li
In: | lib/rss/1.0.rb
Parent: | Element

Methods

full_name new required_uri

Included Modules

RSS10

Public Class methods

new(*args)
required_uri()

Public Instance methods

full_name()


Class: RSS::RDF::Seq

Class | RSS::RDF::Seq
In: | lib/rss/1.0.rb
Parent: | Element

Methods

full_name new required_uri setup_maker

Included Modules

RSS10

Constants

Li = ::RSS::RDF::Li

Public Class methods

new(*args)
required_uri()

Public Instance methods

full_name()
setup_maker(target)


Class: RSS::RDF::Textinput

Class | RSS::RDF::Textinput
In: | lib/rss/dublincore.rb lib/rss/1.0.rb
Parent: | Object

Methods

new required_uri

Included Modules

DublinCoreModel RSS10

Public Class methods

new(*args)
required_uri()


Class: RSS::REXMLLikeXMLParser

Class | RSS::REXMLLikeXMLParser
In: | lib/rss/xmlparser.rb
Parent: | ::XML::Parser

Methods

character endElement listener= processingInstruction startElement xmlDecl

Included Modules

::XML::Encoding_ja

Public Instance methods

character(data)
endElement(name)
listener=(listener)
processingInstruction(target, content)
startElement(name, attrs)
xmlDecl(version, encoding, standalone)


Class: RSS::REXMLListener

Class | RSS::REXMLListener
In: | lib/rss/rexmlparser.rb
Parent: | BaseListener

Methods

raise_for_undefined_entity? xmldecl

Included Modules

REXML::StreamListener ListenerMixin

External Aliases

text -> cdata

Public Class methods

raise_for_undefined_entity?()

Public Instance methods

xmldecl(version, encoding, standalone)


Class: RSS::REXMLParser

Class | RSS::REXMLParser
In: | lib/rss/rexmlparser.rb
Parent: | BaseParser

Methods

listener

Public Class methods

listener()


Module: RSS::RSS09

Module | RSS::RSS09
In: | lib/rss/0.9.rb

Methods

append_features

Constants

NSPOOL | = | {}
ELEMENTS | = | []

Public Class methods

append_features(klass)


Module: RSS::RSS10

Module | RSS::RSS10
In: | lib/rss/1.0.rb

Methods

append_features

Constants

NSPOOL | = | {}
ELEMENTS | = | []

Public Class methods

append_features(klass)


Module: RSS::RootElementMixin

Module | RSS::RootElementMixin
In: | lib/rss/rss.rb

Methods

new output_encoding= setup_maker to_xml

Included Modules

XMLStyleSheetMixin

Attributes

output_encoding [R]

Public Class methods

new(rss_version, version=nil, encoding=nil, standalone=nil)

Public Instance methods

output_encoding=(enc)
setup_maker(maker)
to_xml(version=nil, &block)


Class: RSS::Rss

Class | RSS::Rss
In: | lib/rss/trackback.rb lib/rss/2.0.rb lib/rss/0.9.rb
Parent: | Object

Methods

image items new setup_maker_elements textinput

Included Modules

RSS09 RootElementMixin

Classes and Modules

Class RSS::Rss::Channel

Attributes

encoding | [RW]
rss_version | [RW]
standalone | [RW]
version | [RW]

Public Class methods

new(rss_version, version=nil, encoding=nil, standalone=nil)

Public Instance methods

image()
items()
setup_maker_elements(maker)
textinput()


Class: RSS::Rss::Channel

Class | RSS::Rss::Channel
In: | lib/rss/trackback.rb lib/rss/2.0.rb lib/rss/0.9.rb
Parent: | Object

Included Modules

RSS09

Classes and Modules

Class RSS::Rss::Channel::Cloud
Class RSS::Rss::Channel::Image
Class RSS::Rss::Channel::Item
Class RSS::Rss::Channel::SkipDays
Class RSS::Rss::Channel::SkipHours
Class RSS::Rss::Channel::TextInput

Constants

Category = Item::Category

External Aliases

pubDate | -> | date
pubDate= | -> | date=


Class: RSS::Rss::Channel::Cloud

Class | RSS::Rss::Channel::Cloud
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::Image

Class | RSS::Rss::Channel::Image
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::Item

Class | RSS::Rss::Channel::Item
In: | lib/rss/trackback.rb lib/rss/2.0.rb lib/rss/0.9.rb
Parent: | Object

Included Modules

TrackBackModel20 RSS09

Classes and Modules

Class RSS::Rss::Channel::Item::Category
Class RSS::Rss::Channel::Item::Enclosure
Class RSS::Rss::Channel::Item::Guid
Class RSS::Rss::Channel::Item::Source

External Aliases

pubDate | -> | date
pubDate= | -> | date=
setup_maker_element | -> | _setup_maker_element


Class: RSS::Rss::Channel::Item::Category

Class | RSS::Rss::Channel::Item::Category
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::Item::Enclosure

Class | RSS::Rss::Channel::Item::Enclosure
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::Item::Guid

Class | RSS::Rss::Channel::Item::Guid
In: | lib/rss/2.0.rb
Parent: | Element

Methods

PermaLink? new

Included Modules

RSS09

External Aliases

PermaLink? -> _PermaLink?

Public Class methods

new(*args)

Public Instance methods

PermaLink?()


Class: RSS::Rss::Channel::Item::Source

Class | RSS::Rss::Channel::Item::Source
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::SkipDays

Class | RSS::Rss::Channel::SkipDays
In: | lib/rss/0.9.rb
Parent: | Element

Included Modules

RSS09

Classes and Modules

Class RSS::Rss::Channel::SkipDays::Day


Class: RSS::Rss::Channel::SkipDays::Day

Class | RSS::Rss::Channel::SkipDays::Day
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::SkipHours

Class | RSS::Rss::Channel::SkipHours
In: | lib/rss/0.9.rb
Parent: | Element

Included Modules

RSS09

Classes and Modules

Class RSS::Rss::Channel::SkipHours::Hour


Class: RSS::Rss::Channel::SkipHours::Hour

Class | RSS::Rss::Channel::SkipHours::Hour
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Class: RSS::Rss::Channel::TextInput

Class | RSS::Rss::Channel::TextInput
In: | lib/rss/0.9.rb
Parent: | Element

Methods

new

Included Modules

RSS09

Public Class methods

new(*args)


Module: RSS::SyndicationModel

Module | RSS::SyndicationModel
In: | lib/rss/syndication.rb

Methods

append_features sy_updatePeriod=

Constants

ELEMENTS | = | []
SY_UPDATEPERIOD_AVAILABLE_VALUES | = | %w(hourly daily weekly monthly yearly)

Public Class methods

append_features(klass)

Public Instance methods

sy_updatePeriod=(new_value)


Module: RSS::TaxonomyTopicModel

Module | RSS::TaxonomyTopicModel
In: | lib/rss/taxonomy.rb

Methods

append_features

Classes and Modules

Class RSS::TaxonomyTopicModel::TaxonomyTopic

Public Class methods

append_features(klass)


Class: RSS::TaxonomyTopicModel::TaxonomyTopic

Class | RSS::TaxonomyTopicModel::TaxonomyTopic
In: | lib/rss/taxonomy.rb
Parent: | Element

Methods

full_name maker_target new required_prefix required_uri

Included Modules

RSS10 DublinCoreModel TaxonomyTopicsModel

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()
maker_target(target)


Module: RSS::TaxonomyTopicsModel

Module | RSS::TaxonomyTopicsModel
In: | lib/rss/taxonomy.rb

Methods

append_features

Classes and Modules

Class RSS::TaxonomyTopicsModel::TaxonomyTopics

Public Class methods

append_features(klass)


Class: RSS::TaxonomyTopicsModel::TaxonomyTopics

Class | RSS::TaxonomyTopicsModel::TaxonomyTopics
In: | lib/rss/taxonomy.rb
Parent: | Element

Methods

full_name maker_target new required_prefix required_uri resources

Included Modules

RSS10

Constants

Bag | = | ::RSS::RDF::Bag
Bag | = | args[0]

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()
maker_target(target)
resources()


Class: RSS::TooMuchTagError

Class | RSS::TooMuchTagError
In: | lib/rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

parent | [R]
tag | [R]

Public Class methods

new(tag, parent)


Module: RSS::TrackBackModel10

Module | RSS::TrackBackModel10
In: | lib/rss/trackback.rb

Classes and Modules

Class RSS::TrackBackModel10::TrackBackAbout
Class RSS::TrackBackModel10::TrackBackPing


Class: RSS::TrackBackModel10::TrackBackAbout

Class | RSS::TrackBackModel10::TrackBackAbout
In: | lib/rss/trackback.rb
Parent: | Element

Methods

full_name new required_prefix required_uri

Included Modules

RSS10

External Aliases

resource | -> | value
resource= | -> | value=

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()


Class: RSS::TrackBackModel10::TrackBackPing

Class | RSS::TrackBackModel10::TrackBackPing
In: | lib/rss/trackback.rb
Parent: | Element

Methods

full_name new required_prefix required_uri

Included Modules

RSS10

External Aliases

resource | -> | value
resource= | -> | value=

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()


Module: RSS::TrackBackModel20

Module | RSS::TrackBackModel20
In: | lib/rss/trackback.rb

Classes and Modules

Class RSS::TrackBackModel20::TrackBackAbout
Class RSS::TrackBackModel20::TrackBackPing


Class: RSS::TrackBackModel20::TrackBackAbout

Class | RSS::TrackBackModel20::TrackBackAbout
In: | lib/rss/trackback.rb
Parent: | Element

Methods

full_name new required_prefix required_uri

Included Modules

RSS09

External Aliases

content | -> | value
content= | -> | value=

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()


Class: RSS::TrackBackModel20::TrackBackPing

Class | RSS::TrackBackModel20::TrackBackPing
In: | lib/rss/trackback.rb
Parent: | Element

Methods

full_name new required_prefix required_uri

Included Modules

RSS09

External Aliases

content | -> | value
content= | -> | value=

Public Class methods

new(*args)
required_prefix()
required_uri()

Public Instance methods

full_name()


Module: RSS::TrackBackUtils

Module | RSS::TrackBackUtils
In: | lib/rss/trackback.rb


Class: RSS::UnknownConversionMethodError

Class | RSS::UnknownConversionMethodError
In: | lib/rss/rss.rb
Parent: | Error

Methods

new

Attributes

from | [R]
to | [R]

Public Class methods

new(to, from)


Class: RSS::UnknownTagError

Class | RSS::UnknownTagError
In: | lib/rss/rss.rb
Parent: | InvalidRSSError

Methods

new

Attributes

tag | [R]
uri | [R]

Public Class methods

new(tag, uri)


Module: RSS::Utils

Module | RSS::Utils
In: | lib/rss/utils.rb

Methods

element_initialize_arguments? get_file_and_line_from_caller h html_escape new_with_value_if_need to_class_name

Public Instance methods

element_initialize_arguments?(args)
get_file_and_line_from_caller(i=0)
h(s)

Alias for html_escape

html_escape(s)

escape ’&’, ’"’, ’<’ and ’>’ for use in HTML.

new_with_value_if_need(klass, value)

If value is an instance of class klass, return it, else create a new instance of klass with value value.

to_class_name(name)

Convert a name_with_underscores to CamelCase.


Class: RSS::XMLParserListener

Class | RSS::XMLParserListener
In: | lib/rss/xmlparser.rb
Parent: | BaseListener

Methods

xmldecl

Included Modules

ListenerMixin

Public Instance methods

xmldecl(version, encoding, standalone)


Class: RSS::XMLParserNotFound

Class | RSS::XMLParserNotFound
In: | lib/rss/parser.rb
Parent: | Error

Methods

new

Public Class methods

new()


Class: RSS::XMLParserParser

Class | RSS::XMLParserParser
In: | lib/rss/xmlparser.rb
Parent: | BaseParser

Methods

listener

Public Class methods

listener()


Class: RSS::XMLScanListener

Class | RSS::XMLScanListener
In: | lib/rss/xmlscanner.rb
Parent: | BaseListener

Methods

on_attr_charref on_attr_charref_hex on_attr_entityref on_attr_value on_attribute on_charref on_charref_hex on_entityref on_etag on_stag on_stag_end on_stag_end_empty on_xmldecl_encoding on_xmldecl_end on_xmldecl_standalone on_xmldecl_version

Included Modules

XMLScan::Visitor ListenerMixin

Constants

ENTITIES = { 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '"', 'apos' => '\''

External Aliases

instruction | -> | on_pi
text | -> | on_chardata
text | -> | on_cdata

Public Instance methods

on_attr_charref(code)
on_attr_charref_hex(code)

Alias for on_attr_charref

on_attr_entityref(ref)
on_attr_value(str)
on_attribute(name)
on_charref(code)
on_charref_hex(code)

Alias for on_charref

on_entityref(ref)
on_etag(name)
on_stag(name)
on_stag_end(name)
on_stag_end_empty(name)
on_xmldecl_encoding(str)
on_xmldecl_end()
on_xmldecl_standalone(str)
on_xmldecl_version(str)


Class: RSS::XMLScanParser

Class | RSS::XMLScanParser
In: | lib/rss/xmlscanner.rb
Parent: | BaseParser

Methods

listener

Public Class methods

listener()


Class: RSS::XMLStyleSheet

Class | RSS::XMLStyleSheet
In: | lib/rss/xml-stylesheet.rb
Parent: | Object

Methods

alternate= href= new setup_maker to_s

Included Modules

Utils

Constants

ATTRIBUTES | = | %w(href type title media charset alternate)
GUESS_TABLE | = | { "xsl" => "text/xsl", "css" => "text/css", }

Attributes

do_validate [RW]

Public Class methods

new(*attrs)

Public Instance methods

alternate=(value)
href=(value)
setup_maker(maker)
to_s()


Module: RSS::XMLStyleSheetMixin

Module | RSS::XMLStyleSheetMixin
In: | lib/rss/xml-stylesheet.rb

Methods

new

Attributes

xml_stylesheets [RW]

Public Class methods

new(*args)


Module: RUNIT

Module | RUNIT
In: | lib/runit/assert.rb lib/runit/testresult.rb lib/runit/cui/testrunner.rb lib/runit/testsuite.rb lib/runit/testcase.rb lib/runit/topublic.rb lib/runit/error.rb
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Classes and Modules

Module RUNIT::Assert
Module RUNIT::CUI
Module RUNIT::ToPublic
Class RUNIT::TestCase
Class RUNIT::TestResult
Class RUNIT::TestSuite

Constants

AssertionFailedError = Test::Unit::AssertionFailedError


Module: RUNIT::Assert

Module | RUNIT::Assert
In: | lib/runit/assert.rb

Methods

assert_equal_float assert_exception assert_fail assert_match assert_matches assert_no_exception assert_not_match assert_not_nil assert_respond_to assert_send called_internally? setup_assert

Included Modules

Test::Unit::Assertions

Public Instance methods

assert_equal_float(expected, actual, delta, message="")
assert_exception(exception, message="", &block)
assert_fail(message="")
assert_match(actual_string, expected_re, message="")

To deal with the fact that RubyUnit does not check that the regular expression is, indeed, a regular expression, if it is not, we do our own assertion using the same semantics as RubyUnit

assert_matches(*args)
assert_no_exception(*args, &block)
assert_not_match(actual_string, expected_re, message="")
assert_not_nil(actual, message="")
assert_respond_to(method, object, message="")
assert_send(object, method, *args)
called_internally?()
setup_assert()


Module: RUNIT::CUI

Module | RUNIT::CUI
In: | lib/runit/cui/testrunner.rb

Classes and Modules

Class RUNIT::CUI::TestRunner


Class: RUNIT::CUI::TestRunner

Class | RUNIT::CUI::TestRunner
In: | lib/runit/cui/testrunner.rb
Parent: | Test::Unit::UI::Console::TestRunner

Methods

create_mediator create_result new quiet_mode= run run

Public Class methods

new()
quiet_mode=(boolean)
run(suite)

Public Instance methods

create_mediator(suite)
create_result()
run(suite, quiet_mode=@@quiet_mode)


Class: RUNIT::TestCase

Class | RUNIT::TestCase
In: | lib/runit/testcase.rb
Parent: | Test::Unit::TestCase

Methods

assert_equals name new run suite

Included Modules

RUNIT::Assert

Public Class methods

new(test_name, suite_name=self.class.name)
suite()

Public Instance methods

assert_equals(*args)
name()
run(result, &progress_block)


Class: RUNIT::TestResult

Class | RUNIT::TestResult
In: | lib/runit/testresult.rb
Parent: | Test::Unit::TestResult

Methods

add_error add_failure error_size failure_size run_asserts run_tests succeed?

Attributes

errors | [R]
failures | [R]

Public Instance methods

add_error(error)
add_failure(failure)
error_size()
failure_size()
run_asserts()
run_tests()
succeed?()


Class: RUNIT::TestSuite

Class | RUNIT::TestSuite
In: | lib/runit/testsuite.rb
Parent: | Test::Unit::TestSuite

Methods

add add_test count_test_cases run

Public Instance methods

add(*args)
add_test(*args)
count_test_cases()
run(result, &progress_block)


Module: RUNIT::ToPublic

Module | RUNIT::ToPublic
In: | lib/runit/topublic.rb


Module: Racc

Module | Racc
In: | lib/racc/parser.rb

Classes and Modules

Class Racc::ParseError
Class Racc::Parser

Constants

Racc_No_Extentions = false


Class: Racc::ParseError

Class | Racc::ParseError
In: | lib/racc/parser.rb
Parent: | StandardError


Class: Racc::Parser

Class | Racc::Parser
In: | lib/racc/parser.rb
Parent: | Object

Methods

racc_runtime_type

Constants

Racc_Runtime_Version | = | '1.4.5'
Racc_Runtime_Revision | = | '$originalRevision: 1.8 $'.split[1]
Racc_Runtime_Core_Version_R | = | '1.4.5'
Racc_Runtime_Core_Revision_R | = | '$originalRevision: 1.8 $'.split[1]
Racc_Runtime_Core_Revision_C | = | Racc_Runtime_Core_Id_C.split[2] | Racc_Runtime_Core_Version_C = (defined in extention)
Racc_Main_Parsing_Routine | = | :_racc_do_parse_c
Racc_YY_Parse_Method | = | :_racc_yyparse_c
Racc_Runtime_Core_Version | = | Racc_Runtime_Core_Version_C
Racc_Runtime_Core_Revision | = | Racc_Runtime_Core_Revision_C
Racc_Runtime_Type | = | 'c'
Racc_Main_Parsing_Routine | = | :_racc_do_parse_rb
Racc_YY_Parse_Method | = | :_racc_yyparse_rb
Racc_Runtime_Core_Version | = | Racc_Runtime_Core_Version_R
Racc_Runtime_Core_Revision | = | Racc_Runtime_Core_Revision_R
Racc_Runtime_Type | = | 'ruby'

Public Class methods

racc_runtime_type()


Class: Range

Class | Range
In: | range.c lib/pp.rb lib/yaml/rubytypes.rb
Parent: | Object

A Range represents an interval—a set of values with a start and an end. Ranges may be constructed using the s..e and s…e literals, or with Range::new. Ranges constructed using .. run from the start to the end inclusively. Those created using … exclude the end value. When used as an iterator, ranges return each value in the sequence.

   (-1..-5).to_a      #=> []
   (-5..-1).to_a      #=> [-5, -4, -3, -2, -1]
   ('a'..'e').to_a    #=> ["a", "b", "c", "d", "e"]
   ('a'...'e').to_a   #=> ["a", "b", "c", "d"]

Ranges can be constructed using objects of any type, as long as the objects can be compared using their <=> operator and they support the succ method to return the next object in sequence.

   class Xs                # represent a string of 'x's
     include Comparable
     attr :length
     def initialize(n)
       @length = n
     end
     def succ
       Xs.new(@length + 1)
     end
     def <=>(other)
       @length <=> other.length
     end
     def to_s
       sprintf "%2d #{inspect}", @length
     end
     def inspect
       'x' * @length
     end
   end

   r = Xs.new(3)..Xs.new(6)   #=> xxx..xxxxxx
   r.to_a                     #=> [xxx, xxxx, xxxxx, xxxxxx]
   r.member?(Xs.new(5))       #=> true

In the previous code example, class Xs includes the Comparable module. This is because Enumerable#member? checks for equality using ==. Including Comparable ensures that the == method is defined in terms of the <=> method implemented in Xs.

Methods

== === begin each end eql? exclude_end? first hash include? inspect last member? new pretty_print step to_s to_yaml yaml_new

Included Modules

Enumerable

Public Class methods

Range.new(start, end, exclusive=false) => range

Constructs a range using the given start and end. If the third parameter is omitted or is false, the range will include the end object; otherwise, it will be excluded.

yaml_new( klass, tag, val )

Public Instance methods

rng == obj => true or false

Returns true only if obj is a Range, has equivalent beginning and end items (by comparing them with ==), and has the same exclude_end? setting as <i>rng</t>.

  (0..2) == (0..2)            #=> true
  (0..2) == Range.new(0,2)    #=> true
  (0..2) == (0...2)           #=> false
rng === obj => true or false
rng.member?(val) => true or false
rng.include?(val) => true or false

Returns true if obj is an element of rng, false otherwise. Conveniently, === is the comparison operator used by case statements.

   case 79
   when 1..50   then   print "low\n"
   when 51..75  then   print "medium\n"
   when 76..100 then   print "high\n"
   end

produces:

   high
rng.first => obj
rng.begin => obj

Returns the first object in rng.

rng.each {| i | block } => rng

Iterates over the elements rng, passing each in turn to the block. You can only iterate if the start object of the range supports the succ method (which means that you can‘t iterate over ranges of Float objects).

   (10..15).each do |n|
      print n, ' '
   end

produces:

   10 11 12 13 14 15
rng.end => obj
rng.last => obj

Returns the object that defines the end of rng.

   (1..10).end    #=> 10
   (1...10).end   #=> 10
rng.eql?(obj) => true or false

Returns true only if obj is a Range, has equivalent beginning and end items (by comparing them with eql?), and has the same exclude_end? setting as rng.

  (0..2) == (0..2)            #=> true
  (0..2) == Range.new(0,2)    #=> true
  (0..2) == (0...2)           #=> false
rng.exclude_end? => true or false

Returns true if rng excludes its end value.

rng.first => obj
rng.begin => obj

Returns the first object in rng.

rng.hash => fixnum

Generate a hash value such that two ranges with the same start and end points, and the same value for the "exclude end" flag, generate the same hash value.

rng === obj => true or false
rng.member?(val) => true or false
rng.include?(val) => true or false

Returns true if obj is an element of rng, false otherwise. Conveniently, === is the comparison operator used by case statements.

   case 79
   when 1..50   then   print "low\n"
   when 51..75  then   print "medium\n"
   when 76..100 then   print "high\n"
   end

produces:

   high
rng.inspect => string

Convert this range object to a printable form (using inspect to convert the start and end objects).

rng.end => obj
rng.last => obj

Returns the object that defines the end of rng.

   (1..10).end    #=> 10
   (1...10).end   #=> 10
rng === obj => true or false
rng.member?(val) => true or false
rng.include?(val) => true or false

Returns true if obj is an element of rng, false otherwise. Conveniently, === is the comparison operator used by case statements.

   case 79
   when 1..50   then   print "low\n"
   when 51..75  then   print "medium\n"
   when 76..100 then   print "high\n"
   end

produces:

   high
pretty_print(q)
rng.step(n=1) {| obj | block } => rng

Iterates over rng, passing each nth element to the block. If the range contains numbers or strings, natural ordering is used. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.

   range = Xs.new(1)..Xs.new(10)
   range.step(2) {|x| puts x}
   range.step(3) {|x| puts x}

produces:

    1 x
    3 xxx
    5 xxxxx
    7 xxxxxxx
    9 xxxxxxxxx
    1 x
    4 xxxx
    7 xxxxxxx
   10 xxxxxxxxxx
rng.to_s => string

Convert this range object to a printable form.

to_yaml( opts = {} )


Class: RangeError

Class | RangeError
In: | error.c
Parent: | StandardError


Class: Rational

Class | Rational
In: | lib/mathn.rb lib/rational.rb
Parent: | Object

Rational implements a rational class for numbers.

A rational number is a number that can be expressed as a fraction p/q where p and q are integers and q != 0. A rational number p/q is said to have numerator p and denominator q. Numbers that are not rational are called irrational numbers. (mathworld.wolfram.com/RationalNumber.html)

To create a Rational Number:

  Rational(a,b)             # -> a/b
  Rational.new!(a,b)        # -> a/b

Examples:

  Rational(5,6)             # -> 5/6
  Rational(5)               # -> 5/1

Rational numbers are reduced to their lowest terms:

  Rational(6,10)            # -> 3/5

But not if you use the unusual method "new!":

  Rational.new!(6,10)       # -> 6/10

Division by zero is obviously not allowed:

  Rational(3,0)             # -> ZeroDivisionError

Methods

% * ** ** + - / <=> == abs coerce divmod hash inspect inspect new new! power2 reduce to_f to_i to_r to_s

Constants

Unify = true

External Aliases

** -> power!

Attributes

denominator | [R]
numerator | [R]

Public Class methods

new(num, den)

This method is actually private.

new!(num, den = 1)

Implements the constructor. This method does not reduce to lowest terms or check for division by zero. Therefore Rational() should be preferred in normal use.

reduce(num, den = 1)

Reduces the given numerator and denominator to their lowest terms. Use Rational() instead.

Public Instance methods

%(other)

Returns the remainder when this value is divided by other.

Examples:

  r = Rational(7,4)    # -> Rational(7,4)
  r % Rational(1,2)    # -> Rational(1,4)
  r % 1                # -> Rational(3,4)
  r % Rational(1,7)    # -> Rational(1,28)
  r % 0.26             # -> 0.19
*(a)

Returns the product of this value and a.

Examples:

  r = Rational(3,4)    # -> Rational(3,4)
  r * 2                # -> Rational(3,2)
  r * 4                # -> Rational(3,1)
  r * 0.5              # -> 0.375
  r * Rational(1,2)    # -> Rational(3,8)
**(other)
**(other)

Returns this value raised to the given power.

Examples:

  r = Rational(3,4)    # -> Rational(3,4)
  r ** 2               # -> Rational(9,16)
  r ** 2.0             # -> 0.5625
  r ** Rational(1,2)   # -> 0.866025403784439
+(a)

Returns the addition of this value and a.

Examples:

  r = Rational(3,4)      # -> Rational(3,4)
  r + 1                  # -> Rational(7,4)
  r + 0.5                # -> 1.25
-(a)

Returns the difference of this value and a. subtracted.

Examples:

  r = Rational(3,4)    # -> Rational(3,4)
  r - 1                # -> Rational(-1,4)
  r - 0.5              # -> 0.25
/(a)

Returns the quotient of this value and a.

  r = Rational(3,4)    # -> Rational(3,4)
  r / 2                # -> Rational(3,8)
  r / 2.0              # -> 0.375
  r / Rational(1,2)    # -> Rational(3,2)
<=>(other)

Standard comparison operator.

==(other)

Returns true iff this value is numerically equal to other.

But beware:

  Rational(1,2) == Rational(4,8)          # -> true
  Rational(1,2) == Rational.new!(4,8)     # -> false

Don‘t use Rational.new!

abs()

Returns the absolute value.

coerce(other)
divmod(other)

Returns the quotient and remainder.

Examples:

  r = Rational(7,4)        # -> Rational(7,4)
  r.divmod Rational(1,2)   # -> [3, Rational(1,4)]
hash()

Returns a hash code for the object.

inspect()
inspect()

Returns a reconstructable string representation:

  Rational(5,8).inspect     # -> "Rational(5, 8)"
power2(other)
to_f()

Converts the rational to a Float.

to_i()

Converts the rational to an Integer. Not the nearest integer, the truncated integer. Study the following example carefully:

  Rational(+7,4).to_i             # -> 1
  Rational(-7,4).to_i             # -> -2
  (-1.75).to_i                    # -> -1

In other words:

  Rational(-7,4) == -1.75                 # -> true
  Rational(-7,4).to_i == (-1.75).to_i     # false
to_r()

Returns self.

to_s()

Returns a string representation of the rational number.

Example:

  Rational(3,4).to_s          #  "3/4"
  Rational(8).to_s            #  "8"


Class: RegAnd

Class | RegAnd
In: | lib/eregex.rb
Parent: | Object

Methods

=~ new

Public Class methods

new(re1, re2)

Public Instance methods

=~(str)


Class: RegOr

Class | RegOr
In: | lib/eregex.rb
Parent: | Object

this is just a proof of concept toy.

Methods

=~ new

Public Class methods

new(re1, re2)

Public Instance methods

=~(str)


Class: Regexp

Class | Regexp
In: | re.c lib/eregex.rb lib/yaml/rubytypes.rb
Parent: | Object

Document-class: Regexp

A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /…/ and %r{…} literals, and by the Regexp::new constructor.

Methods

& == === =~ casefold? compile eql? escape hash inspect kcode last_match match new options quote source to_s to_yaml union yaml_new | ~

Constants

IGNORECASE | = | INT2FIX(RE_OPTION_IGNORECASE)
EXTENDED | = | INT2FIX(RE_OPTION_EXTENDED)
MULTILINE | = | INT2FIX(RE_OPTION_MULTILINE)

Public Class methods

compile(...)

Synonym for Regexp.new

Regexp.escape(str) => a_str
Regexp.quote(str) => a_str

Escapes any characters that would have special meaning in a regular expression. Returns a new escaped string, or self if no characters are escaped. For any string, Regexp.escape(str)=~str will be true.

   Regexp.escape('\\*?{}.')   #=> \\\\\*\?\{\}\.
Regexp.last_match => matchdata
Regexp.last_match(fixnum) => str

The first form returns the MatchData object generated by the last successful pattern match. Equivalent to reading the global variable $~. The second form returns the nth field in this MatchData object.

   /c(.)t/ =~ 'cat'       #=> 0
   Regexp.last_match      #=> #<MatchData:0x401b3d30>
   Regexp.last_match(0)   #=> "cat"
   Regexp.last_match(1)   #=> "a"
   Regexp.last_match(2)   #=> nil
Regexp.new(string [, options [, lang]]) => regexp
Regexp.new(regexp) => regexp
Regexp.compile(string [, options [, lang]]) => regexp
Regexp.compile(regexp) => regexp

Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp‘s options are propagated, and new options may not be specified (a change as of Ruby 1.8). If options is a Fixnum, it should be one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE, or-ed together. Otherwise, if options is not nil, the regexp will be case insensitive. The lang parameter enables multibyte support for the regexp: `n’, `N’ = none, `e’, `E’ = EUC, `s’, `S’ = SJIS, `u’, `U’ = UTF-8.

   r1 = Regexp.new('^a-z+:\\s+\w+')           #=> /^a-z+:\s+\w+/
   r2 = Regexp.new('cat', true)               #=> /cat/i
   r3 = Regexp.new('dog', Regexp::EXTENDED)   #=> /dog/x
   r4 = Regexp.new(r2)                        #=> /cat/i
Regexp.escape(str) => a_str
Regexp.quote(str) => a_str

Escapes any characters that would have special meaning in a regular expression. Returns a new escaped string, or self if no characters are escaped. For any string, Regexp.escape(str)=~str will be true.

   Regexp.escape('\\*?{}.')   #=> \\\\\*\?\{\}\.
Regexp.union([pattern]*) => new_str

Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts. The patterns can be Regexp objects, in which case their options will be preserved, or Strings. If no arguments are given, returns /(?!)/.

   Regexp.union                         #=> /(?!)/
   Regexp.union("penzance")             #=> /penzance/
   Regexp.union("skiing", "sledding")   #=> /skiing|sledding/
   Regexp.union(/dogs/, /cats/i)        #=> /(?-mix:dogs)|(?i-mx:cats)/
yaml_new( klass, tag, val )

Public Instance methods

&(other)
rxp == other_rxp => true or false
rxp.eql?(other_rxp) => true or false

Equality—Two regexps are equal if their patterns are identical, they have the same character set code, and their casefold? values are the same.

   /abc/  == /abc/x   #=> false
   /abc/  == /abc/i   #=> false
   /abc/u == /abc/n   #=> false
rxp === str => true or false

Case Equality—Synonym for Regexp#=~ used in case statements.

   a = "HELLO"
   case a
   when /^[a-z]*$/; print "Lower case\n"
   when /^[A-Z]*$/; print "Upper case\n"
   else;            print "Mixed case\n"
   end

produces:

   Upper case
rxp.match(str) => matchdata or nil

Returns a MatchData object describing the match, or nil if there was no match. This is equivalent to retrieving the value of the special variable $~ following a normal match.

   /(.)(.)(.)/.match("abc")[2]   #=> "b"
rxp.casefold? => true or false

Returns the value of the case-insensitive flag.

rxp == other_rxp => true or false
rxp.eql?(other_rxp) => true or false

Equality—Two regexps are equal if their patterns are identical, they have the same character set code, and their casefold? values are the same.

   /abc/  == /abc/x   #=> false
   /abc/  == /abc/i   #=> false
   /abc/u == /abc/n   #=> false
rxp.hash => fixnum

Produce a hash based on the text and options of this regular expression.

rxp.inspect => string

Produce a nicely formatted string-version of rxp. Perhaps surprisingly, inspect actually produces the more natural version of the string than to_s.

    /ab+c/ix.to_s         #=> /ab+c/ix
rxp.kcode => str

Returns the character set code for the regexp.

rxp.match(str) => matchdata or nil

Returns a MatchData object describing the match, or nil if there was no match. This is equivalent to retrieving the value of the special variable $~ following a normal match.

   /(.)(.)(.)/.match("abc")[2]   #=> "b"
rxp.options => fixnum

Returns the set of bits corresponding to the options used when creating this Regexp (see Regexp::new for details. Note that additional bits may be set in the returned options: these are used internally by the regular expression code. These extra bits are ignored if the options are passed to Regexp::new.

   Regexp::IGNORECASE                  #=> 1
   Regexp::EXTENDED                    #=> 2
   Regexp::MULTILINE                   #=> 4

   /cat/.options                       #=> 128
   /cat/ix.options                     #=> 131
   Regexp.new('cat', true).options     #=> 129
   Regexp.new('cat', 0, 's').options   #=> 384

   r = /cat/ix
   Regexp.new(r.source, r.options)     #=> /cat/ix
rxp.source => str

Returns the original string of the pattern.

   /ab+c/ix.source   #=> "ab+c"
rxp.to_s => str

Returns a string containing the regular expression and its options (using the (?xxx:yyy) notation. This string can be fed back in to Regexp::new to a regular expression with the same semantics as the original. (However, Regexp#== may not return true when comparing the two, as the source of the regular expression itself may differ, as the example shows). Regexp#inspect produces a generally more readable version of rxp.

   r1 = /ab+c/ix         #=> /ab+c/ix
   s1 = r1.to_s          #=> "(?ix-m:ab+c)"
   r2 = Regexp.new(s1)   #=> /(?ix-m:ab+c)/
   r1 == r2              #=> false
   r1.source             #=> "ab+c"
   r2.source             #=> "(?ix-m:ab+c)"
to_yaml( opts = {} )
|(other)
~ rxp => integer or nil

Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

   $_ = "input data"
   ~ /at/   #=> 7


Class: RegexpError

Class | RegexpError
In: | re.c
Parent: | StandardError


Class: Resolv

Class | Resolv
In: | lib/resolv.rb
Parent: | Object

Methods

each_address each_address each_name each_name getaddress getaddress getaddresses getaddresses getname getname getnames getnames new

Classes and Modules

Class Resolv::DNS
Class Resolv::Hosts
Class Resolv::IPv4
Class Resolv::IPv6
Class Resolv::ResolvError
Class Resolv::ResolvTimeout

Constants

DefaultResolver | = | self.new
AddressRegex | = | /(?:#{IPv4::Regex})|(?:#{IPv6::Regex})/

Public Class methods

each_address(name, &block)
each_name(address, &proc)
getaddress(name)
getaddresses(name)
getname(address)
getnames(address)
new(resolvers=[Hosts.new, DNS.new])

Public Instance methods

each_address(name) {|name| ...}
each_name(address) {|name.to_s| ...}
getaddress(name)
getaddresses(name)
getname(address)
getnames(address)


Class: Resolv::DNS

Class | Resolv::DNS
In: | lib/resolv.rb
Parent: | Object

Methods

close each_address each_name each_resource extract_resources getaddress getaddresses getname getnames getresource getresources lazy_initialize new open

Classes and Modules

Module Resolv::DNS::Label
Module Resolv::DNS::OpCode
Module Resolv::DNS::RCode
Class Resolv::DNS::Config
Class Resolv::DNS::DecodeError
Class Resolv::DNS::EncodeError
Class Resolv::DNS::Message
Class Resolv::DNS::Name
Class Resolv::DNS::Query
Class Resolv::DNS::Requester
Class Resolv::DNS::Resource

Constants

Port | = | 53 | STD0013 (RFC 1035, etc.) ftp.isi.edu/in-notes/iana/assignments/dns-parameters
UDPSize | = | 512
DNSThreadGroup | = | ThreadGroup.new

Public Class methods

new(config_info=nil)
open(*args) {|dns| ...}

Public Instance methods

close()
each_address(name) {|resource.address| ...}
each_name(address) {|resource.name| ...}
each_resource(name, typeclass, &proc)
extract_resources(msg, name, typeclass) {|data if n0 == n| ...}
getaddress(name)
getaddresses(name)
getname(address)
getnames(address)
getresource(name, typeclass)
getresources(name, typeclass)
lazy_initialize()


Class: Resolv::DNS::Config

Class | Resolv::DNS::Config
In: | lib/resolv.rb
Parent: | Object

Methods

default_config_hash generate_candidates generate_timeouts lazy_initialize new parse_resolv_conf resolv single?

Classes and Modules

Class Resolv::DNS::Config::NXDomain
Class Resolv::DNS::Config::OtherResolvError

Constants

InitialTimeout = 5

Public Class methods

default_config_hash(filename="/etc/resolv.conf")
new(config_info=nil)
parse_resolv_conf(filename)

Public Instance methods

generate_candidates(name)
generate_timeouts()
lazy_initialize()
resolv(name) {|candidate, tout, nameserver| ...}
single?()


Class: Resolv::DNS::Config::NXDomain

Class | Resolv::DNS::Config::NXDomain
In: | lib/resolv.rb
Parent: | ResolvError


Class: Resolv::DNS::Config::OtherResolvError

Class | Resolv::DNS::Config::OtherResolvError
In: | lib/resolv.rb
Parent: | ResolvError


Class: Resolv::DNS::DecodeError

Class | Resolv::DNS::DecodeError
In: | lib/resolv.rb
Parent: | StandardError


Class: Resolv::DNS::EncodeError

Class | Resolv::DNS::EncodeError
In: | lib/resolv.rb
Parent: | StandardError


Module: Resolv::DNS::Label

Module | Resolv::DNS::Label
In: | lib/resolv.rb

Methods

split

Classes and Modules

Class Resolv::DNS::Label::Str

Public Class methods

split(arg)


Class: Resolv::DNS::Label::Str

Class | Resolv::DNS::Label::Str
In: | lib/resolv.rb
Parent: | Object

Methods

== eql? hash inspect new to_s

Attributes

downcase | [R]
string | [R]

Public Class methods

new(string)

Public Instance methods

==(other)
eql?(other)
hash()
inspect()
to_s()


Class: Resolv::DNS::Message

Class | Resolv::DNS::Message
In: | lib/resolv.rb
Parent: | Object

Methods

== add_additional add_answer add_authority add_question decode each_additional each_answer each_authority each_question each_resource encode new

Classes and Modules

Class Resolv::DNS::Message::MessageDecoder
Class Resolv::DNS::Message::MessageEncoder

Attributes

aa | [RW]
additional | [R]
answer | [R]
authority | [R]
id | [RW]
opcode | [RW]
qr | [RW]
question | [R]
ra | [RW]
rcode | [RW]
rd | [RW]
tc | [RW]

Public Class methods

decode(m)
new(id = (@@identifier += 1) & 0xffff)

Public Instance methods

==(other)
add_additional(name, ttl, data)
add_answer(name, ttl, data)
add_authority(name, ttl, data)
add_question(name, typeclass)
each_additional() {|name, ttl, data| ...}
each_answer() {|name, ttl, data| ...}
each_authority() {|name, ttl, data| ...}
each_question() {|name, typeclass| ...}
each_resource() {|name, ttl, data| ...}
encode()


Class: Resolv::DNS::Message::MessageDecoder

Class | Resolv::DNS::Message::MessageDecoder
In: | lib/resolv.rb
Parent: | Object

Methods

get_bytes get_label get_labels get_length16 get_name get_question get_rr get_string get_string_list get_unpack new

Public Class methods

new(data) {|self| ...}

Public Instance methods

get_bytes(len = @limit - @index)
get_label()
get_labels(limit=nil)
get_length16() {|len| ...}
get_name()
get_question()
get_rr()
get_string()
get_string_list()
get_unpack(template)


Class: Resolv::DNS::Message::MessageEncoder

Class | Resolv::DNS::Message::MessageEncoder
In: | lib/resolv.rb
Parent: | Object

Methods

new put_bytes put_label put_labels put_length16 put_name put_pack put_string put_string_list to_s

Public Class methods

new() {|self| ...}

Public Instance methods

put_bytes(d)
put_label(d)
put_labels(d)
put_length16() {|| ...}
put_name(d)
put_pack(template, *d)
put_string(d)
put_string_list(ds)
to_s()


Class: Resolv::DNS::Name

Class | Resolv::DNS::Name
In: | lib/resolv.rb
Parent: | Object

Methods

== [] absolute? create eql? hash inspect length new subdomain_of? to_a to_s

Public Class methods

create(arg)
new(labels, absolute=true)

Public Instance methods

==(other)
[](i)
absolute?()
eql?(other)

Alias for #==

hash()
inspect()
length()
subdomain_of?(other)

tests subdomain-of relation.

  domain = Resolv::DNS::Name.create("y.z")
  p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
  p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
  p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
  p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
  p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
  p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
to_a()
to_s()

returns the domain name as a string.

The domain name doesn‘t have a trailing dot even if the name object is absolute.

  p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
  p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"


Module: Resolv::DNS::OpCode

Module | Resolv::DNS::OpCode
In: | lib/resolv.rb

Constants

Query | = | 0
IQuery | = | 1
Status | = | 2
Notify | = | 4
Update | = | 5


Class: Resolv::DNS::Query

Class | Resolv::DNS::Query
In: | lib/resolv.rb
Parent: | Object

Methods

decode_rdata encode_rdata

Public Class methods

decode_rdata(msg)

Public Instance methods

encode_rdata(msg)


Module: Resolv::DNS::RCode

Module | Resolv::DNS::RCode
In: | lib/resolv.rb

Constants

NoError | = | 0
FormErr | = | 1
ServFail | = | 2
NXDomain | = | 3
NotImp | = | 4
Refused | = | 5
YXDomain | = | 6
YXRRSet | = | 7
NXRRSet | = | 8
NotAuth | = | 9
NotZone | = | 10
BADVERS | = | 16
BADSIG | = | 16
BADKEY | = | 17
BADTIME | = | 18
BADMODE | = | 19
BADNAME | = | 20
BADALG | = | 21


Class: Resolv::DNS::Requester

Class | Resolv::DNS::Requester
In: | lib/resolv.rb
Parent: | Object

Methods

close delete new

Classes and Modules

Class Resolv::DNS::Requester::ConnectedUDP
Class Resolv::DNS::Requester::RequestError
Class Resolv::DNS::Requester::Sender
Class Resolv::DNS::Requester::TCP
Class Resolv::DNS::Requester::UnconnectedUDP

Public Class methods

new()

Public Instance methods

close()
delete(arg)


Class: Resolv::DNS::Requester::ConnectedUDP

Class | Resolv::DNS::Requester::ConnectedUDP
In: | lib/resolv.rb
Parent: | Requester

Methods

new sender

Classes and Modules

Class Resolv::DNS::Requester::ConnectedUDP::Sender

Public Class methods

new(host, port=Port)

Public Instance methods

sender(msg, data, queue, host=@host, port=@port)


Class: Resolv::DNS::Requester::ConnectedUDP::Sender

Class | Resolv::DNS::Requester::ConnectedUDP::Sender
In: | lib/resolv.rb
Parent: | Requester::Sender

Methods

send

Public Instance methods

send()


Class: Resolv::DNS::Requester::RequestError

Class | Resolv::DNS::Requester::RequestError
In: | lib/resolv.rb
Parent: | StandardError


Class: Resolv::DNS::Requester::Sender

Class | Resolv::DNS::Requester::Sender
In: | lib/resolv.rb
Parent: | Object

Methods

new recv

Attributes

queue [R]

Public Class methods

new(msg, data, sock, queue)

Public Instance methods

recv(msg)


Class: Resolv::DNS::Requester::TCP

Class | Resolv::DNS::Requester::TCP
In: | lib/resolv.rb
Parent: | Requester

Methods

new sender

Classes and Modules

Class Resolv::DNS::Requester::TCP::Sender

Public Class methods

new(host, port=Port)

Public Instance methods

sender(msg, data, queue, host=@host, port=@port)


Class: Resolv::DNS::Requester::TCP::Sender

Class | Resolv::DNS::Requester::TCP::Sender
In: | lib/resolv.rb
Parent: | Requester::Sender

Methods

send

Public Instance methods

send()


Class: Resolv::DNS::Requester::UnconnectedUDP

Class | Resolv::DNS::Requester::UnconnectedUDP
In: | lib/resolv.rb
Parent: | Requester

Methods

new sender

Classes and Modules

Class Resolv::DNS::Requester::UnconnectedUDP::Sender

Public Class methods

new()

Public Instance methods

sender(msg, data, queue, host, port=Port)


Class: Resolv::DNS::Requester::UnconnectedUDP::Sender

Class | Resolv::DNS::Requester::UnconnectedUDP::Sender
In: | lib/resolv.rb
Parent: | Requester::Sender

Methods

new send

Public Class methods

new(msg, data, sock, host, port, queue)

Public Instance methods

send()


Class: Resolv::DNS::Resource

Class | Resolv::DNS::Resource
In: | lib/resolv.rb
Parent: | Query

Methods

== decode_rdata encode_rdata eql? get_class hash

Classes and Modules

Module Resolv::DNS::Resource::IN
Class Resolv::DNS::Resource::ANY
Class Resolv::DNS::Resource::CNAME
Class Resolv::DNS::Resource::DomainName
Class Resolv::DNS::Resource::Generic
Class Resolv::DNS::Resource::HINFO
Class Resolv::DNS::Resource::MINFO
Class Resolv::DNS::Resource::MX
Class Resolv::DNS::Resource::NS
Class Resolv::DNS::Resource::PTR
Class Resolv::DNS::Resource::SOA
Class Resolv::DNS::Resource::TXT

Constants

ClassHash | = | {}
ClassValue | = | nil | Standard (class generic) RRs
ClassInsensitiveTypes | = | [ NS, CNAME, SOA, PTR, HINFO, MINFO, MX, TXT, ANY

Public Class methods

decode_rdata(msg)
get_class(type_value, class_value)

Public Instance methods

==(other)
encode_rdata(msg)
eql?(other)
hash()


Class: Resolv::DNS::Resource::ANY

Class | Resolv::DNS::Resource::ANY
In: | lib/resolv.rb
Parent: | Query

Constants

TypeValue = 255


Class: Resolv::DNS::Resource::CNAME

Class | Resolv::DNS::Resource::CNAME
In: | lib/resolv.rb
Parent: | DomainName

Constants

TypeValue = 5


Class: Resolv::DNS::Resource::DomainName

Class | Resolv::DNS::Resource::DomainName
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Attributes

name [R]

Public Class methods

decode_rdata(msg)
new(name)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::Generic

Class | Resolv::DNS::Resource::Generic
In: | lib/resolv.rb
Parent: | Resource

Methods

create decode_rdata encode_rdata new

Attributes

data [R]

Public Class methods

create(type_value, class_value)
decode_rdata(msg)
new(data)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::HINFO

Class | Resolv::DNS::Resource::HINFO
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 13

Attributes

cpu | [R]
os | [R]

Public Class methods

decode_rdata(msg)
new(cpu, os)

Public Instance methods

encode_rdata(msg)


Module: Resolv::DNS::Resource::IN

Module | Resolv::DNS::Resource::IN
In: | lib/resolv.rb

ARPA Internet specific RRs

Classes and Modules

Class Resolv::DNS::Resource::IN::A
Class Resolv::DNS::Resource::IN::AAAA
Class Resolv::DNS::Resource::IN::SRV
Class Resolv::DNS::Resource::IN::WKS

Constants

ClassValue = 1


Class: Resolv::DNS::Resource::IN::A

Class | Resolv::DNS::Resource::IN::A
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 1, ClassValue = ClassValue]] = self

Attributes

address [R]

Public Class methods

decode_rdata(msg)
new(address)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::IN::AAAA

Class | Resolv::DNS::Resource::IN::AAAA
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 28, ClassValue = ClassValue]] = self

Attributes

address [R]

Public Class methods

decode_rdata(msg)
new(address)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::IN::SRV

Class | Resolv::DNS::Resource::IN::SRV
In: | lib/resolv.rb
Parent: | Resource

SRV resource record defined in RFC 2782

These records identify the hostname and port that a service is available at.

The format is:

  _Service._Proto.Name TTL Class SRV Priority Weight Port Target

The fields specific to SRV are defined in RFC 2782 as meaning:

  • priority The priority of this target host. A client MUST attempt to contact the target host with the lowest-numbered priority it can reach; target hosts with the same priority SHOULD be tried in an order defined by the weight field. The range is 0-65535. Note that it is not widely implemented and should be set to zero.
  • weight A server selection mechanism. The weight field specifies a relative weight for entries with the same priority. Larger weights SHOULD be given a proportionately higher probability of being selected. The range of this number is 0-65535. Domain administrators SHOULD use Weight 0 when there isn‘t any server selection to do, to make the RR easier to read for humans (less noisy). Note that it is not widely implemented and should be set to zero.
  • port The port on this target host of this service. The range is 0- 65535.
  • target The domain name of the target host. A target of "." means that the service is decidedly not available at this domain.

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 33, ClassValue = ClassValue]] = self

Attributes

port | [R]
priority | [R]
target | [R]
weight | [R]

Public Class methods

decode_rdata(msg)
new(priority, weight, port, target)

Create a SRV resource record.

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::IN::WKS

Class | Resolv::DNS::Resource::IN::WKS
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 11, ClassValue = ClassValue]] = self

Attributes

address | [R]
bitmap | [R]
protocol | [R]

Public Class methods

decode_rdata(msg)
new(address, protocol, bitmap)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::MINFO

Class | Resolv::DNS::Resource::MINFO
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 14

Attributes

emailbx | [R]
rmailbx | [R]

Public Class methods

decode_rdata(msg)
new(rmailbx, emailbx)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::MX

Class | Resolv::DNS::Resource::MX
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 15

Attributes

exchange | [R]
preference | [R]

Public Class methods

decode_rdata(msg)
new(preference, exchange)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::NS

Class | Resolv::DNS::Resource::NS
In: | lib/resolv.rb
Parent: | DomainName

Constants

TypeValue = 2


Class: Resolv::DNS::Resource::PTR

Class | Resolv::DNS::Resource::PTR
In: | lib/resolv.rb
Parent: | DomainName

Constants

TypeValue = 12


Class: Resolv::DNS::Resource::SOA

Class | Resolv::DNS::Resource::SOA
In: | lib/resolv.rb
Parent: | Resource

Methods

decode_rdata encode_rdata new

Constants

TypeValue = 6

Attributes

expire | [R]
minimum | [R]
mname | [R]
refresh | [R]
retry | [R]
rname | [R]
serial | [R]

Public Class methods

decode_rdata(msg)
new(mname, rname, serial, refresh, retry_, expire, minimum)

Public Instance methods

encode_rdata(msg)


Class: Resolv::DNS::Resource::TXT

Class | Resolv::DNS::Resource::TXT
In: | lib/resolv.rb
Parent: | Resource

Methods

data decode_rdata encode_rdata new

Constants

TypeValue = 16

Attributes

strings [R]

Public Class methods

decode_rdata(msg)
new(first_string, *rest_strings)

Public Instance methods

data()
encode_rdata(msg)


Class: Resolv::Hosts

Class | Resolv::Hosts
In: | lib/resolv.rb
Parent: | Object

Methods

each_address each_name getaddress getaddresses getname getnames lazy_initialize new

Constants

DefaultFileName | = | Win32::Resolv.get_hosts_path
DefaultFileName | = | '/etc/hosts'

Public Class methods

new(filename = DefaultFileName)

Public Instance methods

each_address(name, &proc)
each_name(address, &proc)
getaddress(name)
getaddresses(name)
getname(address)
getnames(address)
lazy_initialize()


Class: Resolv::IPv4

Class | Resolv::IPv4
In: | lib/resolv.rb
Parent: | Object

Methods

== create eql? hash inspect new to_name to_s

Constants

Regex = /\A(\d+)\.(\d+)\.(\d+)\.(\d+)\z/

Attributes

address [R]

Public Class methods

create(arg)
new(address)

Public Instance methods

==(other)
eql?(other)
hash()
inspect()
to_name()
to_s()


Class: Resolv::IPv6

Class | Resolv::IPv6
In: | lib/resolv.rb
Parent: | Object

Methods

== create eql? hash inspect new to_name to_s

Constants

Regex_8Hex | = | /\A (?:[0-9A-Fa-f]{1,4}:){7} [0-9A-Fa-f]{1,4} \z/x
Regex_CompressedHex | = | /\A ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) :: ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) \z/x
Regex_6Hex4Dec | = | /\A ((?:[0-9A-Fa-f]{1,4}:){6,6}) (\d+)\.(\d+)\.(\d+)\.(\d+) \z/x
Regex_CompressedHex4Dec | = | /\A ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) :: ((?:[0-9A-Fa-f]{1,4}:)*) (\d+)\.(\d+)\.(\d+)\.(\d+) \z/x
Regex | = | / (?:#{Regex_8Hex}) | (?:#{Regex_CompressedHex}) | (?:#{Regex_6Hex4Dec}) | (?:#{Regex_CompressedHex4Dec})/x

Attributes

address [R]

Public Class methods

create(arg)
new(address)

Public Instance methods

==(other)
eql?(other)
hash()
inspect()
to_name()
to_s()


Class: Resolv::ResolvError

Class | Resolv::ResolvError
In: | lib/resolv.rb
Parent: | StandardError


Class: Resolv::ResolvTimeout

Class | Resolv::ResolvTimeout
In: | lib/resolv.rb
Parent: | TimeoutError


Module: RiDisplay

Module | RiDisplay
In: | lib/rdoc/ri/ri_display.rb

This is a kind of ‘flag’ module. If you want to write your own ‘ri’ display module (perhaps because you‘r writing an IDE or somesuch beast), you simply write a class which implements the various ‘display’ methods in ‘DefaultDisplay’, and include the ‘RiDisplay’ module in that class.

To access your class from the command line, you can do

   ruby -r <your source file>  ../ri ....

If folks really want to do this from the command line, I‘ll build an option in

Methods

append_features new

Public Class methods

append_features(display_class)
new(*args)


Class: RiDriver

Class | RiDriver
In: | lib/rdoc/ri/ri_driver.rb
Parent: | Object

Methods

get_info_for new process_args report_class_stuff report_method_stuff report_missing_documentation

Public Class methods

new()

Public Instance methods

get_info_for(arg)
process_args()
report_class_stuff(namespaces)
report_method_stuff(requested_method_name, methods)

If the list of matching methods contains exactly one entry, or if it contains an entry that exactly matches the requested method, then display that entry, otherwise display the list of matching method names

report_missing_documentation(path)

Couldn‘t find documentation in path, so tell the user what to do


Class: RiError

Class | RiError
In: | lib/rdoc/ri/ri_util.rb
Parent: | Exception


Module: Rinda

Module | Rinda
In: | lib/rinda/ring.rb lib/rinda/tuplespace.rb lib/rinda/rinda.rb

A module to implement the Linda distributed computing paradigm in Ruby.

Rinda is part of DRb (dRuby).

Example(s)

See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.

Classes and Modules

Class Rinda::DRbObjectTemplate
Class Rinda::InvalidHashTupleKey
Class Rinda::NotifyTemplateEntry
Class Rinda::RequestCanceledError
Class Rinda::RequestExpiredError
Class Rinda::RindaError
Class Rinda::RingFinger
Class Rinda::RingProvider
Class Rinda::RingServer
Class Rinda::SimpleRenewer
Class Rinda::Template
Class Rinda::TemplateEntry
Class Rinda::Tuple
Class Rinda::TupleBag
Class Rinda::TupleEntry
Class Rinda::TupleSpace
Class Rinda::TupleSpaceProxy
Class Rinda::WaitTemplateEntry

Constants

Ring_PORT = 7647 The default port Ring discovery will use.


Class: Rinda::DRbObjectTemplate

Class | Rinda::DRbObjectTemplate
In: | lib/rinda/rinda.rb
Parent: | Object

Documentation?

Methods

=== new

Public Class methods

new(uri=nil, ref=nil)

Creates a new DRbObjectTemplate that will match against uri and ref.

Public Instance methods

===(ro)

This DRbObjectTemplate matches ro if the remote object‘s drburi and drbref are the same. nil is used as a wildcard.


Class: Rinda::InvalidHashTupleKey

Class | Rinda::InvalidHashTupleKey
In: | lib/rinda/rinda.rb
Parent: | RindaError

Raised when a hash-based tuple has an invalid key.


Class: Rinda::NotifyTemplateEntry

Class | Rinda::NotifyTemplateEntry
In: | lib/rinda/tuplespace.rb
Parent: | TemplateEntry

A NotifyTemplateEntry is returned by TupleSpace#notify and is notified of TupleSpace changes. You may receive either your subscribed event or the ‘close’ event when iterating over notifications.

See TupleSpace#notify_event for valid notification types.

Example

  ts = Rinda::TupleSpace.new
  observer = ts.notify 'write', [nil]

  Thread.start do
    observer.each { |t| p t }
  end

  3.times { |i| ts.write [i] }

Outputs:

  ['write', [0]]
  ['write', [1]]
  ['write', [2]]

Methods

each new notify pop

Public Class methods

new(place, event, tuple, expires=nil)

Creates a new NotifyTemplateEntry that watches place for +event+s that match tuple.

Public Instance methods

each( {|event, tuple| ...}

Yields event/tuple pairs until this NotifyTemplateEntry expires.

notify(ev)

Called by TupleSpace to notify this NotifyTemplateEntry of a new event.

pop()

Retrieves a notification. Raises RequestExpiredError when this NotifyTemplateEntry expires.


Class: Rinda::RequestCanceledError

Class | Rinda::RequestCanceledError
In: | lib/rinda/rinda.rb
Parent: | ThreadError

Raised when trying to use a canceled tuple.


Class: Rinda::RequestExpiredError

Class | Rinda::RequestExpiredError
In: | lib/rinda/rinda.rb
Parent: | ThreadError

Raised when trying to use an expired tuple.


Class: Rinda::RindaError

Class | Rinda::RindaError
In: | lib/rinda/rinda.rb
Parent: | RuntimeError

Rinda error base class


Class: Rinda::RingFinger

Class | Rinda::RingFinger
In: | lib/rinda/ring.rb
Parent: | Object

RingFinger is used by RingServer clients to discover the RingServer‘s TupleSpace. Typically, all a client needs to do is call RingFinger.primary to retrieve the remote TupleSpace, which it can then begin using.

Methods

each finger lookup_ring lookup_ring_any new primary to_a to_a

Attributes

broadcast_list | [RW] | The list of addresses where RingFinger will send query packets.
port | [RW] | The port that RingFinger will send query packets to.
primary | [RW] | Contain the first advertised TupleSpace after lookup_ring_any is called.

Public Class methods

finger()

Creates a singleton RingFinger and looks for a RingServer. Returns the created RingFinger.

new(broadcast_list=@@broadcast_list, port=Ring_PORT)

Creates a new RingFinger that will look for RingServers at port on the addresses in broadcast_list.

primary()

Returns the first advertised TupleSpace.

to_a()

Contains all discoverd TupleSpaces except for the primary.

Public Instance methods

each() {|@primary| ...}

Iterates over all discovered TupleSpaces starting with the primary.

lookup_ring(timeout=5, &block)

Looks up RingServers waiting timeout seconds. RingServers will be given block as a callback, which will be called with the remote TupleSpace.

lookup_ring_any(timeout=5)

Returns the first found remote TupleSpace. Any further recovered TupleSpaces can be found by calling to_a.

to_a()

Contains all discovered TupleSpaces except for the primary.


Class: Rinda::RingProvider

Class | Rinda::RingProvider
In: | lib/rinda/ring.rb
Parent: | Object

RingProvider uses a RingServer advertised TupleSpace as a name service. TupleSpace clients can register themselves with the remote TupleSpace and look up other provided services via the remote TupleSpace.

Services are registered with a tuple of the format [:name, klass, DRbObject, description].

Methods

new provide

Public Class methods

new(klass, front, desc, renewer = nil)

Creates a RingProvider that will provide a klass service running on front, with a description. renewer is optional.

Public Instance methods

provide()

Advertises this service on the primary remote TupleSpace.


Class: Rinda::RingServer

Class | Rinda::RingServer
In: | lib/rinda/ring.rb
Parent: | Object

A RingServer allows a Rinda::TupleSpace to be located via UDP broadcasts. Service location uses the following steps:

  1. A RingServer begins listening on the broadcast UDP address.
  2. A RingFinger sends a UDP packet containing the DRb URI where it will listen for a reply.
  3. The RingServer recieves the UDP packet and connects back to the provided DRb URI with the DRb service.

Methods

do_reply do_write new reply_service write_service

Included Modules

DRbUndumped

Public Class methods

new(ts, port=Ring_PORT)

Advertises ts on the UDP broadcast address at port.

Public Instance methods

do_reply()

Pulls lookup tuples out of the TupleSpace and sends their DRb object the address of the local TupleSpace.

do_write(msg)

Extracts the response URI from msg and adds it to TupleSpace where it will be picked up by reply_service for notification.

reply_service()

Creates a thread that notifies waiting clients from the TupleSpace.

write_service()

Creates a thread that picks up UDP packets and passes them to do_write for decoding.


Class: Rinda::SimpleRenewer

Class | Rinda::SimpleRenewer
In: | lib/rinda/rinda.rb
Parent: | Object

An SimpleRenewer allows a TupleSpace to check if a TupleEntry is still alive.

Methods

new renew

Included Modules

DRbUndumped

Public Class methods

new(sec=180)

Creates a new SimpleRenewer that keeps an object alive for another sec seconds.

Public Instance methods

renew()

Called by the TupleSpace to check if the object is still alive.


Class: Rinda::Template

Class | Rinda::Template
In: | lib/rinda/rinda.rb
Parent: | Tuple

Templates are used to match tuples in Rinda.

Methods

=== match

Public Instance methods

===(tuple)

Alias for match.

match(tuple)

Matches this template against tuple. The tuple must be the same size as the template. An element with a nil value in a template acts as a wildcard, matching any value in the corresponding position in the tuple. Elements of the template match the tuple if the are #== or #===.

  Template.new([:foo, 5]).match   Tuple.new([:foo, 5]) # => true
  Template.new([:foo, nil]).match Tuple.new([:foo, 5]) # => true
  Template.new([String]).match    Tuple.new(['hello']) # => true

  Template.new([:foo]).match      Tuple.new([:foo, 5]) # => false
  Template.new([:foo, 6]).match   Tuple.new([:foo, 5]) # => false
  Template.new([:foo, nil]).match Tuple.new([:foo])    # => false
  Template.new([:foo, 6]).match   Tuple.new([:foo])    # => false


Class: Rinda::TemplateEntry

Class | Rinda::TemplateEntry
In: | lib/rinda/tuplespace.rb
Parent: | TupleEntry

A TemplateEntry is a Template together with expiry and cancellation data.

Methods

=== match

Public Instance methods

===(tuple)

Alias for match

match(tuple)

Matches this TemplateEntry against tuple. See Template#match for details on how a Template matches a Tuple.


Class: Rinda::Tuple

Class | Rinda::Tuple
In: | lib/rinda/rinda.rb
Parent: | Object

A tuple is the elementary object in Rinda programming. Tuples may be matched against templates if the tuple and the template are the same size.

Methods

[] each fetch new size value

Public Class methods

new(ary_or_hash)

Creates a new Tuple from ary_or_hash which must be an Array or Hash.

Public Instance methods

[](k)

Accessor method for elements of the tuple.

each( {|k, v| ...}

Iterate through the tuple, yielding the index or key, and the value, thus ensuring arrays are iterated similarly to hashes.

fetch(k)

Fetches item k from the tuple.

size()

The number of elements in the tuple.

value()

Return the tuple itself


Class: Rinda::TupleBag

Class | Rinda::TupleBag
In: | lib/rinda/tuplespace.rb
Parent: | Object

TupleBag is an unordered collection of tuples. It is the basis of Tuplespace.

Methods

delete delete_unless_alive find find_all find_all_template has_expires? push

Public Instance methods

delete(ary)

Removes ary from the TupleBag.

delete_unless_alive()

Delete tuples which dead tuples from the TupleBag, returning the deleted tuples.

find(template)

Finds a live tuple that matches template.

find_all(template)

Finds all live tuples that match template.

find_all_template(tuple)

Finds all tuples in the TupleBag which when treated as templates, match tuple and are alive.

has_expires?()

true if the TupleBag to see if it has any expired entries.

push(ary)

Add ary to the TupleBag.


Class: Rinda::TupleEntry

Class | Rinda::TupleEntry
In: | lib/rinda/tuplespace.rb
Parent: | Object

A TupleEntry is a Tuple (i.e. a possible entry in some Tuplespace) together with expiry and cancellation data.

Methods

[] alive? cancel canceled? expired? fetch make_expires make_tuple new renew size value

Included Modules

DRbUndumped

Attributes

expires [RW]

Public Class methods

new(ary, sec=nil)

Creates a TupleEntry based on ary with an optional renewer or expiry time sec.

A renewer must implement the renew method which returns a Numeric, nil, or true to indicate when the tuple has expired.

Public Instance methods

[](key)

Retrieves key from the tuple.

alive?()

A TupleEntry is dead when it is canceled or expired.

cancel()

Marks this TupleEntry as canceled.

canceled?()

Returns the canceled status.

expired?()

Has this tuple expired? (true/false).

A tuple has expired when its expiry timer based on the sec argument to initialize runs out.

fetch(key)

Fetches key from the tuple.

make_expires(sec=nil)

Returns an expiry Time based on sec which can be one of:

Numeric: | sec seconds into the future
true: | the expiry time is the start of 1970 (i.e. expired)
nil: | it is Tue Jan 19 03:14:07 GMT Standard Time 2038 (i.e. when UNIX clocks will die)
make_tuple(ary)

Creates a Rinda::Tuple for ary.

renew(sec_or_renewer)

Reset the expiry time according to sec_or_renewer.

nil: | it is set to expire in the far future.
false: | it has expired.
Numeric: | it will expire in that many seconds.

Otherwise the argument refers to some kind of renewer object which will reset its expiry time.

size()

The size of the tuple.

value()

Return the object which makes up the tuple itself: the Array or Hash.


Class: Rinda::TupleSpace

Class | Rinda::TupleSpace
In: | lib/rinda/tuplespace.rb
Parent: | Object

The Tuplespace manages access to the tuples it contains, ensuring mutual exclusion requirements are met.

The sec option for the write, take, move, read and notify methods may either be a number of seconds or a Renewer object.

Methods

move new notify read read_all take write

Included Modules

DRbUndumped MonitorMixin

Public Class methods

new(period=60)

Creates a new TupleSpace. period is used to control how often to look for dead tuples after modifications to the TupleSpace.

If no dead tuples are found period seconds after the last modification, the TupleSpace will stop looking for dead tuples.

Public Instance methods

move(port, tuple, sec=nil) {|template| ...}

Moves tuple to port.

notify(event, tuple, sec=nil)

Registers for notifications of event. Returns a NotifyTemplateEntry. See NotifyTemplateEntry for examples of how to listen for notifications.

event can be:

‘write’: | A tuple was added
‘take’: | A tuple was taken or moved
‘delete’: | A tuple was lost after being overwritten or expiring

The TupleSpace will also notify you of the ‘close’ event when the NotifyTemplateEntry has expired.

read(tuple, sec=nil) {|template| ...}

Reads tuple, but does not remove it.

read_all(tuple)

Returns all tuples matching tuple. Does not remove the found tuples.

take(tuple, sec=nil, &block)

Removes tuple

write(tuple, sec=nil)

Adds tuple


Class: Rinda::TupleSpaceProxy

Class | Rinda::TupleSpaceProxy
In: | lib/rinda/rinda.rb
Parent: | Object

TupleSpaceProxy allows a remote Tuplespace to appear as local.

Methods

new notify read read_all take write

Public Class methods

new(ts)

Creates a new TupleSpaceProxy to wrap ts.

Public Instance methods

notify(ev, tuple, sec=nil)

Registers for notifications of event ev on the proxied TupleSpace. See TupleSpace#notify

read(tuple, sec=nil, &block)

Reads tuple from the proxied TupleSpace. See TupleSpace#read.

read_all(tuple)

Reads all tuples matching tuple from the proxied TupleSpace. See TupleSpace#read_all.

take(tuple, sec=nil, &block)

Takes tuple from the proxied TupleSpace. See TupleSpace#take.

write(tuple, sec=nil)

Adds tuple to the proxied TupleSpace. See TupleSpace#write.


Class: Rinda::WaitTemplateEntry

Class | Rinda::WaitTemplateEntry
In: | lib/rinda/tuplespace.rb
Parent: | TemplateEntry

Documentation?

Methods

cancel new read signal wait

Attributes

found [R]

Public Class methods

new(place, ary, expires=nil)

Public Instance methods

cancel()
read(tuple)
signal()
wait()


Class: RubyLex

Class | RubyLex
In: | lib/irb/ruby-lex.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Object

Lexical analyzer for Ruby source

Methods

char_no debug? debug? each_top_level_statement eof? get_read get_readed getc getc getc_of_rests getc_of_rests gets gets identify_comment identify_comment identify_gvar identify_gvar identify_here_document identify_here_document identify_identifier identify_identifier identify_number identify_number identify_quotation identify_quotation identify_string identify_string initialize_input lex lex lex_init lex_init lex_int2 lex_int2 line_no new new peek peek peek_equal? peek_equal? peek_match? prompt read_escape read_escape set_input set_prompt skip_inner_expression token token ungetc ungetc

Included Modules

RubyToken RubyToken IRB

Classes and Modules

Class RubyLex::BufferedReader

Constants

ENINDENT_CLAUSE | = | [ "case", "class", "def", "do", "for", "if", "module", "unless", "until", "while", "begin"
DEINDENT_CLAUSE | = | ["end"
PERCENT_LTYPE | = | { "q" => "\'", "Q" => "\"", "x" => "\`", "r" => "/", "w" => "]", "W" => "]", "s" => ":"
PERCENT_PAREN | = | { "{" => "}", "[" => "]", "<" => ">", "(" => ")"
Ltype2Token | = | { "\'" => TkSTRING, "\"" => TkSTRING, "\`" => TkXSTRING, "/" => TkREGEXP, "]" => TkDSTRING, ":" => TkSYMBOL
DLtype2Token | = | { "\"" => TkDSTRING, "\`" => TkDXSTRING, "/" => TkDREGEXP, }
ENINDENT_CLAUSE | = | [ "case", "class", "def", "do", "for", "if", "module", "unless", "until", "while", "begin"
DEINDENT_CLAUSE | = | ["end"
PERCENT_LTYPE | = | { "q" => "\'", "Q" => "\"", "x" => "\`", "r" => "/", "w" => "]"
PERCENT_PAREN | = | { "{" => "}", "[" => "]", "<" => ">", "(" => ")"
Ltype2Token | = | { "\'" => TkSTRING, "\"" => TkSTRING, "\`" => TkXSTRING, "/" => TkREGEXP, "]" => TkDSTRING
DLtype2Token | = | { "\"" => TkDSTRING, "\`" => TkDXSTRING, "/" => TkDREGEXP, }

Attributes

char_no | [R]
continue | [R]
debug_level | [RW]
exception_on_syntax_error | [RW]
exception_on_syntax_error | [RW]
indent | [R]
indent | [R]
lex_state | [R]
line_no | [R]
read_auto_clean_up | [RW]
readed_auto_clean_up | [RW]
seek | [R]
skip_space | [RW]
skip_space | [RW]

Public Class methods

debug?()
debug?()
new()
new(content)

Public Instance methods

char_no()
each_top_level_statement() {|@line, @exp_line_no| ...}
eof?()
get_read()
get_readed()
getc()
getc()
getc_of_rests()
getc_of_rests()
gets()
gets()
identify_comment()
identify_comment()
identify_gvar()
identify_gvar()
identify_here_document()
identify_here_document()
identify_identifier()
identify_identifier()
identify_number(start)
identify_number()
identify_quotation(initial_char)
identify_quotation()
identify_string(ltype, quoted = ltype)
identify_string(ltype, quoted = ltype, opener=nil, initial_char = nil)
initialize_input()
lex()
lex()
lex_init()
lex_init()
lex_int2()
lex_int2()
line_no()

io functions

peek(i = 0)
peek(i = 0)
peek_equal?(str)
peek_equal?(str)
peek_match?(regexp)
prompt()
read_escape()
read_escape()
set_input(io, p = nil, &block)

io functions

set_prompt(p = nil, &block)
skip_inner_expression()
token()
token()
ungetc(c = nil)
ungetc(c = nil)


Class: RubyLex::BufferedReader

Class | RubyLex::BufferedReader
In: | lib/rdoc/parsers/parse_rb.rb
Parent: | Object

Read an input stream character by character. We allow for unlimited ungetting of characters just read.

We simplify the implementation greatly by reading the entire input into a buffer initially, and then simply traversing it using pointers.

We also have to allow for the here document diversion. This little gem comes about when the lexer encounters a here document. At this point we effectively need to split the input stream into two parts: one to read the body of the here document, the other to read the rest of the input line where the here document was initially encountered. For example, we might have

  do_something(<<-A, <<-B)
    stuff
    for
  A
    stuff
    for
  B

When the lexer encounters the <<A, it reads until the end of the line, and keeps it around for later. It then reads the body of the here document. Once complete, it needs to read the rest of the original line, but then skip the here document body.

Methods

column divert_read_from get_read getc getc_already_read new peek peek_equal ungetc

Attributes

line_num [R]

Public Class methods

new(content)

Public Instance methods

column()
divert_read_from(reserve)
get_read()
getc()
getc_already_read()
peek(at)
peek_equal(str)
ungetc(ch)


Module: RubyToken

Module | RubyToken
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb

Definitions of all tokens involved in the lexical analysis

Methods

Token Token def_token def_token set_token_position

Classes and Modules

Class RubyToken::TkError
Class RubyToken::TkId
Class RubyToken::TkKW
Class RubyToken::TkNode
Class RubyToken::TkOPASGN
Class RubyToken::TkOp
Class RubyToken::TkUnknownChar
Class RubyToken::TkVal
Class RubyToken::Token

Constants

EXPR_BEG = :EXPR_BEG
EXPR_MID = :EXPR_MID
EXPR_END = :EXPR_END
EXPR_ARG = :EXPR_ARG
EXPR_FNAME = :EXPR_FNAME
EXPR_DOT = :EXPR_DOT
EXPR_CLASS = :EXPR_CLASS
Symbol = Integer
TokenDefinitions = [ [:TkCLASS, TkId, "class", EXPR_CLASS], [:TkMODULE, TkId, "module", EXPR_BEG], [:TkDEF, TkId, "def", EXPR_FNAME], [:TkUNDEF, TkId, "undef", EXPR_FNAME], [:TkBEGIN, TkId, "begin", EXPR_BEG], [:TkRESCUE, TkId, "rescue", EXPR_MID], [:TkENSURE, TkId, "ensure", EXPR_BEG], [:TkEND, TkId, "end", EXPR_END], [:TkIF, TkId, "if", EXPR_BEG, :TkIF_MOD], [:TkUNLESS, TkId, "unless", EXPR_BEG, :TkUNLESS_MOD], [:TkTHEN, TkId, "then", EXPR_BEG], [:TkELSIF, TkId, "elsif", EXPR_BEG], [:TkELSE, TkId, "else", EXPR_BEG], [:TkCASE, TkId, "case", EXPR_BEG], [:TkWHEN, TkId, "when", EXPR_BEG], [:TkWHILE, TkId, "while", EXPR_BEG, :TkWHILE_MOD], [:TkUNTIL, TkId, "until", EXPR_BEG, :TkUNTIL_MOD], [:TkFOR, TkId, "for", EXPR_BEG], [:TkBREAK, TkId, "break", EXPR_END], [:TkNEXT, TkId, "next", EXPR_END], [:TkREDO, TkId, "redo", EXPR_END], [:TkRETRY, TkId, "retry", EXPR_END], [:TkIN, TkId, "in", EXPR_BEG], [:TkDO, TkId, "do", EXPR_BEG], [:TkRETURN, TkId, "return", EXPR_MID], [:TkYIELD, TkId, "yield", EXPR_END], [:TkSUPER, TkId, "super", EXPR_END], [:TkSELF, TkId, "self", EXPR_END], [:TkNIL, TkId, "nil", EXPR_END], [:TkTRUE, TkId, "true", EXPR_END], [:TkFALSE, TkId, "false", EXPR_END], [:TkAND, TkId, "and", EXPR_BEG], [:TkOR, TkId, "or", EXPR_BEG], [:TkNOT, TkId, "not", EXPR_BEG], [:TkIF_MOD, TkId], [:TkUNLESS_MOD, TkId], [:TkWHILE_MOD, TkId], [:TkUNTIL_MOD, TkId], [:TkALIAS, TkId, "alias", EXPR_FNAME], [:TkDEFINED, TkId, "defined?", EXPR_END], [:TklBEGIN, TkId, "BEGIN", EXPR_END], [:TklEND, TkId, "END", EXPR_END], [:Tk__LINE__, TkId, "__LINE__", EXPR_END], [:Tk__FILE__, TkId, "__FILE__", EXPR_END], [:TkIDENTIFIER, TkId], [:TkFID, TkId], [:TkGVAR, TkId], [:TkCVAR, TkId], [:TkIVAR, TkId], [:TkCONSTANT, TkId], [:TkINTEGER, TkVal], [:TkFLOAT, TkVal], [:TkSTRING, TkVal], [:TkXSTRING, TkVal], [:TkREGEXP, TkVal], [:TkSYMBOL, TkVal], [:TkDSTRING, TkNode], [:TkDXSTRING, TkNode], [:TkDREGEXP, TkNode], [:TkNTH_REF, TkNode], [:TkBACK_REF, TkNode], [:TkUPLUS, TkOp, "+@"], [:TkUMINUS, TkOp, "-@"], [:TkPOW, TkOp, "**"], [:TkCMP, TkOp, "<=>"], [:TkEQ, TkOp, "=="], [:TkEQQ, TkOp, "==="], [:TkNEQ, TkOp, "!="], [:TkGEQ, TkOp, ">="], [:TkLEQ, TkOp, "<="], [:TkANDOP, TkOp, "&&"], [:TkOROP, TkOp, "||"], [:TkMATCH, TkOp, "=~"], [:TkNMATCH, TkOp, "!~"], [:TkDOT2, TkOp, ".."], [:TkDOT3, TkOp, "..."], [:TkAREF, TkOp, "[]"], [:TkASET, TkOp, "[]="], [:TkLSHFT, TkOp, "<<"], [:TkRSHFT, TkOp, ">>"], [:TkCOLON2, TkOp], [:TkCOLON3, TkOp], # [:OPASGN, TkOp], # +=, -= etc. # [:TkASSOC, TkOp, "=>"], [:TkQUESTION, TkOp, "?"], #? [:TkCOLON, TkOp, ":"], #: [:TkfLPAREN], # func( # [:TkfLBRACK], # func[ # [:TkfLBRACE], # func{ # [:TkSTAR], # *arg [:TkAMPER], # &arg # [:TkSYMBEG], # :SYMBOL [:TkGT, TkOp, ">"], [:TkLT, TkOp, "<"], [:TkPLUS, TkOp, "+"], [:TkMINUS, TkOp, "-"], [:TkMULT, TkOp, "*"], [:TkDIV, TkOp, "/"], [:TkMOD, TkOp, "%"], [:TkBITOR, TkOp, "|"], [:TkBITXOR, TkOp, "^"], [:TkBITAND, TkOp, "&"], [:TkBITNOT, TkOp, "~"], [:TkNOTOP, TkOp, "!"], [:TkBACKQUOTE, TkOp, "`"], [:TkASSIGN, Token, "="], [:TkDOT, Token, "."], [:TkLPAREN, Token, "("], #(exp) [:TkLBRACK, Token, "["], #[arry] [:TkLBRACE, Token, "{"], #{hash} [:TkRPAREN, Token, ")"], [:TkRBRACK, Token, "]"], [:TkRBRACE, Token, "}"], [:TkCOMMA, Token, ","], [:TkSEMICOLON, Token, ";"], [:TkCOMMENT], [:TkRD_COMMENT], [:TkSPACE], [:TkNL], [:TkEND_OF_SCRIPT], [:TkBACKSLASH, TkUnknownChar, "\\"], [:TkAT, TkUnknownChar, "@"], [:TkDOLLAR, TkUnknownChar, "$"], ]
TkReading2Token = {} {reading => token_class} {reading => [token_class, *opt]}
TkSymbol2Token = {}
EXPR_BEG = :EXPR_BEG
EXPR_MID = :EXPR_MID
EXPR_END = :EXPR_END
EXPR_ARG = :EXPR_ARG
EXPR_FNAME = :EXPR_FNAME
EXPR_DOT = :EXPR_DOT
EXPR_CLASS = :EXPR_CLASS
TokenDefinitions = [ [:TkCLASS, TkKW, "class", EXPR_CLASS], [:TkMODULE, TkKW, "module", EXPR_BEG], [:TkDEF, TkKW, "def", EXPR_FNAME], [:TkUNDEF, TkKW, "undef", EXPR_FNAME], [:TkBEGIN, TkKW, "begin", EXPR_BEG], [:TkRESCUE, TkKW, "rescue", EXPR_MID], [:TkENSURE, TkKW, "ensure", EXPR_BEG], [:TkEND, TkKW, "end", EXPR_END], [:TkIF, TkKW, "if", EXPR_BEG, :TkIF_MOD], [:TkUNLESS, TkKW, "unless", EXPR_BEG, :TkUNLESS_MOD], [:TkTHEN, TkKW, "then", EXPR_BEG], [:TkELSIF, TkKW, "elsif", EXPR_BEG], [:TkELSE, TkKW, "else", EXPR_BEG], [:TkCASE, TkKW, "case", EXPR_BEG], [:TkWHEN, TkKW, "when", EXPR_BEG], [:TkWHILE, TkKW, "while", EXPR_BEG, :TkWHILE_MOD], [:TkUNTIL, TkKW, "until", EXPR_BEG, :TkUNTIL_MOD], [:TkFOR, TkKW, "for", EXPR_BEG], [:TkBREAK, TkKW, "break", EXPR_END], [:TkNEXT, TkKW, "next", EXPR_END], [:TkREDO, TkKW, "redo", EXPR_END], [:TkRETRY, TkKW, "retry", EXPR_END], [:TkIN, TkKW, "in", EXPR_BEG], [:TkDO, TkKW, "do", EXPR_BEG], [:TkRETURN, TkKW, "return", EXPR_MID], [:TkYIELD, TkKW, "yield", EXPR_END], [:TkSUPER, TkKW, "super", EXPR_END], [:TkSELF, TkKW, "self", EXPR_END], [:TkNIL, TkKW, "nil", EXPR_END], [:TkTRUE, TkKW, "true", EXPR_END], [:TkFALSE, TkKW, "false", EXPR_END], [:TkAND, TkKW, "and", EXPR_BEG], [:TkOR, TkKW, "or", EXPR_BEG], [:TkNOT, TkKW, "not", EXPR_BEG], [:TkIF_MOD, TkKW], [:TkUNLESS_MOD, TkKW], [:TkWHILE_MOD, TkKW], [:TkUNTIL_MOD, TkKW], [:TkALIAS, TkKW, "alias", EXPR_FNAME], [:TkDEFINED, TkKW, "defined?", EXPR_END], [:TklBEGIN, TkKW, "BEGIN", EXPR_END], [:TklEND, TkKW, "END", EXPR_END], [:Tk__LINE__, TkKW, "__LINE__", EXPR_END], [:Tk__FILE__, TkKW, "__FILE__", EXPR_END], [:TkIDENTIFIER, TkId], [:TkFID, TkId], [:TkGVAR, TkId], [:TkIVAR, TkId], [:TkCONSTANT, TkId], [:TkINTEGER, TkVal], [:TkFLOAT, TkVal], [:TkSTRING, TkVal], [:TkXSTRING, TkVal], [:TkREGEXP, TkVal], [:TkCOMMENT, TkVal], [:TkDSTRING, TkNode], [:TkDXSTRING, TkNode], [:TkDREGEXP, TkNode], [:TkNTH_REF, TkId], [:TkBACK_REF, TkId], [:TkUPLUS, TkOp, "+@"], [:TkUMINUS, TkOp, "-@"], [:TkPOW, TkOp, "**"], [:TkCMP, TkOp, "<=>"], [:TkEQ, TkOp, "=="], [:TkEQQ, TkOp, "==="], [:TkNEQ, TkOp, "!="], [:TkGEQ, TkOp, ">="], [:TkLEQ, TkOp, "<="], [:TkANDOP, TkOp, "&&"], [:TkOROP, TkOp, "||"], [:TkMATCH, TkOp, "=~"], [:TkNMATCH, TkOp, "!~"], [:TkDOT2, TkOp, ".."], [:TkDOT3, TkOp, "..."], [:TkAREF, TkOp, "[]"], [:TkASET, TkOp, "[]="], [:TkLSHFT, TkOp, "<<"], [:TkRSHFT, TkOp, ">>"], [:TkCOLON2, TkOp], [:TkCOLON3, TkOp], # [:OPASGN, TkOp], # +=, -= etc. # [:TkASSOC, TkOp, "=>"], [:TkQUESTION, TkOp, "?"], #? [:TkCOLON, TkOp, ":"], #: [:TkfLPAREN], # func( # [:TkfLBRACK], # func[ # [:TkfLBRACE], # func{ # [:TkSTAR], # *arg [:TkAMPER], # &arg # [:TkSYMBOL, TkId], # :SYMBOL [:TkSYMBEG, TkId], [:TkGT, TkOp, ">"], [:TkLT, TkOp, "<"], [:TkPLUS, TkOp, "+"], [:TkMINUS, TkOp, "-"], [:TkMULT, TkOp, "*"], [:TkDIV, TkOp, "/"], [:TkMOD, TkOp, "%"], [:TkBITOR, TkOp, "|"], [:TkBITXOR, TkOp, "^"], [:TkBITAND, TkOp, "&"], [:TkBITNOT, TkOp, "~"], [:TkNOTOP, TkOp, "!"], [:TkBACKQUOTE, TkOp, "`"], [:TkASSIGN, Token, "="], [:TkDOT, Token, "."], [:TkLPAREN, Token, "("], #(exp) [:TkLBRACK, Token, "["], #[arry] [:TkLBRACE, Token, "{"], #{hash} [:TkRPAREN, Token, ")"], [:TkRBRACK, Token, "]"], [:TkRBRACE, Token, "}"], [:TkCOMMA, Token, ","], [:TkSEMICOLON, Token, ";"], [:TkRD_COMMENT], [:TkSPACE], [:TkNL], [:TkEND_OF_SCRIPT], [:TkBACKSLASH, TkUnknownChar, "\\"], [:TkAT, TkUnknownChar, "@"], [:TkDOLLAR, TkUnknownChar, "\$"], #" ]
TkReading2Token = {} {reading => token_class} {reading => [token_class, *opt]}
TkSymbol2Token = {}
NEWLINE_TOKEN = TkNL.new(0,0)

Public Class methods

def_token(token_n, super_token = Token, reading = nil, *opts)
def_token(token_n, super_token = Token, reading = nil, *opts)

Public Instance methods

Token(token, value = nil)
Token(token, value = nil)
set_token_position(line, char)


Class: RubyToken::TkError

Class | RubyToken::TkError
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Token


Class: RubyToken::TkId

Class | RubyToken::TkId
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new new

Attributes

name | [R]
name | [R]

Public Class methods

new(seek, line_no, char_no, name)
new(line_no, char_no, name)


Class: RubyToken::TkKW

Class | RubyToken::TkKW
In: | lib/rdoc/parsers/parse_rb.rb
Parent: | TkId


Class: RubyToken::TkNode

Class | RubyToken::TkNode
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new

Attributes

node | [R]
node | [R]

Public Class methods

new(seek, line_no, char_no)


Class: RubyToken::TkOPASGN

Class | RubyToken::TkOPASGN
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | TkOp

Methods

new new

Attributes

op | [R]
op | [R]

Public Class methods

new(seek, line_no, char_no, op)
new(line_no, char_no, op)


Class: RubyToken::TkOp

Class | RubyToken::TkOp
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

name

Attributes

name [RW]

Public Instance methods

name()


Class: RubyToken::TkUnknownChar

Class | RubyToken::TkUnknownChar
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new new

Attributes

name | [R]
name | [R]

Public Class methods

new(seek, line_no, char_no, id)
new(line_no, char_no, id)


Class: RubyToken::TkVal

Class | RubyToken::TkVal
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Token

Methods

new new

Attributes

value [R]

Public Class methods

new(seek, line_no, char_no, value = nil)
new(line_no, char_no, value = nil)


Class: RubyToken::Token

Class | RubyToken::Token
In: | lib/irb/ruby-token.rb lib/rdoc/parsers/parse_rb.rb
Parent: | Object

Methods

new new set_text

Constants

NO_TEXT = "??".freeze

Attributes

char_no | [R]
char_no | [R]
line_no | [R]
line_no | [R]
seek | [R]
text | [R]
text | [R]

Public Class methods

new(seek, line_no, char_no)
new(line_no, char_no)

Public Instance methods

set_text(text)

Because we‘re used in contexts that expect to return a token, we set the text string and then return ourselves


Class: RuntimeError

Class | RuntimeError
In: | error.c
Parent: | StandardError


Class: SM::AttrChanger

Class | SM::AttrChanger
In: | lib/rdoc/markup/simple_markup/inline.rb
Parent: | Object

Methods

to_s

Public Instance methods

to_s()


Class: SM::AttrSpan

Class | SM::AttrSpan
In: | lib/rdoc/markup/simple_markup/inline.rb
Parent: | Object

An array of attributes which parallels the characters in a string

Methods

[] new set_attrs

Public Class methods

new(length)

Public Instance methods

[](n)
set_attrs(start, length, bits)


Class: SM::Attribute

Class | SM::Attribute
In: | lib/rdoc/markup/simple_markup/inline.rb
Parent: | Object

We manage a set of attributes. Each attribute has a symbol name and a bit value

Methods

as_string bitmap_for each_name_of

Constants

SPECIAL = 1

Public Class methods

as_string(bitmap)
bitmap_for(name)
each_name_of(bitmap) {|name.to_s if (bitmap & bit) != 0| ...}


Class: SM::AttributeManager

Class | SM::AttributeManager
In: | lib/rdoc/markup/simple_markup/inline.rb
Parent: | Object

Methods

add_html add_special add_word_pair attribute change_attribute changed_attribute_by_name convert_attrs convert_html convert_specials copy_string display_attributes flow mask_protected_sequences new split_into_flow unmask_protected_sequences

Constants

NULL | = | "\000".freeze
A_PROTECT | = | 004 | We work by substituting non-printing characters in to the text. For now I‘m assuming that I can substitute a character in the range 0..8 for a 7 bit character without damaging the encoded string, but this might be optimistic
PROTECT_ATTR | = | A_PROTECT.chr
MATCHING_WORD_PAIRS | = | {} | This maps delimiters that occur around words (such as bold or tt) where the start and end delimiters and the same. This lets us optimize the regexp
WORD_PAIR_MAP | = | {} | And this is used when the delimiters aren‘t the same. In this case the hash maps a pattern to the attribute character
HTML_TAGS | = | {} | This maps HTML tags to the corresponding attribute char
SPECIAL | = | {} | And this maps special sequences to a name. A special sequence is something like a WikiWord
PROTECTABLE | = | [ "<" << "\\" ] | A \ in front of a character that would normally be processed turns off processing. We do this by turning < into <#{PROTECT}

Public Class methods

new()

Public Instance methods

add_html(tag, name)
add_special(pattern, name)
add_word_pair(start, stop, name)
attribute(turn_on, turn_off)

Return an attribute object with the given turn_on and turn_off bits set

change_attribute(current, new)
changed_attribute_by_name(current_set, new_set)
convert_attrs(str, attrs)

Map attributes like textto the sequence \001\002<char>\001\003<char>, where <char> is a per-attribute specific character

convert_html(str, attrs)
convert_specials(str, attrs)
copy_string(start_pos, end_pos)
display_attributes()
flow(str)
mask_protected_sequences()
split_into_flow()
unmask_protected_sequences()


Class: SM::BlankLine

Class | SM::BlankLine
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Paragraph


Module: SM::Flow

Module | SM::Flow
In: | lib/rdoc/markup/simple_markup/to_flow.rb

Classes and Modules

Class SM::Flow::LIST

Constants

P | = | Struct.new(:body)
VERB | = | Struct.new(:body)
RULE | = | Struct.new(:width)
LI | = | Struct.new(:label, :body)
H | = | Struct.new(:level, :text)


Class: SM::Flow::LIST

Class | SM::Flow::LIST
In: | lib/rdoc/markup/simple_markup/to_flow.rb
Parent: | Object

Methods

<< new

Attributes

contents | [R]
type | [R]

Public Class methods

new(type)

Public Instance methods

<<(stuff)


Class: SM::Fragment

Class | SM::Fragment
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Object

A Fragment is a chunk of text, subclassed as a paragraph, a list entry, or verbatim text

Methods

add_text for new to_s type_name

Constants

TYPE_MAP = {} This is a simple factory system that lets us associate fragement types (a string) with a subclass of fragment

Attributes

level | [R]
param | [R]
txt | [R]
type | [RW]

Public Class methods

for(line)
new(level, param, type, txt)
type_name(name)

Public Instance methods

add_text(txt)
to_s()


Class: SM::Heading

Class | SM::Heading
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Paragraph

Methods

head_level

Public Instance methods

head_level()


Class: SM::Line

Class | SM::Line
In: | lib/rdoc/markup/simple_markup/lines.rb
Parent: | Object

Methods

isBlank? new stamp strip_leading to_s

Constants

INFINITY | = | 9999
BLANK | = | :BLANK
HEADING | = | :HEADING
LIST | = | :LIST
RULE | = | :RULE
PARAGRAPH | = | :PARAGRAPH
VERBATIM | = | :VERBATIM

Attributes

deleted | [RW] | true if this line has been deleted from the list of lines
flag | [RW] | A flag. For list lines, this is the type of the list
leading_spaces | [RW] | the number of leading spaces
level | [RW] | The indentation nesting level
param | [RW] | A prefix or parameter. For LIST lines, this is the text that introduced the list item (the label)
text | [RW] | The contents
type | [RW] | line type

Public Class methods

new(text)

Public Instance methods

isBlank?()

Return true if this line is blank

stamp(type, level, param="", flag=nil)

stamp a line with a type, a level, a prefix, and a flag

strip_leading(size)

Strip off the leading margin

to_s()


Class: SM::LineCollection

Class | SM::LineCollection
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Object

Collect groups of lines together. Each group will end up containing a flow of text

Methods

accept add each fragment_for new normalize to_a to_s

Public Class methods

new()

Public Instance methods

accept(am, visitor)
add(fragment)
each(&b)
fragment_for(*args)

Factory for different fragment types

normalize()

tidy up at the end

to_a()

For testing

to_s()


Class: SM::Lines

Class | SM::Lines
In: | lib/rdoc/markup/simple_markup/lines.rb
Parent: | Object

A container for all the lines

Methods

as_text delete each empty? line_types new next normalize rewind unget

Included Modules

Enumerable

Attributes

lines [R]

Public Class methods

new(lines)

Public Instance methods

as_text()
delete(a_line)
each() {|line unless line.deleted| ...}
empty?()
line_types()
next()
normalize()
rewind()

def [](index)

  @lines[index]

end

unget()


Class: SM::ListBase

Class | SM::ListBase
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Paragraph

A List is a fragment with some kind of label

Constants

BULLET | = | :BULLET | List types
NUMBER | = | :NUMBER
UPPERALPHA | = | :UPPERALPHA
LOWERALPHA | = | :LOWERALPHA
LABELED | = | :LABELED
NOTE | = | :NOTE


Class: SM::ListEnd

Class | SM::ListEnd
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | ListBase

Methods

new

Public Class methods

new(level, type)


Class: SM::ListItem

Class | SM::ListItem
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | ListBase


Class: SM::ListStart

Class | SM::ListStart
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | ListBase

Methods

new

Public Class methods

new(level, param, type)


Class: SM::Paragraph

Class | SM::Paragraph
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Fragment

A paragraph is a fragment which gets wrapped to fit. We remove all newlines when we‘re created, and have them put back on output


Class: SM::PreProcess

Class | SM::PreProcess
In: | lib/rdoc/markup/simple_markup/preprocess.rb
Parent: | Object

Handle common directives that can occur in a block of text:

: include : filename

Methods

handle new

Public Class methods

new(input_file_name, include_path)

Public Instance methods

handle(text) {|directive, param| ...}

Look for common options in a chunk of text. Options that we don‘t handle are passed back to our caller as |directive, param|


Class: SM::Rule

Class | SM::Rule
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Fragment

A horizontal rule


Class: SM::SimpleMarkup

Class | SM::SimpleMarkup
In: | lib/rdoc/markup/simple_markup.rb
Parent: | Object

Synopsis

This code converts input_string, which is in the format described in markup/simple_markup.rb, to HTML. The conversion takes place in the convert method, so you can use the same SimpleMarkup object to convert multiple input strings.

  require 'rdoc/markup/simple_markup'
  require 'rdoc/markup/simple_markup/to_html'

  p = SM::SimpleMarkup.new
  h = SM::ToHtml.new

  puts p.convert(input_string, h)

You can extend the SimpleMarkup parser to recognise new markup sequences, and to add special processing for text that matches a regular epxression. Here we make WikiWords significant to the parser, and also make the sequences {word} and <no>text…</no> signify strike-through text. When then subclass the HTML output class to deal with these:

  require 'rdoc/markup/simple_markup'
  require 'rdoc/markup/simple_markup/to_html'

  class WikiHtml < SM::ToHtml
    def handle_special_WIKIWORD(special)
      "<font color=red>" + special.text + "</font>"
    end
  end

  p = SM::SimpleMarkup.new
  p.add_word_pair("{", "}", :STRIKE)
  p.add_html("no", :STRIKE)

  p.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)

  h = WikiHtml.new
  h.add_tag(:STRIKE, "<strike>", "</strike>")

  puts "<body>" + p.convert(ARGF.read, h) + "</body>"

Output Formatters

missing

Methods

add_html add_special add_word_pair content convert get_line_types new

Constants

SPACE = ?\s
SIMPLE_LIST_RE = /^( ( \* (?# bullet) |- (?# bullet) |\d+\. (?# numbered ) |[A-Za-z]\. (?# alphabetically numbered ) ) \s+ )\S/x List entries look like:
 *       text
 1.      text
 [label] text
 label:: text

Flag it as a list entry, and work out the indent for subsequent lines

LABEL_LIST_RE = /^( ( \[.*?\] (?# labeled ) |\S.*:: (?# note ) )(?:\s+|$) )/x

Public Class methods

new()

take a block of text and use various heuristics to determine it‘s structure (paragraphs, lists, and so on). Invoke an event handler as we identify significant chunks.

Public Instance methods

add_html(tag, name)

Add to the sequences recognized as general markup

add_special(pattern, name)

Add to other inline sequences. For example, we could add WikiWords using something like:

   parser.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)

Each wiki word will be presented to the output formatter via the accept_special method

add_word_pair(start, stop, name)

Add to the sequences used to add formatting to an individual word (such as bold). Matching entries will generate attibutes that the output formatters can recognize by their name

content()

for debugging, we allow access to our line contents as text

convert(str, op)

We take a string, split it into lines, work out the type of each line, and from there deduce groups of lines (for example all lines in a paragraph). We then invoke the output formatter using a Visitor to display the result

get_line_types()

for debugging, return the list of line types


Class: SM::Special

Class | SM::Special
In: | lib/rdoc/markup/simple_markup/inline.rb
Parent: | Object

Hold details of a special sequence

Methods

== new to_s

Attributes

text | [RW]
type | [R]

Public Class methods

new(type, text)

Public Instance methods

==(o)
to_s()


Class: SM::ToFlow

Class | SM::ToFlow
In: | lib/rdoc/markup/simple_markup/to_flow.rb
Parent: | Object

Methods

accept_blank_line accept_heading accept_list_end accept_list_item accept_list_start accept_paragraph accept_rule accept_verbatim add_tag annotate end_accepting init_tags new start_accepting

Constants

LIST_TYPE_TO_HTML | = | { SM::ListBase::BULLET => [ "<ul>", "</ul>" ], SM::ListBase::NUMBER => [ "<ol>", "</ol>" ], SM::ListBase::UPPERALPHA => [ "<ol>", "</ol>" ], SM::ListBase::LOWERALPHA => [ "<ol>", "</ol>" ], SM::ListBase::LABELED => [ "<dl>", "</dl>" ], SM::ListBase::NOTE => [ "<table>", "</table>" ], }
InlineTag | = | Struct.new(:bit, :on, :off)

Public Class methods

new()

Public Instance methods

accept_blank_line(am, fragment)
accept_heading(am, fragment)
accept_list_end(am, fragment)
accept_list_item(am, fragment)
accept_list_start(am, fragment)
accept_paragraph(am, fragment)
accept_rule(am, fragment)
accept_verbatim(am, fragment)
add_tag(name, start, stop)

Add a new set of HTML tags for an attribute. We allow separate start and end tags for flexibility

annotate(tag)

Given an HTML tag, decorate it with class information and the like if required. This is a no-op in the base class, but is overridden in HTML output classes that implement style sheets

end_accepting()
init_tags()

Set up the standard mapping of attributes to HTML tags

start_accepting()

Here‘s the client side of the visitor pattern


Class: SM::ToHtml

Class | SM::ToHtml
In: | lib/rdoc/markup/simple_markup/to_html.rb
Parent: | Object

Methods

accept_blank_line accept_heading accept_list_end accept_list_item accept_list_start accept_paragraph accept_rule accept_verbatim add_tag annotate end_accepting init_tags new start_accepting wrap

Constants

LIST_TYPE_TO_HTML | = | { ListBase::BULLET => [ "<ul>", "</ul>" ], ListBase::NUMBER => [ "<ol>", "</ol>" ], ListBase::UPPERALPHA => [ "<ol>", "</ol>" ], ListBase::LOWERALPHA => [ "<ol>", "</ol>" ], ListBase::LABELED => [ "<dl>", "</dl>" ], ListBase::NOTE => [ "<table>", "</table>" ], }
InlineTag | = | Struct.new(:bit, :on, :off)

Public Class methods

new()

Public Instance methods

accept_blank_line(am, fragment)
accept_heading(am, fragment)
accept_list_end(am, fragment)
accept_list_item(am, fragment)
accept_list_start(am, fragment)
accept_paragraph(am, fragment)
accept_rule(am, fragment)
accept_verbatim(am, fragment)
add_tag(name, start, stop)

Add a new set of HTML tags for an attribute. We allow separate start and end tags for flexibility

annotate(tag)

Given an HTML tag, decorate it with class information and the like if required. This is a no-op in the base class, but is overridden in HTML output classes that implement style sheets

end_accepting()
init_tags()

Set up the standard mapping of attributes to HTML tags

start_accepting()

Here‘s the client side of the visitor pattern

wrap(txt, line_len = 76)

This is a higher speed (if messier) version of wrap


Class: SM::ToLaTeX

Class | SM::ToLaTeX
In: | lib/rdoc/markup/simple_markup/to_latex.rb
Parent: | Object

Convert SimpleMarkup to basic LaTeX report format

Methods

accept_blank_line accept_heading accept_list_end accept_list_item accept_list_start accept_paragraph accept_rule accept_verbatim add_tag end_accepting escape init_tags l l new start_accepting wrap

Constants

BS | = | "\020"
CB | = | "\022"
DL | = | "\023"
BACKSLASH | = | "#{BS}symbol#{OB}92#{CB}"
HAT | = | "#{BS}symbol#{OB}94#{CB}"
BACKQUOTE | = | "#{BS}symbol#{OB}0#{CB}"
TILDE | = | "#{DL}#{BS}sim#{DL}"
LESSTHAN | = | "#{DL}<#{DL}"
GREATERTHAN | = | "#{DL}>#{DL}"
LIST_TYPE_TO_LATEX | = | { ListBase::BULLET => [ l("\\begin{itemize}"), l("\\end{itemize}") ], ListBase::NUMBER => [ l("\\begin{enumerate}"), l("\\end{enumerate}"), "\\arabic" ], ListBase::UPPERALPHA => [ l("\\begin{enumerate}"), l("\\end{enumerate}"), "\\Alph" ], ListBase::LOWERALPHA => [ l("\\begin{enumerate}"), l("\\end{enumerate}"), "\\alph" ], ListBase::LABELED => [ l("\\begin{description}"), l("\\end{description}") ], ListBase::NOTE => [ l("\\begin{tabularx}{\\linewidth}{@{} l X @{}}"), l("\\end{tabularx}") ], }
InlineTag | = | Struct.new(:bit, :on, :off)

Public Class methods

l(str)
new()

Public Instance methods

accept_blank_line(am, fragment)
accept_heading(am, fragment)
accept_list_end(am, fragment)
accept_list_item(am, fragment)
accept_list_start(am, fragment)
accept_paragraph(am, fragment)
accept_rule(am, fragment)
accept_verbatim(am, fragment)
add_tag(name, start, stop)

Add a new set of LaTeX tags for an attribute. We allow separate start and end tags for flexibility

end_accepting()
escape(str)

Escape a LaTeX string

init_tags()

Set up the standard mapping of attributes to LaTeX

l(arg)
start_accepting()

Here‘s the client side of the visitor pattern

wrap(txt, line_len = 76)

This is a higher speed (if messier) version of wrap


Class: SM::Verbatim

Class | SM::Verbatim
In: | lib/rdoc/markup/simple_markup/fragments.rb
Parent: | Fragment

Verbatim code contains lines that don‘t get wrapped.

Methods

add_text

Public Instance methods

add_text(txt)


Module: SOAP
In: lib/soap/httpconfigloader.rb
lib/soap/wsdlDriver.rb
lib/soap/mapping/registry.rb
lib/soap/mapping/mapping.rb
lib/soap/mapping/factory.rb
lib/soap/mapping/rubytypeFactory.rb
lib/soap/mapping/wsdlliteralregistry.rb
lib/soap/mapping/typeMap.rb
lib/soap/mapping/wsdlencodedregistry.rb
lib/soap/streamHandler.rb
lib/soap/netHttpClient.rb
lib/soap/processor.rb
lib/soap/mimemessage.rb
lib/soap/generator.rb
lib/soap/marshal.rb
lib/soap/element.rb
lib/soap/attachment.rb
lib/soap/property.rb
lib/soap/baseData.rb
lib/soap/rpc/cgistub.rb
lib/soap/rpc/router.rb
lib/soap/rpc/driver.rb
lib/soap/rpc/httpserver.rb
lib/soap/rpc/element.rb
lib/soap/rpc/standaloneServer.rb
lib/soap/rpc/proxy.rb
lib/soap/rpc/soaplet.rb
lib/soap/rpc/rpc.rb
lib/soap/soap.rb
lib/soap/encodingstyle/aspDotNetHandler.rb
lib/soap/encodingstyle/handler.rb
lib/soap/encodingstyle/literalHandler.rb
lib/soap/encodingstyle/soapHandler.rb
lib/soap/parser.rb
lib/soap/header/handler.rb
lib/soap/header/handlerset.rb
lib/soap/header/simplehandler.rb

This program is copyrighted free software by NAKAMURA, Hiroshi. You can redistribute it and/or modify it under the same terms of Ruby‘s license; either the dual license version in 2003, or any later version.

Methods

get_content new post proxy= reset reset_all save_cookie_store set_basic_auth set_cookie_store test_loopback_response

Classes and Modules

Module SOAP::EncodingStyle
Module SOAP::Env
Module SOAP::HTTPConfigLoader
Module SOAP::Header
Module SOAP::Mapping
Module SOAP::Marshal
Module SOAP::Marshallable
Module SOAP::Processor
Module SOAP::RPC
Module SOAP::SOAPBasetype
Module SOAP::SOAPCompoundtype
Module SOAP::SOAPEnvelopeElement
Module SOAP::SOAPModuleUtils
Module SOAP::SOAPType
Class SOAP::ArrayIndexOutOfBoundsError
Class SOAP::ArrayStoreError
Class SOAP::Attachment
Class SOAP::EmptyResponseError
Class SOAP::Error
Class SOAP::FaultError
Class SOAP::HTTPStreamError
Class SOAP::HTTPStreamHandler
Class SOAP::MIMEMessage
Class SOAP::MPostUnavailableError
Class SOAP::NetHttpClient
Class SOAP::Parser
Class SOAP::PostUnavailableError
Class SOAP::Property
Class SOAP::RPCRoutingError
Class SOAP::Response
Class SOAP::ResponseFormatError
Class SOAP::SOAPAnySimpleType
Class SOAP::SOAPAnyURI
Class SOAP::SOAPArray
Class SOAP::SOAPAttachment
Class SOAP::SOAPBase64
Class SOAP::SOAPBody
Class SOAP::SOAPBoolean
Class SOAP::SOAPByte
Class SOAP::SOAPDate
Class SOAP::SOAPDateTime
Class SOAP::SOAPDecimal
Class SOAP::SOAPDouble
Class SOAP::SOAPDuration
Class SOAP::SOAPElement
Class SOAP::SOAPEnvelope
Class SOAP::SOAPExternalReference
Class SOAP::SOAPFault
Class SOAP::SOAPFloat
Class SOAP::SOAPGDay
Class SOAP::SOAPGMonth
Class SOAP::SOAPGMonthDay
Class SOAP::SOAPGYear
Class SOAP::SOAPGYearMonth
Class SOAP::SOAPGenerator
Class SOAP::SOAPHeader
Class SOAP::SOAPHeaderItem
Class SOAP::SOAPHexBinary
Class SOAP::SOAPInt
Class SOAP::SOAPInteger
Class SOAP::SOAPLong
Class SOAP::SOAPNegativeInteger
Class SOAP::SOAPNil
Class SOAP::SOAPNonNegativeInteger
Class SOAP::SOAPNonPositiveInteger
Class SOAP::SOAPPositiveInteger
Class SOAP::SOAPQName
Class SOAP::SOAPRawString
Class SOAP::SOAPReference
Class SOAP::SOAPShort
Class SOAP::SOAPString
Class SOAP::SOAPStruct
Class SOAP::SOAPTime
Class SOAP::SOAPUnsignedByte
Class SOAP::SOAPUnsignedInt
Class SOAP::SOAPUnsignedLong
Class SOAP::SOAPUnsignedShort
Class SOAP::SessionManager
Class SOAP::StreamError
Class SOAP::StreamHandler
Class SOAP::UnhandledMustUnderstandHeaderError
Class SOAP::WSDLDriver
Class SOAP::WSDLDriverFactory

Constants

TypeMap = { XSD::XSDAnySimpleType::Type => SOAPAnySimpleType, XSD::XSDString::Type => SOAPString, XSD::XSDBoolean::Type => SOAPBoolean, XSD::XSDDecimal::Type => SOAPDecimal, XSD::XSDFloat::Type => SOAPFloat, XSD::XSDDouble::Type => SOAPDouble, XSD::XSDDuration::Type => SOAPDuration, XSD::XSDDateTime::Type => SOAPDateTime, XSD::XSDTime::Type => SOAPTime, XSD::XSDDate::Type => SOAPDate, XSD::XSDGYearMonth::Type => SOAPGYearMonth, XSD::XSDGYear::Type => SOAPGYear, XSD::XSDGMonthDay::Type => SOAPGMonthDay, XSD::XSDGDay::Type => SOAPGDay, XSD::XSDGMonth::Type => SOAPGMonth, XSD::XSDHexBinary::Type => SOAPHexBinary, XSD::XSDBase64Binary::Type => SOAPBase64, XSD::XSDAnyURI::Type => SOAPAnyURI, XSD::XSDQName::Type => SOAPQName, XSD::XSDInteger::Type => SOAPInteger, XSD::XSDNonPositiveInteger::Type => SOAPNonPositiveInteger, XSD::XSDNegativeInteger::Type => SOAPNegativeInteger, XSD::XSDLong::Type => SOAPLong, XSD::XSDInt::Type => SOAPInt, XSD::XSDShort::Type => SOAPShort, XSD::XSDByte::Type => SOAPByte, XSD::XSDNonNegativeInteger::Type => SOAPNonNegativeInteger, XSD::XSDUnsignedLong::Type => SOAPUnsignedLong, XSD::XSDUnsignedInt::Type => SOAPUnsignedInt, XSD::XSDUnsignedShort::Type => SOAPUnsignedShort, XSD::XSDUnsignedByte::Type => SOAPUnsignedByte, XSD::XSDPositiveInteger::Type => SOAPPositiveInteger, SOAP::SOAPBase64::Type => SOAPBase64, }
NO_PROXY_HOSTS = ['localhost']
VERSION = Version = '1.5.5'
PropertyName = 'soap/property'
EnvelopeNamespace = 'http://schemas.xmlsoap.org/soap/envelope/'
EncodingNamespace = 'http://schemas.xmlsoap.org/soap/encoding/'
LiteralNamespace = 'http://xml.apache.org/xml-soap/literalxml'
NextActor = 'http://schemas.xmlsoap.org/soap/actor/next'
EleEnvelope = 'Envelope'
EleHeader = 'Header'
EleBody = 'Body'
EleFault = 'Fault'
EleFaultString = 'faultstring'
EleFaultActor = 'faultactor'
EleFaultCode = 'faultcode'
EleFaultDetail = 'detail'
AttrMustUnderstand = 'mustUnderstand'
AttrEncodingStyle = 'encodingStyle'
AttrActor = 'actor'
AttrRoot = 'root'
AttrArrayType = 'arrayType'
AttrOffset = 'offset'
AttrPosition = 'position'
ValueArray = 'Array'
EleEnvelopeName = XSD::QName.new(EnvelopeNamespace, EleEnvelope).freeze
EleHeaderName = XSD::QName.new(EnvelopeNamespace, EleHeader).freeze
EleBodyName = XSD::QName.new(EnvelopeNamespace, EleBody).freeze
EleFaultName = XSD::QName.new(EnvelopeNamespace, EleFault).freeze
EleFaultStringName = XSD::QName.new(nil, EleFaultString).freeze
EleFaultActorName = XSD::QName.new(nil, EleFaultActor).freeze
EleFaultCodeName = XSD::QName.new(nil, EleFaultCode).freeze
EleFaultDetailName = XSD::QName.new(nil, EleFaultDetail).freeze
AttrMustUnderstandName = XSD::QName.new(EnvelopeNamespace, AttrMustUnderstand).freeze
AttrEncodingStyleName = XSD::QName.new(EnvelopeNamespace, AttrEncodingStyle).freeze
AttrRootName = XSD::QName.new(EncodingNamespace, AttrRoot).freeze
AttrArrayTypeName = XSD::QName.new(EncodingNamespace, AttrArrayType).freeze
AttrOffsetName = XSD::QName.new(EncodingNamespace, AttrOffset).freeze
AttrPositionName = XSD::QName.new(EncodingNamespace, AttrPosition).freeze
ValueArrayName = XSD::QName.new(EncodingNamespace, ValueArray).freeze
Base64Literal = 'base64'
SOAPNamespaceTag = 'env'
XSDNamespaceTag = 'xsd'
XSINamespaceTag = 'xsi'
MediaType = 'text/xml'

Attributes

connect_timeout | [RW]
debug_dev | [RW]
no_proxy | [RW]
protocol_version | [RW]
proxy | [R]
receive_timeout | [RW]
send_timeout | [RW]
ssl_config | [RW]

Public Class methods

new(proxy = nil, agent = nil)

Public Instance methods

get_content(url, header = {})
post(url, req_body, header = {})
proxy=(proxy)
reset(url)
reset_all()
save_cookie_store(filename)
set_basic_auth(uri, user_id, passwd)
set_cookie_store(filename)
test_loopback_response()


Class: SOAP::ArrayIndexOutOfBoundsError

Class | SOAP::ArrayIndexOutOfBoundsError
In: | lib/soap/soap.rb
Parent: | Error


Class: SOAP::ArrayStoreError

Class | SOAP::ArrayStoreError
In: | lib/soap/soap.rb
Parent: | Error


Class: SOAP::Attachment

Class | SOAP::Attachment
In: | lib/soap/attachment.rb
Parent: | Object

Methods

content contentid contentid contentid= mime_contentid mime_contentid new save to_s write

Attributes

contenttype | [RW]
io | [R]

Public Class methods

contentid(obj)
mime_contentid(obj)
new(string_or_readable = nil)

Public Instance methods

content()
contentid()
contentid=(contentid)
mime_contentid()
save(filename)
to_s()
write(out)


Class: SOAP::EmptyResponseError

Class | SOAP::EmptyResponseError
In: | lib/soap/soap.rb
Parent: | Error


Module: SOAP::EncodingStyle

Module | SOAP::EncodingStyle
In: | lib/soap/encodingstyle/aspDotNetHandler.rb lib/soap/encodingstyle/handler.rb lib/soap/encodingstyle/literalHandler.rb lib/soap/encodingstyle/soapHandler.rb

Classes and Modules

Class SOAP::EncodingStyle::ASPDotNetHandler
Class SOAP::EncodingStyle::Handler
Class SOAP::EncodingStyle::LiteralHandler
Class SOAP::EncodingStyle::SOAPHandler


Class: SOAP::EncodingStyle::ASPDotNetHandler

Class | SOAP::EncodingStyle::ASPDotNetHandler
In: | lib/soap/encodingstyle/aspDotNetHandler.rb
Parent: | Handler

Methods

decode_epilogue decode_parent decode_prologue decode_tag decode_tag_end decode_text encode_data encode_data_end new

Classes and Modules

Class SOAP::EncodingStyle::ASPDotNetHandler::SOAPTemporalObject
Class SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown

Constants

Namespace = 'http://tempuri.org/ASP.NET'

Public Class methods

new(charset = nil)

Public Instance methods

decode_epilogue()
decode_parent(parent, node)
decode_prologue()
decode_tag(ns, elename, attrs, parent)
decode_tag_end(ns, node)
decode_text(ns, text)
encode_data(generator, ns, data, parent)

encode interface.

encode_data_end(generator, ns, data, parent)


Class: SOAP::EncodingStyle::ASPDotNetHandler::SOAPTemporalObject

Class | SOAP::EncodingStyle::ASPDotNetHandler::SOAPTemporalObject
In: | lib/soap/encodingstyle/aspDotNetHandler.rb
Parent: | Object

decode interface.

Methods

new

Attributes

parent [RW]

Public Class methods

new()


Class: SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown

Class | SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown
In: | lib/soap/encodingstyle/aspDotNetHandler.rb
Parent: | SOAPTemporalObject

Methods

as_nil as_string as_struct new

Public Class methods

new(handler, elename)

Public Instance methods

as_nil()
as_string()
as_struct()


Class: SOAP::EncodingStyle::Handler

Class | SOAP::EncodingStyle::Handler
In: | lib/soap/encodingstyle/handler.rb
Parent: | Object

Methods

decode_epilogue decode_prologue decode_tag decode_tag_end decode_text decode_typemap= each encode_data encode_data_end encode_epilogue encode_prologue handler new uri

Classes and Modules

Class SOAP::EncodingStyle::Handler::EncodingStyleError

Attributes

charset | [R]
generate_explicit_type | [RW]

Public Class methods

each() {|value| ...}
handler(uri)
new(charset)
uri()

Public Instance methods

decode_epilogue()
decode_prologue()
decode_tag(ns, name, attrs, parent)
 decode interface.

Returns SOAP/OM data.

decode_tag_end(ns, name)
decode_text(ns, text)
decode_typemap=(definedtypes)
encode_data(generator, ns, data, parent)
 encode interface.

Returns a XML instance as a string.

encode_data_end(generator, ns, data, parent)
encode_epilogue()
encode_prologue()


Class: SOAP::EncodingStyle::Handler::EncodingStyleError

Class | SOAP::EncodingStyle::Handler::EncodingStyleError
In: | lib/soap/encodingstyle/handler.rb
Parent: | Error


Class: SOAP::EncodingStyle::LiteralHandler

Class | SOAP::EncodingStyle::LiteralHandler
In: | lib/soap/encodingstyle/literalHandler.rb
Parent: | Handler

Methods

decode_attrs decode_epilogue decode_parent decode_prologue decode_tag decode_tag_end decode_text encode_data encode_data_end new

Classes and Modules

Class SOAP::EncodingStyle::LiteralHandler::SOAPTemporalObject
Class SOAP::EncodingStyle::LiteralHandler::SOAPUnknown

Constants

Namespace = SOAP::LiteralNamespace

Public Class methods

new(charset = nil)

Public Instance methods

decode_attrs(ns, attrs)
decode_epilogue()
decode_parent(parent, node)
decode_prologue()
decode_tag(ns, elename, attrs, parent)
decode_tag_end(ns, node)
decode_text(ns, text)
encode_data(generator, ns, data, parent)

encode interface.

encode_data_end(generator, ns, data, parent)


Class: SOAP::EncodingStyle::LiteralHandler::SOAPTemporalObject

Class | SOAP::EncodingStyle::LiteralHandler::SOAPTemporalObject
In: | lib/soap/encodingstyle/literalHandler.rb
Parent: | Object

decode interface.

Methods

new

Attributes

parent [RW]

Public Class methods

new()


Class: SOAP::EncodingStyle::LiteralHandler::SOAPUnknown

Class | SOAP::EncodingStyle::LiteralHandler::SOAPUnknown
In: | lib/soap/encodingstyle/literalHandler.rb
Parent: | SOAPTemporalObject

Methods

as_element as_nil as_string new

Public Class methods

new(handler, elename, extraattr)

Public Instance methods

as_element()
as_nil()
as_string()


Class: SOAP::EncodingStyle::SOAPHandler

Class | SOAP::EncodingStyle::SOAPHandler
In: | lib/soap/encodingstyle/soapHandler.rb
Parent: | Handler

Methods

decode_epilogue decode_parent decode_prologue decode_tag decode_tag_end decode_text encode_data encode_data_end new

Classes and Modules

Class SOAP::EncodingStyle::SOAPHandler::SOAPTemporalObject
Class SOAP::EncodingStyle::SOAPHandler::SOAPUnknown

Constants

Namespace | = | SOAP::EncodingNamespace
NilLiteralMap | = | { 'true' => true, '1' => true, 'false' => false, '0' => false
RootLiteralMap | = | { '1' => 1, '0' => 0

Public Class methods

new(charset = nil)

Public Instance methods

decode_epilogue()
decode_parent(parent, node)
decode_prologue()
decode_tag(ns, elename, attrs, parent)
decode_tag_end(ns, node)
decode_text(ns, text)
encode_data(generator, ns, data, parent)

encode interface.

encode_data_end(generator, ns, data, parent)


Class: SOAP::EncodingStyle::SOAPHandler::SOAPTemporalObject

Class | SOAP::EncodingStyle::SOAPHandler::SOAPTemporalObject
In: | lib/soap/encodingstyle/soapHandler.rb
Parent: | Object

decode interface.

Methods

new

Attributes

id | [RW]
parent | [RW]
position | [RW]
root | [RW]

Public Class methods

new()


Class: SOAP::EncodingStyle::SOAPHandler::SOAPUnknown

Class | SOAP::EncodingStyle::SOAPHandler::SOAPUnknown
In: | lib/soap/encodingstyle/soapHandler.rb
Parent: | SOAPTemporalObject

Methods

as_nil as_string as_struct new

Attributes

definedtype | [RW]
extraattr | [R]
type | [R]

Public Class methods

new(handler, elename, type, extraattr)

Public Instance methods

as_nil()
as_string()
as_struct()


Module: SOAP::Env

Module | SOAP::Env
In: | lib/soap/soap.rb

Methods

getenv

Constants

HTTP_PROXY | = | use_proxy ? getenv('http_proxy') : nil
NO_PROXY | = | use_proxy ? getenv('no_proxy') : nil

Public Class methods

getenv(name)


Class: SOAP::Error

Class | SOAP::Error
In: | lib/soap/soap.rb
Parent: | StandardError


Class: SOAP::FaultError

Class | SOAP::FaultError
In: | lib/soap/soap.rb
Parent: | Error

Methods

new to_s

Attributes

detail | [RW]
faultactor | [R]
faultcode | [R]
faultstring | [R]

Public Class methods

new(fault)

Public Instance methods

to_s()


Module: SOAP::HTTPConfigLoader

Module | SOAP::HTTPConfigLoader
In: | lib/soap/httpconfigloader.rb

Methods

cert_from_file key_from_file set_basic_auth set_options set_ssl_config ssl_config_int

Public Instance methods

cert_from_file(filename)
key_from_file(filename)
set_basic_auth(client, basic_auth)
set_options(client, options)
set_ssl_config(client, ssl_config)
ssl_config_int(value)


Class: SOAP::HTTPStreamError

Class | SOAP::HTTPStreamError
In: | lib/soap/soap.rb
Parent: | StreamError


Class: SOAP::HTTPStreamHandler

Class | SOAP::HTTPStreamHandler
In: | lib/soap/streamHandler.rb
Parent: | StreamHandler

Methods

accept_encoding_gzip= inspect new reset send test_loopback_response

Included Modules

SOAP

Constants

Client | = | HTTPAccess2::Client
RETRYABLE | = | true
Client | = | SOAP::NetHttpClient
RETRYABLE | = | false
MAX_RETRY_COUNT | = | 10

Attributes

client | [R]
wiredump_file_base | [RW]

Public Class methods

new(options)

Public Instance methods

accept_encoding_gzip=(allow)
inspect()
reset(endpoint_url = nil)
send(endpoint_url, conn_data, soapaction = nil, charset = @charset)
test_loopback_response()


Module: SOAP::Header

Module | SOAP::Header
In: | lib/soap/header/handler.rb lib/soap/header/handlerset.rb lib/soap/header/simplehandler.rb

Classes and Modules

Class SOAP::Header::Handler
Class SOAP::Header::HandlerSet
Class SOAP::Header::SimpleHandler


Class: SOAP::Header::Handler

Class | SOAP::Header::Handler
In: | lib/soap/header/handler.rb
Parent: | Object

Methods

new on_inbound on_inbound_headeritem on_outbound on_outbound_headeritem

Attributes

elename | [R]
encodingstyle | [R]
mustunderstand | [R]

Public Class methods

new(elename)

Public Instance methods

on_inbound(header, mustunderstand = false)

Given header is a SOAPHeaderItem or nil.

on_inbound_headeritem(header)
on_outbound()

Should return a SOAP/OM, a SOAPHeaderItem or nil.

on_outbound_headeritem()


Class: SOAP::Header::HandlerSet

Class | SOAP::Header::HandlerSet
In: | lib/soap/header/handlerset.rb
Parent: | Object

Methods

<< add delete dup include? new on_inbound on_outbound store=

Public Class methods

new()

Public Instance methods

<<(handler)

Alias for add

add(handler)
delete(handler)
dup()
include?(handler)
on_inbound(headers)

headers: SOAPHeaderItem enumerable object

on_outbound()

returns: Array of SOAPHeaderItem

Protected Instance methods

store=(store)


Class: SOAP::Header::SimpleHandler

Class | SOAP::Header::SimpleHandler
In: | lib/soap/header/simplehandler.rb
Parent: | SOAP::Header::Handler

Methods

new on_inbound on_outbound on_simple_inbound on_simple_outbound

Public Class methods

new(elename)

Public Instance methods

on_inbound(header, mustunderstand)
on_outbound()
on_simple_inbound(header, mustunderstand)

Given header is a Hash, String or nil.

on_simple_outbound()

Should return a Hash, String or nil.


Class: SOAP::MIMEMessage

Class | SOAP::MIMEMessage
In: | lib/soap/mimemessage.rb
Parent: | Object

Classes for MIME message handling. Should be put somewhere else! Tried using the ‘tmail’ module but found that I needed something lighter in weight.

Methods

add_attachment add_part boundary close content_str has_parts? headers_str new parse parse root to_s

Classes and Modules

Class SOAP::MIMEMessage::Header
Class SOAP::MIMEMessage::Headers
Class SOAP::MIMEMessage::MIMEMessageError
Class SOAP::MIMEMessage::Part

Constants

MultipartContentType = 'multipart/\w+'

Attributes

headers | [R]
parts | [R]

Public Class methods

new()
parse(head, str)

Public Instance methods

add_attachment(attach)
add_part(content)
boundary()
close()
content_str()
has_parts?()
headers_str()
parse(head, str)
root()
to_s()


Class: SOAP::MIMEMessage::Header

Class | SOAP::MIMEMessage::Header
In: | lib/soap/mimemessage.rb
Parent: | Object

Methods

[] []= new to_s

Attributes

key | [RW]
root | [RW]
str | [RW]

Public Class methods

new()

Public Instance methods

[](key)
[]=(key, value)
to_s()


Class: SOAP::MIMEMessage::Headers

Class | SOAP::MIMEMessage::Headers
In: | lib/soap/mimemessage.rb
Parent: | Hash

Methods

add parse parse parse_line parse_rhs to_s

Public Class methods

parse(str)

Public Instance methods

add(key, value)
parse(str)
parse_line(line)
parse_rhs(str)
to_s()


Class: SOAP::MIMEMessage::MIMEMessageError

Class | SOAP::MIMEMessage::MIMEMessageError
In: | lib/soap/mimemessage.rb
Parent: | StandardError


Class: SOAP::MIMEMessage::Part

Class | SOAP::MIMEMessage::Part
In: | lib/soap/mimemessage.rb
Parent: | Object

Methods

contentid new parse parse to_s

External Aliases

body -> content

Attributes

body | [RW]
headers | [RW]

Public Class methods

new()
parse(str)

Public Instance methods

contentid()
parse(str)
to_s()


Class: SOAP::MPostUnavailableError

Class | SOAP::MPostUnavailableError
In: | lib/soap/soap.rb
Parent: | HTTPStreamError


Module: SOAP::Mapping

Module | SOAP::Mapping
In: | lib/soap/mapping/registry.rb lib/soap/mapping/mapping.rb lib/soap/mapping/factory.rb lib/soap/mapping/rubytypeFactory.rb lib/soap/mapping/wsdlliteralregistry.rb lib/soap/mapping/wsdlencodedregistry.rb lib/soap/attachment.rb

Methods

_obj2soap _soap2obj ary2md ary2soap class2element class2qname class_from_name const_from_name create_empty_object create_empty_object define_attr_accessor define_singleton_method elename2name fault2exception get_attribute module_from_name name2elename obj2element obj2soap schema_attribute_definition schema_element_definition schema_ns_definition schema_type_definition set_attributes soap2obj

Classes and Modules

Module SOAP::Mapping::MappedException
Module SOAP::Mapping::TraverseSupport
Class SOAP::Mapping::ArrayFactory_
Class SOAP::Mapping::AttachmentFactory
Class SOAP::Mapping::Base64Factory_
Class SOAP::Mapping::BasetypeFactory_
Class SOAP::Mapping::DateTimeFactory_
Class SOAP::Mapping::Factory
Class SOAP::Mapping::HashFactory_
Class SOAP::Mapping::MappingError
Class SOAP::Mapping::Object
Class SOAP::Mapping::Registry
Class SOAP::Mapping::RubytypeFactory
Class SOAP::Mapping::SOAPException
Class SOAP::Mapping::StringFactory_
Class SOAP::Mapping::TypedArrayFactory_
Class SOAP::Mapping::TypedStructFactory_
Class SOAP::Mapping::URIFactory_
Class SOAP::Mapping::WSDLEncodedRegistry
Class SOAP::Mapping::WSDLLiteralRegistry

Constants

RubyTypeName | = | XSD::QName.new(RubyTypeInstanceNamespace, 'rubyType')
RubyExtendName | = | XSD::QName.new(RubyTypeInstanceNamespace, 'extends')
RubyIVarName | = | XSD::QName.new(RubyTypeInstanceNamespace, 'ivars')
DefaultRegistry | = | Registry.new
RubyOriginalRegistry | = | Registry.new(:allow_original_mapping => true)
RubyTypeNamespace | = | 'http://www.ruby-lang.org/xmlns/ruby/type/1.6'
RubyTypeInstanceNamespace | = | 'http://www.ruby-lang.org/xmlns/ruby/type-instance'
RubyCustomTypeNamespace | = | 'http://www.ruby-lang.org/xmlns/ruby/type/custom'
ApacheSOAPTypeNamespace | = | 'http://xml.apache.org/xml-soap'
EMPTY_OPT | = | {}
MARSHAL_TAG | = | { String => ['"', 1], Regexp => ['/', 2], Array => ['[', 1], Hash => ['{', 1]
MapQName | = | XSD::QName.new(ApacheSOAPTypeNamespace, 'Map')

Public Class methods

_obj2soap(obj, registry, type = nil)
_soap2obj(node, registry, klass = nil)
ary2md(ary, rank, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)
ary2soap(ary, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)
class2element(klass)
class2qname(klass)
class_from_name(name, lenient = false)
const_from_name(name, lenient = false)
create_empty_object(klass)

ruby/1.7 or later.

create_empty_object(klass)
define_attr_accessor(obj, name, getterproc, setterproc = nil)
define_singleton_method(obj, name, &block)
elename2name(name)
fault2exception(fault, registry = nil)
get_attribute(obj, attr_name)
module_from_name(name, lenient = false)
name2elename(name)

Allow only (Letter | ‘_’) (Letter | Digit | ’-’ | ‘_’)* here. Caution: ’.’ is not allowed here. To follow XML spec., it should be NCName.

  (denied chars) => .[0-F][0-F]
  ex. a.b => a.2eb
obj2element(obj)
obj2soap(obj, registry = nil, type = nil, opt = EMPTY_OPT)
schema_attribute_definition(klass)
schema_element_definition(klass)
schema_ns_definition(klass)
schema_type_definition(klass)
set_attributes(obj, values)
soap2obj(node, registry = nil, klass = nil, opt = EMPTY_OPT)


Class: SOAP::Mapping::ArrayFactory_

Class | SOAP::Mapping::ArrayFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

Public Instance methods

obj2soap(soap_class, obj, info, map)
[1], [2]
is converted to Array of Array, not 2-D Array.

To create M-D Array, you must call Mapping.ary2md.

soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::AttachmentFactory

Class | SOAP::Mapping::AttachmentFactory
In: | lib/soap/attachment.rb
Parent: | SOAP::Mapping::Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::Base64Factory_

Class | SOAP::Mapping::Base64Factory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::BasetypeFactory_

Class | SOAP::Mapping::BasetypeFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::DateTimeFactory_

Class | SOAP::Mapping::DateTimeFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::Factory

Class | SOAP::Mapping::Factory
In: | lib/soap/mapping/factory.rb
Parent: | Object

Methods

new obj2soap setiv2obj setiv2soap soap2obj

Included Modules

TraverseSupport

Public Class methods

new()

Public Instance methods

obj2soap(soap_class, obj, info, map)
setiv2obj(obj, node, map)
setiv2soap(node, obj, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::HashFactory_

Class | SOAP::Mapping::HashFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Module: SOAP::Mapping::MappedException

Module | SOAP::Mapping::MappedException
In: | lib/soap/mapping/registry.rb


Class: SOAP::Mapping::MappingError

Class | SOAP::Mapping::MappingError
In: | lib/soap/mapping/registry.rb
Parent: | Error


Class: SOAP::Mapping::Object

Class | SOAP::Mapping::Object
In: | lib/soap/mapping/registry.rb
Parent: | Object

For anyType object: SOAP::Mapping::Object not ::Object

Methods

[] []= __add_xmlele_value __xmlattr __xmlele inspect new

Included Modules

Marshallable

Public Class methods

new()

Public Instance methods

[](qname)
[]=(qname, value)
__add_xmlele_value(qname, value)
__xmlattr()
__xmlele()
inspect()


Class: SOAP::Mapping::Registry

Class | SOAP::Mapping::Registry
In: | lib/soap/mapping/registry.rb
Parent: | Object

Methods

add find_mapped_obj_class find_mapped_soap_class new obj2soap set soap2obj

Classes and Modules

Class SOAP::Mapping::Registry::Map

Constants

StringFactory = StringFactory_.new
BasetypeFactory = BasetypeFactory_.new
DateTimeFactory = DateTimeFactory_.new
ArrayFactory = ArrayFactory_.new
Base64Factory = Base64Factory_.new
URIFactory = URIFactory_.new
TypedArrayFactory = TypedArrayFactory_.new
TypedStructFactory = TypedStructFactory_.new
HashFactory = HashFactory_.new
SOAPBaseMap = [ [::NilClass, ::SOAP::SOAPNil, BasetypeFactory], [::TrueClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::FalseClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::String, ::SOAP::SOAPString, StringFactory], [::DateTime, ::SOAP::SOAPDateTime, DateTimeFactory], [::Date, ::SOAP::SOAPDate, DateTimeFactory], [::Time, ::SOAP::SOAPDateTime, DateTimeFactory], [::Time, ::SOAP::SOAPTime, DateTimeFactory], [::Float, ::SOAP::SOAPDouble, BasetypeFactory, {:derived_class => true}], [::Float, ::SOAP::SOAPFloat, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPByte, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedByte, BasetypeFactory, {:derived_class => true}], [::URI::Generic, ::SOAP::SOAPAnyURI, URIFactory, {:derived_class => true}], [::String, ::SOAP::SOAPBase64, Base64Factory], [::String, ::SOAP::SOAPHexBinary, Base64Factory], [::String, ::SOAP::SOAPDecimal, BasetypeFactory], [::String, ::SOAP::SOAPDuration, BasetypeFactory], [::String, ::SOAP::SOAPGYearMonth, BasetypeFactory], [::String, ::SOAP::SOAPGYear, BasetypeFactory], [::String, ::SOAP::SOAPGMonthDay, BasetypeFactory], [::String, ::SOAP::SOAPGDay, BasetypeFactory], [::String, ::SOAP::SOAPGMonth, BasetypeFactory], [::String, ::SOAP::SOAPQName, BasetypeFactory], [::Hash, ::SOAP::SOAPArray, HashFactory], [::Hash, ::SOAP::SOAPStruct, HashFactory], [::Array, ::SOAP::SOAPArray, ArrayFactory, {:derived_class => true}], [::SOAP::Mapping::SOAPException, ::SOAP::SOAPStruct, TypedStructFactory, {:type => XSD::QName.new(RubyCustomTypeNamespace, "SOAPException")}], ]
RubyOriginalMap = [ [::NilClass, ::SOAP::SOAPNil, BasetypeFactory], [::TrueClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::FalseClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::String, ::SOAP::SOAPString, StringFactory], [::DateTime, ::SOAP::SOAPDateTime, DateTimeFactory], [::Date, ::SOAP::SOAPDate, DateTimeFactory], [::Time, ::SOAP::SOAPDateTime, DateTimeFactory], [::Time, ::SOAP::SOAPTime, DateTimeFactory], [::Float, ::SOAP::SOAPDouble, BasetypeFactory, {:derived_class => true}], [::Float, ::SOAP::SOAPFloat, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPByte, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedByte, BasetypeFactory, {:derived_class => true}], [::URI::Generic, ::SOAP::SOAPAnyURI, URIFactory, {:derived_class => true}], [::String, ::SOAP::SOAPBase64, Base64Factory], [::String, ::SOAP::SOAPHexBinary, Base64Factory], [::String, ::SOAP::SOAPDecimal, BasetypeFactory], [::String, ::SOAP::SOAPDuration, BasetypeFactory], [::String, ::SOAP::SOAPGYearMonth, BasetypeFactory], [::String, ::SOAP::SOAPGYear, BasetypeFactory], [::String, ::SOAP::SOAPGMonthDay, BasetypeFactory], [::String, ::SOAP::SOAPGDay, BasetypeFactory], [::String, ::SOAP::SOAPGMonth, BasetypeFactory], [::String, ::SOAP::SOAPQName, BasetypeFactory], [::Hash, ::SOAP::SOAPArray, HashFactory], [::Hash, ::SOAP::SOAPStruct, HashFactory], # Does not allow Array's subclass here. [::Array, ::SOAP::SOAPArray, ArrayFactory], [::SOAP::Mapping::SOAPException, ::SOAP::SOAPStruct, TypedStructFactory, {:type => XSD::QName.new(RubyCustomTypeNamespace, "SOAPException")}], ]

Attributes

default_factory | [RW]
excn_handler_obj2soap | [RW]
excn_handler_soap2obj | [RW]

Public Class methods

new(config = {})

Public Instance methods

add(obj_class, soap_class, factory, info = nil)
find_mapped_obj_class(soap_class)
find_mapped_soap_class(obj_class)
obj2soap(obj, type_qname = nil)

general Registry ignores type_qname

set(obj_class, soap_class, factory, info = nil)

Alias for add

soap2obj(node, klass = nil)


Class: SOAP::Mapping::Registry::Map

Class | SOAP::Mapping::Registry::Map
In: | lib/soap/mapping/registry.rb
Parent: | Object

Methods

add clear find_mapped_obj_class find_mapped_soap_class init new obj2soap soap2obj

Public Class methods

new(registry)

Public Instance methods

add(obj_class, soap_class, factory, info)

Give priority to latter entry.

clear()
find_mapped_obj_class(target_soap_class)
find_mapped_soap_class(target_obj_class)
init(init_map = [])

Give priority to former entry.

obj2soap(obj)
soap2obj(node, klass = nil)


Class: SOAP::Mapping::RubytypeFactory

Class | SOAP::Mapping::RubytypeFactory
In: | lib/soap/mapping/rubytypeFactory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Constants

TYPE_STRING | = | XSD::QName.new(RubyTypeNamespace, 'String')
TYPE_TIME | = | XSD::QName.new(RubyTypeNamespace, 'Time')
TYPE_ARRAY | = | XSD::QName.new(RubyTypeNamespace, 'Array')
TYPE_REGEXP | = | XSD::QName.new(RubyTypeNamespace, 'Regexp')
TYPE_RANGE | = | XSD::QName.new(RubyTypeNamespace, 'Range')
TYPE_CLASS | = | XSD::QName.new(RubyTypeNamespace, 'Class')
TYPE_MODULE | = | XSD::QName.new(RubyTypeNamespace, 'Module')
TYPE_SYMBOL | = | XSD::QName.new(RubyTypeNamespace, 'Symbol')
TYPE_STRUCT | = | XSD::QName.new(RubyTypeNamespace, 'Struct')
TYPE_HASH | = | XSD::QName.new(RubyTypeNamespace, 'Map')

Public Class methods

new(config = {})

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::SOAPException

Class | SOAP::Mapping::SOAPException
In: | lib/soap/mapping/registry.rb
Parent: | Object

Inner class to pass an exception.

Methods

new to_e

Included Modules

Marshallable

Attributes

cause | [R]
excn_type_name | [R]

Public Class methods

new(e)

Public Instance methods

to_e()


Class: SOAP::Mapping::StringFactory_

Class | SOAP::Mapping::StringFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Module: SOAP::Mapping::TraverseSupport

Module | SOAP::Mapping::TraverseSupport
In: | lib/soap/mapping/mapping.rb

TraverseSupport breaks following thread variables.

  Thread.current[:SOAPMarshalDataKey]

Methods

mark_marshalled_obj mark_unmarshalled_obj

Public Instance methods

mark_marshalled_obj(obj, soap_obj)
mark_unmarshalled_obj(node, obj)


Class: SOAP::Mapping::TypedArrayFactory_

Class | SOAP::Mapping::TypedArrayFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

new obj2soap soap2obj

Public Class methods

new(allow_original_mapping = false)

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::TypedStructFactory_

Class | SOAP::Mapping::TypedStructFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::URIFactory_

Class | SOAP::Mapping::URIFactory_
In: | lib/soap/mapping/factory.rb
Parent: | Factory

Methods

obj2soap soap2obj

Public Instance methods

obj2soap(soap_class, obj, info, map)
soap2obj(obj_class, node, info, map)


Class: SOAP::Mapping::WSDLEncodedRegistry

Class | SOAP::Mapping::WSDLEncodedRegistry
In: | lib/soap/mapping/wsdlencodedregistry.rb
Parent: | Registry

Methods

new obj2soap soap2obj

Included Modules

TraverseSupport

Constants

MapKeyName | = | XSD::QName.new(nil, "key")
MapValueName | = | XSD::QName.new(nil, "value")

Attributes

definedelements | [R]
definedtypes | [R]
excn_handler_obj2soap | [RW]
excn_handler_soap2obj | [RW]

Public Class methods

new(definedtypes = XSD::NamedElements::Empty)

Public Instance methods

obj2soap(obj, qname = nil)
soap2obj(node, obj_class = nil)

map anything for now: must refer WSDL while mapping. [ToDo]


Class: SOAP::Mapping::WSDLLiteralRegistry

Class | SOAP::Mapping::WSDLLiteralRegistry
In: | lib/soap/mapping/wsdlliteralregistry.rb
Parent: | Registry

Methods

new obj2soap soap2obj

Constants

MAPPING_OPT = { :no_reference => true }

Attributes

definedelements | [R]
definedtypes | [R]
excn_handler_obj2soap | [RW]
excn_handler_soap2obj | [RW]

Public Class methods

new(definedtypes = XSD::NamedElements::Empty, definedelements = XSD::NamedElements::Empty)

Public Instance methods

obj2soap(obj, qname)
soap2obj(node, obj_class = nil)

node should be a SOAPElement


Module: SOAP::Marshal

Module | SOAP::Marshal
In: | lib/soap/marshal.rb

Methods

dump load marshal unmarshal

Constants

MarshalMappingRegistry = Mapping::Registry.new( :allow_original_mapping => true) Trying xsd:dateTime data to be recovered as aTime.

Public Class methods

dump(obj, io = nil)
load(stream)
marshal(obj, mapping_registry = MarshalMappingRegistry, io = nil)
unmarshal(stream, mapping_registry = MarshalMappingRegistry)


Module: SOAP::Marshallable

Module | SOAP::Marshallable
In: | lib/soap/mapping/registry.rb


Class: SOAP::NetHttpClient

Class | SOAP::NetHttpClient
In: | lib/soap/netHttpClient.rb
Parent: | Object

Constants

SSLEnabled = begin require 'net/https'


Class: SOAP::Parser

Class | SOAP::Parser
In: | lib/soap/parser.rb
Parent: | Object

Methods

characters charset end_element new parse start_element

Included Modules

SOAP

Classes and Modules

Class SOAP::Parser::FormatDecodeError
Class SOAP::Parser::ParseError
Class SOAP::Parser::ParseFrame
Class SOAP::Parser::UnexpectedElementError

Attributes

allow_unqualified_element | [RW]
decode_typemap | [RW]
default_encodingstyle | [RW]
envelopenamespace | [RW]

Public Class methods

new(opt = {})

Public Instance methods

characters(text)
charset()
end_element(name)
parse(string_or_readable)
start_element(name, attrs)


Class: SOAP::Parser::FormatDecodeError

Class | SOAP::Parser::FormatDecodeError
In: | lib/soap/parser.rb
Parent: | ParseError


Class: SOAP::Parser::ParseError

Class | SOAP::Parser::ParseError
In: | lib/soap/parser.rb
Parent: | Error


Class: SOAP::Parser::ParseFrame

Class | SOAP::Parser::ParseFrame
In: | lib/soap/parser.rb
Parent: | Object

Methods

new node=

Classes and Modules

Class SOAP::Parser::ParseFrame::NodeContainer

Attributes

encodingstyle | [R]
name | [R]
node | [R]
ns | [R]

Public Class methods

new(ns, name, node, encodingstyle)

Public Instance methods

node=(node)


Class: SOAP::Parser::ParseFrame::NodeContainer

Class | SOAP::Parser::ParseFrame::NodeContainer
In: | lib/soap/parser.rb
Parent: | Object

Methods

new node replace_node

Public Class methods

new(node)

Public Instance methods

node()
replace_node(node)


Class: SOAP::Parser::UnexpectedElementError

Class | SOAP::Parser::UnexpectedElementError
In: | lib/soap/parser.rb
Parent: | ParseError


Class: SOAP::PostUnavailableError

Class | SOAP::PostUnavailableError
In: | lib/soap/soap.rb
Parent: | HTTPStreamError


Module: SOAP::Processor

Module | SOAP::Processor
In: | lib/soap/processor.rb

Methods

default_parser_option default_parser_option= marshal unmarshal

Public Class methods

default_parser_option()
default_parser_option=(rhs)
marshal(env, opt = {}, io = nil)
unmarshal(stream, opt = {})


Class: SOAP::Property

Class | SOAP::Property
In: | lib/soap/property.rb
Parent: | Object

Property stream format:

  line separator is \r?\n.  1 line per a property.
  line which begins with '#' is a comment line.  empty line is ignored, too.
  key/value separator is ':' or '='.
  '\' as escape character.  but line separator cannot be escaped.
  \s at the head/tail of key/value are trimmed.

  '[' + key + ']' indicates property section.  for example,

    [aaa.bbb]
    ccc = ddd
    eee.fff = ggg
    []
    aaa.hhh = iii

  is the same as;

    aaa.bbb.ccc = ddd
    aaa.bbb.eee.fff = ggg
    aaa.hhh = iii

Methods

<< [] []= add_hook deref_key each empty? keys load load loadproperty loadproperty local_assign local_assign_hook local_hook local_referent lock locked? new unlock values

Included Modules

Enumerable

Classes and Modules

Module SOAP::Property::Util

Constants

FrozenError | = | (RUBY_VERSION >= "1.9.0") ? RuntimeError : TypeError
KEY_REGSRC | = | '([^=:\\\\]*(?:\\\\.[^=:\\\\]*)*)'
DEF_REGSRC | = | '\\s*' + KEY_REGSRC + '\\s*[=:]\\s*(.*)'
COMMENT_REGEXP | = | Regexp.new('^(?:#.*|)$')
CATDEF_REGEXP | = | Regexp.new("^\\[\\s*#{KEY_REGSRC}\\s*\\]$")
LINE_REGEXP | = | Regexp.new("^#{DEF_REGSRC}$")
NO_HOOK | = | [].freeze

Public Class methods

load(stream)
loadproperty(propname)
new()

Public Instance methods

<<(value)

value: an Object key is generated by property

[](name)

name: a Symbol, String or an Array

[]=(name, value)

name: a Symbol, String or an Array value: an Object

add_hook(name = nil, cascade = false, &hook)

name: a Symbol, String or an Array; nil means hook to the root cascade: true/false; for cascading hook of sub key hook: block which will be called with 2 args, name and value

each() {|key, value| ...}
empty?()
keys()
load(stream)
loadproperty(propname)

find property from $:.

lock(cascade = false)
locked?()
unlock(cascade = false)
values()

Protected Instance methods

deref_key(key)
local_assign(key, value)
local_assign_hook(key, cascade, &hook)
local_hook(key, direct)
local_referent(key)


Module: SOAP::Property::Util

Module | SOAP::Property::Util
In: | lib/soap/property.rb

Methods

const_from_name require_from_name

Public Instance methods

const_from_name(fqname)
require_from_name(fqname)


Module: SOAP::RPC

Module | SOAP::RPC
In: | lib/soap/rpc/cgistub.rb lib/soap/rpc/router.rb lib/soap/rpc/driver.rb lib/soap/rpc/httpserver.rb lib/soap/rpc/element.rb lib/soap/rpc/standaloneServer.rb lib/soap/rpc/proxy.rb lib/soap/rpc/soaplet.rb lib/soap/rpc/rpc.rb

Methods

defined_methods

Classes and Modules

Class SOAP::RPC::CGIStub
Class SOAP::RPC::Driver
Class SOAP::RPC::HTTPServer
Class SOAP::RPC::MethodDefinitionError
Class SOAP::RPC::ParameterError
Class SOAP::RPC::Proxy
Class SOAP::RPC::RPCError
Class SOAP::RPC::Router
Class SOAP::RPC::SOAPMethod
Class SOAP::RPC::SOAPMethodRequest
Class SOAP::RPC::SOAPMethodResponse
Class SOAP::RPC::SOAPVoid
Class SOAP::RPC::SOAPlet
Class SOAP::RPC::StandaloneServer

Constants

ServerException = Mapping::MappedException

Public Class methods

defined_methods(obj)


Class: SOAP::RPC::CGIStub

Class | SOAP::RPC::CGIStub
In: | lib/soap/rpc/cgistub.rb
Parent: | Logger::Application

SYNOPSIS

  CGIStub.new

DESCRIPTION

  To be written...

Methods

add_document_operation add_headerhandler add_method add_method_as add_method_with_namespace add_method_with_namespace_as add_rpc_headerhandler add_rpc_method add_rpc_method_as add_rpc_method_with_namespace add_rpc_method_with_namespace_as add_rpc_operation add_rpc_servant add_servant generate_explicit_type generate_explicit_type= mapping_registry mapping_registry= new on_init set_fcgi_request

Included Modules

SOAP WEBrick

Classes and Modules

Class SOAP::RPC::CGIStub::SOAPFCGIRequest
Class SOAP::RPC::CGIStub::SOAPRequest
Class SOAP::RPC::CGIStub::SOAPStdinRequest

Constants

HTTPVersion = WEBrick::HTTPVersion.new('1.0')

Public Class methods

new(appname, default_namespace)

Public Instance methods

add_document_operation(receiver, soapaction, name, param_def, opt = {})
add_headerhandler(obj)
add_method(obj, name, *param)

Alias for add_rpc_method

add_method_as(obj, name, name_as, *param)

Alias for add_rpc_method_as

add_method_with_namespace(namespace, obj, name, *param)

Alias for add_rpc_method_with_namespace

add_method_with_namespace_as(namespace, obj, name, name_as, *param)

Alias for add_rpc_method_with_namespace_as

add_rpc_headerhandler(obj)

Alias for add_headerhandler

add_rpc_method(obj, name, *param)

method entry interface

add_rpc_method_as(obj, name, name_as, *param)
add_rpc_method_with_namespace(namespace, obj, name, *param)
add_rpc_method_with_namespace_as(namespace, obj, name, name_as, *param)
add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
add_rpc_servant(obj, namespace = @default_namespace)

servant entry interface

add_servant(obj, namespace = @default_namespace)

Alias for add_rpc_servant

generate_explicit_type()
generate_explicit_type=(generate_explicit_type)
mapping_registry()
mapping_registry=(value)
on_init()
set_fcgi_request(request)


Class: SOAP::RPC::CGIStub::SOAPFCGIRequest

Class | SOAP::RPC::CGIStub::SOAPFCGIRequest
In: | lib/soap/rpc/cgistub.rb
Parent: | SOAPRequest

Methods

[] meta_vars new

Attributes

body [R]

Public Class methods

new(request)

Public Instance methods

[](var)
meta_vars()


Class: SOAP::RPC::CGIStub::SOAPRequest

Class | SOAP::RPC::CGIStub::SOAPRequest
In: | lib/soap/rpc/cgistub.rb
Parent: | Object

Methods

[] meta_vars

Attributes

body [R]

Public Instance methods

[](var)
meta_vars()


Class: SOAP::RPC::CGIStub::SOAPStdinRequest

Class | SOAP::RPC::CGIStub::SOAPStdinRequest
In: | lib/soap/rpc/cgistub.rb
Parent: | SOAPRequest

Methods

[] meta_vars new

Attributes

body [R]

Public Class methods

new(stream)

Public Instance methods

[](var)
meta_vars()


Class: SOAP::RPC::Driver

Class | SOAP::RPC::Driver
In: | lib/soap/rpc/driver.rb
Parent: | Object

Methods

__attr_proxy __attr_proxy add_document_method add_document_operation add_method add_method_as add_method_with_soapaction add_method_with_soapaction_as add_rpc_method add_rpc_method_as add_rpc_method_with_soapaction add_rpc_method_with_soapaction_as add_rpc_operation call httpproxy httpproxy= inspect invoke loadproperty mandatorycharset mandatorycharset= new wiredump_dev wiredump_dev= wiredump_file_base wiredump_file_base=

Attributes

options | [R]
proxy | [R]
soapaction | [RW]

Public Class methods

__attr_proxy(symbol, assignable = false)
__attr_proxy(symbol, assignable = false)
new(endpoint_url, namespace = nil, soapaction = nil)

Public Instance methods

add_document_method(name, soapaction, req_qname, res_qname)
add_document_operation(soapaction, name, param_def, opt = {})
add_method(name, *params)

Alias for add_rpc_method

add_method_as(name, name_as, *params)

Alias for add_rpc_method_as

add_method_with_soapaction(name, soapaction, *params)

Alias for add_rpc_method_with_soapaction

add_method_with_soapaction_as(name, name_as, soapaction, *params)

Alias for add_rpc_method_with_soapaction_as

add_rpc_method(name, *params)
add_rpc_method_as(name, name_as, *params)
add_rpc_method_with_soapaction(name, soapaction, *params)
add_rpc_method_with_soapaction_as(name, name_as, soapaction, *params)
add_rpc_operation(qname, soapaction, name, param_def, opt = {})
call(name, *params)
httpproxy()
httpproxy=(httpproxy)
inspect()
invoke(headers, body)
loadproperty(propertyname)
mandatorycharset()
mandatorycharset=(mandatorycharset)
wiredump_dev()
wiredump_dev=(wiredump_dev)
wiredump_file_base()
wiredump_file_base=(wiredump_file_base)


Class: SOAP::RPC::HTTPServer

Class | SOAP::RPC::HTTPServer
In: | lib/soap/rpc/httpserver.rb
Parent: | Logger::Application

Methods

add_document_method add_document_operation add_document_request_operation add_headerhandler add_method add_method_as add_request_headerhandler add_rpc_headerhandler add_rpc_method add_rpc_method_as add_rpc_operation add_rpc_request_operation add_rpc_request_servant add_rpc_servant generate_explicit_type generate_explicit_type= mapping_registry mapping_registry= new on_init shutdown status

Attributes

default_namespace | [RW]
server | [R]

Public Class methods

new(config)

Public Instance methods

add_document_method(obj, soapaction, name, req_qnames, res_qnames)
add_document_operation(receiver, soapaction, name, param_def, opt = {})
add_document_request_operation(factory, soapaction, name, param_def, opt = {})
add_headerhandler(obj)
add_method(obj, name, *param)

Alias for add_rpc_method

add_method_as(obj, name, name_as, *param)

Alias for add_rpc_method_as

add_request_headerhandler(factory)
add_rpc_headerhandler(obj)

Alias for add_headerhandler

add_rpc_method(obj, name, *param)

method entry interface

add_rpc_method_as(obj, name, name_as, *param)
add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {})
add_rpc_request_servant(factory, namespace = @default_namespace)

servant entry interface

add_rpc_servant(obj, namespace = @default_namespace)
generate_explicit_type()
generate_explicit_type=(generate_explicit_type)
mapping_registry()
mapping_registry=(mapping_registry)
on_init()
shutdown()
status()


Class: SOAP::RPC::MethodDefinitionError

Class | SOAP::RPC::MethodDefinitionError
In: | lib/soap/rpc/element.rb
Parent: | RPCError


Class: SOAP::RPC::ParameterError

Class | SOAP::RPC::ParameterError
In: | lib/soap/rpc/element.rb
Parent: | RPCError


Class: SOAP::RPC::Proxy

Class | SOAP::RPC::Proxy
In: | lib/soap/rpc/proxy.rb
Parent: | Object

Methods

add_document_method add_document_operation add_method add_rpc_method add_rpc_operation call check_fault endpoint_url endpoint_url= inspect invoke new reset_stream route set_wiredump_file_base test_loopback_response

Included Modules

SOAP

Classes and Modules

Class SOAP::RPC::Proxy::Operation

Attributes

allow_unqualified_element | [RW]
default_encodingstyle | [RW]
generate_explicit_type | [RW]
headerhandler | [R]
literal_mapping_registry | [RW]
mandatorycharset | [RW]
mapping_registry | [RW]
operation | [R]
soapaction | [RW]
streamhandler | [R]

Public Class methods

new(endpoint_url, soapaction, options)

Public Instance methods

add_document_method(soapaction, name, param_def, opt = {})

Alias for add_document_operation

add_document_operation(soapaction, name, param_def, opt = {})
add_method(qname, soapaction, name, param_def, opt = {})

Alias for add_rpc_operation

add_rpc_method(qname, soapaction, name, param_def, opt = {})

Alias for add_rpc_operation

add_rpc_operation(qname, soapaction, name, param_def, opt = {})
call(name, *params)
check_fault(body)
endpoint_url()
endpoint_url=(endpoint_url)
inspect()
invoke(req_header, req_body, opt = nil)
reset_stream()
route(req_header, req_body, reqopt, resopt)
set_wiredump_file_base(wiredump_file_base)
test_loopback_response()


Class: SOAP::RPC::Proxy::Operation

Class | SOAP::RPC::Proxy::Operation
In: | lib/soap/rpc/proxy.rb
Parent: | Object

Methods

new raise_fault request_body request_default_encodingstyle response_default_encodingstyle response_obj

Attributes

attributeformdefault | [R]
elementformdefault | [R]
request_style | [R]
request_use | [R]
response_style | [R]
response_use | [R]
soapaction | [R]

Public Class methods

new(soapaction, param_def, opt)

Public Instance methods

raise_fault(e, mapping_registry, literal_mapping_registry)
request_body(values, mapping_registry, literal_mapping_registry, opt)
request_default_encodingstyle()
response_default_encodingstyle()
response_obj(body, mapping_registry, literal_mapping_registry, opt)


Class: SOAP::RPC::RPCError

Class | SOAP::RPC::RPCError
In: | lib/soap/rpc/element.rb
Parent: | Error


Class: SOAP::RPC::Router

Class | SOAP::RPC::Router
In: | lib/soap/rpc/router.rb
Parent: | Object

Methods

add_document_method add_document_operation add_document_request_operation add_headerhandler add_method add_request_headerhandler add_rpc_method add_rpc_operation add_rpc_request_operation add_rpc_request_servant add_rpc_servant add_servant create_fault_response new route

Included Modules

SOAP

Classes and Modules

Class SOAP::RPC::Router::ApplicationScopeOperation
Class SOAP::RPC::Router::Operation
Class SOAP::RPC::Router::RequestScopeOperation

Attributes

actor | [R]
external_ces | [RW]
generate_explicit_type | [RW]
literal_mapping_registry | [RW]
mapping_registry | [RW]

Public Class methods

new(actor)

Public Instance methods

add_document_method(receiver, soapaction, name, param_def, opt = {})

Alias for add_document_operation

add_document_operation(receiver, soapaction, name, param_def, opt = {})
add_document_request_operation(factory, soapaction, name, param_def, opt = {})
add_headerhandler(handler)
add_method(receiver, qname, soapaction, name, param_def, opt = {})

Alias for add_rpc_operation

add_request_headerhandler(factory)

header handler interface

add_rpc_method(receiver, qname, soapaction, name, param_def, opt = {})

Alias for add_rpc_operation

add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})

operation definition interface

add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {})
add_rpc_request_servant(factory, namespace)

servant definition interface

add_rpc_servant(obj, namespace)
add_servant(obj, namespace)

Alias for add_rpc_servant

create_fault_response(e)

Create fault response string.

route(conn_data)


Class: SOAP::RPC::Router::ApplicationScopeOperation

Class | SOAP::RPC::Router::ApplicationScopeOperation
In: | lib/soap/rpc/router.rb
Parent: | Operation

Methods

new

Public Class methods

new(soapaction, receiver, name, param_def, opt)


Class: SOAP::RPC::Router::Operation

Class | SOAP::RPC::Router::Operation
In: | lib/soap/rpc/router.rb
Parent: | Object

Methods

call new request_default_encodingstyle response_default_encodingstyle

Attributes

name | [R]
request_style | [R]
request_use | [R]
response_style | [R]
response_use | [R]
soapaction | [R]

Public Class methods

new(soapaction, name, param_def, opt)

Public Instance methods

call(body, mapping_registry, literal_mapping_registry, opt)
request_default_encodingstyle()
response_default_encodingstyle()


Class: SOAP::RPC::Router::RequestScopeOperation

Class | SOAP::RPC::Router::RequestScopeOperation
In: | lib/soap/rpc/router.rb
Parent: | Operation

Methods

new

Public Class methods

new(soapaction, receiver_factory, name, param_def, opt)


Class: SOAP::RPC::SOAPMethod

Class | SOAP::RPC::SOAPMethod
In: | lib/soap/rpc/element.rb
Parent: | SOAPStruct

Methods

create_doc_param_def create_rpc_param_def derive_rpc_param_def have_outparam? input_params new output_params param_count set_outparam set_param

Constants

RETVAL | = | 'retval'
IN | = | 'in'
OUT | = | 'out'
INOUT | = | 'inout'

Attributes

inparam | [R]
outparam | [R]
param_def | [R]
retval_class_name | [R]
retval_name | [R]

Public Class methods

create_doc_param_def(req_qnames, res_qnames)
create_rpc_param_def(param_names)
derive_rpc_param_def(obj, name, *param)
new(qname, param_def = nil)
param_count(param_def, *type)

Public Instance methods

have_outparam?()
input_params()
output_params()
set_outparam(params)
set_param(params)


Class: SOAP::RPC::SOAPMethodRequest

Class | SOAP::RPC::SOAPMethodRequest
In: | lib/soap/rpc/element.rb
Parent: | SOAPMethod

Methods

create_method_response create_request dup each new

Attributes

soapaction [RW]

Public Class methods

create_request(qname, *params)
new(qname, param_def = nil, soapaction = nil)

Public Instance methods

create_method_response(response_name = nil)
dup()
each() {|name, @inparam[name]| ...}


Class: SOAP::RPC::SOAPMethodResponse

Class | SOAP::RPC::SOAPMethodResponse
In: | lib/soap/rpc/element.rb
Parent: | SOAPMethod

Methods

each new retval=

Public Class methods

new(qname, param_def = nil)

Public Instance methods

each() {|@retval_name, @retval| ...}
retval=(retval)


Class: SOAP::RPC::SOAPVoid

Class | SOAP::RPC::SOAPVoid
In: | lib/soap/rpc/element.rb
Parent: | XSD::XSDAnySimpleType

To return(?) void explicitly.

 def foo(input_var)
   ...
   return SOAP::RPC::SOAPVoid.new
 end

Methods

new

Included Modules

SOAPBasetype

Constants

Name = XSD::QName.new(Mapping::RubyCustomTypeNamespace, nil)

Public Class methods

new()


Class: SOAP::RPC::SOAPlet

Class | SOAP::RPC::SOAPlet
In: | lib/soap/rpc/soaplet.rb
Parent: | WEBrick::HTTPServlet::AbstractServlet

Methods

add_servant allow_content_encoding_gzip= app_scope_router do_GET do_POST get_instance new require_path_info?

Attributes

options [R]

Public Class methods

new(router = nil)

Public Instance methods

add_servant(obj, namespace)

for backward compatibility

allow_content_encoding_gzip=(allow)
app_scope_router()

for backward compatibility

do_GET(req, res)
do_POST(req, res)
get_instance(config, *options)

Servlet interfaces for WEBrick.

require_path_info?()


Class: SOAP::RPC::StandaloneServer

Class | SOAP::RPC::StandaloneServer
In: | lib/soap/rpc/standaloneServer.rb
Parent: | HTTPServer

Methods

new

External Aliases

add_rpc_servant | -> | add_servant
add_rpc_headerhandler | -> | add_headerhandler

Public Class methods

new(appname, default_namespace, host = "0.0.0.0", port = 8080)


Class: SOAP::RPCRoutingError

Class | SOAP::RPCRoutingError
In: | lib/soap/soap.rb
Parent: | Error


Class: SOAP::Response

Class | SOAP::Response
In: | lib/soap/netHttpClient.rb
Parent: | Object

Methods

new

Attributes

content | [R]
contenttype | [R]
reason | [R]
status | [R]

Public Class methods

new(res)


Class: SOAP::ResponseFormatError

Class | SOAP::ResponseFormatError
In: | lib/soap/soap.rb
Parent: | Error


Class: SOAP::SOAPAnySimpleType

Class | SOAP::SOAPAnySimpleType
In: | lib/soap/baseData.rb
Parent: | XSD::XSDAnySimpleType

Basic datatypes.

Included Modules

SOAPBasetype


Class: SOAP::SOAPAnyURI

Class | SOAP::SOAPAnyURI
In: | lib/soap/baseData.rb
Parent: | XSD::XSDAnyURI

Included Modules

SOAPBasetype


Class: SOAP::SOAPArray

Class | SOAP::SOAPArray
In: | lib/soap/baseData.rb
Parent: | XSD::NSDBase

Methods

[] []= add decode deep_map each include? new offset= position replace soap2array to_a traverse

Included Modules

SOAPCompoundtype Enumerable

Constants

ITEM_NAME | = | XSD::QName.new(nil, 'item')
TypeParseRegexp | = | Regexp.new('^(.+)\[([\d,]*)\]$')

Attributes

arytype | [R]
offset | [R]
rank | [R]
size | [RW]
size_fixed | [RW]
sparse | [RW]

Public Class methods

decode(elename, type, arytype)

Module function

new(type = nil, rank = 1, arytype = nil)

Public Instance methods

[](*idxary)
[]=(*idxary)
add(value)
deep_map(ary, &block)
each() {|data| ...}
include?(var)
offset=(var)
position()
replace() {|ele| ...}
soap2array(ary) {|v| ...}
to_a()
traverse() {|v| ...}


Class: SOAP::SOAPAttachment

Class | SOAP::SOAPAttachment
In: | lib/soap/attachment.rb
Parent: | SOAPExternalReference

Methods

new

Attributes

data [R]

Public Class methods

new(value)


Class: SOAP::SOAPBase64

Class | SOAP::SOAPBase64
In: | lib/soap/baseData.rb
Parent: | XSD::XSDBase64Binary

Methods

as_xsd new

Included Modules

SOAPBasetype

Constants

Type = QName.new(EncodingNamespace, Base64Literal)

Public Class methods

new(value = nil)

Override the definition in SOAPBasetype.

Public Instance methods

as_xsd()


Module: SOAP::SOAPBasetype

Module | SOAP::SOAPBasetype
In: | lib/soap/baseData.rb

for SOAP base type

Methods

new

Included Modules

SOAPType SOAP

Public Class methods

new(*arg)


Class: SOAP::SOAPBody

Class | SOAP::SOAPBody
In: | lib/soap/element.rb lib/soap/rpc/element.rb
Parent: | SOAPStruct

Add method definitions for RPC to common definition in element.rb

Methods

encode fault fault= new outparams request response root_node

Included Modules

SOAPEnvelopeElement

Public Class methods

new(data = nil, is_fault = false)

Public Instance methods

encode(generator, ns, attrs = {}) {|@data| ...}
fault()
fault=(fault)
outparams()
request()
response()
root_node()


Class: SOAP::SOAPBoolean

Class | SOAP::SOAPBoolean
In: | lib/soap/baseData.rb
Parent: | XSD::XSDBoolean

Included Modules

SOAPBasetype


Class: SOAP::SOAPByte

Class | SOAP::SOAPByte
In: | lib/soap/baseData.rb
Parent: | XSD::XSDByte

Included Modules

SOAPBasetype


Module: SOAP::SOAPCompoundtype

Module | SOAP::SOAPCompoundtype
In: | lib/soap/baseData.rb

for SOAP compound type

Methods

new

Included Modules

SOAPType SOAP

Public Class methods

new(*arg)


Class: SOAP::SOAPDate

Class | SOAP::SOAPDate
In: | lib/soap/baseData.rb
Parent: | XSD::XSDDate

Included Modules

SOAPBasetype


Class: SOAP::SOAPDateTime

Class | SOAP::SOAPDateTime
In: | lib/soap/baseData.rb
Parent: | XSD::XSDDateTime

Included Modules

SOAPBasetype


Class: SOAP::SOAPDecimal

Class | SOAP::SOAPDecimal
In: | lib/soap/baseData.rb
Parent: | XSD::XSDDecimal

Included Modules

SOAPBasetype


Class: SOAP::SOAPDouble

Class | SOAP::SOAPDouble
In: | lib/soap/baseData.rb
Parent: | XSD::XSDDouble

Included Modules

SOAPBasetype


Class: SOAP::SOAPDuration

Class | SOAP::SOAPDuration
In: | lib/soap/baseData.rb
Parent: | XSD::XSDDuration

Included Modules

SOAPBasetype


Class: SOAP::SOAPElement

Class | SOAP::SOAPElement
In: | lib/soap/baseData.rb
Parent: | Object

SOAPElement is not typed so it is not derived from NSDBase.

Methods

[] []= add decode each from_obj inspect key? members new to_elename to_obj

Included Modules

Enumerable

External Aliases

text -> data

Attributes

elename | [RW] |
encodingstyle | [RW] |
extraattr | [RW] |
id | [RW] |
parent | [RW] |
position | [RW] |
precedents | [R] |
qualified | [RW] |
root | [RW] |
text | [RW] | Text interface.

Public Class methods

decode(elename)
from_obj(obj, namespace = nil)
new(elename, text = nil)
to_elename(obj, namespace = nil)

Public Instance methods

[](idx)
[]=(idx, data)
add(value)

Element interfaces.

each() {|@array[idx], @data[idx]| ...}
inspect()
key?(name)
members()
to_obj()


Class: SOAP::SOAPEnvelope

Class | SOAP::SOAPEnvelope
In: | lib/soap/element.rb
Parent: | XSD::NSDBase

Methods

body= encode header= new to_ary

Included Modules

SOAPEnvelopeElement SOAPCompoundtype

Attributes

body | [R]
external_content | [R]
header | [R]

Public Class methods

new(header = nil, body = nil)

Public Instance methods

body=(body)
encode(generator, ns, attrs = {}) {|@header| ...}
header=(header)
to_ary()


Module: SOAP::SOAPEnvelopeElement

Module | SOAP::SOAPEnvelopeElement
In: | lib/soap/element.rb

SOAP elements


Class: SOAP::SOAPExternalReference

Class | SOAP::SOAPExternalReference
In: | lib/soap/baseData.rb
Parent: | XSD::NSDBase

Methods

new referred refidstr

Included Modules

SOAPBasetype

Public Class methods

new()

Public Instance methods

referred()
refidstr()


Class: SOAP::SOAPFault

Class | SOAP::SOAPFault
In: | lib/soap/element.rb
Parent: | SOAPStruct

Methods

detail detail= encode faultactor faultactor= faultcode faultcode= faultstring faultstring= new

Included Modules

SOAPEnvelopeElement SOAPCompoundtype

Public Class methods

new(faultcode = nil, faultstring = nil, faultactor = nil, detail = nil)

Public Instance methods

detail()
detail=(rhs)
encode(generator, ns, attrs = {}) {|self.faultcode| ...}
faultactor()
faultactor=(rhs)
faultcode()
faultcode=(rhs)
faultstring()
faultstring=(rhs)


Class: SOAP::SOAPFloat

Class | SOAP::SOAPFloat
In: | lib/soap/baseData.rb
Parent: | XSD::XSDFloat

Included Modules

SOAPBasetype


Class: SOAP::SOAPGDay

Class | SOAP::SOAPGDay
In: | lib/soap/baseData.rb
Parent: | XSD::XSDGDay

Included Modules

SOAPBasetype


Class: SOAP::SOAPGMonth

Class | SOAP::SOAPGMonth
In: | lib/soap/baseData.rb
Parent: | XSD::XSDGMonth

Included Modules

SOAPBasetype


Class: SOAP::SOAPGMonthDay

Class | SOAP::SOAPGMonthDay
In: | lib/soap/baseData.rb
Parent: | XSD::XSDGMonthDay

Included Modules

SOAPBasetype


Class: SOAP::SOAPGYear

Class | SOAP::SOAPGYear
In: | lib/soap/baseData.rb
Parent: | XSD::XSDGYear

Included Modules

SOAPBasetype


Class: SOAP::SOAPGYearMonth

Class | SOAP::SOAPGYearMonth
In: | lib/soap/baseData.rb
Parent: | XSD::XSDGYearMonth

Included Modules

SOAPBasetype


Class: SOAP::SOAPGenerator

Class | SOAP::SOAPGenerator
In: | lib/soap/generator.rb
Parent: | Object

CAUTION: MT-unsafe

Methods

add_reftarget assign_ns element_local? element_qualified? encode_child encode_data encode_element encode_name encode_name_end encode_rawstring encode_string encode_tag encode_tag_end generate new

Included Modules

SOAP

Classes and Modules

Class SOAP::SOAPGenerator::FormatEncodeError

Constants

EncodeMap | = | { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', '\'' => '&apos;', "\r" => '&#xd;'
EncodeCharRegexp | = | Regexp.new("[#{EncodeMap.keys.join}]")

Attributes

charset | [RW]
default_encodingstyle | [RW]
generate_explicit_type | [RW]
use_numeric_character_reference | [RW]

Public Class methods

assign_ns(attrs, ns, namespace, tag = nil)
new(opt = {})

Public Instance methods

add_reftarget(name, node)
element_local?(element)
element_qualified?(element)
encode_child(ns, child, parent)
encode_data(ns, obj, parent)
encode_element(ns, obj, parent)
encode_name(ns, data, attrs)
encode_name_end(ns, data)
encode_rawstring(str)
encode_string(str)
encode_tag(elename, attrs = nil)
encode_tag_end(elename, cr = nil)
generate(obj, io = nil)


Class: SOAP::SOAPGenerator::FormatEncodeError

Class | SOAP::SOAPGenerator::FormatEncodeError
In: | lib/soap/generator.rb
Parent: | Error


Class: SOAP::SOAPHeader

Class | SOAP::SOAPHeader
In: | lib/soap/element.rb
Parent: | SOAPStruct

Methods

add encode length new size

Included Modules

SOAPEnvelopeElement

Public Class methods

new()

Public Instance methods

add(name, value)
encode(generator, ns, attrs = {}) {|data| ...}
length()
size()

Alias for length


Class: SOAP::SOAPHeaderItem

Class | SOAP::SOAPHeaderItem
In: | lib/soap/element.rb
Parent: | XSD::NSDBase

Methods

encode new

Included Modules

SOAPEnvelopeElement SOAPCompoundtype

Attributes

element | [RW]
encodingstyle | [RW]
mustunderstand | [RW]

Public Class methods

new(element, mustunderstand = true, encodingstyle = nil)

Public Instance methods

encode(generator, ns, attrs = {}) {|@element| ...}


Class: SOAP::SOAPHexBinary

Class | SOAP::SOAPHexBinary
In: | lib/soap/baseData.rb
Parent: | XSD::XSDHexBinary

Included Modules

SOAPBasetype


Class: SOAP::SOAPInt

Class | SOAP::SOAPInt
In: | lib/soap/baseData.rb
Parent: | XSD::XSDInt

Included Modules

SOAPBasetype


Class: SOAP::SOAPInteger

Class | SOAP::SOAPInteger
In: | lib/soap/baseData.rb
Parent: | XSD::XSDInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPLong

Class | SOAP::SOAPLong
In: | lib/soap/baseData.rb
Parent: | XSD::XSDLong

Included Modules

SOAPBasetype


Module: SOAP::SOAPModuleUtils

Module | SOAP::SOAPModuleUtils
In: | lib/soap/baseData.rb

Mix-in module for SOAP base type classes.

Methods

decode

Included Modules

SOAP

Public Instance methods

decode(elename)


Class: SOAP::SOAPNegativeInteger

Class | SOAP::SOAPNegativeInteger
In: | lib/soap/baseData.rb
Parent: | XSD::XSDNegativeInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPNil

Class | SOAP::SOAPNil
In: | lib/soap/baseData.rb
Parent: | XSD::XSDNil

Included Modules

SOAPBasetype


Class: SOAP::SOAPNonNegativeInteger

Class | SOAP::SOAPNonNegativeInteger
In: | lib/soap/baseData.rb
Parent: | XSD::XSDNonNegativeInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPNonPositiveInteger

Class | SOAP::SOAPNonPositiveInteger
In: | lib/soap/baseData.rb
Parent: | XSD::XSDNonPositiveInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPPositiveInteger

Class | SOAP::SOAPPositiveInteger
In: | lib/soap/baseData.rb
Parent: | XSD::XSDPositiveInteger

Included Modules

SOAPBasetype


Class: SOAP::SOAPQName

Class | SOAP::SOAPQName
In: | lib/soap/baseData.rb
Parent: | XSD::XSDQName

Included Modules

SOAPBasetype


Class: SOAP::SOAPRawString

Class | SOAP::SOAPRawString
In: | lib/soap/baseData.rb
Parent: | XSD::XSDString

SOAPRawString is for sending raw string. In contrast to SOAPString, SOAP4R does not do XML encoding and does not convert its CES. The string it holds is embedded to XML instance directly as a ‘xsd:string’.

Included Modules

SOAPBasetype


Class: SOAP::SOAPReference

Class | SOAP::SOAPReference
In: | lib/soap/baseData.rb
Parent: | XSD::NSDBase

Convenience datatypes.

Methods

__getobj__ __setobj__ create_refid decode method_missing new refidstr

Included Modules

SOAPBasetype

Attributes

refid [RW]

Public Class methods

create_refid(obj)
decode(elename, refidstr)
new(obj = nil)

Override the definition in SOAPBasetype.

Public Instance methods

__getobj__()
__setobj__(obj)
method_missing(msg_id, *params)

Why don‘t I use delegate.rb? -> delegate requires target object type at initialize time. Why don‘t I use forwardable.rb? -> forwardable requires a list of forwarding methods.

ToDo: Maybe I should use forwardable.rb and give it a methods list like delegate.rb…

refidstr()


Class: SOAP::SOAPShort

Class | SOAP::SOAPShort
In: | lib/soap/baseData.rb
Parent: | XSD::XSDShort

Included Modules

SOAPBasetype


Class: SOAP::SOAPString

Class | SOAP::SOAPString
In: | lib/soap/baseData.rb
Parent: | XSD::XSDString

Included Modules

SOAPBasetype


Class: SOAP::SOAPStruct

Class | SOAP::SOAPStruct
In: | lib/soap/baseData.rb
Parent: | XSD::NSDBase

Compound datatypes.

Methods

[] []= add decode each key? members new replace to_obj to_s

Included Modules

SOAPCompoundtype Enumerable

Public Class methods

decode(elename, type)
new(type = nil)

Public Instance methods

[](idx)
[]=(idx, data)
add(name, value)
each() {|@array[idx], @data[idx]| ...}
key?(name)
members()
replace() {|self[member]| ...}
to_obj()
to_s()


Class: SOAP::SOAPTime

Class | SOAP::SOAPTime
In: | lib/soap/baseData.rb
Parent: | XSD::XSDTime

Included Modules

SOAPBasetype


Module: SOAP::SOAPType

Module | SOAP::SOAPType
In: | lib/soap/baseData.rb

for SOAP type(base and compound)

Methods

inspect new rootnode

Attributes

definedtype | [RW]
elename | [RW]
encodingstyle | [RW]
extraattr | [R]
id | [RW]
parent | [RW]
position | [RW]
precedents | [R]
root | [RW]

Public Class methods

new(*arg)

Public Instance methods

inspect()
rootnode()


Class: SOAP::SOAPUnsignedByte

Class | SOAP::SOAPUnsignedByte
In: | lib/soap/baseData.rb
Parent: | XSD::XSDUnsignedByte

Included Modules

SOAPBasetype


Class: SOAP::SOAPUnsignedInt

Class | SOAP::SOAPUnsignedInt
In: | lib/soap/baseData.rb
Parent: | XSD::XSDUnsignedInt

Included Modules

SOAPBasetype


Class: SOAP::SOAPUnsignedLong

Class | SOAP::SOAPUnsignedLong
In: | lib/soap/baseData.rb
Parent: | XSD::XSDUnsignedLong

Included Modules

SOAPBasetype


Class: SOAP::SOAPUnsignedShort

Class | SOAP::SOAPUnsignedShort
In: | lib/soap/baseData.rb
Parent: | XSD::XSDUnsignedShort

Included Modules

SOAPBasetype


Class: SOAP::SessionManager

Class | SOAP::SessionManager
In: | lib/soap/netHttpClient.rb
Parent: | Object

Attributes

connect_timeout | [RW]
receive_timeout | [RW]
send_timeout | [RW]


Class: SOAP::StreamError

Class | SOAP::StreamError
In: | lib/soap/soap.rb
Parent: | Error


Class: SOAP::StreamHandler

Class | SOAP::StreamHandler
In: | lib/soap/streamHandler.rb
Parent: | Object

Methods

create_media_type parse_media_type

Classes and Modules

Class SOAP::StreamHandler::ConnectionData

Constants

RUBY_VERSION_STRING = "ruby #{ RUBY_VERSION } (#{ RUBY_RELEASE_DATE }) [#{ RUBY_PLATFORM }]"

Public Class methods

create_media_type(charset)
parse_media_type(str)


Class: SOAP::StreamHandler::ConnectionData

Class | SOAP::StreamHandler::ConnectionData
In: | lib/soap/streamHandler.rb
Parent: | Object

Methods

new

Attributes

is_fault | [RW]
receive_contenttype | [RW]
receive_string | [RW]
send_contenttype | [RW]
send_string | [RW]
soapaction | [RW]

Public Class methods

new(send_string = nil)


Class: SOAP::UnhandledMustUnderstandHeaderError

Class | SOAP::UnhandledMustUnderstandHeaderError
In: | lib/soap/soap.rb
Parent: | Error


Class: SOAP::WSDLDriver

Class | SOAP::WSDLDriver
In: | lib/soap/wsdlDriver.rb
Parent: | Object

Methods

__attr_proxy __attr_proxy httpproxy httpproxy= inspect mandatorycharset mandatorycharset= new reset_stream wiredump_dev wiredump_dev= wiredump_file_base wiredump_file_base=

Classes and Modules

Class SOAP::WSDLDriver::Servant__

External Aliases

generate_explicit_type= | -> | generateEncodeType=
 | Backward compatibility.

Public Class methods

__attr_proxy(symbol, assignable = false)
__attr_proxy(symbol, assignable = false)
new(wsdl, port, logdev)

Public Instance methods

httpproxy()
httpproxy=(httpproxy)
inspect()
mandatorycharset()
mandatorycharset=(mandatorycharset)
reset_stream()
wiredump_dev()
wiredump_dev=(wiredump_dev)
wiredump_file_base()
wiredump_file_base=(wiredump_file_base)


Class: SOAP::WSDLDriver::Servant__

Class | SOAP::WSDLDriver::Servant__
In: | lib/soap/wsdlDriver.rb
Parent: | Object

Methods

document_send endpoint_url endpoint_url= headerhandler inspect new reset_stream rpc_call streamhandler test_loopback_response

Included Modules

SOAP

Attributes

allow_unqualified_element | [RW]
default_encodingstyle | [RW]
generate_explicit_type | [RW]
mapping_registry | [RW]
options | [R]
port | [R]
soapaction | [RW]
wsdl_mapping_registry | [RW]

Public Class methods

new(host, wsdl, port, logdev)

Public Instance methods

document_send(name, header_obj, body_obj)

req_header: [[element, mustunderstand, encodingstyle(QName/String)], …] req_body: SOAPBasetype/SOAPCompoundtype

endpoint_url()
endpoint_url=(endpoint_url)
headerhandler()
inspect()
reset_stream()
rpc_call(name, *values)
streamhandler()
test_loopback_response()


Class: SOAP::WSDLDriverFactory

Class | SOAP::WSDLDriverFactory
In: | lib/soap/wsdlDriver.rb
Parent: | Object

Methods

createDriver create_driver create_rpc_driver inspect new

Classes and Modules

Class SOAP::WSDLDriverFactory::FactoryError

Attributes

wsdl [R]

Public Class methods

new(wsdl)

Public Instance methods

createDriver(servicename = nil, portname = nil)

Alias for create_driver

create_driver(servicename = nil, portname = nil)

depricated old interface

create_rpc_driver(servicename = nil, portname = nil)
inspect()


Class: SOAP::WSDLDriverFactory::FactoryError

Class | SOAP::WSDLDriverFactory::FactoryError
In: | lib/soap/wsdlDriver.rb
Parent: | StandardError


Class: SOCKSSocket

Class | SOCKSSocket
In: | lib/resolv-replace.rb ext/socket/socket.c
Parent: | Object

Methods

new

External Aliases

initialize -> original_resolv_initialize

Public Class methods

new(host, serv)


Module: Scanf

Module | Scanf
In: | lib/scanf.rb

Classes and Modules

Class Scanf::FormatSpecifier
Class Scanf::FormatString


Class: Scanf::FormatSpecifier

Class | Scanf::FormatSpecifier
In: | lib/scanf.rb
Parent: | Object

Methods

count_space? letter match mid_match? new to_re to_s width

Attributes

conversion | [R]
matched | [R]
matched_string | [R]
re_string | [R]

Public Class methods

new(str)

Public Instance methods

count_space?()
letter()
match(str)
mid_match?()
to_re()
to_s()
width()


Class: Scanf::FormatString

Class | Scanf::FormatString
In: | lib/scanf.rb
Parent: | Object

Methods

last_spec match new prune spec_count to_s

Constants

SPECIFIERS | = | 'diuXxofeEgsc'
REGEX | = | / # possible space, followed by... (?:\s* # percent sign, followed by... % # another percent sign, or... (?:%| # optional assignment suppression flag \*? # optional maximum field width \d* # named character class, ... (?:\[\[:\w+:\]\]| # traditional character class, or... \[[^\]]*\]| # specifier letter. [#{SPECIFIERS}])))| # or miscellaneous characters [^%\s]+/ix

Attributes

last_match_tried | [R]
last_spec_tried | [R]
matched_count | [R]
space | [R]
string_left | [R]

Public Class methods

new(str)

Public Instance methods

last_spec()
match(str)
prune(n=matched_count)
spec_count()
to_s()


Class: ScriptError

Class | ScriptError
In: | error.c
Parent: | Exception


Class: SecurityError

Class | SecurityError
In: | error.c
Parent: | StandardError


Class: Set

Class | Set
In: | lib/set.rb
Parent: | Object

Set implements a collection of unordered values with no duplicates. This is a hybrid of Array‘s intuitive inter-operation facilities and Hash‘s fast lookup.

Several methods accept any Enumerable object (implementing each) for greater flexibility: new, replace, merge, subtract, |, &, -, ^.

The equality of each couple of elements is determined according to Object#eql? and Object#hash, since Set uses Hash as storage.

Finally, if you are using class Set, you can also use Enumerable#to_set for convenience.

Example

  require 'set'
  s1 = Set.new [1, 2]                   # -> #<Set: {1, 2}>
  s2 = [1, 2].to_set                    # -> #<Set: {1, 2}>
  s1 == s2                              # -> true
  s1.add("foo")                         # -> #<Set: {1, 2, "foo"}>
  s1.merge([2, 6])                      # -> #<Set: {6, 1, 2, "foo"}>
  s1.subset? s2                         # -> false
  s2.subset? s1                         # -> true

Methods

& + - << == [] ^ add add? classify clear collect! delete delete? delete_if difference divide each empty? flatten flatten! flatten_merge include? initialize_copy inspect intersection length map! member? merge new proper_subset? proper_superset? reject! replace size subset? subtract superset? to_a union |

Included Modules

Enumerable

Public Class methods

[](*ary)

Creates a new set containing the given objects.

new(enum = nil) {|o| ...}

Creates a new set containing the elements of the given enumerable object.

If a block is given, the elements of enum are preprocessed by the given block.

Public Instance methods

&(enum)

Returns a new set containing elements common to the set and the given enumerable object.

+(enum)

Alias for #|

-(enum)

Returns a new set built by duplicating the set, removing every element that appears in the given enumerable object.

<<(o)

Alias for add

==(set)

Returns true if two sets are equal. The equality of each couple of elements is defined according to Object#eql?.

^(enum)

Returns a new set containing elements exclusive between the set and the given enumerable object. (set ^ enum) is equivalent to ((set | enum) - (set & enum)).

add(o)

Adds the given object to the set and returns self. Use merge to add several elements at once.

add?(o)

Adds the given object to the set and returns self. If the object is already in the set, returns nil.

classify( {|o| ...}

Classifies the set by the return value of the given block and returns a hash of {value => set of elements} pairs. The block is called once for each element of the set, passing the element as parameter.

e.g.:

  require 'set'
  files = Set.new(Dir.glob("*.rb"))
  hash = files.classify { |f| File.mtime(f).year }
  p hash    # => {2000=>#<Set: {"a.rb", "b.rb"}>,
            #     2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
            #     2002=>#<Set: {"f.rb"}>}
clear()

Removes all elements and returns self.

collect!() {|o| ...}

Do collect() destructively.

delete(o)

Deletes the given object from the set and returns self. Use subtract to delete several items at once.

delete?(o)

Deletes the given object from the set and returns self. If the object is not in the set, returns nil.

delete_if() {|o| ...}

Deletes every element of the set for which block evaluates to true, and returns self.

difference(enum)

Alias for #-

divide(&func)

Divides the set into a set of subsets according to the commonality defined by the given block.

If the arity of the block is 2, elements o1 and o2 are in common if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are in common if block.call(o1) == block.call(o2).

e.g.:

  require 'set'
  numbers = Set[1, 3, 4, 6, 9, 10, 11]
  set = numbers.divide { |i,j| (i - j).abs == 1 }
  p set     # => #<Set: {#<Set: {1}>,
            #            #<Set: {11, 9, 10}>,
            #            #<Set: {3, 4}>,
            #            #<Set: {6}>}>
each() {|o| ...}

Calls the given block once for each element in the set, passing the element as parameter.

empty?()

Returns true if the set contains no elements.

flatten()

Returns a new set that is a copy of the set, flattening each containing set recursively.

flatten!()

Equivalent to Set#flatten, but replaces the receiver with the result in place. Returns nil if no modifications were made.

include?(o)

Returns true if the set contains the given object.

initialize_copy(orig)

Copy internal hash.

inspect()

Returns a string containing a human-readable representation of the set. ("#<Set: {element1, element2, …}>")

intersection(enum)

Alias for #&

length()

Alias for size

map!()

Alias for collect!

member?(o)

Alias for include?

merge(enum)

Merges the elements of the given enumerable object to the set and returns self.

proper_subset?(set)

Returns true if the set is a proper subset of the given set.

proper_superset?(set)

Returns true if the set is a proper superset of the given set.

reject!() {|o| ...}

Equivalent to Set#delete_if, but returns nil if no changes were made.

replace(enum)

Replaces the contents of the set with the contents of the given enumerable object and returns self.

size()

Returns the number of elements.

subset?(set)

Returns true if the set is a subset of the given set.

subtract(enum)

Deletes every element that appears in the given enumerable object and returns self.

superset?(set)

Returns true if the set is a superset of the given set.

to_a()

Converts the set to an array. The order of elements is uncertain.

union(enum)

Alias for #|

|(enum)

Returns a new set built by merging the set and the elements of the given enumerable object.

Protected Instance methods

flatten_merge(set, seen = Set.new)


Class: Shell

Class | Shell
In: | lib/shell/process-controller.rb lib/shell/builtin-command.rb lib/shell/version.rb lib/shell/filter.rb lib/shell/system-command.rb lib/shell/command-processor.rb lib/shell/error.rb lib/shell.rb
Parent: | Object
  shell/filter.rb -
      $Release Version: 0.6.0 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—

Methods

alias_command cd cd chdir debug= debug= def_system_command default_record_separator default_record_separator= default_system_path default_system_path= expand_path inspect install_system_commands jobs kill new notify popd popdir pushd pushdir system_path= unalias_command undef_system_command

Included Modules

Error

Classes and Modules

Module Shell::Error
Class Shell::AppendFile
Class Shell::AppendIO
Class Shell::BuiltInCommand
Class Shell::Cat
Class Shell::CommandProcessor
Class Shell::Concat
Class Shell::Echo
Class Shell::Filter
Class Shell::Glob
Class Shell::ProcessController
Class Shell::SystemCommand
Class Shell::Tee

External Aliases

debug | -> | debug?
 | alias cascade? cascade
verbose | -> | verbose?
verbose | -> | verbose?
debug | -> | debug?
cwd | -> | dir
cwd | -> | getwd
cwd | -> | pwd
dir_stack | -> | dirs

Attributes

cascade | [RW] |
command_processor | [R] |
cwd | [R] | Dir related methods Shell#cwd/dir/getwd/pwd Shell#chdir/cd Shell#pushdir/pushd Shell#popdir/popd Shell#mkdir Shell#rmdir
debug | [RW] |
debug | [RW] |
dir_stack | [R] |
process_controller | [R] |
record_separator | [RW] |
system_path | [R] |
umask | [RW] |
verbose | [RW] |
verbose | [RW] |

Public Class methods

alias_command(ali, command, *opts, &block)
cd(path)
debug=(val)
def_system_command(command, path = command)

command definitions

default_record_separator()
default_record_separator=(rs)
default_system_path()
default_system_path=(path)
install_system_commands(pre = "sys_")
new()
notify(*opts) {|mes if iterator?| ...}
unalias_command(ali)
undef_system_command(command)

Public Instance methods

cd(path = nil)

Alias for chdir

chdir(path = nil) {|| ...}

If called as iterator, it restores the current directory when the block ends.

debug=(val)
expand_path(path)
inspect()
jobs()

process management

kill(sig, command)
popd()

Alias for popdir

popdir()
pushd(path = nil)

Alias for pushdir

pushdir(path = nil) {|| ...}
system_path=(path)


Class: Shell::AppendFile

Class | Shell::AppendFile
In: | lib/shell/builtin-command.rb
Parent: | AppendIO

Methods

input= new

Public Class methods

new(sh, to_filename, filter)

Public Instance methods

input=(filter)


Class: Shell::AppendIO

Class | Shell::AppendIO
In: | lib/shell/builtin-command.rb
Parent: | BuiltInCommand

class Sort < Cat

  def initialize(sh, *filenames)
    super
  end

  def each(rs = nil)
    ary = []
    super{|l|       ary.push l}
    for l in ary.sort!
    yield l
    end
  end

end

Methods

input= new

Public Class methods

new(sh, io, filter)

Public Instance methods

input=(filter)


Class: Shell::BuiltInCommand

Class | Shell::BuiltInCommand
In: | lib/shell/builtin-command.rb
Parent: | Filter

Methods

active? wait?

Public Instance methods

active?()
wait?()


Class: Shell::Cat

Class | Shell::Cat
In: | lib/shell/builtin-command.rb
Parent: | BuiltInCommand

Methods

each new

Public Class methods

new(sh, *filenames)

Public Instance methods

each(rs = nil) {|l| ...}


Class: Shell::CommandProcessor

Class | Shell::CommandProcessor
In: | lib/shell/command-processor.rb
Parent: | Object

Methods

[] add_delegate_command_to_shell alias_command alias_map append cat check_point concat def_builtin_commands def_system_command echo expand_path find_system_command finish_all_jobs foreach glob initialize install_builtin_commands install_system_commands method_added mkdir new notify open out rehash rmdir run_config system tee test transact unalias_command undef_system_command unlink

Constants

NoDelegateMethods = ["initialize", "expand_path"] initialize of Shell and related classes.

Public Class methods

add_delegate_command_to_shell(id)
alias_command(ali, command, *opts, &block)
alias_map()
def_builtin_commands(delegation_class, command_specs)

CommandProcessor.def_builtin_commands(delegation_class, command_specs)

    delegation_class: Class or Module
    command_specs: [[command_name, [argument,...]],...]
       command_name: String
       arguments:      String
          FILENAME?? -> expand_path(filename??)
          *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ")
  define command_name(argument,...) as
      delegation_class.command_name(argument,...)
def_system_command(command, path = command)

CommandProcessor.def_system_command(command, path)

    command:  String
    path:       String
  define 'command()' method as method.
initialize()
install_builtin_commands()

define default builtin commands

install_system_commands(pre = "sys_")

CommandProcessor.install_system_commands(pre)

      pre: String - command name prefix

defines every command which belongs in default_system_path via CommandProcessor.command(). It doesn‘t define already defined methods twice. By default, "pre_" is prefixes to each method name. Characters that may not be used in a method name are all converted to ‘_’. Definition errors are just ignored.

method_added(id)
new(shell)
run_config()

include run file.

unalias_command(ali)
undef_system_command(command)

Public Instance methods

[](command, file1, file2=nil)

Alias for test

append(to, filter)
cat(*filenames)
check_point()

ProcessCommand#transact

concat(*jobs)
echo(*strings)
expand_path(path)

CommandProcessor#expand_path(path)

    path:     String
    return: String
  returns the absolute path for <path>
find_system_command(command)
finish_all_jobs()

Alias for check_point

foreach(path = nil, *rs) {|fn| ...}

File related commands Shell#foreach Shell#open Shell#unlink Shell#test

-

CommandProcessor#foreach(path, rs)

    path: String
    rs:     String - record separator
    iterator
  Same as:
    File#foreach (when path is file)
    Dir#foreach (when path is directory)
  path is relative to pwd
glob(pattern)

def sort(*filenames)

  Sort.new(self, *filenames)

end

mkdir(*path)

Dir related methods

Shell#mkdir Shell#rmdir

notify(*opts) {|mes if iterator?| ...}

%pwd, %cwd -> @pwd

open(path, mode)

CommandProcessor#open(path, mode)

    path:     String
    mode:     String
    return: File or Dir
  Same as:
    File#open (when path is file)
    Dir#open  (when path is directory)
  mode has an effect only when path is a file
out(dev = STDOUT, &block)

internal commands

rehash()

ProcessCommand#rehash

  clear command hash table.
rmdir(*path)

CommandProcessor#rmdir(*path)

    path: String
  same as Dir.rmdir()
system(command, *opts)

CommandProcessor#system(command, *opts)

    command: String
    opts:      String
    return:  SystemCommand
  Same as system() function
  example:
    print sh.system("ls", "-l")
    sh.system("ls", "-l") | sh.head > STDOUT
tee(file)
test(command, file1, file2=nil)

CommandProcessor#test(command, file1, file2) CommandProcessor#[command, file1, file2]

    command: char or String or Symbol
    file1:   String
    file2:   String(optional)
    return: Boolean
  same as:
    test()     (when command is char or length 1 string or symbol)
    FileTest.command (others)
  example:
    sh[?e, "foo"]
    sh[:e, "foo"]
    sh["e", "foo"]
    sh[:exists?, "foo"]
    sh["exists?", "foo"]
transact(&block)
unlink(path)

CommandProcessor#unlink(path)

  same as:
    Dir#unlink  (when path is directory)
    File#unlink (when path is file)


Class: Shell::Concat

Class | Shell::Concat
In: | lib/shell/builtin-command.rb
Parent: | BuiltInCommand

Methods

each new

Public Class methods

new(sh, *jobs)

Public Instance methods

each(rs = nil) {|l| ...}


Class: Shell::Echo

Class | Shell::Echo
In: | lib/shell/builtin-command.rb
Parent: | BuiltInCommand

Methods

each new

Public Class methods

new(sh, *strings)

Public Instance methods

each(rs = nil) {|str + rs| ...}


Module: Shell::Error

Module | Shell::Error
In: | lib/shell/error.rb


Class: Shell::Filter

Class | Shell::Filter
In: | lib/shell/filter.rb
Parent: | Object

Filter A method to require

   each()

Methods

+ < > >> each input= inspect new to_a to_s |

Included Modules

Enumerable

Attributes

input [R]

Public Class methods

new(sh)

Public Instance methods

+(filter)
<(src)
>(to)
>>(to)
each(rs = nil) {|l| ...}
input=(filter)
inspect()
to_a()
to_s()
|(filter)


Class: Shell::Glob

Class | Shell::Glob
In: | lib/shell/builtin-command.rb
Parent: | BuiltInCommand

Methods

each new

Public Class methods

new(sh, pattern)

Public Instance methods

each(rs = nil) {|f+rs| ...}


Class: Shell::ProcessController

Class | Shell::ProcessController
In: | lib/shell/process-controller.rb
Parent: | Object

Methods

activate active_job? active_jobs active_jobs_exist? add_schedule each_active_object inactivate jobs jobs_exist? kill_job new process_controllers_exclusive sfork start_job terminate_job wait_all_jobs_execution waiting_job? waiting_jobs waiting_jobs_exist?

Public Class methods

activate(pc)
each_active_object() {|ref| ...}
inactivate(pc)
new(shell)
process_controllers_exclusive() {|| ...}

Public Instance methods

active_job?(job)
active_jobs()
active_jobs_exist?()
add_schedule(command)

schedule a command

jobs()
jobs_exist?()
kill_job(sig, command)

kill a job

sfork(command) {|| ...}

simple fork

start_job(command = nil)

start a job

terminate_job(command)

terminate a job

wait_all_jobs_execution()

wait for all jobs to terminate

waiting_job?(job)
waiting_jobs()
waiting_jobs_exist?()


Class: Shell::SystemCommand

Class | Shell::SystemCommand
In: | lib/shell/system-command.rb
Parent: | Filter

Methods

active? each flush input= kill new notify start start_export start_import terminate wait?

External Aliases

command | -> | name
each | -> | super_each

Attributes

command [R]

Public Class methods

new(sh, command, *opts)

Public Instance methods

active?()
each(rs = nil) {|l| ...}
flush()
input=(inp)
kill(sig)
notify(*opts) {|mes if iterator?| ...}

ex)

   if you wish to output:
      "shell: job(#{@command}:#{@pid}) close pipe-out."
   then
      mes: "job(%id) close pipe-out."
   yorn: Boolean(@shell.debug? or @shell.verbose?)
start()
start_export()
start_import()
terminate()
wait?()


Class: Shell::Tee

Class | Shell::Tee
In: | lib/shell/builtin-command.rb
Parent: | BuiltInCommand

Methods

each new

Public Class methods

new(sh, filename)

Public Instance methods

each(rs = nil) {|l| ...}


Module: Shellwords

Module | Shellwords
In: | lib/shellwords.rb

This module is originally a port of shellwords.pl, but modified to conform to POSIX / SUSv3 (IEEE Std 1003.1-2001).

Examples:

  require 'shellwords'
  words = Shellwords.shellwords(line)

or

  require 'shellwords'
  include Shellwords
  words = shellwords(line)

Methods

shellwords

Public Instance methods

shellwords(line)

Split text into an array of tokens in the same way the UNIX Bourne shell does.

See the Shellwords module documentation for an example.


Module: Signal

Module | Signal
In: | signal.c

Many operating systems allow signals to be sent to running processes. Some signals have a defined effect on the process, while others may be trapped at the code level and acted upon. For example, your process may trap the USR1 signal and use it to toggle debugging, and may use TERM to initiate a controlled shutdown.

    pid = fork do
      Signal.trap("USR1") do
        $debug = !$debug
        puts "Debug now: #$debug"
      end
      Signal.trap("TERM") do
        puts "Terminating..."
        shutdown()
      end
      # . . . do some work . . .
    end

    Process.detach(pid)

    # Controlling program:
    Process.kill("USR1", pid)
    # ...
    Process.kill("USR1", pid)
    # ...
    Process.kill("TERM", pid)

produces:

    Debug now: true
    Debug now: false
   Terminating...

The list of available signal names and their interpretation is system dependent. Signal delivery semantics may also vary between systems; in particular signal delivery may not always be reliable.

Methods

list trap

Public Class methods

Signal.list => a_hash

Returns a list of signal names mapped to the corresponding underlying signal numbers.

Signal.list #=>
{"ABRT"=>6, "ALRM"=>14, "BUS"=>7,
"CHLD"=>17, "CLD"=>17, "CONT"=>18,
"FPE"=>8, "HUP"=>1, "ILL"=>4,
"INT"=>2, "IO"=>29,
"IOT"=>6, "KILL"=>9, "PIPE"=>13,
"POLL"=>29, "PROF"=>27, "PWR"=>30,
"QUIT"=>3, "SEGV"=>11, "STOP"=>19,
"SYS"=>31, "TERM"=>15, "TRAP"=>5,
"TSTP"=>20, "TTIN"=>21, "TTOU"=>22,
"URG"=>23, "USR1"=>10, "USR2"=>12,
"VTALRM"=>26, "WINCH"=>28,
"XCPU"=>24, "XFSZ"=>25}

Signal.trap( signal, proc ) => obj
Signal.trap( signal ) {| | block } => obj

Specifies the handling of signals. The first parameter is a signal name (a string such as ``SIGALRM’’, ``SIGUSR1’’, and so on) or a signal number. The characters ``SIG’’ may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string ``IGNORE’’ or ``SIG_IGN’’, the signal will be ignored. If the command is ``DEFAULT’’ or ``SIG_DFL’’, the operating system‘s default handler will be invoked. If the command is ``EXIT’’, the script will be terminated by the signal. Otherwise, the given command or block will be run. The special signal name ``EXIT’’ or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

    Signal.trap(0, proc { puts "Terminating: #{$$}" })
    Signal.trap("CLD")  { puts "Child died" }
    fork && Process.wait

produces:

    Terminating: 27461
    Child died
    Terminating: 27460


Class: SignalException

Class | SignalException
In: | error.c
Parent: | Exception


Class: SimpleDelegator

Class | SimpleDelegator
In: | lib/delegate.rb
Parent: | Delegator

A concrete implementation of Delegator, this class provides the means to delegate all supported method calls to the object passed into the constructor and even to change the object being delegated to at a later time with __setobj__ .

Methods

__getobj__ __setobj__ clone dup new

Public Class methods

new(obj)

Pass in the obj you would like to delegate method calls to.

Public Instance methods

__getobj__()

Returns the current object method calls are being delegated to.

__setobj__(obj)

Changes the delegate object to obj.

It‘s important to note that this does not cause SimpleDelegator‘s methods to change. Because of this, you probably only want to change delegation to objects of the same type as the original delegate.

Here‘s an example of changing the delegation object.

  names = SimpleDelegator.new(%w{James Edward Gray II})
  puts names[1]    # => Edward
  names.__setobj__(%w{Gavin Sinclair})
  puts names[1]    # => Sinclair
clone()

Clone support for the object returned by __getobj__.

dup(obj)

Duplication support for the object returned by __getobj__.


Module: SingleForwardable

Module | SingleForwardable
In: | lib/forwardable.rb

The SingleForwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.

Also see the example at forwardable.rb.

Methods

def_delegator def_delegators def_singleton_delegator def_singleton_delegators

Public Instance methods

def_delegator(accessor, method, ali = method)

Alias for def_singleton_delegator

def_delegators(accessor, *methods)

Alias for def_singleton_delegators

def_singleton_delegator(accessor, method, ali = method)

Defines a method method which delegates to obj (i.e. it calls the method of the same name in obj). If new_name is provided, it is used as the name for the delegate method.

See the example at forwardable.rb.

def_singleton_delegators(accessor, *methods)

Shortcut for defining multiple delegator methods, but with no provision for using a different name. The following two code samples have the same effect:

  single_forwardable.def_delegators :@records, :size, :<<, :map

  single_forwardable.def_delegator :@records, :size
  single_forwardable.def_delegator :@records, :<<
  single_forwardable.def_delegator :@records, :map

See the example at forwardable.rb.


Module: Singleton

Module | Singleton
In: | lib/singleton.rb

The Singleton module implements the Singleton pattern.

Usage:

   class Klass
      include Singleton
      # ...
   end
  • this ensures that only one instance of Klass lets call it ``the instance’’ can be created.

    a,b = Klass.instance, Klass.instance a == b # => true a.new # NoMethodError - new is private …

  • ``The instance’’ is created at instantiation time, in other words the first call of Klass.instance(), thus
      class OtherKlass
    include Singleton
    # ...
  end
  ObjectSpace.each_object(OtherKlass){} # => 0.
  • This behavior is preserved under inheritance and cloning.

This is achieved by marking

  • Klass.new and Klass.allocate - as private

Providing (or modifying) the class methods

  • Klass.inherited(sub_klass) and Klass.clone() - to ensure that the Singleton pattern is properly inherited and cloned.
  • Klass.instance() - returning ``the instance’’. After a successful self modifying (normally the first) call the method body is a simple:
       def Klass.instance()
     return @__instance__
   end
  • Klass._load(str) - calling Klass.instance()
  • Klass._instantiate?() - returning ``the instance’’ or nil. This hook method puts a second (or nth) thread calling Klass.instance() on a waiting loop. The return value signifies the successful completion or premature termination of the first, or more generally, current "instantiation thread".

The instance method of Singleton are

  • clone and dup - raising TypeErrors to prevent cloning or duping
  • _dump(depth) - returning the empty string. Marshalling strips by default all state information, e.g. instance variables and taint state, from ``the instance’’. Providing custom _load(str) and _dump(depth) hooks allows the (partially) resurrections of a previous state of ``the instance’’.

Methods

clone dup

Public Instance methods

clone()

disable build-in copying methods

dup()


Module: SingletonClassMethods

Module | SingletonClassMethods
In: | lib/singleton.rb

Methods

clone

Public Instance methods

clone()

properly clone the Singleton pattern - did you know that duping doesn‘t copy class methods?


Class: SizedQueue

Class | SizedQueue
In: | lib/thread.rb
Parent: | Queue

This class represents queues of specified size capacity. The push operation may be blocked if the capacity is full.

See Queue for an example of how a SizedQueue works.

Methods

<< deq enq max max= new num_waiting pop push shift

Public Class methods

new(max)

Creates a fixed-length queue with a maximum size of max.

Public Instance methods

<<(obj)

Alias for push

deq(*args)

Alias for pop

enq(obj)

Alias for push

max()

Returns the maximum size of the queue.

max=(max)

Sets the maximum size of the queue.

num_waiting()

Returns the number of threads waiting on the queue.

pop(*args)

Retrieves data from the queue and runs a waiting thread, if any.

push(obj)

Pushes obj to the queue. If there is no space left in the queue, waits until space becomes available.

shift(*args)

Alias for pop


Class: Socket

Class | Socket
In: | lib/ipaddr.rb ext/socket/socket.c
Parent: | Object

Class Socket provides access to the underlying operating system socket implementations. It can be used to provide more operating system specific functionality than the protocol-specific socket classes but at the expense of greater complexity. In particular, the class handles addresses using +struct sockaddr+ structures packed into Ruby strings, which can be a joy to manipulate.

Exception Handling

Ruby‘s implementation of Socket causes an exception to be raised based on the error generated by the system dependent implementation. This is why the methods are documented in a way that isolate Unix-based system exceptions from Windows based exceptions. If more information on particular exception is needed please refer to the Unix manual pages or the Windows WinSock reference.

Documentation by

  • Zach Dennis
  • Sam Roberts
  • Programming Ruby from The Pragmatic Bookshelf.

Much material in this documentation is taken with permission from Programming Ruby from The Pragmatic Bookshelf.

Methods

accept accept_nonblock bind connect connect_nonblock getaddrinfo gethostbyname getservbyname listen recvfrom recvfrom_nonblock sysaccept

Classes and Modules

Module Socket::Constants

Constants

AF_INET6 = Object.new

Public Class methods

Socket.getaddrinfo(host, service, family=nil, socktype=nil, protocol=nil, flags=nil) => addrinfo

Return address information for host and port. The remaining arguments are hints that limit the address information returned.

This method corresponds closely to the POSIX.1g getaddrinfo() definition.

Parameters

  • host is a host name or an address string (dotted decimal for IPv4, or a hex string for IPv6) for which to return information. A nil is also allowed, its meaning depends on flags, see below.
  • service is a service name ("http", "ssh", …), or a port number (80, 22, …), see Socket.getservbyname for more information. A nil is also allowed, meaning zero.
  • family limits the output to a specific address family, one of the Socket::AF_* constants. Socket::AF_INET (IPv4) and Socket::AF_INET6 (IPv6) are the most commonly used families. You will usually pass either nil or Socket::AF_UNSPEC, allowing the IPv6 information to be returned first if host is reachable via IPv6, and IPv4 information otherwise. The two strings "AF_INET" or "AF_INET6" are also allowed, they are converted to their respective Socket::AF_* constants.
  • socktype limits the output to a specific type of socket, one of the Socket::SOCK_* constants. Socket::SOCK_STREAM (for TCP) and Socket::SOCK_DGRAM (for UDP) are the most commonly used socket types. If nil, then information for all types of sockets supported by service will be returned. You will usually know what type of socket you intend to create, and should pass that socket type in.
  • protocol limits the output to a specific protocol numpber, one of the Socket::IPPROTO_* constants. It is usually implied by the socket type (Socket::SOCK_STREAM => Socket::IPPROTO_TCP, …), if you pass other than nil you already know what this is for.
  • flags is one of the Socket::AI_* constants. They mean:
    • Socket::AI_PASSIVE: when set, if host is nil the ‘any’ address will be returned, Socket::INADDR_ANY or 0 for IPv4, "0::0" or "::" for IPv6. This address is suitable for use by servers that will bind their socket and do a passive listen, thus the name of the flag. Otherwise the local or loopback address will be returned, this is "127.0.0.1" for IPv4 and "::1’ for IPv6.
    • …

Returns

Returns an array of arrays, where each subarray contains:

  • address family, a string like "AF_INET" or "AF_INET6"
  • port number, the port number for service
  • host name, either a canonical name for host, or it‘s address in presentation format if the address could not be looked up.
  • host IP, the address of host in presentation format
  • address family, as a numeric value (one of the Socket::AF_* constants).
  • socket type, as a numeric value (one of the Socket::SOCK_* constants).
  • protocol number, as a numeric value (one of the Socket::IPPROTO_* constants).

The first four values are identical to what is commonly returned as an address array, see IPSocket for more information.

Examples

Not all input combinations are valid, and while there are many combinations, only a few cases are common.

A typical client will call getaddrinfo with the host and service it wants to connect to. It knows that it will attempt to connect with either TCP or UDP, and specifies socktype accordingly. It loops through all returned addresses, and try to connect to them in turn:

  addrinfo = Socket::getaddrinfo('www.example.com', 'www', nil, Socket::SOCK_STREAM)
  addrinfo.each do |af, port, name, addr|
    begin
      sock = TCPSocket.new(addr, port)
      # ...
      exit 1
    rescue
    end
  end

With UDP you don‘t know if connect suceeded, but if communication fails, the next address can be tried.

A typical server will call getaddrinfo with a host of nil, the service it listens to, and a flags of Socket::AI_PASSIVE. It will listen for connections on the first returned address:

  addrinfo = Socket::getaddrinfo(nil, 'www', nil, Socket::SOCK_STREAM, nil, Socket::AI_PASSIVE)
  af, port, name, addr = addrinfo.first
  sock = TCPServer(addr, port)
  while( client = s.accept )
    # ...
  end
Socket.gethostbyname(host) => hostent

Resolve host and return name and address information for it, similarly to gethostbyname(3). host can be a domain name or the presentation format of an address.

Returns an array of information similar to that found in a +struct hostent+:

  - cannonical name: the cannonical name for host in the DNS, or a
    string representing the address
  - aliases: an array of aliases for the canonical name, there may be no aliases
  - address family: usually one of Socket::AF_INET or Socket::AF_INET6
  - address: a string, the binary value of the +struct sockaddr+ for this name, in
    the indicated address family
  - ...: if there are multiple addresses for this host,  a series of
    strings/+struct sockaddr+s may follow, not all necessarily in the same
    address family. Note that the fact that they may not be all in the same
    address family is a departure from the behaviour of gethostbyname(3).

Note: I believe that the fact that the multiple addresses returned are not necessarily in the same address family may be a bug, since if this function actually called gethostbyname(3), ALL the addresses returned in the trailing address list (h_addr_list from struct hostent) would be of the same address family! Examples from my system, OS X 10.3:

  ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"]
    and
  ["ensemble.local", [], 30, "\376\200\000\004\000\000\000\000\002\003\223\377\376\255\010\214", "\300\250{\232" ]

Similar information can be returned by Socket.getaddrinfo if called as:

   Socket.getaddrinfo(+host+, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)

Examples

  Socket.gethostbyname "example.com"
  => ["example.com", [], 2, "\300\000\"\246"]

This name has no DNS aliases, and a single IPv4 address.

  Socket.gethostbyname "smtp.telus.net"
  => ["smtp.svc.telus.net", ["smtp.telus.net"], 2, "\307\271\334\371"]

This name is an an alias so the canonical name is returned, as well as the alias and a single IPv4 address.

  Socket.gethostbyname "localhost"
  => ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"]

This machine has no aliases, returns an IPv6 address, and has an additional IPv4 address.

host can also be an IP address in presentation format, in which case a reverse lookup is done on the address:

  Socket.gethostbyname("127.0.0.1")
  => ["localhost", [], 2, "\177\000\000\001"]

  Socket.gethostbyname("192.0.34.166")
  => ["www.example.com", [], 2, "\300\000\"\246"]

See

See: Socket.getaddrinfo

Socket.getservbyname(name, proto="tcp") => port

name is a service name ("ftp", "telnet", …) and proto is a protocol name ("udp", "tcp", …). ’/etc/services’ (or your system‘s equivalent) is searched for a service for name and proto, and the port number is returned.

Note that unlike Socket.getaddrinfo, proto may not be specified using the Socket::SOCK_* constants, a string must must be used.

Public Instance methods

socket.accept => [ socket, string ]

Accepts an incoming connection returning an array containing a new Socket object and a string holding the struct sockaddr information about the caller.

Example

     # In one script, start this first
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )
     socket.listen( 5 )
     client, client_sockaddr = socket.accept
     puts "The client said, '#{client.readline.chomp}'"
     client.puts "Hello from script one!"
     socket.close

     # In another script, start this second
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.connect( sockaddr )
     socket.puts "Hello from script 2."
     puts "The server said, '#{socket.readline.chomp}'"
     socket.close

Unix-based Exceptions

On unix-based based systems the following system exceptions may be raised if the call to accept fails:

  • Errno::EAGAIN - O_NONBLOCK is set for the socket file descriptor and no connections are parent to be accepted
  • Errno::EWOULDBLOCK - same as Errno::EAGAIN
  • Errno::EBADF - the socket is not a valid file descriptor
  • Errno::ECONNABORTED - a connection has been aborted
  • Errno::EFAULT - the socket‘s internal address or address length parameter cannot be access or written
  • Errno::EINTR - the accept method was interrupted by a signal that was caught before a valid connection arrived
  • Errno::EINVAL - the socket is not accepting connections
  • Errno::EMFILE - OPEN_MAX file descriptors are currently open in the calling process
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOMEM - there was insufficient memory available to complete the operation
  • Errno::ENOSR - there was insufficient STREAMS resources available to complete the operation
  • Errno::ENFILE - the maximum number of file descriptors in the system are already open
  • Errno::ENOTSOCK - the socket does not refer to a socket
  • Errno::EOPNOTSUPP - the socket type for the calling socket does not support accept connections
  • Errno::EPROTO - a protocol error has occurred

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to accept fails:

  • Errno::ECONNRESET - an incoming connection was indicated, but was terminated by the remote peer prior to accepting the connection
  • Errno::EFAULT - the socket‘s internal address or address length parameter is too small or is not a valid part of the user space address
  • Errno::EINVAL - the listen method was not invoked prior to calling accept
  • Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or the service provider is still processing a callback function
  • Errno::EMFILE - the queue is not empty, upong etry to accept and there are no socket descriptors available
  • Errno::ENETDOWN - the network is down
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOTSOCK - socket is not a socket
  • Errno::EOPNOTSUPP - socket is not a type that supports connection-oriented service.
  • Errno::EWOULDBLOCK - socket is marked as nonblocking and no connections are present to be accepted

See

  • accept manual pages on unix-based systems
  • accept function in Microsoft‘s Winsock functions reference
socket.accept_nonblock => [client_socket, client_sockaddr]

Accepts an incoming connection using accept(2) after O_NONBLOCK is set for the underlying file descriptor. It returns an array containg the accpeted socket for the incoming connection, client_socket, and a string that contains the struct sockaddr information about the caller, client_sockaddr.

Example

     # In one script, start this first
     require 'socket'
     include Socket::Constants
     socket = Socket.new(AF_INET, SOCK_STREAM, 0)
     sockaddr = Socket.sockaddr_in(2200, 'localhost')
     socket.bind(sockaddr)
     socket.listen(5)
     begin
       client_socket, client_sockaddr = socket.accept_nonblock
     rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
       IO.select([socket])
       retry
     end
     puts "The client said, '#{client_socket.readline.chomp}'"
     client_socket.puts "Hello from script one!"
     socket.close

     # In another script, start this second
     require 'socket'
     include Socket::Constants
     socket = Socket.new(AF_INET, SOCK_STREAM, 0)
     sockaddr = Socket.sockaddr_in(2200, 'localhost')
     socket.connect(sockaddr)
     socket.puts "Hello from script 2."
     puts "The server said, '#{socket.readline.chomp}'"
     socket.close

Refer to Socket#accept for the exceptions that may be thrown if the call to accept_nonblock fails.

Socket#accept_nonblock may raise any error corresponding to accept(2) failure, including Errno::EAGAIN.

See

  • Socket#accept
socket.bind(server_sockaddr) => 0

Binds to the given struct sockaddr.

Parameter

  • server_sockaddr - the struct sockaddr contained in a string

Example

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )

Unix-based Exceptions

On unix-based based systems the following system exceptions may be raised if the call to bind fails:

  • Errno::EACCES - the specified sockaddr is protected and the current user does not have permission to bind to it
  • Errno::EADDRINUSE - the specified sockaddr is already in use
  • Errno::EADDRNOTAVAIL - the specified sockaddr is not available from the local machine
  • Errno::EAFNOSUPPORT - the specified sockaddr isnot a valid address for the family of the calling socket
  • Errno::EBADF - the sockaddr specified is not a valid file descriptor
  • Errno::EFAULT - the sockaddr argument cannot be accessed
  • Errno::EINVAL - the socket is already bound to an address, and the protocol does not support binding to the new sockaddr or the socket has been shut down.
  • Errno::EINVAL - the address length is not a valid length for the address family
  • Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded PATH_MAX
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOSR - there were insufficient STREAMS resources available to complete the operation
  • Errno::ENOTSOCK - the socket does not refer to a socket
  • Errno::EOPNOTSUPP - the socket type of the socket does not support binding to an address

On unix-based based systems if the address family of the calling socket is Socket::AF_UNIX the follow exceptions may be raised if the call to bind fails:

  • Errno::EACCES - search permission is denied for a component of the prefix path or write access to the socket is denided
  • Errno::EDESTADDRREQ - the sockaddr argument is a null pointer
  • Errno::EISDIR - same as Errno::EDESTADDRREQ
  • Errno::EIO - an i/o error occurred
  • Errno::ELOOP - too many symbolic links were encountered in translating the pathname in sockaddr
  • Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX characters, or an entired pathname exceeded PATH_MAX characters
  • Errno::ENOENT - a component of the pathname does not name an existing file or the pathname is an empty string
  • Errno::ENOTDIR - a component of the path prefix of the pathname in sockaddr is not a directory
  • Errno::EROFS - the name would reside on a read only filesystem

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to bind fails:

  • Errno::ENETDOWN— the network is down
  • Errno::EACCES - the attempt to connect the datagram socket to the broadcast address failed
  • Errno::EADDRINUSE - the socket‘s local address is already in use
  • Errno::EADDRNOTAVAIL - the specified address is not a valid address for this computer
  • Errno::EFAULT - the socket‘s internal address or address length parameter is too small or is not a valid part of the user space addressed
  • Errno::EINVAL - the socket is already bound to an address
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOTSOCK - the socket argument does not refer to a socket

See

  • bind manual pages on unix-based systems
  • bind function in Microsoft‘s Winsock functions reference
socket.connect(server_sockaddr) => 0

Requests a connection to be made on the given server_sockaddr. Returns 0 if successful, otherwise an exception is raised.

Parameter

  • server_sockaddr - the struct sockaddr contained in a string

Example:

     # Pull down Google's web page
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
     socket.connect( sockaddr )
     socket.write( "GET / HTTP/1.0\r\n\r\n" )
     results = socket.read

Unix-based Exceptions

On unix-based systems the following system exceptions may be raised if the call to connect fails:

  • Errno::EACCES - search permission is denied for a component of the prefix path or write access to the socket is denided
  • Errno::EADDRINUSE - the sockaddr is already in use
  • Errno::EADDRNOTAVAIL - the specified sockaddr is not available from the local machine
  • Errno::EAFNOSUPPORT - the specified sockaddr is not a valid address for the address family of the specified socket
  • Errno::EALREADY - a connection is already in progress for the specified socket
  • Errno::EBADF - the socket is not a valid file descriptor
  • Errno::ECONNREFUSED - the target sockaddr was not listening for connections refused the connection request
  • Errno::ECONNRESET - the remote host reset the connection request
  • Errno::EFAULT - the sockaddr cannot be accessed
  • Errno::EHOSTUNREACH - the destination host cannot be reached (probably because the host is down or a remote router cannot reach it)
  • Errno::EINPROGRESS - the O_NONBLOCK is set for the socket and the connection cnanot be immediately established; the connection will be established asynchronously
  • Errno::EINTR - the attempt to establish the connection was interrupted by delivery of a signal that was caught; the connection will be established asynchronously
  • Errno::EISCONN - the specified socket is already connected
  • Errno::EINVAL - the address length used for the sockaddr is not a valid length for the address family or there is an invalid family in sockaddr
  • Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded PATH_MAX
  • Errno::ENETDOWN - the local interface used to reach the destination is down
  • Errno::ENETUNREACH - no route to the network is present
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOSR - there were insufficient STREAMS resources available to complete the operation
  • Errno::ENOTSOCK - the socket argument does not refer to a socket
  • Errno::EOPNOTSUPP - the calling socket is listening and cannot be connected
  • Errno::EPROTOTYPE - the sockaddr has a different type than the socket bound to the specified peer address
  • Errno::ETIMEDOUT - the attempt to connect time out before a connection was made.

On unix-based systems if the address family of the calling socket is AF_UNIX the follow exceptions may be raised if the call to connect fails:

  • Errno::EIO - an i/o error occured while reading from or writing to the file system
  • Errno::ELOOP - too many symbolic links were encountered in translating the pathname in sockaddr
  • Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX characters, or an entired pathname exceeded PATH_MAX characters
  • Errno::ENOENT - a component of the pathname does not name an existing file or the pathname is an empty string
  • Errno::ENOTDIR - a component of the path prefix of the pathname in sockaddr is not a directory

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to connect fails:

  • Errno::ENETDOWN - the network is down
  • Errno::EADDRINUSE - the socket‘s local address is already in use
  • Errno::EINTR - the socket was cancelled
  • Errno::EINPROGRESS - a blocking socket is in progress or the service provider is still processing a callback function. Or a nonblocking connect call is in progress on the socket.
  • Errno::EALREADY - see Errno::EINVAL
  • Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as ADDR_ANY TODO check ADDRANY TO INADDR_ANY
  • Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with with this socket
  • Errno::ECONNREFUSED - the target sockaddr was not listening for connections refused the connection request
  • Errno::EFAULT - the socket‘s internal address or address length parameter is too small or is not a valid part of the user space address
  • Errno::EINVAL - the socket is a listening socket
  • Errno::EISCONN - the socket is already connected
  • Errno::ENETUNREACH - the network cannot be reached from this host at this time
  • Errno::EHOSTUNREACH - no route to the network is present
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOTSOCK - the socket argument does not refer to a socket
  • Errno::ETIMEDOUT - the attempt to connect time out before a connection was made.
  • Errno::EWOULDBLOCK - the socket is marked as nonblocking and the connection cannot be completed immediately
  • Errno::EACCES - the attempt to connect the datagram socket to the broadcast address failed

See

  • connect manual pages on unix-based systems
  • connect function in Microsoft‘s Winsock functions reference
socket.connect_nonblock(server_sockaddr) => 0

Requests a connection to be made on the given server_sockaddr after O_NONBLOCK is set for the underlying file descriptor. Returns 0 if successful, otherwise an exception is raised.

Parameter

  • server_sockaddr - the struct sockaddr contained in a string

Example:

     # Pull down Google's web page
     require 'socket'
     include Socket::Constants
     socket = Socket.new(AF_INET, SOCK_STREAM, 0)
     sockaddr = Socket.sockaddr_in(80, 'www.google.com')
     begin
       socket.connect_nonblock(sockaddr)
     rescue Errno::EINPROGRESS
       IO.select(nil, [socket])
       begin
         socket.connect_nonblock(sockaddr)
       rescue Errno::EISCONN
       end
     end
     socket.write("GET / HTTP/1.0\r\n\r\n")
     results = socket.read

Refer to Socket#connect for the exceptions that may be thrown if the call to connect_nonblock fails.

Socket#connect_nonblock may raise any error corresponding to connect(2) failure, including Errno::EINPROGRESS.

See

  • Socket#connect
socket.listen( int ) => 0

Listens for connections, using the specified int as the backlog. A call to listen only applies if the socket is of type SOCK_STREAM or SOCK_SEQPACKET.

Parameter

  • backlog - the maximum length of the queue for pending connections.

Example 1

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )
     socket.listen( 5 )

Example 2 (listening on an arbitary port, unix-based systems only):

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     socket.listen( 1 )

Unix-based Exceptions

On unix based systems the above will work because a new sockaddr struct is created on the address ADDR_ANY, for an arbitrary port number as handed off by the kernel. It will not work on Windows, because Windows requires that the socket is bound by calling bind before it can listen.

If the backlog amount exceeds the implementation-dependent maximum queue length, the implementation‘s maximum queue length will be used.

On unix-based based systems the following system exceptions may be raised if the call to listen fails:

  • Errno::EBADF - the socket argument is not a valid file descriptor
  • Errno::EDESTADDRREQ - the socket is not bound to a local address, and the protocol does not support listening on an unbound socket
  • Errno::EINVAL - the socket is already connected
  • Errno::ENOTSOCK - the socket argument does not refer to a socket
  • Errno::EOPNOTSUPP - the socket protocol does not support listen
  • Errno::EACCES - the calling process does not have approriate privileges
  • Errno::EINVAL - the socket has been shut down
  • Errno::ENOBUFS - insufficient resources are available in the system to complete the call

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to listen fails:

  • Errno::ENETDOWN - the network is down
  • Errno::EADDRINUSE - the socket‘s local address is already in use. This usually occurs during the execution of bind but could be delayed if the call to bind was to a partially wildcard address (involving ADDR_ANY) and if a specific address needs to be commmitted at the time of the call to listen
  • Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the service provider is still processing a callback function
  • Errno::EINVAL - the socket has not been bound with a call to bind.
  • Errno::EISCONN - the socket is already connected
  • Errno::EMFILE - no more socket descriptors are available
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOTSOC - socket is not a socket
  • Errno::EOPNOTSUPP - the referenced socket is not a type that supports the listen method

See

  • listen manual pages on unix-based systems
  • listen function in Microsoft‘s Winsock functions reference
socket.recvfrom(maxlen) => [mesg, sender_sockaddr]
socket.recvfrom(maxlen, flags) => [mesg, sender_sockaddr]

Receives up to maxlen bytes from socket. flags is zero or more of the MSG_ options. The first element of the results, mesg, is the data received. The second element, sender_sockaddr, contains protocol-specific information on the sender.

Parameters

  • maxlen - the number of bytes to receive from the socket
  • flags - zero or more of the MSG_ options

Example

     # In one file, start this first
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )
     socket.listen( 5 )
     client, client_sockaddr = socket.accept
     data = client.recvfrom( 20 )[0].chomp
     puts "I only received 20 bytes '#{data}'"
     sleep 1
     socket.close

     # In another file, start this second
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.connect( sockaddr )
     socket.puts "Watch this get cut short!"
     socket.close

Unix-based Exceptions

On unix-based based systems the following system exceptions may be raised if the call to recvfrom fails:

  • Errno::EAGAIN - the socket file descriptor is marked as O_NONBLOCK and no data is waiting to be received; or MSG_OOB is set and no out-of-band data is available and either the socket file descriptor is marked as O_NONBLOCK or the socket does not support blocking to wait for out-of-band-data
  • Errno::EWOULDBLOCK - see Errno::EAGAIN
  • Errno::EBADF - the socket is not a valid file descriptor
  • Errno::ECONNRESET - a connection was forcibly closed by a peer
  • Errno::EFAULT - the socket‘s internal buffer, address or address length cannot be accessed or written
  • Errno::EINTR - a signal interupted recvfrom before any data was available
  • Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
  • Errno::EIO - an i/o error occurred while reading from or writing to the filesystem
  • Errno::ENOBUFS - insufficient resources were available in the system to perform the operation
  • Errno::ENOMEM - insufficient memory was available to fulfill the request
  • Errno::ENOSR - there were insufficient STREAMS resources available to complete the operation
  • Errno::ENOTCONN - a receive is attempted on a connection-mode socket that is not connected
  • Errno::ENOTSOCK - the socket does not refer to a socket
  • Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
  • Errno::ETIMEDOUT - the connection timed out during connection establishment or due to a transmission timeout on an active connection

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to recvfrom fails:

  • Errno::ENETDOWN - the network is down
  • Errno::EFAULT - the internal buffer and from parameters on socket are not part of the user address space, or the internal fromlen parameter is too small to accomodate the peer address
  • Errno::EINTR - the (blocking) call was cancelled by an internal call to the WinSock function WSACancelBlockingCall
  • Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or the service provider is still processing a callback function
  • Errno::EINVAL - socket has not been bound with a call to bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal len parameter on socket was zero or negative
  • Errno::EISCONN - socket is already connected. The call to recvfrom is not permitted with a connected socket on a socket that is connetion oriented or connectionless.
  • Errno::ENETRESET - the connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress.
  • Errno::EOPNOTSUPP - MSG_OOB was specified, but socket is not stream-style such as type SOCK_STREAM. OOB data is not supported in the communication domain associated with socket, or socket is unidirectional and supports only send operations
  • Errno::ESHUTDOWN - socket has been shutdown. It is not possible to call recvfrom on a socket after shutdown has been invoked.
  • Errno::EWOULDBLOCK - socket is marked as nonblocking and a call to recvfrom would block.
  • Errno::EMSGSIZE - the message was too large to fit into the specified buffer and was truncated.
  • Errno::ETIMEDOUT - the connection has been dropped, because of a network failure or because the system on the other end went down without notice
  • Errno::ECONNRESET - the virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket; it is no longer usable. On a UDP-datagram socket this error indicates a previous send operation resulted in an ICMP Port Unreachable message.
socket.recvfrom_nonblock(maxlen) => [mesg, sender_sockaddr]
socket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_sockaddr]

Receives up to maxlen bytes from socket using recvfrom(2) after O_NONBLOCK is set for the underlying file descriptor. flags is zero or more of the MSG_ options. The first element of the results, mesg, is the data received. The second element, sender_sockaddr, contains protocol-specific information on the sender.

When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns an empty string as data. The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.

Parameters

  • maxlen - the number of bytes to receive from the socket
  • flags - zero or more of the MSG_ options

Example

     # In one file, start this first
     require 'socket'
     include Socket::Constants
     socket = Socket.new(AF_INET, SOCK_STREAM, 0)
     sockaddr = Socket.sockaddr_in(2200, 'localhost')
     socket.bind(sockaddr)
     socket.listen(5)
     client, client_sockaddr = socket.accept
     begin
       pair = client.recvfrom_nonblock(20)
     rescue Errno::EAGAIN
       IO.select([client])
       retry
     end
     data = pair[0].chomp
     puts "I only received 20 bytes '#{data}'"
     sleep 1
     socket.close

     # In another file, start this second
     require 'socket'
     include Socket::Constants
     socket = Socket.new(AF_INET, SOCK_STREAM, 0)
     sockaddr = Socket.sockaddr_in(2200, 'localhost')
     socket.connect(sockaddr)
     socket.puts "Watch this get cut short!"
     socket.close

Refer to Socket#recvfrom for the exceptions that may be thrown if the call to recvfrom_nonblock fails.

Socket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure, including Errno::EAGAIN.

See

  • Socket#recvfrom
socket.sysaccept => [client_socket_fd, client_sockaddr]

Accepts an incoming connection returnings an array containg the (integer) file descriptor for the incoming connection, client_socket_fd, and a string that contains the struct sockaddr information about the caller, client_sockaddr.

Example

     # In one script, start this first
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )
     socket.listen( 5 )
     client_fd, client_sockaddr = socket.sysaccept
     client_socket = Socket.for_fd( client_fd )
     puts "The client said, '#{client_socket.readline.chomp}'"
     client_socket.puts "Hello from script one!"
     socket.close

     # In another script, start this second
     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.connect( sockaddr )
     socket.puts "Hello from script 2."
     puts "The server said, '#{socket.readline.chomp}'"
     socket.close

Refer to Socket#accept for the exceptions that may be thrown if the call to sysaccept fails.

See

  • Socket#accept


Module: Socket::Constants

Module | Socket::Constants
In: | ext/socket/socket.c


Class: SocketError

Class | SocketError
In: | ext/socket/socket.c
Parent: | StandardError


Class: SortedSet

Class | SortedSet
In: | lib/set.rb
Parent: | Set

SortedSet implements a set which elements are sorted in order. See Set.

External Aliases

initialize | -> | old_init
 | a hack to shut up warning


Class: StandardError

Class | StandardError
In: | error.c
Parent: | Exception


Class: StringIO

Class | StringIO
In: | lib/yaml/stringio.rb ext/stringio/stringio.c
Parent: | Object

Pseudo I/O on String object.

Methods

<< binmode close close_read close_write closed? closed_read? closed_write? each each_byte each_line eof eof eof? eof? fcntl fileno flush fsync getc gets isatty length lineno lineno= new new open path pid pos pos pos= print printf putc puts read readchar readline readline readlines reopen rewind rewind seek seek size string string= sync sync= sysread syswrite tell truncate tty? ungetc write

Included Modules

Enumerable

Public Class methods

new(string="")
StringIO.new(string=""[, mode])

Creates new StringIO instance from with string and mode.

StringIO.open(string=""[, mode]) {|strio| ...}

Equivalent to StringIO.new except that when it is called with a block, it yields with the new instance and closes it, and returns the result which returned from the block.

Public Instance methods

strio << obj → strio

See IO#<<.

strio.binmode → true

Returns strio itself. Just for compatibility to IO.

strio.close → nil

Closes strio. The strio is unavailable for any further data operations; an IOError is raised if such an attempt is made.

strio.close_read → nil

Closes the read end of a StringIO. Will raise an IOError if the strio is not readable.

strio.close_write → nil

Closes the write end of a StringIO. Will raise an IOError if the strio is not writeable.

strio.closed? → true or false

Returns true if strio is completely closed, false otherwise.

strio.closed_read? → true or false

Returns true if strio is not readable, false otherwise.

strio.closed_write? → true or false

Returns true if strio is not writable, false otherwise.

strio.each(sep_string=$/) {|line| block } → strio
strio.each_line(sep_string=$/) {|line| block } → strio

See IO#each.

strio.each_byte {|byte| block } → strio

See IO#each_byte.

strio.each(sep_string=$/) {|line| block } → strio
strio.each_line(sep_string=$/) {|line| block } → strio

See IO#each.

eof()
strio.eof → true or false
strio.eof? → true or false

Returns true if strio is at end of file. The stringio must be opened for reading or an IOError will be raised.

eof?()

Alias for eof

strio.eof → true or false
strio.eof? → true or false

Returns true if strio is at end of file. The stringio must be opened for reading or an IOError will be raised.

strio.fcntl

Raises NotImplementedError.

strio.fileno → nil

Returns nil. Just for compatibility to IO.

strio.flush → strio

Returns strio itself. Just for compatibility to IO.

strio.fsync → 0

Returns 0. Just for compatibility to IO.

strio.getc → fixnum or nil

See IO#getc.

strio.gets(sep_string=$/) → string or nil

See IO#gets.

strio.isatty → nil
strio.tty? → nil

Returns false. Just for compatibility to IO.

strio.size → integer

Returns the size of the buffer string.

strio.lineno → integer

Returns the current line number in strio. The stringio must be opened for reading. lineno counts the number of times gets is called, rather than the number of newlines encountered. The two values will differ if gets is called with a separator other than newline. See also the $. variable.

strio.lineno = integer → integer

Manually sets the current line number to the given value. $. is updated only on the next read.

strio.path → nil

Returns nil. Just for compatibility to IO.

strio.pid → nil

Returns nil. Just for compatibility to IO.

pos()
strio.pos → integer
strio.tell → integer

Returns the current offset (in bytes) of strio.

strio.pos = integer → integer

Seeks to the given position (in bytes) in strio.

strio.print() → nil
strio.print(obj, ...) → nil

See IO#print.

strio.printf(format_string [, obj, ...] ) → nil

See IO#printf.

strio.putc(obj) → obj

See IO#putc.

strio.puts(obj, ...) → nil

See IO#puts.

strio.read([length [, buffer]]) → string, buffer, or nil

See IO#read.

strio.readchar → fixnum

See IO#readchar.

readline(rs=$/)
strio.readline(sep_string=$/) → string

See IO#readline.

strio.readlines(sep_string=$/) → array

See IO#readlines.

strio.reopen(other_StrIO) → strio
strio.reopen(string, mode) → strio

Reinitializes strio with the given other_StrIO or string and mode (see StringIO#new).

strio.rewind → 0

Positions strio to the beginning of input, resetting lineno to zero.

rewind()
seek(offset,whence)
strio.seek(amount, whence=SEEK_SET) → 0

Seeks to a given offset amount in the stream according to the value of whence (see IO#seek).

strio.size → integer

Returns the size of the buffer string.

strio.string → string

Returns underlying String object, the subject of IO.

strio.string = string → string

Changes underlying String object, the subject of IO.

strio.sync → true

Returns true always.

strio.sync = boolean → boolean

Returns the argument unchanged. Just for compatibility to IO.

strio.sysread(integer[, outbuf]) → string

Similar to read, but raises EOFError at end of string instead of returning nil, as well as IO#sysread does.

strio.write(string) → integer
strio.syswrite(string) → integer

Appends the given string to the underlying buffer string of strio. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written. See IO#write.

strio.pos → integer
strio.tell → integer

Returns the current offset (in bytes) of strio.

strio.truncate(integer) → 0

Truncates the buffer string to at most integer bytes. The strio must be opened for writing.

strio.isatty → nil
strio.tty? → nil

Returns false. Just for compatibility to IO.

strio.ungetc(integer) → nil

Pushes back one character (passed as a parameter) onto strio such that a subsequent buffered read will return it. Pushing back behind the beginning of the buffer string is not possible. Nothing will be done if such an attempt is made. In other case, there is no limitation for multiple pushbacks.

strio.write(string) → integer
strio.syswrite(string) → integer

Appends the given string to the underlying buffer string of strio. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written. See IO#write.


Class: StringScanner

Class | StringScanner
In: | ext/strscan/strscan.c
Parent: | Object

StringScanner provides for lexical scanning operations on a String. Here is an example of its usage:

  s = StringScanner.new('This is an example string')
  s.eos?               # -> false

  p s.scan(/\w+/)      # -> "This"
  p s.scan(/\w+/)      # -> nil
  p s.scan(/\s+/)      # -> " "
  p s.scan(/\s+/)      # -> nil
  p s.scan(/\w+/)      # -> "is"
  s.eos?               # -> false

  p s.scan(/\s+/)      # -> " "
  p s.scan(/\w+/)      # -> "an"
  p s.scan(/\s+/)      # -> " "
  p s.scan(/\w+/)      # -> "example"
  p s.scan(/\s+/)      # -> " "
  p s.scan(/\w+/)      # -> "string"
  s.eos?               # -> true

  p s.scan(/\s+/)      # -> nil
  p s.scan(/\w+/)      # -> nil

Scanning a string means remembering the position of a scan pointer, which is just an index. The point of scanning is to move forward a bit at a time, so matches are sought after the scan pointer; usually immediately after it.

Given the string "test string", here are the pertinent scan pointer positions:

    t e s t   s t r i n g
  0 1 2 ...             1
                        0

When you scan for a pattern (a regular expression), the match must occur at the character after the scan pointer. If you use scan_until, then the match can occur anywhere after the scan pointer. In both cases, the scan pointer moves just beyond the last character of the match, ready to scan again from the next character onwards. This is demonstrated by the example above.

Method Categories

There are other methods besides the plain scanners. You can look ahead in the string without actually scanning. You can access the most recent match. You can modify the string being scanned, reset or terminate the scanner, find out or change the position of the scan pointer, skip ahead, and so on.

Advancing the Scan Pointer

  • getch
  • get_byte
  • scan
  • scan_until
  • skip
  • skip_until

Looking Ahead

  • check
  • check_until
  • exist?
  • match?
  • peek

Finding Where we Are

  • beginning_of_line? (bol?)
  • eos?
  • rest?
  • rest_size
  • pos

Setting Where we Are

  • reset
  • terminate
  • pos=

Match Data

  • matched
  • matched?
  • matched_size
  • []
  • pre_match
  • post_match

Miscellaneous

  • <<
  • concat
  • string
  • string=
  • unscan

There are aliases to several of the methods.

Methods

<< [] beginning_of_line? check check_until clear concat empty? eos? exist? get_byte getbyte getch initialize_copy inspect match? matched matched? matched_size matchedsize must_C_version new peek peep pointer pointer= pos pos= post_match pre_match reset rest rest? rest_size restsize scan scan_full scan_until search_full skip skip_until string string= terminate unscan

Classes and Modules

Class StringScanner::Error

Public Class methods

StringScanner.must_C_version

This method is defined for backward compatibility.

StringScanner.new(string, dup = false)

Creates a new StringScanner object to scan over the given string. dup argument is obsolete and not used now.

Public Instance methods

concat(str)
<<(str)

Appends str to the string being scanned. This method does not affect scan pointer.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.scan(/Fri /)
  s << " +1000 GMT"
  s.string            # -> "Fri Dec 12 1975 14:39 +1000 GMT"
  s.scan(/Dec/)       # -> "Dec"
[](n)

Return the n-th subgroup in the most recent match.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.scan(/(\w+) (\w+) (\d+) /)       # -> "Fri Dec 12 "
  s[0]                               # -> "Fri Dec 12 "
  s[1]                               # -> "Fri"
  s[2]                               # -> "Dec"
  s[3]                               # -> "12"
  s.post_match                       # -> "1975 14:39"
  s.pre_match                        # -> ""
beginning_of_line?()

Returns true iff the scan pointer is at the beginning of the line.

  s = StringScanner.new("test\ntest\n")
  s.bol?           # => true
  s.scan(/te/)
  s.bol?           # => false
  s.scan(/st\n/)
  s.bol?           # => true
  s.terminate
  s.bol?           # => true
check(pattern)

This returns the value that scan would return, without advancing the scan pointer. The match register is affected, though.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.check /Fri/               # -> "Fri"
  s.pos                       # -> 0
  s.matched                   # -> "Fri"
  s.check /12/                # -> nil
  s.matched                   # -> nil

Mnemonic: it "checks" to see whether a scan will return a value.

check_until(pattern)

This returns the value that scan_until would return, without advancing the scan pointer. The match register is affected, though.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.check_until /12/          # -> "Fri Dec 12"
  s.pos                       # -> 0
  s.matched                   # -> 12

Mnemonic: it "checks" to see whether a scan_until will return a value.

clear()

Equivalent to terminate. This method is obsolete; use terminate instead.

concat(str)
<<(str)

Appends str to the string being scanned. This method does not affect scan pointer.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.scan(/Fri /)
  s << " +1000 GMT"
  s.string            # -> "Fri Dec 12 1975 14:39 +1000 GMT"
  s.scan(/Dec/)       # -> "Dec"
empty?()

Equivalent to eos?. This method is obsolete, use eos? instead.

eos?()

Returns true if the scan pointer is at the end of the string.

  s = StringScanner.new('test string')
  p s.eos?          # => false
  s.scan(/test/)
  p s.eos?          # => false
  s.terminate
  p s.eos?          # => true
exist?(pattern)

Looks ahead to see if the pattern exists anywhere in the string, without advancing the scan pointer. This predicates whether a scan_until will return a value.

  s = StringScanner.new('test string')
  s.exist? /s/            # -> 3
  s.scan /test/           # -> "test"
  s.exist? /s/            # -> 6
  s.exist? /e/            # -> nil
get_byte()

Scans one byte and returns it. This method is NOT multi-byte character sensitive. See also getch.

  s = StringScanner.new('ab')
  s.get_byte         # => "a"
  s.get_byte         # => "b"
  s.get_byte         # => nil

  s = StringScanner.new("\244\242")
  s.get_byte         # => "\244"
  s.get_byte         # => "\242"
  s.get_byte         # => nil
getbyte()

Equivalent to get_byte. This method is obsolete; use get_byte instead.

getch()

Scans one character and returns it. This method is multi-byte character sensitive. See also get_byte.

  s = StringScanner.new('ab')
  s.getch           # => "a"
  s.getch           # => "b"
  s.getch           # => nil

  $KCODE = 'EUC'
  s = StringScanner.new("\244\242")
  s.getch           # => "\244\242"   # Japanese hira-kana "A" in EUC-JP
  s.getch           # => nil
dup
clone

Duplicates a StringScanner object.

inspect()

Returns a string that represents the StringScanner object, showing:

  • the current position
  • the size of the string
  • the characters surrounding the scan pointer

    s = StringScanner.new("Fri Dec 12 1975 14:39") s.inspect # -> ’#<StringScanner 0/21 @ "Fri D…">’ s.scan_until /12/ # -> "Fri Dec 12" s.inspect # -> ’#<StringScanner 10/21 "…ec 12" @ " 1975…">’

match?(pattern)

Tests whether the given pattern is matched from the current scan pointer. Returns the length of the match, or nil. The scan pointer is not advanced.

  s = StringScanner.new('test string')
  p s.match?(/\w+/)   # -> 4
  p s.match?(/\w+/)   # -> 4
  p s.match?(/\s+/)   # -> nil
matched()

Returns the last matched string.

  s = StringScanner.new('test string')
  s.match?(/\w+/)     # -> 4
  s.matched           # -> "test"
matched?()

Returns true iff the last match was successful.

  s = StringScanner.new('test string')
  s.match?(/\w+/)     # => 4
  s.matched?          # => true
  s.match?(/\d+/)     # => nil
  s.matched?          # => false
matched_size()

Returns the size of the most recent match (see matched), or nil if there was no recent match.

  s = StringScanner.new('test string')
  s.check /\w+/           # -> "test"
  s.matched_size          # -> 4
  s.check /\d+/           # -> nil
  s.matched_size          # -> nil
matchedsize()

Equivalent to matched_size. This method is obsolete; use matched_size instead.

peek(len)

Extracts a string corresponding to string[pos,len], without advancing the scan pointer.

  s = StringScanner.new('test string')
  s.peek(7)          # => "test st"
  s.peek(7)          # => "test st"
peep(p1)

Equivalent to peek. This method is obsolete; use peek instead.

pointer()

Returns the position of the scan pointer. In the ‘reset’ position, this value is zero. In the ‘terminated’ position (i.e. the string is exhausted), this value is the length of the string.

In short, it‘s a 0-based index into the string.

  s = StringScanner.new('test string')
  s.pos               # -> 0
  s.scan_until /str/  # -> "test str"
  s.pos               # -> 8
  s.terminate         # -> #<StringScanner fin>
  s.pos               # -> 11
pos=(n)

Modify the scan pointer.

  s = StringScanner.new('test string')
  s.pos = 7            # -> 7
  s.rest               # -> "ring"
pos()

Returns the position of the scan pointer. In the ‘reset’ position, this value is zero. In the ‘terminated’ position (i.e. the string is exhausted), this value is the length of the string.

In short, it‘s a 0-based index into the string.

  s = StringScanner.new('test string')
  s.pos               # -> 0
  s.scan_until /str/  # -> "test str"
  s.pos               # -> 8
  s.terminate         # -> #<StringScanner fin>
  s.pos               # -> 11
pos=(n)

Modify the scan pointer.

  s = StringScanner.new('test string')
  s.pos = 7            # -> 7
  s.rest               # -> "ring"
post_match()

Return the post-match (in the regular expression sense) of the last scan.

  s = StringScanner.new('test string')
  s.scan(/\w+/)           # -> "test"
  s.scan(/\s+/)           # -> " "
  s.pre_match             # -> "test"
  s.post_match            # -> "string"
pre_match()

Return the pre-match (in the regular expression sense) of the last scan.

  s = StringScanner.new('test string')
  s.scan(/\w+/)           # -> "test"
  s.scan(/\s+/)           # -> " "
  s.pre_match             # -> "test"
  s.post_match            # -> "string"
reset()

Reset the scan pointer (index 0) and clear matching data.

rest()

Returns the "rest" of the string (i.e. everything after the scan pointer). If there is no more data (eos? = true), it returns "".

rest?()

Returns true iff there is more data in the string. See eos?. This method is obsolete; use eos? instead.

  s = StringScanner.new('test string')
  s.eos?              # These two
  s.rest?             # are opposites.
rest_size()

s.rest_size is equivalent to s.rest.size.

restsize()

s.restsize is equivalent to s.rest_size. This method is obsolete; use rest_size instead.

scan(pattern) => String

Tries to match with pattern at the current position. If there‘s a match, the scanner advances the "scan pointer" and returns the matched string. Otherwise, the scanner returns nil.

  s = StringScanner.new('test string')
  p s.scan(/\w+/)   # -> "test"
  p s.scan(/\w+/)   # -> nil
  p s.scan(/\s+/)   # -> " "
  p s.scan(/\w+/)   # -> "string"
  p s.scan(/./)     # -> nil
scan_full(pattern, return_string_p, advance_pointer_p)

Tests whether the given pattern is matched from the current scan pointer. Returns the matched string if return_string_p is true. Advances the scan pointer if advance_pointer_p is true. The match register is affected.

"full" means "scan with full parameters".

scan_until(pattern)

Scans the string until the pattern is matched. Returns the substring up to and including the end of the match, advancing the scan pointer to that location. If there is no match, nil is returned.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.scan_until(/1/)        # -> "Fri Dec 1"
  s.pre_match              # -> "Fri Dec "
  s.scan_until(/XYZ/)      # -> nil
search_full(pattern, return_string_p, advance_pointer_p)

Scans the string until the pattern is matched. Returns the matched string if return_string_p is true, otherwise returns the number of bytes advanced. Advances the scan pointer if advance_pointer_p, otherwise not. This method does affect the match register.

skip(pattern)

Attempts to skip over the given pattern beginning with the scan pointer. If it matches, the scan pointer is advanced to the end of the match, and the length of the match is returned. Otherwise, nil is returned.

It‘s similar to scan, but without returning the matched string.

  s = StringScanner.new('test string')
  p s.skip(/\w+/)   # -> 4
  p s.skip(/\w+/)   # -> nil
  p s.skip(/\s+/)   # -> 1
  p s.skip(/\w+/)   # -> 6
  p s.skip(/./)     # -> nil
skip_until(pattern)

Advances the scan pointer until pattern is matched and consumed. Returns the number of bytes advanced, or nil if no match was found.

Look ahead to match pattern, and advance the scan pointer to the end of the match. Return the number of characters advanced, or nil if the match was unsuccessful.

It‘s similar to scan_until, but without returning the intervening string.

  s = StringScanner.new("Fri Dec 12 1975 14:39")
  s.skip_until /12/           # -> 10
  s                           #
string()

Returns the string being scanned.

string=(str)

Changes the string being scanned to str and resets the scanner. Returns str.

terminate
clear

Set the scan pointer to the end of the string and clear matching data.

unscan()

Set the scan pointer to the previous position. Only one previous position is remembered, and it changes with each scanning operation.

  s = StringScanner.new('test string')
  s.scan(/\w+/)        # => "test"
  s.unscan
  s.scan(/../)         # => "te"
  s.scan(/\d/)         # => nil
  s.unscan             # ScanError: unscan failed: previous match had failed


Class: StringScanner::Error

Class | StringScanner::Error
In: | ext/strscan/strscan.c
Parent: | StandardError


Class: Struct

Class | Struct
In: | struct.c lib/pp.rb lib/yaml/rubytypes.rb
Parent: | Object

A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.

The Struct class is a generator of specific classes, each one of which is defined to hold a set of variables and their accessors. In these examples, we‘ll call the generated class ``Customer Class,’’ and we‘ll show an example instance of that class as ``CustomerInst.’‘

In the descriptions that follow, the parameter symbol refers to a symbol, which is either a quoted string or a Symbol (such as :name).

Methods

== [] []= each each_pair eql? hash inspect length members new new pretty_print pretty_print_cycle select size to_a to_s to_yaml values values_at yaml_new yaml_tag_class_name yaml_tag_read_class

Included Modules

Enumerable

Public Class methods

Struct.new( [aString] [, aSym]+> ) => StructClass
StructClass.new(arg, ...) => obj
StructClass[arg, ...] => obj

Creates a new class, named by aString, containing accessor methods for the given symbols. If the name aString is omitted, an anonymous structure class will be created. Otherwise, the name of this struct will appear as a constant in class Struct, so it must be unique for all Structs in the system and should start with a capital letter. Assigning a structure class to a constant effectively gives the class the name of the constant.

Struct::new returns a new Class object, which can then be used to create specific instances of the new structure. The number of actual parameters must be less than or equal to the number of attributes defined for this class; unset parameters default to \nil{}. Passing too many parameters will raise an \E{ArgumentError}.

The remaining methods listed in this section (class and instance) are defined for this generated class.

   # Create a structure with a name in Struct
   Struct.new("Customer", :name, :address)    #=> Struct::Customer
   Struct::Customer.new("Dave", "123 Main")   #=> #<Struct::Customer name="Dave", address="123 Main">

   # Create a structure named by its constant
   Customer = Struct.new(:name, :address)     #=> Customer
   Customer.new("Dave", "123 Main")           #=> #<Customer name="Dave", address="123 Main">
new(...)
yaml_new( klass, tag, val )
yaml_tag_class_name()
yaml_tag_read_class( name )

Public Instance methods

struct == other_struct => true or false

Equality—Returns true if other_struct is equal to this one: they must be of the same class as generated by Struct::new, and the values of all instance variables must be equal (according to Object#==).

   Customer = Struct.new(:name, :address, :zip)
   joe   = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   jane  = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
   joe == joejr   #=> true
   joe == jane    #=> false
struct[symbol] => anObject
struct[fixnum] => anObject

Attribute Reference—Returns the value of the instance variable named by symbol, or indexed (0..length-1) by fixnum. Will raise NameError if the named variable does not exist, or IndexError if the index is out of range.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

   joe["name"]   #=> "Joe Smith"
   joe[:name]    #=> "Joe Smith"
   joe[0]        #=> "Joe Smith"
struct[symbol] = obj => obj
struct[fixnum] = obj => obj

Attribute Assignment—Assigns to the instance variable named by symbol or fixnum the value obj and returns it. Will raise a NameError if the named variable does not exist, or an IndexError if the index is out of range.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

   joe["name"] = "Luke"
   joe[:zip]   = "90210"

   joe.name   #=> "Luke"
   joe.zip    #=> "90210"
struct.each {|obj| block } => struct

Calls block once for each instance variable, passing the value as a parameter.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.each {|x| puts(x) }

produces:

   Joe Smith
   123 Maple, Anytown NC
   12345
struct.each_pair {|sym, obj| block } => struct

Calls block once for each instance variable, passing the name (as a symbol) and the value as parameters.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.each_pair {|name, value| puts("#{name} => #{value}") }

produces:

   name => Joe Smith
   address => 123 Maple, Anytown NC
   zip => 12345
eql?(p1)

code-seq:

  struct.eql?(other)   => true or false

Two structures are equal if they are the same object, or if all their fields are equal (using eql?).

struct.hash => fixnum

Return a hash value based on this struct‘s contents.

struct.to_s => string
struct.inspect => string

Describe the contents of this struct in a string.

struct.length => fixnum
struct.size => fixnum

Returns the number of instance variables.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.length   #=> 3
struct.members => array

Returns an array of strings representing the names of the instance variables.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.members   #=> ["name", "address", "zip"]
pretty_print(q)
pretty_print_cycle(q)
struct.select {|i| block } => array

Invokes the block passing in successive elements from struct, returning an array containing those elements for which the block returns a true value (equivalent to Enumerable#select).

   Lots = Struct.new(:a, :b, :c, :d, :e, :f)
   l = Lots.new(11, 22, 33, 44, 55, 66)
   l.select {|v| (v % 2).zero? }   #=> [22, 44, 66]
struct.length => fixnum
struct.size => fixnum

Returns the number of instance variables.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.length   #=> 3
struct.to_a => array
struct.values => array

Returns the values for this instance as an array.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.to_a[1]   #=> "123 Maple, Anytown NC"
struct.to_s => string
struct.inspect => string

Describe the contents of this struct in a string.

to_yaml( opts = {} )
struct.to_a => array
struct.values => array

Returns the values for this instance as an array.

   Customer = Struct.new(:name, :address, :zip)
   joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
   joe.to_a[1]   #=> "123 Maple, Anytown NC"
struct.values_at(selector,... ) => an_array

Returns an array containing the elements in self corresponding to the given selector(s). The selectors may be either integer indices or ranges. See also </code>.select<code>.

   a = %w{ a b c d e f }
   a.values_at(1, 3, 5)
   a.values_at(1, 3, 5, 7)
   a.values_at(-1, -3, -5, -7)
   a.values_at(1..3, 2...5)


Class: Symbol

Class | Symbol
In: | object.c lib/rexml/xpath_parser.rb lib/yaml/rubytypes.rb
Parent: | Object

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program‘s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

   module One
     class Fred
     end
     $f1 = :Fred
   end
   module Two
     Fred = 1
     $f2 = :Fred
   end
   def Fred()
   end
   $f3 = :Fred
   $f1.id   #=> 2514190
   $f2.id   #=> 2514190
   $f3.id   #=> 2514190

Methods

=== all_symbols dclone id2name inspect to_i to_int to_s to_sym to_yaml yaml_new

Public Class methods

Symbol.all_symbols => array

Returns an array of all the symbols currently in Ruby‘s symbol table.

   Symbol.all_symbols.size    #=> 903
   Symbol.all_symbols[1,20]   #=> [:floor, :ARGV, :Binding, :symlink,
                                   :chown, :EOFError, :$;, :String,
                                   :LOCK_SH, :"setuid?", :$<,
                                   :default_proc, :compact, :extend,
                                   :Tms, :getwd, :$=, :ThreadGroup,
                                   :wait2, :$>]
yaml_new( klass, tag, val )

Public Instance methods

obj == other => true or false
obj.equal?(other) => true or false
obj.eql?(other) => true or false

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

   1 == 1.0     #=> true
   1.eql? 1.0   #=> false
dclone()
sym.id2name => string
sym.to_s => string

Returns the name or string corresponding to sym.

   :fred.id2name   #=> "fred"
sym.inspect => string

Returns the representation of sym as a symbol literal.

   :fred.inspect   #=> ":fred"
sym.to_i => fixnum

Returns an integer that is unique for each symbol within a particular execution of a program.

   :fred.to_i           #=> 9809
   "fred".to_sym.to_i   #=> 9809
to_int()

:nodoc:

sym.id2name => string
sym.to_s => string

Returns the name or string corresponding to sym.

   :fred.id2name   #=> "fred"
sym.to_sym => sym

In general, to_sym returns the Symbol corresponding to an object. As sym is already a symbol, self is returned in this case.

to_yaml( opts = {} )


Class: Sync

Class | Sync
In: | lib/sync.rb
Parent: | Object

Methods

new

Included Modules

Sync_m

Public Class methods

new()


Class: SyncEnumerator

Class | SyncEnumerator
In: | lib/generator.rb
Parent: | Object

SyncEnumerator creates an Enumerable object from multiple Enumerable objects and enumerates them synchronously.

Example

  require 'generator'

  s = SyncEnumerator.new([1,2,3], ['a', 'b', 'c'])

  # Yields [1, 'a'], [2, 'b'], and [3,'c']
  s.each { |row| puts row.join(', ') }

Methods

each end? length new size

Included Modules

Enumerable

Public Class methods

new(*enums)

Creates a new SyncEnumerator which enumerates rows of given Enumerable objects.

Public Instance methods

each() {|ret| ...}

Enumerates rows of the Enumerable objects.

end?(i = nil)

Returns true if the given nth Enumerable object has reached the end. If no argument is given, returns true if any of the Enumerable objects has reached the end.

length()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.

size()

Returns the number of enumerated Enumerable objects, i.e. the size of each row.


Module: Sync_m

Module | Sync_m
In: | lib/sync.rb

Methods

append_features define_aliases extend_object new sync_exclusive? sync_extended sync_lock sync_locked? sync_shared? sync_synchronize sync_try_lock sync_unlock

Classes and Modules

Class Sync_m::Err

Constants

RCS_ID | = | '-$Header$-'
UN | = | :UN | lock mode
SH | = | :SH
EX | = | :EX

Attributes

sync_ex_count | [RW]
sync_ex_locker | [RW]
sync_mode | [RW]
sync_sh_locker | [RW]
sync_upgrade_waiting | [RW]
sync_waiting | [RW]

Public Class methods

append_features(cl)
define_aliases(cl)
extend_object(obj)
new(*args)

Public Instance methods

sync_exclusive?()
sync_extended()
sync_lock(m = EX)
sync_locked?()

accessing

sync_shared?()
sync_synchronize(mode = EX) {|| ...}
sync_try_lock(mode = EX)

locking methods.

sync_unlock(m = EX)


Class: Sync_m::Err

Class | Sync_m::Err
In: | lib/sync.rb
Parent: | StandardError

exceptions

Methods

Fail

Classes and Modules

Class Sync_m::Err::LockModeFailer
Class Sync_m::Err::UnknownLocker

Public Class methods

Fail(*opt)


Class: Sync_m::Err::LockModeFailer

Class | Sync_m::Err::LockModeFailer
In: | lib/sync.rb
Parent: | Err

Methods

Fail

Constants

Message = "Unknown lock mode(%s)"

Public Class methods

Fail(mode)


Class: Sync_m::Err::UnknownLocker

Class | Sync_m::Err::UnknownLocker
In: | lib/sync.rb
Parent: | Err

Methods

Fail

Constants

Message = "Thread(%s) not locked."

Public Class methods

Fail(th)


Class: SyntaxError

Class | SyntaxError
In: | error.c
Parent: | ScriptError


Class: SystemCallError

Class | SystemCallError
In: | error.c
Parent: | StandardError

Methods

=== errno new

Public Class methods

system_call_error === other => true or false

Return true if the receiver is a generic SystemCallError, or if the error numbers self and other are the same.

SystemCallError.new(msg, errno) => system_call_error_subclass

If errno corresponds to a known system error code, constructs the appropriate Errno class for that error, otherwise constructs a generic SystemCallError object. The error number is subsequently available via the errno method.

Public Instance methods

system_call_error.errno => fixnum

Return this SystemCallError‘s error number.


Class: SystemExit

Class | SystemExit
In: | error.c
Parent: | Exception

Methods

new status success?

Public Class methods

SystemExit.new(status=0) => system_exit

Create a new SystemExit exception with the given status.

Public Instance methods

system_exit.status => fixnum

Return the status value associated with this system exit.

system_exit.success? => true or false

Returns true if exiting successful, false if not.


Class: SystemStackError

Class | SystemStackError
In: | eval.c
Parent: | StandardError


Class: TCPServer

Class | TCPServer
In: | ext/socket/socket.c
Parent: | TCPSocket

Methods

accept_nonblock listen

Public Instance methods

tcpserver.accept_nonblock => tcpsocket

Accepts an incoming connection using accept(2) after O_NONBLOCK is set for the underlying file descriptor. It returns an accepted TCPSocket for the incoming connection.

Example

     require 'socket'
     serv = TCPServer.new(2202)
     begin
       sock = serv.accept_nonblock
     rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
       IO.select([serv])
       retry
     end
     # sock is an accepted socket.

Refer to Socket#accept for the exceptions that may be thrown if the call to TCPServer#accept_nonblock fails.

TCPServer#accept_nonblock may raise any error corresponding to accept(2) failure, including Errno::EAGAIN.

See

  • TCPServer#accept
  • Socket#accept
socket.listen( int ) => 0

Listens for connections, using the specified int as the backlog. A call to listen only applies if the socket is of type SOCK_STREAM or SOCK_SEQPACKET.

Parameter

  • backlog - the maximum length of the queue for pending connections.

Example 1

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )
     socket.listen( 5 )

Example 2 (listening on an arbitary port, unix-based systems only):

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     socket.listen( 1 )

Unix-based Exceptions

On unix based systems the above will work because a new sockaddr struct is created on the address ADDR_ANY, for an arbitrary port number as handed off by the kernel. It will not work on Windows, because Windows requires that the socket is bound by calling bind before it can listen.

If the backlog amount exceeds the implementation-dependent maximum queue length, the implementation‘s maximum queue length will be used.

On unix-based based systems the following system exceptions may be raised if the call to listen fails:

  • Errno::EBADF - the socket argument is not a valid file descriptor
  • Errno::EDESTADDRREQ - the socket is not bound to a local address, and the protocol does not support listening on an unbound socket
  • Errno::EINVAL - the socket is already connected
  • Errno::ENOTSOCK - the socket argument does not refer to a socket
  • Errno::EOPNOTSUPP - the socket protocol does not support listen
  • Errno::EACCES - the calling process does not have approriate privileges
  • Errno::EINVAL - the socket has been shut down
  • Errno::ENOBUFS - insufficient resources are available in the system to complete the call

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to listen fails:

  • Errno::ENETDOWN - the network is down
  • Errno::EADDRINUSE - the socket‘s local address is already in use. This usually occurs during the execution of bind but could be delayed if the call to bind was to a partially wildcard address (involving ADDR_ANY) and if a specific address needs to be commmitted at the time of the call to listen
  • Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the service provider is still processing a callback function
  • Errno::EINVAL - the socket has not been bound with a call to bind.
  • Errno::EISCONN - the socket is already connected
  • Errno::EMFILE - no more socket descriptors are available
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOTSOC - socket is not a socket
  • Errno::EOPNOTSUPP - the referenced socket is not a type that supports the listen method

See

  • listen manual pages on unix-based systems
  • listen function in Microsoft‘s Winsock functions reference


Class: TCPSocket

Class | TCPSocket
In: | lib/resolv-replace.rb ext/socket/socket.c
Parent: | Object

Methods

gethostbyname new new

External Aliases

initialize -> original_resolv_initialize

Public Class methods

Socket.gethostbyname(host) => hostent

Resolve host and return name and address information for it, similarly to gethostbyname(3). host can be a domain name or the presentation format of an address.

Returns an array of information similar to that found in a +struct hostent+:

  - cannonical name: the cannonical name for host in the DNS, or a
    string representing the address
  - aliases: an array of aliases for the canonical name, there may be no aliases
  - address family: usually one of Socket::AF_INET or Socket::AF_INET6
  - address: a string, the binary value of the +struct sockaddr+ for this name, in
    the indicated address family
  - ...: if there are multiple addresses for this host,  a series of
    strings/+struct sockaddr+s may follow, not all necessarily in the same
    address family. Note that the fact that they may not be all in the same
    address family is a departure from the behaviour of gethostbyname(3).

Note: I believe that the fact that the multiple addresses returned are not necessarily in the same address family may be a bug, since if this function actually called gethostbyname(3), ALL the addresses returned in the trailing address list (h_addr_list from struct hostent) would be of the same address family! Examples from my system, OS X 10.3:

  ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"]
    and
  ["ensemble.local", [], 30, "\376\200\000\004\000\000\000\000\002\003\223\377\376\255\010\214", "\300\250{\232" ]

Similar information can be returned by Socket.getaddrinfo if called as:

   Socket.getaddrinfo(+host+, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)

Examples

  Socket.gethostbyname "example.com"
  => ["example.com", [], 2, "\300\000\"\246"]

This name has no DNS aliases, and a single IPv4 address.

  Socket.gethostbyname "smtp.telus.net"
  => ["smtp.svc.telus.net", ["smtp.telus.net"], 2, "\307\271\334\371"]

This name is an an alias so the canonical name is returned, as well as the alias and a single IPv4 address.

  Socket.gethostbyname "localhost"
  => ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"]

This machine has no aliases, returns an IPv6 address, and has an additional IPv4 address.

host can also be an IP address in presentation format, in which case a reverse lookup is done on the address:

  Socket.gethostbyname("127.0.0.1")
  => ["localhost", [], 2, "\177\000\000\001"]

  Socket.gethostbyname("192.0.34.166")
  => ["www.example.com", [], 2, "\300\000\"\246"]

See

See: Socket.getaddrinfo

new(host, serv, *rest)
TCPSocket.new(remote_host, remote_port, local_host=nil, local_port=nil)

Opens a TCP connection to remote_host on remote_port. If local_host and local_port are specified, then those parameters are used on the local end to establish the connection.


Module: TSort

Module | TSort
In: | lib/tsort.rb

TSort implements topological sorting using Tarjan‘s algorithm for strongly connected components.

TSort is designed to be able to be used with any object which can be interpreted as a directed graph.

TSort requires two methods to interpret an object as a graph, tsort_each_node and tsort_each_child.

  • tsort_each_node is used to iterate for all nodes over a graph.
  • tsort_each_child is used to iterate for child nodes of a given node.

The equality of nodes are defined by eql? and hash since TSort uses Hash internally.

A Simple Example

The following example demonstrates how to mix the TSort module into an existing class (in this case, Hash). Here, we‘re treating each key in the hash as a node in the graph, and so we simply alias the required tsort_each_node method to Hash‘s each_key method. For each key in the hash, the associated value is an array of the node‘s child nodes. This choice in turn leads to our implementation of the required tsort_each_child method, which fetches the array of child nodes and then iterates over that array using the user-supplied block.

  require 'tsort'

  class Hash
    include TSort
    alias tsort_each_node each_key
    def tsort_each_child(node, &block)
      fetch(node).each(&block)
    end
  end

  {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
  #=> [3, 2, 1, 4]

  {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
  #=> [[4], [2, 3], [1]]

A More Realistic Example

A very simple `make’ like tool can be implemented as follows:

  require 'tsort'

  class Make
    def initialize
      @dep = {}
      @dep.default = []
    end

    def rule(outputs, inputs=[], &block)
      triple = [outputs, inputs, block]
      outputs.each {|f| @dep[f] = [triple]}
      @dep[triple] = inputs
    end

    def build(target)
      each_strongly_connected_component_from(target) {|ns|
        if ns.length != 1
          fs = ns.delete_if {|n| Array === n}
          raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
        end
        n = ns.first
        if Array === n
          outputs, inputs, block = n
          inputs_time = inputs.map {|f| File.mtime f}.max
          begin
            outputs_time = outputs.map {|f| File.mtime f}.min
          rescue Errno::ENOENT
            outputs_time = nil
          end
          if outputs_time == nil ||
             inputs_time != nil && outputs_time <= inputs_time
            sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
            block.call
          end
        end
      }
    end

    def tsort_each_child(node, &block)
      @dep[node].each(&block)
    end
    include TSort
  end

  def command(arg)
    print arg, "\n"
    system arg
  end

  m = Make.new
  m.rule(%w[t1]) { command 'date > t1' }
  m.rule(%w[t2]) { command 'date > t2' }
  m.rule(%w[t3]) { command 'date > t3' }
  m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
  m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
  m.build('t5')

Bugs

  • ‘tsort.rb’ is wrong name because this library uses Tarjan‘s algorithm for strongly connected components. Although ‘strongly_connected_components.rb’ is correct but too long.

References

  1. E. Tarjan, "Depth First Search and Linear Graph Algorithms",

SIAM Journal on Computing, Vol. 1, No. 2, pp. 146-160, June 1972.

Methods

each_strongly_connected_component each_strongly_connected_component_from strongly_connected_components tsort tsort_each tsort_each_child tsort_each_node

Classes and Modules

Class TSort::Cyclic

Public Instance methods

each_strongly_connected_component( {|nodes| ...}

The iterator version of the strongly_connected_components method. obj.each_strongly_connected_component is similar to obj.strongly_connected_components.each, but modification of obj during the iteration may lead to unexpected results.

each_strongly_connected_component returns nil.

each_strongly_connected_component_from(node, id_map={}, stack=[]) {|nodes| ...}

Iterates over strongly connected component in the subgraph reachable from node.

Return value is unspecified.

each_strongly_connected_component_from doesn‘t call tsort_each_node.

strongly_connected_components()

Returns strongly connected components as an array of arrays of nodes. The array is sorted from children to parents. Each elements of the array represents a strongly connected component.

tsort()

Returns a topologically sorted array of nodes. The array is sorted from children to parents, i.e. the first element has no child and the last node has no parent.

If there is a cycle, TSort::Cyclic is raised.

tsort_each( {|node| ...}

The iterator version of the tsort method. obj.tsort_each is similar to obj.tsort.each, but modification of obj during the iteration may lead to unexpected results.

tsort_each returns nil. If there is a cycle, TSort::Cyclic is raised.

tsort_each_child(node) {|child| ...}

Should be implemented by a extended class.

tsort_each_child is used to iterate for child nodes of node.

tsort_each_node( {|node| ...}

Should be implemented by a extended class.

tsort_each_node is used to iterate for all nodes over a graph.


Class: TSort::Cyclic

Class | TSort::Cyclic
In: | lib/tsort.rb
Parent: | StandardError


Class: Tempfile

Class | Tempfile
In: | lib/tempfile.rb
Parent: | DelegateClass(File)

A class for managing temporary files. This library is written to be thread safe.

Methods

close close! delete length new open open path size unlink

Constants

MAX_TRY = 10

Public Class methods

new(basename, tmpdir=Dir::tmpdir)

Creates a temporary file of mode 0600 in the temporary directory whose name is basename.pid.n and opens with mode "w+". A Tempfile object works just like a File object.

If tmpdir is omitted, the temporary directory is determined by Dir::tmpdir provided by ‘tmpdir.rb’. When $SAFE > 0 and the given tmpdir is tainted, it uses /tmp. (Note that ENV values are tainted by default)

open(*args) {|tempfile| ...}

If no block is given, this is a synonym for new().

If a block is given, it will be passed tempfile as an argument, and the tempfile will automatically be closed when the block terminates. In this case, open() returns nil.

Public Instance methods

close(unlink_now=false)

Closes the file. If the optional flag is true, unlinks the file after closing.

If you don‘t explicitly unlink the temporary file, the removal will be delayed until the object is finalized.

close!()

Closes and unlinks the file.

delete()

Alias for unlink

length()

Alias for size

open()

Opens or reopens the file with mode "r+".

path()

Returns the full path name of the temporary file.

size()

Returns the size of the temporary file. As a side effect, the IO buffer is flushed before determining the size.

unlink()

Unlinks the file. On UNIX-like systems, it is often a good idea to unlink a temporary file immediately after creating and opening it, because it leaves other programs zero chance to access the file.


Class: TemplatePage

Class | TemplatePage
In: | lib/rdoc/template.rb
Parent: | Object

Cheap-n-cheerful HTML page template system. You create a template containing:

  • variable names between percent signs (%fred%)
  • blocks of repeating stuff:
      START:key
    ... stuff
  END:key

You feed the code a hash. For simple variables, the values are resolved directly from the hash. For blocks, the hash entry corresponding to key will be an array of hashes. The block will be generated once for each entry. Blocks can be nested arbitrarily deeply.

The template may also contain

  IF:key
    ... stuff
  ENDIF:key

stuff will only be included in the output if the corresponding key is set in the value hash.

Usage: Given a set of templates T1, T2, etc

           values = { "name" => "Dave", state => "TX" }

           t = TemplatePage.new(T1, T2, T3)
           File.open(name, "w") {|f| t.write_html_on(f, values)}
        or
           res = ''
           t.write_html_on(res, values)

Methods

expand_line new substitute_into write_html_on

Classes and Modules

Class TemplatePage::Context
Class TemplatePage::LineReader

Public Class methods

new(*templates)

templates is an array of strings containing the templates. We start at the first, and substitute in subsequent ones where the string !INCLUDE! occurs. For example, we could have the overall page template containing

  <html><body>
    <h1>Master</h1>
    !INCLUDE!
  </bost></html>

and substitute subpages in to it by passing [master, sub_page]. This gives us a cheap way of framing pages

Public Instance methods

expand_line(line)

Given an individual line, we look for %xxx% constructs and HREF:ref:name: constructs, substituting for each.

substitute_into(lines, values)

Substitute a set of key/value pairs into the given template. Keys with scalar values have them substituted directly into the page. Those with array values invoke substitute_array (below), which examples a block of the template once for each row in the array.

This routine also copes with the IF:key directive, removing chunks of the template if the corresponding key does not appear in the hash, and the START: directive, which loops its contents for each value in an array

write_html_on(op, value_hash)

Render the templates into HTML, storing the result on op using the method <<. The value_hash contains key/value pairs used to drive the substitution (as described above)


Class: TemplatePage::Context

Class | TemplatePage::Context
In: | lib/rdoc/template.rb
Parent: | Object

A context holds a stack of key/value pairs (like a symbol table). When asked to resolve a key, it first searches the top of the stack, then the next level, and so on until it finds a match (or runs out of entries)

Methods

find_scalar lookup new pop push

Public Class methods

new()

Public Instance methods

find_scalar(key)

Find a scalar value, throwing an exception if not found. This method is used when substituting the %xxx% constructs

lookup(key)

Lookup any key in the stack of hashes

pop()
push(hash)


Class: TemplatePage::LineReader

Class | TemplatePage::LineReader
In: | lib/rdoc/template.rb
Parent: | Object

Simple class to read lines out of a string

Methods

dup new read read_up_to

Public Class methods

new(lines)

we‘re initialized with an array of lines

Public Instance methods

dup()

Return a copy of ourselves that can be modified without affecting us

read()

read the next line

read_up_to(pattern)

Return a list of lines up to the line that matches a pattern. That last line is discarded.


Module: Test::Unit

Module | Test::Unit
In: | lib/test/unit/util/observable.rb lib/test/unit/util/backtracefilter.rb lib/test/unit/util/procwrapper.rb lib/test/unit/assertionfailederror.rb lib/test/unit/ui/console/testrunner.rb lib/test/unit/ui/fox/testrunner.rb lib/test/unit/ui/tk/testrunner.rb lib/test/unit/ui/testrunnerutilities.rb lib/test/unit/ui/gtk/testrunner.rb lib/test/unit/ui/gtk2/testrunner.rb lib/test/unit/ui/testrunnermediator.rb lib/test/unit/assertions.rb lib/test/unit/autorunner.rb lib/test/unit/testresult.rb lib/test/unit/failure.rb lib/test/unit/testsuite.rb lib/test/unit/collector.rb lib/test/unit/testcase.rb lib/test/unit/collector/dir.rb lib/test/unit/collector/objectspace.rb lib/test/unit/error.rb lib/test/unit.rb

Test::Unit - Ruby Unit Testing Framework

Introduction

Unit testing is making waves all over the place, largely due to the fact that it is a core practice of XP. While XP is great, unit testing has been around for a long time and has always been a good idea. One of the keys to good unit testing, though, is not just writing tests, but having tests. What‘s the difference? Well, if you just write a test and throw it away, you have no guarantee that something won‘t change later which breaks your code. If, on the other hand, you have tests (obviously you have to write them first), and run them as often as possible, you slowly build up a wall of things that cannot break without you immediately knowing about it. This is when unit testing hits its peak usefulness.

Enter Test::Unit, a framework for unit testing in Ruby, helping you to design, debug and evaluate your code by making it easy to write and have tests for it.

Notes

Test::Unit has grown out of and superceded Lapidary.

Feedback

I like (and do my best to practice) XP, so I value early releases, user feedback, and clean, simple, expressive code. There is always room for improvement in everything I do, and Test::Unit is no exception. Please, let me know what you think of Test::Unit as it stands, and what you‘d like to see expanded/changed/improved/etc. If you find a bug, let me know ASAP; one good way to let me know what the bug is is to submit a new test that catches it :-) Also, I‘d love to hear about any successes you have with Test::Unit, and any documentation you might add will be greatly appreciated. My contact info is below.

Contact Information

A lot of discussion happens about Ruby in general on the ruby-talk mailing list (www.ruby-lang.org/en/ml.html), and you can ask any questions you might have there. I monitor the list, as do many other helpful Rubyists, and you‘re sure to get a quick answer. Of course, you‘re also welcome to email me (Nathaniel Talbott) directly at testunit@talbott.ws, and I‘ll do my best to help you out.

Credits

I‘d like to thank…

Matz, for a great language!

Masaki Suketa, for his work on RubyUnit, which filled a vital need in the Ruby world for a very long time. I‘m also grateful for his help in polishing Test::Unit and getting the RubyUnit compatibility layer right. His graciousness in allowing Test::Unit to supercede RubyUnit continues to be a challenge to me to be more willing to defer my own rights.

Ken McKinlay, for his interest and work on unit testing, and for his willingness to dialog about it. He was also a great help in pointing out some of the holes in the RubyUnit compatibility layer.

Dave Thomas, for the original idea that led to the extremely simple "require ‘test/unit’", plus his code to improve it even more by allowing the selection of tests from the command-line. Also, without RDoc, the documentation for Test::Unit would stink a lot more than it does now.

Everyone who‘s helped out with bug reports, feature ideas, encouragement to continue, etc. It‘s a real privilege to be a part of the Ruby community.

The guys at RoleModel Software, for putting up with me repeating, "But this would be so much easier in Ruby!" whenever we‘re coding in Java.

My Creator, for giving me life, and giving it more abundantly.

License

Test::Unit is copyright (c) 2000-2003 Nathaniel Talbott. It is free software, and is distributed under the Ruby license. See the COPYING file in the standard Ruby distribution for details.

Warranty

This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose.

Author

Nathaniel Talbott. Copyright (c) 2000-2003, Nathaniel Talbott

Usage

The general idea behind unit testing is that you write a test method that makes certain assertions about your code, working against a test fixture. A bunch of these test methods are bundled up into a test suite and can be run any time the developer wants. The results of a run are gathered in a test result and displayed to the user through some UI. So, lets break this down and see how Test::Unit provides each of these necessary pieces.

Assertions

These are the heart of the framework. Think of an assertion as a statement of expected outcome, i.e. "I assert that x should be equal to y". If, when the assertion is executed, it turns out to be correct, nothing happens, and life is good. If, on the other hand, your assertion turns out to be false, an error is propagated with pertinent information so that you can go back and make your assertion succeed, and, once again, life is good. For an explanation of the current assertions, see Test::Unit::Assertions.

Test Method & Test Fixture

Obviously, these assertions have to be called within a context that knows about them and can do something meaningful with their pass/fail value. Also, it‘s handy to collect a bunch of related tests, each test represented by a method, into a common test class that knows how to run them. The tests will be in a separate class from the code they‘re testing for a couple of reasons. First of all, it allows your code to stay uncluttered with test code, making it easier to maintain. Second, it allows the tests to be stripped out for deployment, since they‘re really there for you, the developer, and your users don‘t need them. Third, and most importantly, it allows you to set up a common test fixture for your tests to run against.

What‘s a test fixture? Well, tests do not live in a vacuum; rather, they‘re run against the code they are testing. Often, a collection of tests will run against a common set of data, also called a fixture. If they‘re all bundled into the same test class, they can all share the setting up and tearing down of that data, eliminating unnecessary duplication and making it much easier to add related tests.

Test::Unit::TestCase wraps up a collection of test methods together and allows you to easily set up and tear down the same test fixture for each test. This is done by overriding setup and/or teardown, which will be called before and after each test method that is run. The TestCase also knows how to collect the results of your assertions into a Test::Unit::TestResult, which can then be reported back to you… but I‘m getting ahead of myself. To write a test, follow these steps:

  • Make sure Test::Unit is in your library path.
  • require ‘test/unit’ in your test script.
  • Create a class that subclasses Test::Unit::TestCase.
  • Add a method that begins with "test" to your class.
  • Make assertions in your test method.
  • Optionally define setup and/or teardown to set up and/or tear down your common test fixture.
  • You can now run your test as you would any other Ruby script… try it and see!

A really simple test might look like this (setup and teardown are commented out to indicate that they are completely optional):

    require 'test/unit'

    class TC_MyTest < Test::Unit::TestCase
      # def setup
      # end

      # def teardown
      # end

      def test_fail
        assert(false, 'Assertion was false.')
      end
    end

Test Runners

So, now you have this great test class, but you still need a way to run it and view any failures that occur during the run. This is where Test::Unit::UI::Console::TestRunner (and others, such as Test::Unit::UI::GTK::TestRunner) comes into play. The console test runner is automatically invoked for you if you require ‘test/unit’ and simply run the file. To use another runner, or to manually invoke a runner, simply call its run class method and pass in an object that responds to the suite message with a Test::Unit::TestSuite. This can be as simple as passing in your TestCase class (which has a class suite method). It might look something like this:

   require 'test/unit/ui/console/testrunner'
   Test::Unit::UI::Console::TestRunner.run(TC_MyTest)

Test Suite

As more and more unit tests accumulate for a given project, it becomes a real drag running them one at a time, and it also introduces the potential to overlook a failing test because you forget to run it. Suddenly it becomes very handy that the TestRunners can take any object that returns a Test::Unit::TestSuite in response to a suite method. The TestSuite can, in turn, contain other TestSuites or individual tests (typically created by a TestCase). In other words, you can easily wrap up a group of TestCases and TestSuites like this:

 require 'test/unit/testsuite'
 require 'tc_myfirsttests'
 require 'tc_moretestsbyme'
 require 'ts_anothersetoftests'

 class TS_MyTests
   def self.suite
     suite = Test::Unit::TestSuite.new
     suite << TC_MyFirstTests.suite
     suite << TC_MoreTestsByMe.suite
     suite << TS_AnotherSetOfTests.suite
     return suite
   end
 end
 Test::Unit::UI::Console::TestRunner.run(TS_MyTests)

Now, this is a bit cumbersome, so Test::Unit does a little bit more for you, by wrapping these up automatically when you require ‘test/unit’. What does this mean? It means you could write the above test case like this instead:

 require 'test/unit'
 require 'tc_myfirsttests'
 require 'tc_moretestsbyme'
 require 'ts_anothersetoftests'

Test::Unit is smart enough to find all the test cases existing in the ObjectSpace and wrap them up into a suite for you. It then runs the dynamic suite using the console TestRunner.

Questions?

I‘d really like to get feedback from all levels of Ruby practitioners about typos, grammatical errors, unclear statements, missing points, etc., in this document (or any other).

Methods

run= run?

Classes and Modules

Module Test::Unit::Assertions
Module Test::Unit::Collector
Module Test::Unit::UI
Module Test::Unit::Util
Class Test::Unit::AssertionFailedError
Class Test::Unit::AutoRunner
Class Test::Unit::Error
Class Test::Unit::Failure
Class Test::Unit::TestCase
Class Test::Unit::TestResult
Class Test::Unit::TestSuite

Constants

OUTPUT_LEVELS | = | [ [:silent, UI::SILENT], [:progress, UI::PROGRESS_ONLY], [:normal, UI::NORMAL], [:verbose, UI::VERBOSE], ]
COLLECTORS | = | { :objectspace => proc do |r| require 'test/unit/collector/objectspace'

Public Class methods

run=(flag)

If set to false Test::Unit will not automatically run at exit.

run?()

Automatically run tests at exit?


Class: Test::Unit::AssertionFailedError

Class | Test::Unit::AssertionFailedError
In: | lib/test/unit/assertionfailederror.rb
Parent: | StandardError

Thrown by Test::Unit::Assertions when an assertion fails.


Module: Test::Unit::Assertions

Module | Test::Unit::Assertions
In: | lib/test/unit/assertions.rb

Test::Unit::Assertions contains the standard Test::Unit assertions. Assertions is included in Test::Unit::TestCase.

To include it in your own code and use its functionality, you simply need to rescue Test::Unit::AssertionFailedError. Additionally you may override add_assertion to get notified whenever an assertion is made.

Notes:

  • The message to each assertion, if given, will be propagated with the failure.
  • It is easy to add your own assertions based on assert_block().

Example Custom Assertion

  def deny(boolean, message = nil)
    message = build_message message, '<?> is not false or nil.', boolean
    assert_block message do
      not boolean
    end
  end

Methods

assert assert_block assert_equal assert_in_delta assert_instance_of assert_kind_of assert_match assert_nil assert_no_match assert_not_equal assert_not_nil assert_not_same assert_nothing_raised assert_nothing_thrown assert_operator assert_raise assert_raises assert_respond_to assert_same assert_send assert_throws build_message flunk use_pp=

Constants

UncaughtThrow = {NameError => /^uncaught throw \`(.+)\'$/, ThreadError => /^uncaught throw \`(.+)\' in thread /}

Public Class methods

use_pp=(value)

Select whether or not to use the pretty-printer. If this option is set to false before any assertions are made, pp.rb will not be required.

Public Instance methods

assert(boolean, message=nil)

Asserts that boolean is not false or nil.

Example:

  assert [1, 2].include?(5)
assert_block(message="assert_block failed.") {|| ...}

The assertion upon which all other assertions are based. Passes if the block yields true.

Example:

  assert_block "Couldn't do the thing" do
    do_the_thing
  end
assert_equal(expected, actual, message=nil)

Passes if expected == +actual.

Note that the ordering of arguments is important, since a helpful error message is generated when this one fails that tells you the values of expected and actual.

Example:

  assert_equal 'MY STRING', 'my string'.upcase
assert_in_delta(expected_float, actual_float, delta, message="")

Passes if expected_float and actual_float are equal within delta tolerance.

Example:

  assert_in_delta 0.05, (50000.0 / 10**6), 0.00001
assert_instance_of(klass, object, message="")

Passes if object .instance_of? klass

Example:

  assert_instance_of String, 'foo'
assert_kind_of(klass, object, message="")

Passes if object .kind_of? klass

Example:

  assert_kind_of Object, 'foo'
assert_match(pattern, string, message="")

Passes if string =~ pattern.

Example:

  assert_match(/\d+/, 'five, 6, seven')
assert_nil(object, message="")

Passes if object is nil.

Example:

  assert_nil [1, 2].uniq!
assert_no_match(regexp, string, message="")

Passes if regexp !~ string

Example:

  assert_no_match(/two/, 'one 2 three')
assert_not_equal(expected, actual, message="")

Passes if expected != actual

Example:

  assert_not_equal 'some string', 5
assert_not_nil(object, message="")

Passes if ! object .nil?

Example:

  assert_not_nil '1 two 3'.sub!(/two/, '2')
assert_not_same(expected, actual, message="")

Passes if ! actual .equal? expected

Example:

  assert_not_same Object.new, Object.new
assert_nothing_raised(*args) {|| ...}

Passes if block does not raise an exception.

Example:

  assert_nothing_raised do
    [1, 2].uniq
  end
assert_nothing_thrown(message="", &proc)

Passes if block does not throw anything.

Example:

 assert_nothing_thrown do
   [1, 2].uniq
 end
assert_operator(object1, operator, object2, message="")

Compares the +object1+ with +object2+ using operator.

Passes if object1.send(operator, object2) is true.

Example:

  assert_operator 5, :>=, 4
assert_raise(*args) {|| ...}

Passes if the block raises one of the given exceptions.

Example:

  assert_raise RuntimeError, LoadError do
    raise 'Boom!!!'
  end
assert_raises(*args, &block)

Alias of assert_raise.

Will be deprecated in 1.9, and removed in 2.0.

assert_respond_to(object, method, message="")

Passes if object .respond_to? method

Example:

  assert_respond_to 'bugbear', :slice
assert_same(expected, actual, message="")

Passes if actual .equal? expected (i.e. they are the same instance).

Example:

  o = Object.new
  assert_same o, o
assert_send(send_array, message="")

Passes if the method send returns a true value.

send_array is composed of:

  • A receiver
  • A method
  • Arguments to the method

Example:

  assert_send [[1, 2], :include?, 4]
assert_throws(expected_symbol, message="", &proc)

Passes if the block throws expected_symbol

Example:

  assert_throws :done do
    throw :done
  end
build_message(head, template=nil, *arguments)

Builds a failure message. head is added before the template and arguments replaces the ’?’s positionally in the template.

flunk(message="Flunked")

Flunk always fails.

Example:

  flunk 'Not done testing yet.'


Class: Test::Unit::AutoRunner

Class | Test::Unit::AutoRunner
In: | lib/test/unit/autorunner.rb
Parent: | Object

Methods

run standalone?

Constants

RUNNERS = { :console => proc do |r| require 'test/unit/ui/console/testrunner'

Public Class methods

run(force_standalone=false, default_dir=nil, argv=ARGV, &block)
standalone?()


Module: Test::Unit::Collector

Module | Test::Unit::Collector
In: | lib/test/unit/collector.rb lib/test/unit/collector/dir.rb lib/test/unit/collector/objectspace.rb

Methods

add_suite filter= include? new sort

Classes and Modules

Class Test::Unit::Collector::Dir
Class Test::Unit::Collector::ObjectSpace

Public Class methods

new()

Public Instance methods

add_suite(destination, suite)
filter=(filters)
include?(test)
sort(suites)


Class: Test::Unit::Collector::Dir

Class | Test::Unit::Collector::Dir
In: | lib/test/unit/collector/dir.rb
Parent: | Object

Methods

collect collect_file find_test_cases new realdir recursive_collect

Included Modules

Collector

Attributes

base | [RW]
exclude | [R]
pattern | [R]

Public Class methods

new(dir=::Dir, file=::File, object_space=::ObjectSpace, req=nil)

Public Instance methods

collect(*from)
collect_file(name, suites, already_gathered)
find_test_cases(ignore=[])
realdir(path)
recursive_collect(name, already_gathered)


Class: Test::Unit::Collector::ObjectSpace

Class | Test::Unit::Collector::ObjectSpace
In: | lib/test/unit/collector/objectspace.rb
Parent: | Object

Methods

collect new

Included Modules

Collector

Constants

NAME = 'collected from the ObjectSpace'

Public Class methods

new(source=::ObjectSpace)

Public Instance methods

collect(name=NAME)


Class: Test::Unit::Error

Class | Test::Unit::Error
In: | lib/test/unit/error.rb
Parent: | Object

Encapsulates an error in a test. Created by Test::Unit::TestCase when it rescues an exception thrown during the processing of a test.

Methods

long_display message new short_display single_character_display to_s

Included Modules

Util::BacktraceFilter

Constants

SINGLE_CHARACTER = 'E'

Attributes

exception | [R]
test_name | [R]

Public Class methods

new(test_name, exception)

Creates a new Error with the given test_name and exception.

Public Instance methods

long_display()

Returns a verbose version of the error description.

message()

Returns the message associated with the error.

short_display()

Returns a brief version of the error description.

single_character_display()

Returns a single character representation of an error.

to_s()

Overridden to return long_display.


Class: Test::Unit::Failure

Class | Test::Unit::Failure
In: | lib/test/unit/failure.rb
Parent: | Object

Encapsulates a test failure. Created by Test::Unit::TestCase when an assertion fails.

Methods

long_display new short_display single_character_display to_s

Constants

SINGLE_CHARACTER = 'F'

Attributes

location | [R]
message | [R]
test_name | [R]

Public Class methods

new(test_name, location, message)

Creates a new Failure with the given location and message.

Public Instance methods

long_display()

Returns a verbose version of the error description.

short_display()

Returns a brief version of the error description.

single_character_display()

Returns a single character representation of a failure.

to_s()

Overridden to return long_display.


Class: Test::Unit::TestCase

Class | Test::Unit::TestCase
In: | lib/test/unit/testcase.rb
Parent: | Object

Ties everything together. If you subclass and add your own test methods, it takes care of making them into tests and wrapping those tests into a suite. It also does the nitty-gritty of actually running an individual test and collecting its results into a Test::Unit::TestResult object.

Methods

== default_test name new run setup size suite teardown to_s

Included Modules

Assertions Util::BacktraceFilter

Constants

STARTED | = | name + "::STARTED"
FINISHED | = | name + "::FINISHED"
PASSTHROUGH_EXCEPTIONS | = | [NoMemoryError, SignalException, Interrupt, SystemExit] | These exceptions are not caught by run.

Attributes

method_name [R]

Public Class methods

new(test_method_name)

Creates a new instance of the fixture for running the test represented by test_method_name.

suite()

Rolls up all of the test* methods in the fixture into one suite, creating a new instance of the fixture for each method.

Public Instance methods

==(other)

It‘s handy to be able to compare TestCase instances.

default_test()
name()

Returns a human-readable name for the specific test that this instance of TestCase represents.

run(result) {|STARTED, name| ...}

Runs the individual test method represented by this instance of the fixture, collecting statistics, failures and errors in result.

setup()

Called before every test method runs. Can be used to set up fixture information.

size()
teardown()

Called after every test method runs. Can be used to tear down fixture information.

to_s()

Overridden to return name.


Class: Test::Unit::TestResult

Class | Test::Unit::TestResult
In: | lib/test/unit/testresult.rb
Parent: | Object

Collects Test::Unit::Failure and Test::Unit::Error so that they can be displayed to the user. To this end, observers can be added to it, allowing the dynamic updating of, say, a UI.

Methods

add_assertion add_error add_failure add_run error_count failure_count new passed? to_s

Included Modules

Util::Observable

Constants

CHANGED | = | "CHANGED"
FAULT | = | "FAULT"

Attributes

assertion_count | [R]
run_count | [R]

Public Class methods

new()

Constructs a new, empty TestResult.

Public Instance methods

add_assertion()

Records an individual assertion.

add_error(error)

Records a Test::Unit::Error.

add_failure(failure)

Records a Test::Unit::Failure.

add_run()

Records a test run.

error_count()

Returns the number of errors this TestResult has recorded.

failure_count()

Returns the number of failures this TestResult has recorded.

passed?()

Returns whether or not this TestResult represents successful completion.

to_s()

Returns a string contain the recorded runs, assertions, failures and errors in this TestResult.


Class: Test::Unit::TestSuite

Class | Test::Unit::TestSuite
In: | lib/test/unit/testsuite.rb
Parent: | Object

A collection of tests which can be run.

Note: It is easy to confuse a TestSuite instance with something that has a static suite method; I know because I have trouble keeping them straight. Think of something that has a suite method as simply providing a way to get a meaningful TestSuite instance.

Methods

<< == delete empty? new run size to_s

Constants

STARTED | = | name + "::STARTED"
FINISHED | = | name + "::FINISHED"

Attributes

name | [R]
tests | [R]

Public Class methods

new(name="Unnamed TestSuite")

Creates a new TestSuite with the given name.

Public Instance methods

<<(test)

Adds the test to the suite.

==(other)

It‘s handy to be able to compare TestSuite instances.

delete(test)
empty?()
run(result) {|STARTED, name| ...}

Runs the tests and/or suites contained in this TestSuite.

size()

Retuns the rolled up number of tests in this suite; i.e. if the suite contains other suites, it counts the tests within those suites, not the suites themselves.

to_s()

Overridden to return the name given the suite at creation.


Module: Test::Unit::UI

Module | Test::Unit::UI
In: | lib/test/unit/ui/console/testrunner.rb lib/test/unit/ui/fox/testrunner.rb lib/test/unit/ui/tk/testrunner.rb lib/test/unit/ui/testrunnerutilities.rb lib/test/unit/ui/gtk/testrunner.rb lib/test/unit/ui/gtk2/testrunner.rb lib/test/unit/ui/testrunnermediator.rb

Classes and Modules

Module Test::Unit::UI::Console
Module Test::Unit::UI::Fox
Module Test::Unit::UI::GTK
Module Test::Unit::UI::GTK2
Module Test::Unit::UI::TestRunnerUtilities
Module Test::Unit::UI::Tk
Class Test::Unit::UI::TestRunnerMediator

Constants

SILENT | = | 0
PROGRESS_ONLY | = | 1
NORMAL | = | 2
VERBOSE | = | 3


Module: Test::Unit::UI::Console

Module | Test::Unit::UI::Console
In: | lib/test/unit/ui/console/testrunner.rb

Classes and Modules

Class Test::Unit::UI::Console::TestRunner


Class: Test::Unit::UI::Console::TestRunner

Class | Test::Unit::UI::Console::TestRunner
In: | lib/test/unit/ui/console/testrunner.rb
Parent: | Object

Runs a Test::Unit::TestSuite on the console.

Methods

new start

Public Class methods

new(suite, output_level=NORMAL, io=STDOUT)

Creates a new TestRunner for running the passed suite. If quiet_mode is true, the output while running is limited to progress dots, errors and failures, and the final result. io specifies where runner output should go to; defaults to STDOUT.

Public Instance methods

start()

Begins the test run.


Module: Test::Unit::UI::Fox

Module | Test::Unit::UI::Fox
In: | lib/test/unit/ui/fox/testrunner.rb

Classes and Modules

Class Test::Unit::UI::Fox::FaultListItem
Class Test::Unit::UI::Fox::TestRunner


Class: Test::Unit::UI::Fox::FaultListItem

Class | Test::Unit::UI::Fox::FaultListItem
In: | lib/test/unit/ui/fox/testrunner.rb
Parent: | FXListItem

Methods

new

Attributes

fault [R]

Public Class methods

new(fault)


Class: Test::Unit::UI::Fox::TestRunner

Class | Test::Unit::UI::Fox::TestRunner
In: | lib/test/unit/ui/fox/testrunner.rb
Parent: | Object

Runs a Test::Unit::TestSuite in a Fox UI. Obviously, this one requires you to have Fox (www.fox-toolkit.org/fox.html) and the Ruby Fox extension (fxruby.sourceforge.net/) installed.

Methods

add_fault attach_to_mediator clear_fault create_application create_button create_detail_panel create_entry create_fault_list create_info_panel create_label create_list_panel create_main_panel create_progress_bar create_suite_panel create_text create_tooltip create_window finished new output_status raw_show_fault reset_ui result_changed setup_mediator setup_ui show_fault start start_ui started stop test_started

Constants

RED_STYLE | = | FXRGBA(0xFF,0,0,0xFF)
GREEN_STYLE | = | FXRGBA(0,0xFF,0,0xFF)

Public Class methods

new(suite, output_level = NORMAL)

Creates a new TestRunner for running the passed suite.

Public Instance methods

add_fault(fault)
attach_to_mediator()
clear_fault()
create_application()
create_button(parent, text, action)
create_detail_panel(parent)
create_entry(parent)
create_fault_list(parent)
create_info_panel(parent)
create_label(parent, text)
create_list_panel(parent)
create_main_panel(parent)
create_progress_bar(parent)
create_suite_panel(parent)
create_text(parent)
create_tooltip(app)
create_window(app)
finished(elapsed_time)
output_status(string)
raw_show_fault(string)
reset_ui(count)
result_changed(result)
setup_mediator()
setup_ui()
show_fault(fault)
start()

Begins the test run.

start_ui()
started(result)
stop()
test_started(test_name)


Module: Test::Unit::UI::GTK

Module | Test::Unit::UI::GTK
In: | lib/test/unit/ui/gtk/testrunner.rb

Classes and Modules

Class Test::Unit::UI::GTK::EnhancedLabel
Class Test::Unit::UI::GTK::EnhancedProgressBar
Class Test::Unit::UI::GTK::FaultListItem
Class Test::Unit::UI::GTK::TestRunner


Class: Test::Unit::UI::GTK::EnhancedLabel

Class | Test::Unit::UI::GTK::EnhancedLabel
In: | lib/test/unit/ui/gtk/testrunner.rb
Parent: | Gtk::Label

Methods

set_text

Public Instance methods

set_text(text)


Class: Test::Unit::UI::GTK::EnhancedProgressBar

Class | Test::Unit::UI::GTK::EnhancedProgressBar
In: | lib/test/unit/ui/gtk/testrunner.rb
Parent: | Gtk::ProgressBar

Methods

set_style

Public Instance methods

set_style(style)


Class: Test::Unit::UI::GTK::FaultListItem

Class | Test::Unit::UI::GTK::FaultListItem
In: | lib/test/unit/ui/gtk/testrunner.rb
Parent: | Gtk::ListItem

Methods

new

Attributes

fault [R]

Public Class methods

new(fault)


Class: Test::Unit::UI::GTK::TestRunner

Class | Test::Unit::UI::GTK::TestRunner
In: | lib/test/unit/ui/gtk/testrunner.rb
Parent: | Object

Runs a Test::Unit::TestSuite in a Gtk UI. Obviously, this one requires you to have Gtk (www.gtk.org/) and the Ruby Gtk extension (ruby-gnome.sourceforge.net/) installed.

Methods

new start

Public Class methods

new(suite, output_level = NORMAL)

Creates a new TestRunner for running the passed suite.

Public Instance methods

start()

Begins the test run.


Module: Test::Unit::UI::GTK2

Module | Test::Unit::UI::GTK2
In: | lib/test/unit/ui/gtk2/testrunner.rb

Classes and Modules

Class Test::Unit::UI::GTK2::EnhancedLabel
Class Test::Unit::UI::GTK2::FaultList
Class Test::Unit::UI::GTK2::TestRunner


Class: Test::Unit::UI::GTK2::EnhancedLabel

Class | Test::Unit::UI::GTK2::EnhancedLabel
In: | lib/test/unit/ui/gtk2/testrunner.rb
Parent: | Gtk::Label

Methods

set_text

Public Instance methods

set_text(text)


Class: Test::Unit::UI::GTK2::FaultList

Class | Test::Unit::UI::GTK2::FaultList
In: | lib/test/unit/ui/gtk2/testrunner.rb
Parent: | Gtk::TreeView

Methods

add_fault clear get_fault new

Public Class methods

new()

Public Instance methods

add_fault(fault)
clear()
get_fault(iter)


Class: Test::Unit::UI::GTK2::TestRunner

Class | Test::Unit::UI::GTK2::TestRunner
In: | lib/test/unit/ui/gtk2/testrunner.rb
Parent: | Object

Methods

new progress_panel run_button start test_finished

Public Class methods

new(suite, output_level = NORMAL)

Public Instance methods

progress_panel()
run_button()
start()
test_finished(result)


Class: Test::Unit::UI::TestRunnerMediator

Class | Test::Unit::UI::TestRunnerMediator
In: | lib/test/unit/ui/testrunnermediator.rb
Parent: | Object

Provides an interface to write any given UI against, hopefully making it easy to write new UIs.

Methods

new run_suite

Included Modules

Util::Observable

Constants

RESET | = | name + "::RESET"
STARTED | = | name + "::STARTED"
FINISHED | = | name + "::FINISHED"

Public Class methods

new(suite)

Creates a new TestRunnerMediator initialized to run the passed suite.

Public Instance methods

run_suite()

Runs the suite the TestRunnerMediator was created with.


Module: Test::Unit::UI::TestRunnerUtilities

Module | Test::Unit::UI::TestRunnerUtilities
In: | lib/test/unit/ui/testrunnerutilities.rb

Provides some utilities common to most, if not all, TestRunners.

Methods

run start_command_line_test

Public Instance methods

run(suite, output_level=NORMAL)

Creates a new TestRunner and runs the suite.

start_command_line_test()

Takes care of the ARGV parsing and suite determination necessary for running one of the TestRunners from the command line.


Module: Test::Unit::UI::Tk

Module | Test::Unit::UI::Tk
In: | lib/test/unit/ui/tk/testrunner.rb

Classes and Modules

Class Test::Unit::UI::Tk::TestRunner


Class: Test::Unit::UI::Tk::TestRunner

Class | Test::Unit::UI::Tk::TestRunner
In: | lib/test/unit/ui/tk/testrunner.rb
Parent: | Object

Runs a Test::Unit::TestSuite in a Tk UI. Obviously, this one requires you to have Tk and the Ruby Tk extension installed.

Methods

new start

Public Class methods

new(suite, output_level = NORMAL)

Creates a new TestRunner for running the passed suite.

Public Instance methods

start()

Begins the test run.


Module: Test::Unit::Util

Module | Test::Unit::Util
In: | lib/test/unit/util/observable.rb lib/test/unit/util/backtracefilter.rb lib/test/unit/util/procwrapper.rb

Classes and Modules

Module Test::Unit::Util::BacktraceFilter
Module Test::Unit::Util::Observable
Class Test::Unit::Util::ProcWrapper


Module: Test::Unit::Util::BacktraceFilter

Module | Test::Unit::Util::BacktraceFilter
In: | lib/test/unit/util/backtracefilter.rb

Methods

filter_backtrace

Constants

TESTUNIT_FILE_SEPARATORS | = | %r{[\\/:]}
TESTUNIT_PREFIX | = | __FILE__.split(TESTUNIT_FILE_SEPARATORS)[0..-3]
TESTUNIT_RB_FILE | = | /\.rb\Z/

Public Instance methods

filter_backtrace(backtrace, prefix=nil)


Module: Test::Unit::Util::Observable

Module | Test::Unit::Util::Observable
In: | lib/test/unit/util/observable.rb

This is a utility class that allows anything mixing it in to notify a set of listeners about interesting events.

Methods

add_listener notify_listeners remove_listener

Constants

NOTHING = "NOTHING/#{__id__}" We use this for defaults since nil might mean something

Public Instance methods

add_listener(channel_name, listener_key=NOTHING) {|value| ...}

Adds the passed proc as a listener on the channel indicated by channel_name. listener_key is used to remove the listener later; if none is specified, the proc itself is used.

Whatever is used as the listener_key is returned, making it very easy to use the proc itself as the listener_key:

 listener = add_listener("Channel") { ... }
 remove_listener("Channel", listener)
notify_listeners(channel_name, *arguments)

Calls all the procs registered on the channel indicated by channel_name. If value is specified, it is passed in to the procs, otherwise they are called with no arguments.

remove_listener(channel_name, listener_key)

Removes the listener indicated by listener_key from the channel indicated by channel_name. Returns the registered proc, or nil if none was found.


Class: Test::Unit::Util::ProcWrapper

Class | Test::Unit::Util::ProcWrapper
In: | lib/test/unit/util/procwrapper.rb
Parent: | Object

Allows the storage of a Proc passed through ’&’ in a hash.

Note: this may be inefficient, since the hash being used is not necessarily very good. In Observable, efficiency is not too important, since the hash is only accessed when adding and removing listeners, not when notifying.

Methods

== eql? hash new to_proc

Public Class methods

new(a_proc)

Creates a new wrapper for a_proc.

Public Instance methods

==(other)
eql?(other)

Alias for #==

hash()
to_proc()


Class: TestMyExcel

Class | TestMyExcel
In: | ext/win32ole/tests/testWIN32OLE.rb
Parent: | TestWin32OLE

Methods

setup test_s_connect test_s_new

Public Instance methods

setup()

because we overrided new() and connect() we need to change the test. also, because the class will be different

test_s_connect()
test_s_new()


Class: TestNIL2VT_EMPTY

Class | TestNIL2VT_EMPTY
In: | ext/win32ole/tests/testNIL2VTEMPTY.rb
Parent: | Test::Unit::TestCase

Methods

setup test_openSchema

Public Instance methods

setup()
test_openSchema()


Class: TestOLEMETHOD

Class | TestOLEMETHOD
In: | ext/win32ole/tests/testOLEMETHOD.rb
Parent: | RUNIT::TestCase

Methods

setup test_dispid test_event test_event_interface test_helpcontext test_helpfile test_helpstring test_invoke_kind test_name test_offset_vtbl test_return_type test_return_type_detail test_return_vtype test_s_new test_to_s test_visible

Included Modules

OLESERVER

Public Instance methods

setup()
test_dispid()
test_event()
test_event_interface()
test_helpcontext()
test_helpfile()
test_helpstring()
test_invoke_kind()
test_name()
test_offset_vtbl()
test_return_type()
test_return_type_detail()
test_return_vtype()
test_s_new()
test_to_s()
test_visible()


Class: TestOLEPARAM

Class | TestOLEPARAM
In: | ext/win32ole/tests/testOLEPARAM.rb
Parent: | RUNIT::TestCase

Methods

test_input test_name test_ole_type test_ole_type_detail test_optional test_output test_to_s

Included Modules

OLESERVER

Public Instance methods

test_input()
test_name()
test_ole_type()
test_ole_type_detail()
test_optional()
test_output()
test_to_s()


Class: TestOLETYPE

Class | TestOLETYPE
In: | ext/win32ole/tests/testOLETYPE.rb
Parent: | RUNIT::TestCase

Methods

test_class_to_s test_helpcontext test_helpfile test_helpstring test_name test_ole_methods test_ole_type test_s_new test_s_ole_classes test_s_progids test_s_typelibs test_src_type test_to_s test_typekind test_variables test_visible

Included Modules

OLESERVER

Public Instance methods

test_class_to_s()
test_helpcontext()
test_helpfile()
test_helpstring()
test_name()
test_ole_methods()
test_ole_type()
test_s_new()
test_s_ole_classes()
test_s_progids()
test_s_typelibs()
test_src_type()
test_to_s()
test_typekind()
test_variables()
test_visible()


Class: TestOLEVARIABLE

Class | TestOLEVARIABLE
In: | ext/win32ole/tests/testOLEVARIABLE.rb
Parent: | RUNIT::TestCase

Methods

test_name test_ole_type test_ole_type_detail test_to_s test_value test_visible

Included Modules

OLESERVER

Public Instance methods

test_name()
test_ole_type()
test_ole_type_detail()
test_to_s()
test_value()
test_visible()


Class: TestWIN32OLE_EVENT

Class | TestWIN32OLE_EVENT
In: | ext/win32ole/tests/testOLEEVENT.rb
Parent: | RUNIT::TestCase

Methods

handler1 handler2 handler3 setup teardown test_on_event test_on_event2 test_on_event3 test_on_event4

Public Instance methods

handler1()
handler2()
handler3()
setup()
teardown()
test_on_event()
test_on_event2()
test_on_event3()
test_on_event4()


Class: TestWIN32OLE_FOR_PROPERTYPUTREF

Class | TestWIN32OLE_FOR_PROPERTYPUTREF
In: | ext/win32ole/tests/test_ole_methods.rb
Parent: | Test::Unit::TestCase

Methods

setup test_ole_methods test_ole_put_methods

Public Instance methods

setup()
test_ole_methods()
test_ole_put_methods()


Class: TestWIN32OLE_PROPERTYPUTREF

Class | TestWIN32OLE_PROPERTYPUTREF
In: | ext/win32ole/tests/test_propertyputref.rb
Parent: | Test::Unit::TestCase

Methods

setup test_sapi

Public Instance methods

setup()
test_sapi()


Class: TestWIN32OLE_WITH_WORD

Class | TestWIN32OLE_WITH_WORD
In: | ext/win32ole/tests/test_word.rb
Parent: | Test::Unit::TestCase

Methods

setup teardown test_ole_methods

Public Instance methods

setup()
teardown()
test_ole_methods()


Class: TestWin32OLE

Class | TestWin32OLE
In: | ext/win32ole/tests/testWIN32OLE.rb
Parent: | RUNIT::TestCase

Methods

setup teardown test_const_CP_ACP test_const_CP_MACCP test_const_CP_OEMCP test_const_CP_SYMBOL test_const_CP_THREAD_ACP test_const_CP_UTF7 test_const_CP_UTF8 test_convert_bignum test_each test_get_win32ole_object test_invoke test_no_exist_property test_ole_func_methods test_ole_get_methods test_ole_invoke_with_named_arg test_ole_invoke_with_named_arg_last test_ole_method_help test_ole_methods test_ole_put_methods test_s_codepage test_s_codepage_changed test_s_codepage_set test_s_connect test_s_const_load test_s_new test_s_new_DCOM test_s_new_from_clsid test_setproperty test_setproperty_bracket test_setproperty_with_equal

Included Modules

OLESERVER

Public Instance methods

setup()
teardown()
test_const_CP_ACP()
test_const_CP_MACCP()
test_const_CP_OEMCP()
test_const_CP_SYMBOL()
test_const_CP_THREAD_ACP()
test_const_CP_UTF7()
test_const_CP_UTF8()
test_convert_bignum()
test_each()
test_get_win32ole_object()
test_invoke()
test_no_exist_property()
test_ole_func_methods()
test_ole_get_methods()
test_ole_invoke_with_named_arg()
test_ole_invoke_with_named_arg_last()
test_ole_method_help()
test_ole_methods()
test_ole_put_methods()
test_s_codepage()
test_s_codepage_changed()
test_s_codepage_set()
test_s_connect()
test_s_const_load()
test_s_new()
test_s_new_DCOM()
test_s_new_from_clsid()
test_setproperty()
test_setproperty_bracket()
test_setproperty_with_equal()


Class: TestWin32OLE_VARIANT

Class | TestWin32OLE_VARIANT
In: | ext/win32ole/tests/testVARIANT.rb
Parent: | RUNIT::TestCase

Methods

test_variant

Included Modules

WIN32OLE::VARIANT

Public Instance methods

test_variant()


Class: TestWin32OLE_WITH_MSI

Class | TestWin32OLE_WITH_MSI
In: | ext/win32ole/tests/testWIN32OLE.rb
Parent: | RUNIT::TestCase

Methods

setup test__invoke test_bracket_equal_with_arg test_setproperty

Public Instance methods

setup()
test__invoke()
test_bracket_equal_with_arg()
test_setproperty()

Sorry, this test fails. Win32OLE does not support this style to set property. Use Win32OLE#setproperty or Win32OLE#[]= . def test_invoke

  @record.invoke("StringData", 1, 'cccc')
  assert_equal('cccc', @record.StringData(1))

end


Class: Thread

Class | Thread
In: | eval.c lib/thread.rb
Parent: | Object

Thread encapsulates the behavior of a thread of execution, including the main thread of the Ruby script.

In the descriptions of the methods in this class, the parameter sym refers to a symbol, which is either a quoted string or a Symbol (such as :name).

Methods

[] []= abort_on_exception abort_on_exception abort_on_exception= abort_on_exception= alive? critical critical= current exclusive exit exit exit! fork group inspect join key? keys kill kill kill! list main new new pass priority priority= raise run safe_level start status stop stop? terminate terminate! value wakeup

Public Class methods

Thread.abort_on_exception => true or false

Returns the status of the global ``abort on exception’’ condition. The default is false. When set to true, or if the global $DEBUG flag is true (perhaps because the command line option -d was specified) all threads will abort (the process will exit(0)) if an exception is raised in any thread. See also Thread::abort_on_exception=.

Thread.abort_on_exception= boolean => true or false

When set to true, all threads will abort if an exception is raised. Returns the new state.

   Thread.abort_on_exception = true
   t1 = Thread.new do
     puts  "In new thread"
     raise "Exception from thread"
   end
   sleep(1)
   puts "not reached"

produces:

   In new thread
   prog.rb:4: Exception from thread (RuntimeError)
    from prog.rb:2:in `initialize'
    from prog.rb:2:in `new'
    from prog.rb:2
Thread.critical => true or false

Returns the status of the global ``thread critical’’ condition.

Thread.critical= boolean => true or false

Sets the status of the global ``thread critical’’ condition and returns it. When set to true, prohibits scheduling of any existing thread. Does not block new threads from being created and run. Certain thread operations (such as stopping or killing a thread, sleeping in the current thread, and raising an exception) may cause a thread to be scheduled even when in a critical section. Thread::critical is not intended for daily use: it is primarily there to support folks writing threading libraries.

Thread.current => thread

Returns the currently executing thread.

   Thread.current   #=> #<Thread:0x401bdf4c run>
exclusive() {|| ...}

Wraps a block in Thread.critical, restoring the original value upon exit from the critical section.

Thread.exit => thread

Terminates the currently running thread and schedules another thread to be run. If this thread is already marked to be killed, exit returns the Thread. If this is the main thread, or the last thread, exit the process.

Thread.start([args]*) {|args| block } => thread
Thread.fork([args]*) {|args| block } => thread

Basically the same as Thread::new. However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass‘s initialize method.

Thread.kill(thread) => thread

Causes the given thread to exit (see Thread::exit).

   count = 0
   a = Thread.new { loop { count += 1 } }
   sleep(0.1)       #=> 0
   Thread.kill(a)   #=> #<Thread:0x401b3d30 dead>
   count            #=> 93947
   a.alive?         #=> false
Thread.list => array

Returns an array of Thread objects for all threads that are either runnable or stopped.

   Thread.new { sleep(200) }
   Thread.new { 1000000.times {|i| i*i } }
   Thread.new { Thread.stop }
   Thread.list.each {|t| p t}

produces:

   #<Thread:0x401b3e84 sleep>
   #<Thread:0x401b3f38 run>
   #<Thread:0x401b3fb0 sleep>
   #<Thread:0x401bdf4c run>
Thread.main => thread

Returns the main thread for the process.

   Thread.main   #=> #<Thread:0x401bdf4c run>
Thread.new([arg]*) {|args| block } => thread

Creates and runs a new thread to execute the instructions given in block. Any arguments passed to Thread::new are passed into the block.

   x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
   a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
   x.join # Let the threads finish before
   a.join # main thread exits...

produces:

   abxyzc
Thread.new([arg]*) {|args| block } => thread

Creates and runs a new thread to execute the instructions given in block. Any arguments passed to Thread::new are passed into the block.

   x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
   a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
   x.join # Let the threads finish before
   a.join # main thread exits...

produces:

   abxyzc
Thread.pass => nil

Invokes the thread scheduler to pass execution to another thread.

   a = Thread.new { print "a"; Thread.pass;
                    print "b"; Thread.pass;
                    print "c" }
   b = Thread.new { print "x"; Thread.pass;
                    print "y"; Thread.pass;
                    print "z" }
   a.join
   b.join

produces:

   axbycz
Thread.start([args]*) {|args| block } => thread
Thread.fork([args]*) {|args| block } => thread

Basically the same as Thread::new. However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass‘s initialize method.

Thread.stop => nil

Stops execution of the current thread, putting it into a ``sleep’’ state, and schedules execution of another thread. Resets the ``critical’’ condition to false.

   a = Thread.new { print "a"; Thread.stop; print "c" }
   Thread.pass
   print "b"
   a.run
   a.join

produces:

   abc

Public Instance methods

thr[sym] => obj or nil

Attribute Reference—Returns the value of a thread-local variable, using either a symbol or a string name. If the specified variable does not exist, returns nil.

   a = Thread.new { Thread.current["name"] = "A"; Thread.stop }
   b = Thread.new { Thread.current[:name]  = "B"; Thread.stop }
   c = Thread.new { Thread.current["name"] = "C"; Thread.stop }
   Thread.list.each {|x| puts "#{x.inspect}: #{x[:name]}" }

produces:

   #<Thread:0x401b3b3c sleep>: C
   #<Thread:0x401b3bc8 sleep>: B
   #<Thread:0x401b3c68 sleep>: A
   #<Thread:0x401bdf4c run>:
thr[sym] = obj => obj

Attribute Assignment—Sets or creates the value of a thread-local variable, using either a symbol or a string. See also Thread#[].

thr.abort_on_exception => true or false

Returns the status of the thread-local ``abort on exception’’ condition for thr. The default is false. See also Thread::abort_on_exception=.

thr.abort_on_exception= boolean => true or false

When set to true, causes all threads (including the main program) to abort if an exception is raised in thr. The process will effectively exit(0).

thr.alive? => true or false

Returns true if thr is running or sleeping.

   thr = Thread.new { }
   thr.join                #=> #<Thread:0x401b3fb0 dead>
   Thread.current.alive?   #=> true
   thr.alive?              #=> false
thr.exit => thr
thr.kill => thr
thr.terminate => thr

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

thr.exit! => thr
thr.kill! => thr
thr.terminate! => thr

Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

See Thread#exit for the safer version.

thr.group => thgrp or nil

Returns the ThreadGroup which contains thr, or nil if the thread is not a member of any group.

   Thread.main.group   #=> #<ThreadGroup:0x4029d914>
thr.inspect => string

Dump the name, id, and status of thr to a string.

thr.join => thr
thr.join(limit) => thr

The calling thread will suspend execution and run thr. Does not return until thr exits or until limit seconds have passed. If the time limit expires, nil will be returned, otherwise thr is returned.

Any threads not joined will be killed when the main program exits. If thr had previously raised an exception and the abort_on_exception and $DEBUG flags are not set (so the exception has not yet been processed) it will be processed at this time.

   a = Thread.new { print "a"; sleep(10); print "b"; print "c" }
   x = Thread.new { print "x"; Thread.pass; print "y"; print "z" }
   x.join # Let x thread finish, a will be killed on exit.

produces:

   axyz

The following example illustrates the limit parameter.

   y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
   puts "Waiting" until y.join(0.15)

produces:

   tick...
   Waiting
   tick...
   Waitingtick...

   tick...
thr.key?(sym) => true or false

Returns true if the given string (or symbol) exists as a thread-local variable.

   me = Thread.current
   me[:oliver] = "a"
   me.key?(:oliver)    #=> true
   me.key?(:stanley)   #=> false
thr.keys => array

Returns an an array of the names of the thread-local variables (as Symbols).

   thr = Thread.new do
     Thread.current[:cat] = 'meow'
     Thread.current["dog"] = 'woof'
   end
   thr.join   #=> #<Thread:0x401b3f10 dead>
   thr.keys   #=> [:dog, :cat]
thr.exit => thr
thr.kill => thr
thr.terminate => thr

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

thr.exit! => thr
thr.kill! => thr
thr.terminate! => thr

Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

See Thread#exit for the safer version.

thr.priority => integer

Returns the priority of thr. Default is inherited from the current thread which creating the new thread, or zero for the initial main thread; higher-priority threads will run before lower-priority threads.

   Thread.current.priority   #=> 0
thr.priority= integer => thr

Sets the priority of thr to integer. Higher-priority threads will run before lower-priority threads.

   count1 = count2 = 0
   a = Thread.new do
         loop { count1 += 1 }
       end
   a.priority = -1

   b = Thread.new do
         loop { count2 += 1 }
       end
   b.priority = -2
   sleep 1   #=> 1
   Thread.critical = 1
   count1    #=> 622504
   count2    #=> 5832
thr.raise(exception)

Raises an exception (see Kernel::raise) from thr. The caller does not have to be thr.

   Thread.abort_on_exception = true
   a = Thread.new { sleep(200) }
   a.raise("Gotcha")

produces:

   prog.rb:3: Gotcha (RuntimeError)
    from prog.rb:2:in `initialize'
    from prog.rb:2:in `new'
    from prog.rb:2
thr.run => thr

Wakes up thr, making it eligible for scheduling. If not in a critical section, then invokes the scheduler.

   a = Thread.new { puts "a"; Thread.stop; puts "c" }
   Thread.pass
   puts "Got here"
   a.run
   a.join

produces:

   a
   Got here
   c
thr.safe_level => integer

Returns the safe level in effect for thr. Setting thread-local safe levels can help when implementing sandboxes which run insecure code.

   thr = Thread.new { $SAFE = 3; sleep }
   Thread.current.safe_level   #=> 0
   thr.safe_level              #=> 3
thr.status => string, false or nil

Returns the status of thr: ``sleep’’ if thr is sleeping or waiting on I/O, ``run’’ if thr is executing, ``aborting’’ if thr is aborting, false if thr terminated normally, and nil if thr terminated with an exception.

   a = Thread.new { raise("die now") }
   b = Thread.new { Thread.stop }
   c = Thread.new { Thread.exit }
   d = Thread.new { sleep }
   Thread.critical = true
   d.kill                  #=> #<Thread:0x401b3678 aborting>
   a.status                #=> nil
   b.status                #=> "sleep"
   c.status                #=> false
   d.status                #=> "aborting"
   Thread.current.status   #=> "run"
thr.stop? => true or false

Returns true if thr is dead or sleeping.

   a = Thread.new { Thread.stop }
   b = Thread.current
   a.stop?   #=> true
   b.stop?   #=> false
thr.exit => thr
thr.kill => thr
thr.terminate => thr

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

thr.exit! => thr
thr.kill! => thr
thr.terminate! => thr

Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

See Thread#exit for the safer version.

thr.value => obj

Waits for thr to complete (via Thread#join) and returns its value.

   a = Thread.new { 2 + 2 }
   a.value   #=> 4
thr.wakeup => thr

Marks thr as eligible for scheduling (it may still remain blocked on I/O, however). Does not invoke the scheduler (see Thread#run).

   c = Thread.new { Thread.stop; puts "hey!" }
   c.wakeup

produces:

   hey!


Class: ThreadError

Class | ThreadError
In: | eval.c
Parent: | StandardError


Class: ThreadGroup

Class | ThreadGroup
In: | eval.c
Parent: | Object

ThreadGroup provides a means of keeping track of a number of threads as a group. A Thread can belong to only one ThreadGroup at a time; adding a thread to a new group will remove it from any previous group.

Newly created threads belong to the same group as the thread from which they were created.

Methods

add enclose enclosed? list

Constants

Default = thgroup_default

Public Instance methods

thgrp.add(thread) => thgrp

Adds the given thread to this group, removing it from any other group to which it may have previously belonged.

   puts "Initial group is #{ThreadGroup::Default.list}"
   tg = ThreadGroup.new
   t1 = Thread.new { sleep }
   t2 = Thread.new { sleep }
   puts "t1 is #{t1}"
   puts "t2 is #{t2}"
   tg.add(t1)
   puts "Initial group now #{ThreadGroup::Default.list}"
   puts "tg group now #{tg.list}"

produces:

   Initial group is #<Thread:0x401bdf4c>
   t1 is #<Thread:0x401b3c90>
   t2 is #<Thread:0x401b3c18>
   Initial group now #<Thread:0x401b3c18>#<Thread:0x401bdf4c>
   tg group now #<Thread:0x401b3c90>
thgrp.enclose => thgrp

Prevents threads from being added to or removed from the receiving ThreadGroup. New threads can still be started in an enclosed ThreadGroup.

   ThreadGroup::Default.enclose        #=> #<ThreadGroup:0x4029d914>
   thr = Thread::new { Thread.stop }   #=> #<Thread:0x402a7210 sleep>
   tg = ThreadGroup::new               #=> #<ThreadGroup:0x402752d4>
   tg.add thr

produces:

   ThreadError: can't move from the enclosed thread group
thgrp.enclosed? => true or false

Returns true if thgrp is enclosed. See also ThreadGroup#enclose.

thgrp.list => array

Returns an array of all existing Thread objects that belong to this group.

   ThreadGroup::Default.list   #=> [#<Thread:0x401bdf4c run>]


Class: ThreadsWait

Class | ThreadsWait
In: | lib/thwait.rb
Parent: | Object

This class watches for termination of multiple threads. Basic functionality (wait until specified threads have terminated) can be accessed through the class method ThreadsWait::all_waits. Finer control can be gained using instance methods.

Example:

  ThreadsWait.all_wait(thr1, thr2, ...) do |t|
    STDERR.puts "Thread #{t} has terminated."
  end

Methods

all_waits all_waits empty? finished? join join_nowait new next_wait

Constants

RCS_ID = '-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-'

Attributes

threads [R] Returns the array of threads in the wait queue.

Public Class methods

all_waits(*threads) {|thread| ...}

Waits until all specified threads have terminated. If a block is provided, it is executed for each thread termination.

new(*threads)

Creates a ThreadsWait object, specifying the threads to wait on. Non-blocking.

Public Instance methods

all_waits() {|th if block_given?| ...}

Waits until all of the specified threads are terminated. If a block is supplied for the method, it is executed for each thread termination.

Raises exceptions in the same manner as next_wait.

empty?()

Returns true if there are no threads to be synchronized.

finished?()

Returns true if any thread has terminated.

join(*threads)

Waits for specified threads to terminate.

join_nowait(*threads)

Specifies the threads that this object will wait for, but does not actually wait.

next_wait(nonblock = nil)

Waits until any of the specified threads has terminated, and returns the one that does.

If there is no thread to wait, raises ErrNoWaitingThread. If nonblock is true, and there is no terminated thread, raises ErrNoFinishedThread.


Module: Timeout

Module | Timeout
In: | lib/timeout.rb

Description

A way of performing a potentially long-running operation in a thread, and terminating it‘s execution if it hasn‘t finished within fixed amount of time.

Previous versions of timeout didn‘t use a module for namespace. This version provides both Timeout.timeout, and a backwards-compatible timeout.

Synopsis

  require 'timeout'
  status = Timeout::timeout(5) {
    # Something that should be interrupted if it takes too much time...
  }

Methods

timeout

Classes and Modules

Class Timeout::Error

Public Instance methods

timeout(sec, exception=Error) {|if sec == nil or sec.zero?| ...}

Executes the method‘s block. If the block execution terminates before sec seconds has passed, it returns true. If not, it terminates the execution and raises exception (which defaults to Timeout::Error).

Note that this is both a method of module Timeout, so you can ‘include Timeout’ into your classes so they have a timeout method, as well as a module method, so you can call it directly as Timeout.timeout().


Class: Timeout::Error

Class | Timeout::Error
In: | lib/timeout.rb
Parent: | Interrupt

Raised by Timeout#timeout when the block times out.


Module: TokenStream

Module | TokenStream
In: | lib/rdoc/tokenstream.rb

A TokenStream is a list of tokens, gathered during the parse of some entity (say a method). Entities populate these streams by being registered with the lexer. Any class can collect tokens by including TokenStream. From the outside, you use such an object by calling the start_collecting_tokens method, followed by calls to add_token and pop_token

Methods

add_token add_tokens pop_token start_collecting_tokens token_stream

Public Instance methods

add_token(tk)
add_tokens(tks)
pop_token()
start_collecting_tokens()
token_stream()


Class: Tracer

Class | Tracer
In: | lib/debug.rb lib/tracer.rb
Parent: | Object

tracer main class

Methods

add_filter add_filter get_line get_thread_no new off off on on set_get_line_procs set_get_line_procs stdout trace_func trace_func

Constants

EVENT_SYMBOL | = | { "line" => "-", "call" => ">", "return" => "<", "class" => "C", "end" => "E", "c-call" => ">", "c-return" => "<", }
Single | = | new

External Aliases

verbose -> verbose?

Attributes

stdout | [RW]
verbose | [RW]

Public Class methods

add_filter(p = proc)
new()
off()
on() {|| ...}
set_get_line_procs(file_name, p = proc)
trace_func(*vars)

Public Instance methods

add_filter(p = proc)
get_line(file, line)
get_thread_no()
off()
on() {|| ...}
set_get_line_procs(file, p = proc)
stdout()
trace_func(event, file, line, id, binding, klass, *)


Class: TrueClass

Class | TrueClass
In: | object.c lib/yaml/rubytypes.rb
Parent: | Object

The global value true is the only instance of class TrueClass and represents a logically true value in boolean expressions. The class provides operators allowing true to be used in logical expressions.

Methods

& ^ to_s to_yaml |

Public Instance methods

true & obj => true or false

And—Returns false if obj is nil or false, true otherwise.

true ^ obj => !obj

Exclusive Or—Returns true if obj is nil or false, false otherwise.

true.to_s => "true"

The string representation of true is "true".

to_yaml( opts = {} )
true | obj => true

Or—Returns true. As anObject is an argument to a method call, it is always evaluated; there is no short-circuit evaluation in this case.

   true |  puts("or")
   true || puts("logical or")

produces:

   or


Class: TruncatedDataError

Class | TruncatedDataError
In: | lib/readbytes.rb
Parent: | IOError

TruncatedDataError is raised when IO#readbytes fails to read enough data.

Attributes

data [R] The read portion of an IO#readbytes attempt.


Class: TypeError

Class | TypeError
In: | error.c
Parent: | StandardError


Class: UDPSocket

Class | UDPSocket
In: | lib/resolv-replace.rb ext/socket/socket.c
Parent: | Object

Methods

bind connect recvfrom_nonblock send

External Aliases

bind | -> | original_resolv_bind
connect | -> | original_resolv_connect
send | -> | original_resolv_send

Public Instance methods

bind(host, port)
connect(host, port)
udpsocket.recvfrom_nonblock(maxlen) => [mesg, sender_inet_addr]
udpsocket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_inet_addr]

Receives up to maxlen bytes from udpsocket using recvfrom(2) after O_NONBLOCK is set for the underlying file descriptor. flags is zero or more of the MSG_ options. The first element of the results, mesg, is the data received. The second element, sender_inet_addr, is an array to represent the sender address.

When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns an empty string as data. It means an empty packet.

Parameters

  • maxlen - the number of bytes to receive from the socket
  • flags - zero or more of the MSG_ options

Example

     require 'socket'
     s1 = UDPSocket.new
     s1.bind("127.0.0.1", 0)
     s2 = UDPSocket.new
     s2.bind("127.0.0.1", 0)
     s2.connect(*s1.addr.values_at(3,1))
     s1.connect(*s2.addr.values_at(3,1))
     s1.send "aaa", 0
     IO.select([s2])
     p s2.recvfrom_nonblock(10)  #=> ["aaa", ["AF_INET", 33302, "localhost.localdomain", "127.0.0.1"]]

Refer to Socket#recvfrom for the exceptions that may be thrown if the call to recvfrom_nonblock fails.

UDPSocket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure, including Errno::EAGAIN.

See

  • Socket#recvfrom
send(mesg, flags, *rest)


Class: UNIXServer

Class | UNIXServer
In: | ext/socket/socket.c
Parent: | UNIXSocket

Methods

accept_nonblock listen

Public Instance methods

unixserver.accept_nonblock => unixsocket

Accepts an incoming connection using accept(2) after O_NONBLOCK is set for the underlying file descriptor. It returns an accepted UNIXSocket for the incoming connection.

Example

     require 'socket'
     serv = UNIXServer.new("/tmp/sock")
     begin
       sock = serv.accept_nonblock
     rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
       IO.select([serv])
       retry
     end
     # sock is an accepted socket.

Refer to Socket#accept for the exceptions that may be thrown if the call to UNIXServer#accept_nonblock fails.

UNIXServer#accept_nonblock may raise any error corresponding to accept(2) failure, including Errno::EAGAIN.

See

  • UNIXServer#accept
  • Socket#accept
socket.listen( int ) => 0

Listens for connections, using the specified int as the backlog. A call to listen only applies if the socket is of type SOCK_STREAM or SOCK_SEQPACKET.

Parameter

  • backlog - the maximum length of the queue for pending connections.

Example 1

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
     socket.bind( sockaddr )
     socket.listen( 5 )

Example 2 (listening on an arbitary port, unix-based systems only):

     require 'socket'
     include Socket::Constants
     socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
     socket.listen( 1 )

Unix-based Exceptions

On unix based systems the above will work because a new sockaddr struct is created on the address ADDR_ANY, for an arbitrary port number as handed off by the kernel. It will not work on Windows, because Windows requires that the socket is bound by calling bind before it can listen.

If the backlog amount exceeds the implementation-dependent maximum queue length, the implementation‘s maximum queue length will be used.

On unix-based based systems the following system exceptions may be raised if the call to listen fails:

  • Errno::EBADF - the socket argument is not a valid file descriptor
  • Errno::EDESTADDRREQ - the socket is not bound to a local address, and the protocol does not support listening on an unbound socket
  • Errno::EINVAL - the socket is already connected
  • Errno::ENOTSOCK - the socket argument does not refer to a socket
  • Errno::EOPNOTSUPP - the socket protocol does not support listen
  • Errno::EACCES - the calling process does not have approriate privileges
  • Errno::EINVAL - the socket has been shut down
  • Errno::ENOBUFS - insufficient resources are available in the system to complete the call

Windows Exceptions

On Windows systems the following system exceptions may be raised if the call to listen fails:

  • Errno::ENETDOWN - the network is down
  • Errno::EADDRINUSE - the socket‘s local address is already in use. This usually occurs during the execution of bind but could be delayed if the call to bind was to a partially wildcard address (involving ADDR_ANY) and if a specific address needs to be commmitted at the time of the call to listen
  • Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the service provider is still processing a callback function
  • Errno::EINVAL - the socket has not been bound with a call to bind.
  • Errno::EISCONN - the socket is already connected
  • Errno::EMFILE - no more socket descriptors are available
  • Errno::ENOBUFS - no buffer space is available
  • Errno::ENOTSOC - socket is not a socket
  • Errno::EOPNOTSUPP - the referenced socket is not a type that supports the listen method

See

  • listen manual pages on unix-based systems
  • listen function in Microsoft‘s Winsock functions reference


Class: UNIXSocket

Class | UNIXSocket
In: | ext/socket/socket.c
Parent: | BasicSocket


Module: URI

Module | URI
In: | lib/open-uri.rb lib/uri/ftp.rb lib/uri/ldap.rb lib/uri/https.rb lib/uri/generic.rb lib/uri/common.rb lib/uri/http.rb lib/uri/mailto.rb lib/uri.rb

URI support for Ruby

Author: | Akira Yamada <akira@ruby-lang.org>
Documentation: | Akira Yamada <akira@ruby-lang.org>, Dmitry V. Sabanin <sdmitry@lrn.ru>
License: | Copyright (c) 2001 akira yamada <akira@ruby-lang.org> You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: uri.rb 11708 2007-02-12 23:01:19Z shyouhei $

See URI for documentation

Methods

extract join parse regexp split

Included Modules

REGEXP

Classes and Modules

Module URI::Escape
Module URI::REGEXP
Class URI::BadURIError
Class URI::Error
Class URI::FTP
Class URI::Generic
Class URI::HTTP
Class URI::HTTPS
Class URI::InvalidComponentError
Class URI::InvalidURIError
Class URI::LDAP
Class URI::MailTo

Public Class methods

extract(str, schemes = nil) {|$&| ...}

Synopsis

  URI::extract(str[, schemes][,&blk])

Args

str: | String to extract URIs from.
schemes: | Limit URI matching to a specific schemes.

Description

Extracts URIs from a string. If block given, iterates through all matched URIs. Returns nil if block given or array with matches.

Usage

  require "uri"

  URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
  # => ["http://foo.example.com/bla", "mailto:test@example.com"]
join(*str)

Synopsis

  URI::join(str[, str, ...])

Args

str: String(s) to work with

Description

Joins URIs.

Usage

  require 'uri'

  p URI.join("http://localhost/","main.rbx")
  # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx>
parse(uri)

Synopsis

  URI::parse(uri_str)

Args

uri_str: String with URI.

Description

Creates one of the URI‘s subclasses instance from the string.

Raises

URI::InvalidURIError

  Raised if URI given is not a correct one.

Usage

  require 'uri'

  uri = URI.parse("http://www.ruby-lang.org/")
  p uri
  # => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/>
  p uri.scheme
  # => "http"
  p uri.host
  # => "www.ruby-lang.org"
regexp(schemes = nil)

Synopsis

  URI::regexp([match_schemes])

Args

match_schemes: Array of schemes. If given, resulting regexp matches to URIs whose scheme is one of the match_schemes.

Description

Returns a Regexp object which matches to URI-like strings. The Regexp object returned by this method includes arbitrary number of capture group (parentheses). Never rely on it‘s number.

Usage

  require 'uri'

  # extract first URI from html_string
  html_string.slice(URI.regexp)

  # remove ftp URIs
  html_string.sub(URI.regexp(['ftp'])

  # You should not rely on the number of parentheses
  html_string.scan(URI.regexp) do |*matches|
    p $&
  end
split(uri)

Synopsis

  URI::split(uri)

Args

uri: String with URI.

Description

Splits the string on following parts and returns array with result:

  * Scheme
  * Userinfo
  * Host
  * Port
  * Registry
  * Path
  * Opaque
  * Query
  * Fragment

Usage

  require 'uri'

  p URI.split("http://www.ruby-lang.org/")
  # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]


Class: URI::BadURIError

Class | URI::BadURIError
In: | lib/uri/common.rb
Parent: | Error

URI is valid, bad usage is not.


Class: URI::Error

Class | URI::Error
In: | lib/uri/common.rb
Parent: | StandardError

Base class for all URI exceptions.


Module: URI::Escape

Module | URI::Escape
In: | lib/uri/common.rb

Methods

decode encode escape unescape

Included Modules

REGEXP

Public Instance methods

decode(str)

Alias for unescape

encode(str, unsafe = UNSAFE)

Alias for escape

escape(str, unsafe = UNSAFE)

Synopsis

  URI.escape(str [, unsafe])

Args

str: | String to replaces in.
unsafe: | Regexp that matches all symbols that must be replaced with codes. By default uses REGEXP::UNSAFE. When this argument is a String, it represents a character set.

Description

Escapes the string, replacing all unsafe characters with codes.

Usage

  require 'uri'

  enc_uri = URI.escape("http://example.com/?a=\11\15")
  p enc_uri
  # => "http://example.com/?a=%09%0D"

  p URI.unescape(enc_uri)
  # => "http://example.com/?a=\t\r"

  p URI.escape("@?@!", "!?")
  # => "@%3F@%21"
unescape(str)

Synopsis

  URI.unescape(str)

Args

str: Unescapes the string.

Usage

  require 'uri'

  enc_uri = URI.escape("http://example.com/?a=\11\15")
  p enc_uri
  # => "http://example.com/?a=%09%0D"

  p URI.unescape(enc_uri)
  # => "http://example.com/?a=\t\r"


Class: URI::FTP

Class | URI::FTP
In: | lib/open-uri.rb lib/uri/ftp.rb
Parent: | Object

RFC1738 section 3.2.

Methods

build new new2 set_typecode to_s typecode=

Included Modules

OpenURI::OpenRead

Constants

DEFAULT_PORT | = | 21
COMPONENT | = | [ :scheme, :userinfo, :host, :port, :path, :typecode
TYPECODE | = | ['a', 'i', 'd'].freeze | Typecode is, "a", "i" or "d". As for "a" the text, as for "i" binary, as for "d" the directory is displayed. "A" with the text, as for "i" being binary, is because the respective data type was called ASCII and IMAGE with the protocol of FTP.
TYPECODE_PREFIX | = | ';type='.freeze

Attributes

typecode [R]

Public Class methods

build(args)

Description

Creates a new URI::FTP object from components of URI::FTP with check. It is scheme, userinfo, host, port, path and typecode. It provided by an Array or a Hash. typecode is "a", "i" or "d".

new(*arg)

Description

Create a new URI::FTP object from ``generic’’ components with no check.

Usage

  require 'uri'
  p ftp = URI.parse("ftp://ftp.ruby-lang.org/pub/ruby/;type=d")
  # => #<URI::FTP:0x201fad08 URL:ftp://ftp.ruby-lang.org/pub/ruby/;type=d>
  p ftp.typecode
  # => "d"
new2(user, password, host, port, path, typecode = nil, arg_check = true)

Public Instance methods

to_s()
typecode=(typecode)

Protected Instance methods

set_typecode(v)


Class: URI::Generic

Class | URI::Generic
In: | lib/open-uri.rb lib/uri/generic.rb
Parent: | Object

Base class for all URI classes. Implements generic URI syntax as per RFC 2396.

Methods

+ - == absolute absolute? build build2 coerce component component component_ary default_port default_port eql? find_proxy fragment= hash hierarchical? host= inspect merge merge! new normalize normalize! opaque= password password= path= port= query= registry= relative? route_from route_to scheme= select set_fragment set_host set_opaque set_password set_path set_port set_query set_registry set_scheme set_user set_userinfo to_s use_registry user user= userinfo userinfo=

Included Modules

URI REGEXP

Constants

DEFAULT_PORT | = | nil
COMPONENT | = | [ :scheme, :userinfo, :host, :port, :registry, :path, :opaque, :query, :fragment
USE_REGISTRY | = | false

Attributes

fragment | [R]
host | [R]
opaque | [R]
path | [R]
port | [R]
query | [R]
registry | [R]
scheme | [R]

Public Class methods

build(args)

Synopsis

See new

Description

Creates a new URI::Generic instance from components of URI::Generic with check. Components are: scheme, userinfo, host, port, registry, path, opaque, query and fragment. You can provide arguments either by an Array or a Hash. See new for hash keys to use or for order of array items.

build2(args)

Synopsis

See new

Description

At first, tries to create a new URI::Generic instance using URI::Generic::build. But, if exception URI::InvalidComponentError is raised, then it URI::Escape.escape all URI components and tries again.

component()

Components of the URI in the order.

default_port()

Returns default port

new(scheme, userinfo, host, port, registry, path, opaque, query, fragment, arg_check = false)

Args

scheme: | Protocol scheme, i.e. ‘http’,’ftp’,’mailto’ and so on.
userinfo: | User name and password, i.e. ‘sdmitry:bla‘
host: | Server host name
port: | Server port
registry: | DOC: FIXME!
path: | Path on server
opaque: | DOC: FIXME!
query: | Query data
fragment: | A part of URI after ’#’ sign
arg_check: | Check arguments [false by default]

Description

Creates a new URI::Generic instance from ``generic’’ components without check.

use_registry()

DOC: FIXME!

Public Instance methods

+(oth)

Alias for merge

-(oth)

Alias for route_from

==(oth)

Compares to URI‘s

absolute()

Alias for absolute?

absolute?()

Checks if URI is an absolute one

coerce(oth)
component()
default_port()
eql?(oth)
find_proxy()

returns a proxy URI. The proxy URI is obtained from environment variables such as http_proxy, ftp_proxy, no_proxy, etc. If there is no proper proxy, nil is returned.

Note that capitalized variables (HTTP_PROXY, FTP_PROXY, NO_PROXY, etc.) are examined too.

But http_proxy and HTTP_PROXY is treated specially under CGI environment. It‘s because HTTP_PROXY may be set by Proxy: header. So HTTP_PROXY is not used. http_proxy is not used too if the variable is case insensitive. CGI_HTTP_PROXY can be used instead.

fragment=(v)
hash()
hierarchical?()

Checks if URI has a path

host=(v)
inspect()
merge(oth)

Args

oth: URI or String

Description

Merges two URI‘s.

Usage

  require 'uri'

  uri = URI.parse("http://my.example.com")
  p uri.merge("/main.rbx?page=1")
  # =>  #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
merge!(oth)

Args

oth: URI or String

Description

Destructive form of merge

Usage

  require 'uri'

  uri = URI.parse("http://my.example.com")
  uri.merge!("/main.rbx?page=1")
  p uri
  # =>  #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
normalize()

Returns normalized URI

normalize!()

Destructive version of normalize

opaque=(v)
password()
password=(password)
path=(v)
port=(v)
query=(v)
registry=(v)
relative?()

Checks if URI is relative

route_from(oth)

Args

oth: URI or String

Description

Calculates relative path from oth to self

Usage

  require 'uri'

  uri = URI.parse('http://my.example.com/main.rbx?page=1')
  p uri.route_from('http://my.example.com')
  #=> #<URI::Generic:0x20218858 URL:/main.rbx?page=1>
route_to(oth)

Args

oth: URI or String

Description

Calculates relative path to oth from self

Usage

  require 'uri'

  uri = URI.parse('http://my.example.com')
  p uri.route_to('http://my.example.com/main.rbx?page=1')
  #=> #<URI::Generic:0x2020c2f6 URL:/main.rbx?page=1>
scheme=(v)
select(*components)

Args

components: Multiple Symbol arguments defined in URI::HTTP

Description

Selects specified components from URI

Usage

  require 'uri'

  uri = URI.parse('http://myuser:mypass@my.example.com/test.rbx')
  p uri.select(:userinfo, :host, :path)
  # => ["myuser:mypass", "my.example.com", "/test.rbx"]
to_s()

Constructs String from URI

user()
user=(user)
userinfo()
userinfo=(userinfo)

Sets userinfo, argument is string like ‘name:pass‘

Protected Instance methods

component_ary()
set_fragment(v)
set_host(v)
set_opaque(v)
set_password(v)
set_path(v)
set_port(v)
set_query(v)
set_registry(v)
set_scheme(v)
set_user(v)
set_userinfo(user, password = nil)


Class: URI::HTTP

Class | URI::HTTP
In: | lib/open-uri.rb lib/uri/http.rb
Parent: | Object

The syntax of HTTP URIs is defined in RFC1738 section 3.3.

Note that the Ruby URI library allows HTTP URLs containing usernames and passwords. This is not legal as per the RFC, but used to be supported in Internet Explorer 5 and 6, before the MS04-004 security update. See <URL:support.microsoft.com/kb/834489>.

Methods

build new request_uri

Included Modules

OpenURI::OpenRead

Constants

DEFAULT_PORT | = | 80
COMPONENT | = | [ :scheme, :userinfo, :host, :port, :path, :query, :fragment

Public Class methods

build(args)

Description

Create a new URI::HTTP object from components, with syntax checking.

The components accepted are userinfo, host, port, path, query and fragment.

The components should be provided either as an Array, or as a Hash with keys formed by preceding the component names with a colon.

If an Array is used, the components must be passed in the order [userinfo, host, port, path, query, fragment].

Example:

    newuri = URI::HTTP.build({:host => 'www.example.com',
      :path> => '/foo/bar'})

    newuri = URI::HTTP.build([nil, "www.example.com", nil, "/path",
      "query", 'fragment'])

Currently, if passed userinfo components this method generates invalid HTTP URIs as per RFC 1738.

new(*arg)

Description

Create a new URI::HTTP object from generic URI components as per RFC 2396. No HTTP-specific syntax checking (as per RFC 1738) is performed.

Arguments are scheme, userinfo, host, port, registry, path, opaque, query and fragment, in that order.

Example:

    uri = URI::HTTP.new(['http', nil, "www.example.com", nil, "/path",
      "query", 'fragment'])

Public Instance methods

request_uri()

Description

Returns the full path for an HTTP request, as required by Net::HTTP::Get.

If the URI contains a query, the full path is URI#path + ’?’ + URI#query. Otherwise, the path is simply URI#path.


Class: URI::HTTPS

Class | URI::HTTPS
In: | lib/uri/https.rb
Parent: | HTTP

The default port for HTTPS URIs is 443, and the scheme is ‘https:’ rather than ‘http:’. Other than that, HTTPS URIs are identical to HTTP URIs; see URI::HTTP.

Constants

DEFAULT_PORT = 443


Class: URI::InvalidComponentError

Class | URI::InvalidComponentError
In: | lib/uri/common.rb
Parent: | Error

Not a URI component.


Class: URI::InvalidURIError

Class | URI::InvalidURIError
In: | lib/uri/common.rb
Parent: | Error

Not a URI.


Class: URI::LDAP

Class | URI::LDAP
In: | lib/uri/ldap.rb
Parent: | Generic

LDAP URI SCHEMA (described in RFC2255) ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]]

Methods

attributes attributes= build dn dn= extensions extensions= filter filter= hierarchical? new scope scope= set_attributes set_dn set_extensions set_filter set_scope

Constants

DEFAULT_PORT | = | 389
COMPONENT | = | [ :scheme, :host, :port, :dn, :attributes, :scope, :filter, :extensions, ].freeze
SCOPE | = | [ SCOPE_ONE = 'one', SCOPE_SUB = 'sub', SCOPE_BASE = 'base', ].freeze

Public Class methods

build(args)
new(*arg)

Public Instance methods

attributes()
attributes=(val)
dn()
dn=(val)
extensions()
extensions=(val)
filter()
filter=(val)
hierarchical?()
scope()
scope=(val)

Protected Instance methods

set_attributes(val)
set_dn(val)
set_extensions(val)
set_filter(val)
set_scope(val)


Class: URI::MailTo

Class | URI::MailTo
In: | lib/uri/mailto.rb
Parent: | Generic

RFC2368, The mailto URL scheme

Methods

build headers= new set_headers set_to to= to_mailtext to_rfc822text to_s

Included Modules

REGEXP

Constants

DEFAULT_PORT | = | nil
COMPONENT | = | [ :scheme, :to, :headers ].freeze

Attributes

headers | [R] | E-mail headers set by the URL, as an Array of Arrays
to | [R] | The primary e-mail address of the URL, as a String

Public Class methods

build(args)

Description

Creates a new URI::MailTo object from components, with syntax checking.

Components can be provided as an Array or Hash. If an Array is used, the components must be supplied as [to, headers].

If a Hash is used, the keys are the component names preceded by colons.

The headers can be supplied as a pre-encoded string, such as "subject=subscribe&cc=address", or as an Array of Arrays like [[‘subject’, ‘subscribe’], [‘cc’, ‘address’]]

Examples:

   require 'uri'

   m1 = URI::MailTo.build(['joe@example.com', 'subject=Ruby'])
   puts m1.to_s  ->  mailto:joe@example.com?subject=Ruby

   m2 = URI::MailTo.build(['john@example.com', [['Subject', 'Ruby'], ['Cc', 'jack@example.com']]])
   puts m2.to_s  ->  mailto:john@example.com?Subject=Ruby&Cc=jack@example.com

   m3 = URI::MailTo.build({:to => 'listman@example.com', :headers => [['subject', 'subscribe']]})
   puts m3.to_s  ->  mailto:listman@example.com?subject=subscribe
new(*arg)

Description

Creates a new URI::MailTo object from generic URL components with no syntax checking.

This method is usually called from URI::parse, which checks the validity of each component.

Public Instance methods

headers=(v)
to=(v)
to_mailtext()

Returns the RFC822 e-mail text equivalent of the URL, as a String.

Example:

  require 'uri'

  uri = URI.parse("mailto:ruby-list@ruby-lang.org?Subject=subscribe&cc=myaddr")
  uri.to_mailtext
  # => "To: ruby-list@ruby-lang.org\nSubject: subscribe\nCc: myaddr\n\n\n"
to_rfc822text()

Alias for to_mailtext

to_s()

Protected Instance methods

set_headers(v)
set_to(v)


Module: URI::REGEXP

Module | URI::REGEXP
In: | lib/uri/common.rb

Classes and Modules

Module URI::REGEXP::PATTERN


Module: URI::REGEXP::PATTERN

Module | URI::REGEXP::PATTERN
In: | lib/uri/common.rb

Patterns used to parse URI‘s


Class: UnboundMethod

Class | UnboundMethod
In: | eval.c
Parent: | Object

Ruby supports two forms of objectified methods. Class Method is used to represent methods that are associated with a particular object: these method objects are bound to that object. Bound method objects for an object can be created using Object#method.

Ruby also supports unbound methods; methods objects that are not associated with a particular object. These can be created either by calling Module#instance_method or by calling unbind on a bound method object. The result of both of these is an UnboundMethod object.

Unbound methods can only be called after they are bound to an object. That object must be be a kind_of? the method‘s original class.

   class Square
     def area
       @side * @side
     end
     def initialize(side)
       @side = side
     end
   end

   area_un = Square.instance_method(:area)

   s = Square.new(12)
   area = area_un.bind(s)
   area.call   #=> 144

Unbound methods are a reference to the method at the time it was objectified: subsequent changes to the underlying class will not affect the unbound method.

   class Test
     def test
       :original
     end
   end
   um = Test.instance_method(:test)
   class Test
     def test
       :modified
     end
   end
   t = Test.new
   t.test            #=> :modified
   um.bind(t).call   #=> :original

Methods

== arity bind clone inspect to_s

Public Instance methods

meth == other_meth => true or false

Two method objects are equal if that are bound to the same object and contain the same body.

meth.arity => fixnum

Returns an indication of the number of arguments accepted by a method. Returns a nonnegative integer for methods that take a fixed number of arguments. For Ruby methods that take a variable number of arguments, returns -n-1, where n is the number of required arguments. For methods written in C, returns -1 if the call takes a variable number of arguments.

   class C
     def one;    end
     def two(a); end
     def three(*a);  end
     def four(a, b); end
     def five(a, b, *c);    end
     def six(a, b, *c, &d); end
   end
   c = C.new
   c.method(:one).arity     #=> 0
   c.method(:two).arity     #=> 1
   c.method(:three).arity   #=> -1
   c.method(:four).arity    #=> 2
   c.method(:five).arity    #=> -3
   c.method(:six).arity     #=> -3

   "cat".method(:size).arity      #=> 0
   "cat".method(:replace).arity   #=> 1
   "cat".method(:squeeze).arity   #=> -1
   "cat".method(:count).arity     #=> -1
umeth.bind(obj) → method

Bind umeth to obj. If Klass was the class from which umeth was obtained, obj.kind_of?(Klass) must be true.

   class A
     def test
       puts "In test, class = #{self.class}"
     end
   end
   class B < A
   end
   class C < B
   end

   um = B.instance_method(:test)
   bm = um.bind(C.new)
   bm.call
   bm = um.bind(B.new)
   bm.call
   bm = um.bind(A.new)
   bm.call

produces:

   In test, class = C
   In test, class = B
   prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
    from prog.rb:16
clone()

MISSING: documentation

meth.to_s => string
meth.inspect => string

Show the name of the underlying method.

  "cat".method(:count).inspect   #=> "#<Method: String#count>"
meth.to_s => string
meth.inspect => string

Show the name of the underlying method.

  "cat".method(:count).inspect   #=> "#<Method: String#count>"


Class: Vector

Class | Vector
In: | lib/matrix.rb
Parent: | Object

The Vector class represents a mathematical vector, which is useful in its own right, and also constitutes a row or column of a Matrix.

Method Catalogue

To create a Vector:

  • Vector.[](*array)
  • Vector.elements(array, copy = true)

To access elements:

  • [](i)

To enumerate the elements:

  • each2(v)
  • collect2(v)

Vector arithmetic:

  • *(x) "is matrix or number"
  • +(v)
  • -(v)

Vector functions:

  • inner_product(v)
  • collect
  • map
  • map2(v)
  • r
  • size

Conversion to other data types:

  • covector
  • to_a
  • coerce(other)

String representations:

  • to_s
  • inspect

Methods

* + - == [] [] clone coerce collect collect2 compare_by covector each2 elements eqn? hash init_elements inner_product inspect map map2 new r size to_a to_s

Included Modules

ExceptionForMatrix

Public Class methods

[](*array)

Creates a Vector from a list of elements.

  Vector[7, 4, ...]
elements(array, copy = true)

Creates a vector from an Array. The optional second argument specifies whether the array itself or a copy is used internally.

new(method, array, copy)

For internal use.

Public Instance methods

*(x)

Multiplies the vector by x, where x is a number or another vector.

+(v)

Vector addition.

-(v)

Vector subtraction.

==(other)

Returns true iff the two vectors have the same elements in the same order.

[](i)

Returns element number i (starting at zero) of the vector.

clone()

Return a copy of the vector.

coerce(other)

FIXME: describe Vector#coerce.

collect( {|e| ...}

Like Array#collect.

collect2(v) {|e1, e2| ...}

Collects (as in Enumerable#collect) over the elements of this vector and v in conjunction.

compare_by(elements)

For internal use.

covector()

Creates a single-row matrix from this vector.

each2(v) {|e1, e2| ...}

Iterate over the elements of this vector and v in conjunction.

eqn?(other)

Alias for #==

hash()

Return a hash-code for the vector.

init_elements(array, copy)

For internal use.

inner_product(v)

Returns the inner product of this vector with the other.

  Vector[4,7].inner_product Vector[10,1]  => 47
inspect()

Overrides Object#inspect

map(

Alias for collect

map2(v) {|e1, e2| ...}

Like Vector#collect2, but returns a Vector instead of an Array.

r()

Returns the modulus (Pythagorean distance) of the vector.

  Vector[5,8,2].r => 9.643650761
size()

Returns the number of elements in the vector.

to_a()

Returns the elements of the vector in an array.

to_s()

Overrides Object#to_s


Module: WEBrick

Module | WEBrick
In: | lib/soap/rpc/soaplet.rb lib/webrick/httpservlet/erbhandler.rb lib/webrick/httpservlet/cgihandler.rb lib/webrick/httpservlet/prochandler.rb lib/webrick/httpservlet/filehandler.rb lib/webrick/httpservlet/abstract.rb lib/webrick/httpstatus.rb lib/webrick/httprequest.rb lib/webrick/httpservlet.rb lib/webrick/config.rb lib/webrick/httpserver.rb lib/webrick/httputils.rb lib/webrick/cookie.rb lib/webrick/server.rb lib/webrick/log.rb lib/webrick/httpauth.rb lib/webrick/version.rb lib/webrick/httpproxy.rb lib/webrick/utils.rb lib/webrick/httpauth/basicauth.rb lib/webrick/httpauth/htpasswd.rb lib/webrick/httpauth/authenticator.rb lib/webrick/httpauth/digestauth.rb lib/webrick/httpauth/htgroup.rb lib/webrick/httpauth/userdb.rb lib/webrick/httpauth/htdigest.rb lib/webrick/https.rb lib/webrick/cgi.rb lib/webrick/ssl.rb lib/webrick/htmlutils.rb lib/webrick/accesslog.rb lib/webrick/httpversion.rb lib/webrick/httpresponse.rb

HTTPVersion.rb — presentation of HTTP version

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpversion.rb,v 1.5 2002/09/21 12:23:37 gotoyuzo Exp $

Classes and Modules

Module WEBrick::AccessLog
Module WEBrick::Config
Module WEBrick::HTMLUtils
Module WEBrick::HTTPAuth
Module WEBrick::HTTPServlet
Module WEBrick::HTTPStatus
Module WEBrick::HTTPUtils
Module WEBrick::Utils
Class WEBrick::BasicLog
Class WEBrick::CGI
Class WEBrick::Cookie
Class WEBrick::Daemon
Class WEBrick::GenericServer
Class WEBrick::HTTPProxyServer
Class WEBrick::HTTPRequest
Class WEBrick::HTTPResponse
Class WEBrick::HTTPServer
Class WEBrick::HTTPServerError
Class WEBrick::HTTPVersion
Class WEBrick::Log
Class WEBrick::ServerError
Class WEBrick::SimpleServer

Constants

CR | = | "\x0d"
LF | = | "\x0a"
CRLF | = | "\x0d\x0a"
VERSION | = | "1.3.1"
NullReader | = | Object.new


Module: WEBrick::AccessLog

Module | WEBrick::AccessLog
In: | lib/webrick/accesslog.rb

Methods

format setup_params

Classes and Modules

Class WEBrick::AccessLog::AccessLogError

Constants

CLF_TIME_FORMAT | = | "[%d/%b/%Y:%H:%M:%S %Z]"
COMMON_LOG_FORMAT | = | "%h %l %u %t \"%r\" %s %b"
CLF | = | COMMON_LOG_FORMAT
REFERER_LOG_FORMAT | = | "%{Referer}i -> %U"
AGENT_LOG_FORMAT | = | "%{User-Agent}i"
COMBINED_LOG_FORMAT | = | "#{CLF} \"%{Referer}i\" \"%{User-agent}i\""

Public Instance methods

format(format_string, params)
setup_params(config, req, res)

This format specification is a subset of mod_log_config of Apache.

  http://httpd.apache.org/docs/mod/mod_log_config.html#formats


Class: WEBrick::AccessLog::AccessLogError

Class | WEBrick::AccessLog::AccessLogError
In: | lib/webrick/accesslog.rb
Parent: | StandardError


Class: WEBrick::BasicLog

Class | WEBrick::BasicLog
In: | lib/webrick/log.rb
Parent: | Object

Methods

<< close debug debug? error error? fatal fatal? info info? log new warn warn?

Constants

DEBUG = 1, 2, 3, 4, 5

Attributes

level [RW]

Public Class methods

new(log_file=nil, level=nil)

Public Instance methods

<<(obj)
close()
debug(msg)
debug?()
error(msg)
error?()
fatal(msg)
fatal?()
info(msg)
info?()
log(level, data)
warn(msg)
warn?()


Class: WEBrick::CGI

Class | WEBrick::CGI
In: | lib/webrick/cgi.rb
Parent: | Object

Methods

[] new service start

Classes and Modules

Class WEBrick::CGI::Socket

Constants

CGIError = Class.new(StandardError)

Attributes

config | [R]
logger | [R]

Public Class methods

new(*args)

Public Instance methods

[](key)
service(req, res)
start(env=ENV, stdin=$stdin, stdout=$stdout)


Class: WEBrick::CGI::Socket

Class | WEBrick::CGI::Socket
In: | lib/webrick/cgi.rb
Parent: | Object

Methods

<< addr cert cipher each gets new peer_cert peer_cert_chain peeraddr read

Included Modules

Enumerable

Public Class methods

new(config, env, stdin, stdout)

Public Instance methods

<<(data)
addr()
cert()
cipher()
each() {|line| ...}
gets(eol=LF)
peer_cert()
peer_cert_chain()
peeraddr()
read(size=nil)


Module: WEBrick::Config

Module | WEBrick::Config
In: | lib/webrick/config.rb lib/webrick/https.rb lib/webrick/ssl.rb

Constants

LIBDIR | = | File::dirname(__FILE__)
General | = | { :ServerName => Utils::getservername, :BindAddress => nil, # "0.0.0.0" or "::" or nil :Port => nil, # users MUST specifiy this!! :MaxClients => 100, # maximum number of the concurrent connections :ServerType => nil, # default: WEBrick::SimpleServer :Logger => nil, # default: WEBrick::Log.new :ServerSoftware => "WEBrick/#{WEBrick::VERSION} " + "(Ruby/#{RUBY_VERSION}/#{RUBY_RELEASE_DATE})", :TempDir => ENV['TMPDIR']||ENV['TMP']||ENV['TEMP']||'/tmp', :DoNotListen => false, :StartCallback => nil, :StopCallback => nil, :AcceptCallback => nil, } | for GenericServer
HTTP | = | General.dup.update( :Port => 80, :RequestTimeout => 30, :HTTPVersion => HTTPVersion.new("1.1"), :AccessLog => nil, :MimeTypes => HTTPUtils::DefaultMimeTypes, :DirectoryIndex => ["index.html","index.htm","index.cgi","index.rhtml"], :DocumentRoot => nil, :DocumentRootOptions => { :FancyIndexing => true }, :RequestHandler => nil, :RequestCallback => nil, # alias of :RequestHandler :ServerAlias => nil, # for HTTPProxyServer :ProxyAuthProc => nil, :ProxyContentHandler => nil, :ProxyVia => true, :ProxyTimeout => true, :ProxyURI => nil, :CGIInterpreter => nil, :CGIPathEnv => nil, # workaround: if Request-URIs contain 8bit chars, # they should be escaped before calling of URI::parse(). :Escape8bitURI => false | for HTTPServer, HTTPRequest, HTTPResponse …
FileHandler | = | { :NondisclosureName => [".ht*", "*~"], :FancyIndexing => false, :HandlerTable => {}, :HandlerCallback => nil, :DirectoryCallback => nil, :FileCallback => nil, :UserDir => nil, # e.g. "public_html" :AcceptableLanguages => []
BasicAuth | = | { :AutoReloadUserDB => true, }
DigestAuth | = | { :Algorithm => 'MD5-sess', # or 'MD5' :Domain => nil, # an array includes domain names. :Qop => [ 'auth' ], # 'auth' or 'auth-int' or both. :UseOpaque => true, :UseNextNonce => false, :CheckNc => false, :UseAuthenticationInfoHeader => true, :AutoReloadUserDB => true, :NonceExpirePeriod => 30*60, :NonceExpireDelta => 60, :InternetExplorerHack => true, :OperaHack => true, }
SSL | = | { :ServerSoftware => "#{svrsoft} OpenSSL/#{osslv}", :SSLEnable => false, :SSLCertificate => nil, :SSLPrivateKey => nil, :SSLClientCA => nil, :SSLExtraChainCert => nil, :SSLCACertificateFile => nil, :SSLCACertificatePath => nil, :SSLCertificateStore => nil, :SSLVerifyClient => ::OpenSSL::SSL::VERIFY_NONE, :SSLVerifyDepth => nil, :SSLVerifyCallback => nil, # custom verification :SSLTimeout => nil, :SSLOptions => nil, :SSLStartImmediately => true, # Must specify if you use auto generated certificate. :SSLCertName => nil, :SSLCertComment => "Generated by Ruby/OpenSSL"


Class: WEBrick::Cookie

Class | WEBrick::Cookie
In: | lib/webrick/cookie.rb
Parent: | Object

Methods

expires expires= new parse parse_set_cookie parse_set_cookies to_s

Attributes

comment | [RW]
domain | [RW]
max_age | [RW]
name | [R]
path | [RW]
secure | [RW]
value | [RW]
version | [RW]

Public Class methods

new(name, value)

attr_accessor :comment_url, :discard, :port

parse(str)

Cookie::parse()

  It parses Cookie field sent from the user agent.
parse_set_cookie(str)
parse_set_cookies(str)

Public Instance methods

expires()
expires=(t)
to_s()


Class: WEBrick::Daemon

Class | WEBrick::Daemon
In: | lib/webrick/server.rb
Parent: | Object

Methods

start

Public Class methods

start() {|if block_given?| ...}


Class: WEBrick::GenericServer

Class | WEBrick::GenericServer
In: | lib/webrick/server.rb lib/webrick/ssl.rb
Parent: | Object

Methods

[] listen listen new run setup_ssl_context shutdown ssl_context start stop

Attributes

config | [R]
listeners | [R]
logger | [R]
status | [R]
tokens | [R]

Public Class methods

new(config={}, default=Config::General)

Public Instance methods

[](key)
listen(address, port)
listen(address, port)
run(sock)
setup_ssl_context(config)
shutdown()
ssl_context()
start(&block)
stop()


Module: WEBrick::HTMLUtils

Module | WEBrick::HTMLUtils
In: | lib/webrick/htmlutils.rb

Methods

escape

Public Instance methods

escape(string)


Module: WEBrick::HTTPAuth

Module | WEBrick::HTTPAuth
In: | lib/webrick/httpauth.rb lib/webrick/httpauth/basicauth.rb lib/webrick/httpauth/htpasswd.rb lib/webrick/httpauth/authenticator.rb lib/webrick/httpauth/digestauth.rb lib/webrick/httpauth/htgroup.rb lib/webrick/httpauth/userdb.rb lib/webrick/httpauth/htdigest.rb

Methods

_basic_auth basic_auth proxy_basic_auth

Classes and Modules

Module WEBrick::HTTPAuth::Authenticator
Module WEBrick::HTTPAuth::ProxyAuthenticator
Module WEBrick::HTTPAuth::UserDB
Class WEBrick::HTTPAuth::BasicAuth
Class WEBrick::HTTPAuth::DigestAuth
Class WEBrick::HTTPAuth::Htdigest
Class WEBrick::HTTPAuth::Htgroup
Class WEBrick::HTTPAuth::Htpasswd
Class WEBrick::HTTPAuth::ProxyBasicAuth
Class WEBrick::HTTPAuth::ProxyDigestAuth

Public Instance methods

_basic_auth(req, res, realm, req_field, res_field, err_type, block)
basic_auth(req, res, realm, &block)
proxy_basic_auth(req, res, realm, &block)


Module: WEBrick::HTTPAuth::Authenticator

Module | WEBrick::HTTPAuth::Authenticator
In: | lib/webrick/httpauth/authenticator.rb

Constants

RequestField | = | "Authorization"
ResponseField | = | "WWW-Authenticate"
ResponseInfoField | = | "Authentication-Info"
AuthException | = | HTTPStatus::Unauthorized
AuthScheme | = | nil

Attributes

logger | [R]
realm | [R]
userdb | [R]


Class: WEBrick::HTTPAuth::BasicAuth

Class | WEBrick::HTTPAuth::BasicAuth
In: | lib/webrick/httpauth/basicauth.rb
Parent: | Object

Methods

authenticate challenge make_passwd new

Included Modules

Authenticator

Constants

AuthScheme = "Basic"

Attributes

logger | [R]
realm | [R]
userdb | [R]

Public Class methods

make_passwd(realm, user, pass)
new(config, default=Config::BasicAuth)

Public Instance methods

authenticate(req, res)
challenge(req, res)


Class: WEBrick::HTTPAuth::DigestAuth

Class | WEBrick::HTTPAuth::DigestAuth
In: | lib/webrick/httpauth/digestauth.rb
Parent: | Object

Methods

authenticate challenge make_passwd new

Included Modules

Authenticator

Constants

AuthScheme | = | "Digest"
OpaqueInfo | = | Struct.new(:time, :nonce, :nc)
MustParams | = | ['username','realm','nonce','uri','response']
MustParamsAuth | = | ['cnonce','nc']

Attributes

algorithm | [R]
qop | [R]

Public Class methods

make_passwd(realm, user, pass)
new(config, default=Config::DigestAuth)

Public Instance methods

authenticate(req, res)
challenge(req, res, stale=false)


Class: WEBrick::HTTPAuth::Htdigest

Class | WEBrick::HTTPAuth::Htdigest
In: | lib/webrick/httpauth/htdigest.rb
Parent: | Object

Methods

delete_passwd each flush get_passwd new reload set_passwd

Included Modules

UserDB

Public Class methods

new(path)

Public Instance methods

delete_passwd(realm, user)
each() {|[user, realm, hash[user]]| ...}
flush(output=nil)
get_passwd(realm, user, reload_db)
reload()
set_passwd(realm, user, pass)


Class: WEBrick::HTTPAuth::Htgroup

Class | WEBrick::HTTPAuth::Htgroup
In: | lib/webrick/httpauth/htgroup.rb
Parent: | Object

Methods

add flush members new reload

Public Class methods

new(path)

Public Instance methods

add(group, members)
flush(output=nil)
members(group)
reload()


Class: WEBrick::HTTPAuth::Htpasswd

Class | WEBrick::HTTPAuth::Htpasswd
In: | lib/webrick/httpauth/htpasswd.rb
Parent: | Object

Methods

delete_passwd each flush get_passwd new reload set_passwd

Included Modules

UserDB

Public Class methods

new(path)

Public Instance methods

delete_passwd(realm, user)
each() {|[user, @passwd[user]]| ...}
flush(output=nil)
get_passwd(realm, user, reload_db)
reload()
set_passwd(realm, user, pass)


Module: WEBrick::HTTPAuth::ProxyAuthenticator

Module | WEBrick::HTTPAuth::ProxyAuthenticator
In: | lib/webrick/httpauth/authenticator.rb

Constants

RequestField | = | "Proxy-Authorization"
ResponseField | = | "Proxy-Authenticate"
InfoField | = | "Proxy-Authentication-Info"
AuthException | = | HTTPStatus::ProxyAuthenticationRequired


Class: WEBrick::HTTPAuth::ProxyBasicAuth

Class | WEBrick::HTTPAuth::ProxyBasicAuth
In: | lib/webrick/httpauth/basicauth.rb
Parent: | BasicAuth

Included Modules

ProxyAuthenticator


Class: WEBrick::HTTPAuth::ProxyDigestAuth

Class | WEBrick::HTTPAuth::ProxyDigestAuth
In: | lib/webrick/httpauth/digestauth.rb
Parent: | DigestAuth

Methods

check_uri

Included Modules

ProxyAuthenticator

Public Instance methods

check_uri(req, auth_req)


Module: WEBrick::HTTPAuth::UserDB

Module | WEBrick::HTTPAuth::UserDB
In: | lib/webrick/httpauth/userdb.rb

Methods

get_passwd make_passwd set_passwd

Attributes

auth_type [RW]

Public Instance methods

get_passwd(realm, user, reload_db=false)
make_passwd(realm, user, pass)
set_passwd(realm, user, pass)


Class: WEBrick::HTTPProxyServer

Class | WEBrick::HTTPProxyServer
In: | lib/webrick/httpproxy.rb
Parent: | HTTPServer

Methods

choose_header do_OPTIONS new proxy_auth proxy_connect proxy_service proxy_uri service set_cookie set_via split_field

Constants

HopByHop | = | %w( connection keep-alive proxy-authenticate upgrade proxy-authorization te trailers transfer-encoding ) | Some header fields shuold not be transfered.
ShouldNotTransfer | = | %w( set-cookie proxy-connection )

Public Class methods

new(config)

Public Instance methods

choose_header(src, dst)
do_OPTIONS(req, res)
proxy_auth(req, res)
proxy_connect(req, res)
proxy_service(req, res)
proxy_uri(req, res)
service(req, res)
set_cookie(src, dst)

Net::HTTP is stupid about the multiple header fields. Here is workaround:

set_via(h)
split_field(f)


Class: WEBrick::HTTPRequest

Class | WEBrick::HTTPRequest
In: | lib/webrick/httprequest.rb lib/webrick/https.rb
Parent: | Object

Methods

[] body content_length content_type each fixup keep_alive? meta_vars meta_vars new orig_meta_vars orig_parse orig_parse_uri parse parse parse_uri query to_s

Constants

BODY_CONTAINABLE_METHODS | = | [ "POST", "PUT" ]
BUFSIZE | = | 1024*4

Attributes

accept | [R] |
accept_charset | [R] |
accept_encoding | [R] |
accept_language | [R] |
addr | [R] |
attributes | [R] |
cipher | [R] |
client_cert | [R] |
cookies | [R] | Header and entity body
header | [R] | Header and entity body
host | [R] | Request-URI
http_version | [R] |
keep_alive | [R] |
path | [R] | Request-URI
path_info | [RW] |
peeraddr | [R] |
port | [R] | Request-URI
query_string | [RW] |
raw_header | [R] | Header and entity body
request_line | [R] | Request line
request_method | [R] |
request_time | [R] |
request_uri | [R] | Request-URI
script_name | [RW] |
server_cert | [R] |
unparsed_uri | [R] |
user | [RW] | Misc

Public Class methods

new(config)

Public Instance methods

[](header_name)
body(&block)
content_length()
content_type()
each() {|k, value.empty? ? nil : value.join(", ")| ...}
fixup()
keep_alive?()
meta_vars()
meta_vars()
orig_meta_vars()

Alias for meta_vars

orig_parse(socket=nil)

Alias for parse

orig_parse_uri(str, scheme="http")

Alias for parse_uri

parse(socket=nil)
parse(socket=nil)
parse_uri(str, scheme="https")
query()
to_s()


Class: WEBrick::HTTPResponse

Class | WEBrick::HTTPResponse
In: | lib/webrick/httpresponse.rb
Parent: | Object

Methods

[] []= chunked= chunked? content_length content_length= content_type content_type= each keep_alive? new send_body send_header send_response set_error set_redirect setup_header status= status_line to_s

Constants

BUFSIZE = 1024*4

Attributes

body | [RW]
config | [R]
cookies | [R]
filename | [RW]
header | [R]
http_version | [R]
keep_alive | [RW]
reason_phrase | [RW]
request_http_version | [RW]
request_method | [RW]
request_uri | [RW]
sent_size | [R]
status | [R]

Public Class methods

new(config)

Public Instance methods

[](field)
[]=(field, value)
chunked=(val)
chunked?()
content_length()
content_length=(len)
content_type()
content_type=(type)
each() {|k, v| ...}
keep_alive?()
send_body(socket)
send_header(socket)
send_response(socket)
set_error(ex, backtrace=false)
set_redirect(status, url)
setup_header()
status=(status)
status_line()
to_s()


Class: WEBrick::HTTPServer

Class | WEBrick::HTTPServer
In: | lib/webrick/httpserver.rb
Parent: | ::WEBrick::GenericServer

Methods

access_log do_OPTIONS lookup_server mount mount_proc new run search_servlet service umount unmount virtual_host

Classes and Modules

Class WEBrick::HTTPServer::MountTable

Public Class methods

new(config={}, default=Config::HTTP)

Public Instance methods

access_log(config, req, res)
do_OPTIONS(req, res)
lookup_server(req)
mount(dir, servlet, *options)
mount_proc(dir, proc=nil, &block)
run(sock)
search_servlet(path)
service(req, res)
umount(dir)

Alias for unmount

unmount(dir)
virtual_host(server)


Class: WEBrick::HTTPServer::MountTable

Class | WEBrick::HTTPServer::MountTable
In: | lib/webrick/httpserver.rb
Parent: | Object

Methods

[] []= delete new scan

Public Class methods

new()

Public Instance methods

[](dir)
[]=(dir, val)
delete(dir)
scan(path)


Class: WEBrick::HTTPServerError

Class | WEBrick::HTTPServerError
In: | lib/webrick/httpserver.rb
Parent: | ServerError


Module: WEBrick::HTTPServlet

Module | WEBrick::HTTPServlet
In: | lib/webrick/httpservlet/erbhandler.rb lib/webrick/httpservlet/cgihandler.rb lib/webrick/httpservlet/prochandler.rb lib/webrick/httpservlet/filehandler.rb lib/webrick/httpservlet/abstract.rb lib/webrick/httpservlet.rb

Classes and Modules

Class WEBrick::HTTPServlet::AbstractServlet
Class WEBrick::HTTPServlet::CGIHandler
Class WEBrick::HTTPServlet::DefaultFileHandler
Class WEBrick::HTTPServlet::ERBHandler
Class WEBrick::HTTPServlet::FileHandler
Class WEBrick::HTTPServlet::HTTPServletError
Class WEBrick::HTTPServlet::ProcHandler


Class: WEBrick::HTTPServlet::AbstractServlet

Class | WEBrick::HTTPServlet::AbstractServlet
In: | lib/webrick/httpservlet/abstract.rb
Parent: | Object

Methods

do_GET do_HEAD do_OPTIONS get_instance new service

Public Class methods

get_instance(config, *options)
new(server, *options)

Public Instance methods

do_GET(req, res)
do_HEAD(req, res)
do_OPTIONS(req, res)
service(req, res)


Class: WEBrick::HTTPServlet::CGIHandler

Class | WEBrick::HTTPServlet::CGIHandler
In: | lib/webrick/httpservlet/cgihandler.rb
Parent: | AbstractServlet

Methods

do_GET do_POST new

Constants

Ruby | = | File::join(::Config::CONFIG['bindir'], ::Config::CONFIG['ruby_install_name'])
CGIRunner | = | "\"#{Ruby}\" \"#{Config::LIBDIR}/httpservlet/cgi_runner.rb\""

Public Class methods

new(server, name)

Public Instance methods

do_GET(req, res)
do_POST(req, res)

Alias for do_GET


Class: WEBrick::HTTPServlet::DefaultFileHandler

Class | WEBrick::HTTPServlet::DefaultFileHandler
In: | lib/webrick/httpservlet/filehandler.rb
Parent: | AbstractServlet

Methods

do_GET make_partial_content new not_modified? prepare_range

Public Class methods

new(server, local_path)

Public Instance methods

do_GET(req, res)
make_partial_content(req, res, filename, filesize)
not_modified?(req, res, mtime, etag)
prepare_range(range, filesize)


Class: WEBrick::HTTPServlet::ERBHandler

Class | WEBrick::HTTPServlet::ERBHandler
In: | lib/webrick/httpservlet/erbhandler.rb
Parent: | AbstractServlet

Methods

do_GET do_POST new

Public Class methods

new(server, name)

Public Instance methods

do_GET(req, res)
do_POST(req, res)

Alias for do_GET


Class: WEBrick::HTTPServlet::FileHandler

Class | WEBrick::HTTPServlet::FileHandler
In: | lib/webrick/httpservlet/filehandler.rb
Parent: | AbstractServlet

Methods

add_handler do_GET do_OPTIONS do_POST new remove_handler service

Constants

HandlerTable = Hash.new

Public Class methods

add_handler(suffix, handler)
new(server, root, options={}, default=Config::FileHandler)
remove_handler(suffix)

Public Instance methods

do_GET(req, res)
do_OPTIONS(req, res)
do_POST(req, res)
service(req, res)


Class: WEBrick::HTTPServlet::HTTPServletError

Class | WEBrick::HTTPServlet::HTTPServletError
In: | lib/webrick/httpservlet/abstract.rb
Parent: | StandardError


Class: WEBrick::HTTPServlet::ProcHandler

Class | WEBrick::HTTPServlet::ProcHandler
In: | lib/webrick/httpservlet/prochandler.rb
Parent: | AbstractServlet

Methods

do_GET do_POST get_instance new

Public Class methods

new(proc)

Public Instance methods

do_GET(request, response)
do_POST(request, response)

Alias for do_GET

get_instance(server, *options)


Module: WEBrick::HTTPStatus

Module | WEBrick::HTTPStatus
In: | lib/webrick/httpstatus.rb

Methods

[] client_error? error? info? reason_phrase redirect? server_error? success?

Classes and Modules

Class WEBrick::HTTPStatus::ClientError
Class WEBrick::HTTPStatus::EOFError
Class WEBrick::HTTPStatus::Error
Class WEBrick::HTTPStatus::Info
Class WEBrick::HTTPStatus::Redirect
Class WEBrick::HTTPStatus::ServerError
Class WEBrick::HTTPStatus::Status
Class WEBrick::HTTPStatus::Success

Constants

StatusMessage | = | { 100, 'Continue', 101, 'Switching Protocols', 200, 'OK', 201, 'Created', 202, 'Accepted', 203, 'Non-Authoritative Information', 204, 'No Content', 205, 'Reset Content', 206, 'Partial Content', 300, 'Multiple Choices', 301, 'Moved Permanently', 302, 'Found', 303, 'See Other', 304, 'Not Modified', 305, 'Use Proxy', 307, 'Temporary Redirect', 400, 'Bad Request', 401, 'Unauthorized', 402, 'Payment Required', 403, 'Forbidden', 404, 'Not Found', 405, 'Method Not Allowed', 406, 'Not Acceptable', 407, 'Proxy Authentication Required', 408, 'Request Timeout', 409, 'Conflict', 410, 'Gone', 411, 'Length Required', 412, 'Precondition Failed', 413, 'Request Entity Too Large', 414, 'Request-URI Too Large', 415, 'Unsupported Media Type', 416, 'Request Range Not Satisfiable', 417, 'Expectation Failed', 500, 'Internal Server Error', 501, 'Not Implemented', 502, 'Bad Gateway', 503, 'Service Unavailable', 504, 'Gateway Timeout', 505, 'HTTP Version Not Supported'
CodeToError | = | {}

Public Class methods

[](code)

Public Instance methods

client_error?(code)
error?(code)
info?(code)
reason_phrase(code)
redirect?(code)
server_error?(code)
success?(code)


Class: WEBrick::HTTPStatus::ClientError

Class | WEBrick::HTTPStatus::ClientError
In: | lib/webrick/httpstatus.rb
Parent: | Error


Class: WEBrick::HTTPStatus::EOFError

Class | WEBrick::HTTPStatus::EOFError
In: | lib/webrick/httpstatus.rb
Parent: | StandardError


Class: WEBrick::HTTPStatus::Error

Class | WEBrick::HTTPStatus::Error
In: | lib/webrick/httpstatus.rb
Parent: | Status


Class: WEBrick::HTTPStatus::Info

Class | WEBrick::HTTPStatus::Info
In: | lib/webrick/httpstatus.rb
Parent: | Status


Class: WEBrick::HTTPStatus::Redirect

Class | WEBrick::HTTPStatus::Redirect
In: | lib/webrick/httpstatus.rb
Parent: | Status


Class: WEBrick::HTTPStatus::ServerError

Class | WEBrick::HTTPStatus::ServerError
In: | lib/webrick/httpstatus.rb
Parent: | Error


Class: WEBrick::HTTPStatus::Status

Class | WEBrick::HTTPStatus::Status
In: | lib/webrick/httpstatus.rb
Parent: | StandardError


Class: WEBrick::HTTPStatus::Success

Class | WEBrick::HTTPStatus::Success
In: | lib/webrick/httpstatus.rb
Parent: | Status


Module: WEBrick::HTTPUtils

Module | WEBrick::HTTPUtils
In: | lib/webrick/httputils.rb

Methods

_escape _make_regex _make_regex! _unescape dequote escape escape8bit escape_form escape_path load_mime_types mime_type normalize_path parse_form_data parse_header parse_query parse_qvalues parse_range_header quote split_header_value unescape unescape_form

Classes and Modules

Class WEBrick::HTTPUtils::FormData

Constants

DefaultMimeTypes = { "ai" => "application/postscript", "asc" => "text/plain", "avi" => "video/x-msvideo", "bin" => "application/octet-stream", "bmp" => "image/bmp", "class" => "application/octet-stream", "cer" => "application/pkix-cert", "crl" => "application/pkix-crl", "crt" => "application/x-x509-ca-cert", #"crl" => "application/x-pkcs7-crl", "css" => "text/css", "dms" => "application/octet-stream", "doc" => "application/msword", "dvi" => "application/x-dvi", "eps" => "application/postscript", "etx" => "text/x-setext", "exe" => "application/octet-stream", "gif" => "image/gif", "htm" => "text/html", "html" => "text/html", "jpe" => "image/jpeg", "jpeg" => "image/jpeg", "jpg" => "image/jpeg", "lha" => "application/octet-stream", "lzh" => "application/octet-stream", "mov" => "video/quicktime", "mpe" => "video/mpeg", "mpeg" => "video/mpeg", "mpg" => "video/mpeg", "pbm" => "image/x-portable-bitmap", "pdf" => "application/pdf", "pgm" => "image/x-portable-graymap", "png" => "image/png", "pnm" => "image/x-portable-anymap", "ppm" => "image/x-portable-pixmap", "ppt" => "application/vnd.ms-powerpoint", "ps" => "application/postscript", "qt" => "video/quicktime", "ras" => "image/x-cmu-raster", "rb" => "text/plain", "rd" => "text/plain", "rtf" => "application/rtf", "sgm" => "text/sgml", "sgml" => "text/sgml", "tif" => "image/tiff", "tiff" => "image/tiff", "txt" => "text/plain", "xbm" => "image/x-xbitmap", "xls" => "application/vnd.ms-excel", "xml" => "text/xml", "xpm" => "image/x-xpixmap", "xwd" => "image/x-xwindowdump", "zip" => "application/zip", }
UNESCAPED = _make_regex(control+space+delims+unwise+nonascii)
UNESCAPED_FORM = _make_regex(reserved+control+delims+unwise+nonascii)
NONASCII = _make_regex(nonascii)
ESCAPED = /%([0-9a-fA-F]{2})/
UNESCAPED_PCHAR = _make_regex!(unreserved+":@&=+$,")

Public Instance methods

_escape(str, regex)
_make_regex(str)
_make_regex!(str)
_unescape(str, regex)
dequote(str)
escape(str)
escape8bit(str)
escape_form(str)
escape_path(str)
load_mime_types(file)

Load Apache compatible mime.types file.

mime_type(filename, mime_tab)
normalize_path(path)
parse_form_data(io, boundary)
parse_header(raw)
parse_query(str)
parse_qvalues(value)
parse_range_header(ranges_specifier)
quote(str)
split_header_value(str)
unescape(str)
unescape_form(str)


Class: WEBrick::HTTPUtils::FormData

Class | WEBrick::HTTPUtils::FormData
In: | lib/webrick/httputils.rb
Parent: | String

Methods

<< [] append_data each_data list new to_ary to_s

Constants

EmptyRawHeader | = | [].freeze
EmptyHeader | = | {}.freeze

Attributes

filename | [RW]
name | [RW]
next_data | [RW]

Public Class methods

new(*args)

Public Instance methods

<<(str)
[](*key)
append_data(data)
each_data() {|tmp| ...}
list()
to_ary()

Alias for list

to_s()


Class: WEBrick::HTTPVersion

Class | WEBrick::HTTPVersion
In: | lib/webrick/httpversion.rb
Parent: | Object

Methods

<=> convert new to_s

Included Modules

Comparable

Attributes

major | [RW]
minor | [RW]

Public Class methods

convert(version)
new(version)

Public Instance methods

<=>(other)
to_s()


Class: WEBrick::Log

Class | WEBrick::Log
In: | lib/soap/rpc/soaplet.rb lib/webrick/log.rb
Parent: | BasicLog

Methods

debug log new

External Aliases

debug -> __debug

Attributes

time_format [RW]

Public Class methods

new(log_file=nil, level=nil)

Public Instance methods

debug(msg = nil) {|| ...}
log(level, data)


Class: WEBrick::ServerError

Class | WEBrick::ServerError
In: | lib/webrick/server.rb
Parent: | StandardError


Class: WEBrick::SimpleServer

Class | WEBrick::SimpleServer
In: | lib/webrick/server.rb
Parent: | Object

Methods

start

Public Class methods

start() {|| ...}


Module: WEBrick::Utils

Module | WEBrick::Utils
In: | lib/webrick/utils.rb lib/webrick/ssl.rb

Methods

create_listeners create_self_signed_cert getservername random_string set_close_on_exec set_non_blocking su

Constants

RAND_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvwxyz"

Public Instance methods

create_listeners(address, port, logger=nil)
create_self_signed_cert(bits, cn, comment)
getservername()
random_string(len)
set_close_on_exec(io)
set_non_blocking(io)
su(user)


Class: WIN32COMGen

Class | WIN32COMGen
In: | ext/win32ole/sample/olegen.rb
Parent: | Object

Methods

class_name define_class define_include define_initialize define_instance_variables define_method_missing define_module generate generate_args generate_argtype generate_argtypes generate_class generate_constants generate_func_methods generate_method generate_method_args_help generate_method_body generate_method_help generate_methods generate_properties_with_args generate_propget_methods generate_propput_methods generate_propputref_methods new ole_classes

Attributes

typelib [R]

Public Class methods

new(typelib)

Public Instance methods

class_name(klass)
define_class(klass, io = STDOUT)
define_include()
define_initialize(klass)
define_instance_variables()
define_method_missing()
define_module(klass, io = STDOUT)
generate(io = STDOUT)
generate_args(method)
generate_argtype(typedetails)
generate_argtypes(method, proptypes)
generate_class(klass, io = STDOUT)
generate_constants(klass, io = STDOUT)
generate_func_methods(klass, io = STDOUT)
generate_method(method, disptype, io = STDOUT, types = nil)
generate_method_args_help(method)
generate_method_body(method, disptype, types=nil)
generate_method_help(method, type = nil)
generate_methods(klass, io = STDOUT)
generate_properties_with_args(klass, io = STDOUT)
generate_propget_methods(klass, io = STDOUT)
generate_propput_methods(klass, io = STDOUT)
generate_propputref_methods(klass, io = STDOUT)
ole_classes(typelib)


Class: WIN32OLE

Class | WIN32OLE
In: | ext/win32ole/win32ole.c
Parent: | Object

WIN32OLE objects represent OLE Automation object in Ruby.

Methods

[] []= _getproperty _invoke _setproperty codepage codepage= connect const_load each invoke method_missing new ole_free ole_free ole_func_methods ole_get_methods ole_method ole_method_help ole_methods ole_obj_help ole_put_methods ole_reference_count ole_show_help setproperty

Classes and Modules

Module WIN32OLE::VARIANT

Constants

VERSION | = | rb_str_new2(WIN32OLE_VERSION)
ARGV | = | rb_ary_new()
CP_THREAD_ACP | = | INT2FIX(CP_THREAD_ACP)

Public Class methods

WIN32OLE.codepage

Returns current codepage.

   WIN32OLE.codepage # => WIN32OLE::CP_ACP
WIN32OLE.codepage = CP

Sets current codepage.

   WIN32OLE.codepage = WIN32OLE::CP_UTF8
WIN32OLE.connect( ole ) -→ aWIN32OLE

Returns running OLE Automation object or WIN32OLE object from moniker. 1st argument should be OLE program id or class id or moniker.

   WIN32OLE.connect('Excel.Application') # => WIN32OLE object which represents running Excel.
WIN32OLE.const_load( ole, mod = WIN32OLE)

Defines the constants of OLE Automation server as mod‘s constants. The first argument is WIN32OLE object or type library name. If 2nd argument is omitted, the default is WIN32OLE. The first letter of Ruby‘s constant variable name is upper case, so constant variable name of WIN32OLE object is capitalized. For example, the ‘xlTop’ constant of Excel is changed to ‘XlTop’ in WIN32OLE. If the first letter of constant variabl is not [A-Z], then the constant is defined as CONSTANTS hash element.

   module EXCEL_CONST
   end
   excel = WIN32OLE.new('Excel.Application')
   WIN32OLE.const_load(excel, EXCEL_CONST)
   puts EXCEL_CONST::XlTop # => -4160
   puts EXCEL_CONST::CONSTANTS['_xlDialogChartSourceData'] # => 541

   WIN32OLE.const_load(excel)
   puts WIN32OLE::XlTop # => -4160

   module MSO
   end
   WIN32OLE.const_load('Microsoft Office 9.0 Object Library', MSO)
   puts MSO::MsoLineSingle # => 1
WIN32OLE.new(server, [host]) → WIN32OLE object

Returns a new WIN32OLE object(OLE Automation object). The first argument server specifies OLE Automation server. The first argument should be CLSID or PROGID. If second argument host specified, then returns OLE Automation object on host.

    WIN32OLE.new('Excel.Application') # => Excel OLE Automation WIN32OLE object.
    WIN32OLE.new('{00024500-0000-0000-C000-000000000046}') # => Excel OLE Automation WIN32OLE object.
WIN32OLE.ole_free(aWIN32OLE) -→ number

Invokes Release method of Dispatch interface of WIN32OLE object. You should not use this method because this method exists only for debugging WIN32OLE. The return value is reference counter of OLE object.

WIN32OLE.ole_reference_count(aWIN32OLE) -→ number

Returns reference counter of Dispatch interface of WIN32OLE object. You should not use this method because this method exists only for debugging WIN32OLE.

WIN32OLE.ole_show_help(obj [,helpcontext])

Displays helpfile. The 1st argument specifies WIN32OLE_TYPE object or WIN32OLE_METHOD object or helpfile.

   excel = WIN32OLE.new('Excel.Application')
   typeobj = excel.ole_type
   WIN32OLE.ole_show_help(typeobj)

Public Instance methods

WIN32OLE['property']

Returns property of OLE object.

   excel = WIN32OLE.new('Excel.Application')
   puts excel['Visible'] # => false
WIN32OLE['property']=val
WIN32OLE.setproperty('property', [arg1, arg2,...] val)

Sets property of OLE object. When you want to set property with argument, you can use this method.

   excel = WIN32OLE.new('Excel.Application')
   excel['Visible'] = true
   book = excel.workbooks.add
   sheet = book.worksheets(1)
   sheet.setproperty('Cells', 1, 2, 10) # => The B1 cell value is 10.
WIN32OLE#_getproperty(dispid, args, types)

Runs the early binding method to get property. The 1st argument specifies dispatch ID, the 2nd argument specifies the array of arguments, the 3rd argument specifies the array of the type of arguments.

   excel = WIN32OLE.new('Excel.Application')
   puts excel._getproperty(558, [], []) # same effect as puts excel.visible
WIN32OLE#_invoke(dispid, args, types)

Runs the early binding method. The 1st argument specifies dispatch ID, the 2nd argument specifies the array of arguments, the 3rd argument specifies the array of the type of arguments.

   excel = WIN32OLE.new('Excel.Application')
   excel._invoke(302, [], []) #  same effect as excel.Quit
WIN32OLE#_setproperty(dispid, args, types)

Runs the early binding method to set property. The 1st argument specifies dispatch ID, the 2nd argument specifies the array of arguments, the 3rd argument specifies the array of the type of arguments.

   excel = WIN32OLE.new('Excel.Application')
   excel._setproperty(558, [true], [WIN32OLE::VARIANT::VT_BOOL]) # same effect as excel.visible = true
WIN32OLE#each {|i|...}

Iterates over each item of OLE collection which has IEnumVARIANT interface.

   excel = WIN32OLE.new('Excel.Application')
   book = excel.workbooks.add
   sheets = book.worksheets(1)
   cells = sheets.cells("A1:A5")
   cells.each do |cell|
     cell.value = 10
   end
WIN32OLE#invoke(method, [arg1,...]) => return value of method.

Runs OLE method. The first argument specifies the method name of OLE Automation object. The others specify argument of the method. If you can not execute method directly, then use this method instead.

  excel = WIN32OLE.new('Excel.Application')
  excel.invoke('Quit')  # => same as excel.Quit
WIN32OLE#method_missing(id [,arg1, arg2, ...])

Calls WIN32OLE#invoke method.

WIN32OLE#ole_free

invokes Release method of Dispatch interface of WIN32OLE object. Usually, you do not need to call this method because Release method called automatically when WIN32OLE object garbaged.

WIN32OLE#ole_func_methods

Returns the array of WIN32OLE_METHOD object . The element of the array is functional method of WIN32OLE object.

   excel = WIN32OLE.new('Excel.Application')
   properties = excel.ole_func_methods
WIN32OLE#ole_get_methods

Returns the array of WIN32OLE_METHOD object . The element of the array is property (gettable) of WIN32OLE object.

   excel = WIN32OLE.new('Excel.Application')
   properties = excel.ole_get_methods
WIN32OLE#ole_method_help(method)

Returns WIN32OLE_METHOD object corresponding with method specified by 1st argument.

   excel = WIN32OLE.new('Excel.Application')
   method = excel.ole_method_help('Quit')
ole_method_help(p1)

Alias for ole_method

WIN32OLE#ole_methods

Returns the array of WIN32OLE_METHOD object. The element is OLE method of WIN32OLE object.

   excel = WIN32OLE.new('Excel.Application')
   methods = excel.ole_methods
WIN32OLE#ole_obj_help

Returns WIN32OLE_TYPE object.

   excel = WIN32OLE.new('Excel.Application')
   tobj = excel.ole_obj_help
WIN32OLE#ole_put_methods

Returns the array of WIN32OLE_METHOD object . The element of the array is property (settable) of WIN32OLE object.

   excel = WIN32OLE.new('Excel.Application')
   properties = excel.ole_put_methods
WIN32OLE['property']=val
WIN32OLE.setproperty('property', [arg1, arg2,...] val)

Sets property of OLE object. When you want to set property with argument, you can use this method.

   excel = WIN32OLE.new('Excel.Application')
   excel['Visible'] = true
   book = excel.workbooks.add
   sheet = book.worksheets(1)
   sheet.setproperty('Cells', 1, 2, 10) # => The B1 cell value is 10.


Module: WIN32OLE::VARIANT

Module | WIN32OLE::VARIANT
In: | ext/win32ole/win32ole.c

Constants

VT_I2 | = | INT2FIX(VT_I2)
VT_I4 | = | INT2FIX(VT_I4)
VT_R4 | = | INT2FIX(VT_R4)
VT_R8 | = | INT2FIX(VT_R8)
VT_CY | = | INT2FIX(VT_CY)
VT_DATE | = | INT2FIX(VT_DATE)
VT_BSTR | = | INT2FIX(VT_BSTR)
VT_USERDEFINED | = | INT2FIX(VT_USERDEFINED)
VT_PTR | = | INT2FIX(VT_PTR)
VT_DISPATCH | = | INT2FIX(VT_DISPATCH)
VT_ERROR | = | INT2FIX(VT_ERROR)
VT_BOOL | = | INT2FIX(VT_BOOL)
VT_VARIANT | = | INT2FIX(VT_VARIANT)
VT_UNKNOWN | = | INT2FIX(VT_UNKNOWN)
VT_I1 | = | INT2FIX(VT_I1)
VT_UI1 | = | INT2FIX(VT_UI1)
VT_UI2 | = | INT2FIX(VT_UI2)
VT_UI4 | = | INT2FIX(VT_UI4)
VT_INT | = | INT2FIX(VT_INT)
VT_UINT | = | INT2FIX(VT_UINT)
VT_ARRAY | = | INT2FIX(VT_ARRAY)
VT_BYREF | = | INT2FIX(VT_BYREF)


Class: WIN32OLERuntimeError

Class | WIN32OLERuntimeError
In: | ext/win32ole/win32ole.c
Parent: | RuntimeError


Class: WIN32OLE_EVENT

Class | WIN32OLE_EVENT
In: | ext/win32ole/win32ole.c
Parent: | Object

WIN32OLE_EVENT objects controls OLE event.

Methods

message_loop new on_event on_event_with_outargs

Public Class methods

WIN32OLE_EVENT.message_loop

Translates and dispatches Windows message.

WIN32OLE_EVENT.new(ole, event) #=> WIN32OLE_EVENT object.

Returns OLE event object. The first argument specifies WIN32OLE object. The second argument specifies OLE event name.

   ie = WIN32OLE.new('InternetExplorer.Application')
   ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')

Public Instance methods

WIN32OLE_EVENT#on_event([event]){...}

Defines the callback event. If argument is omitted, this method defines the callback of all events.

  ie = WIN32OLE.new('InternetExplorer.Application')
  ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
  ev.on_event("NavigateComplete") {|url| puts url}
WIN32OLE_EVENT#on_event_with_outargs([event]){...}

Defines the callback of event. If you want modify argument in callback, you should use this method instead of WIN32OLE_EVENT#on_event.


Class: WIN32OLE_METHOD

Class | WIN32OLE_METHOD
In: | ext/win32ole/win32ole.c
Parent: | Object

WIN32OLE_METHOD objects represent OLE method information.

Methods

dispid event? event_interface helpcontext helpfile helpstring invkind invoke_kind name new offset_vtbl params return_type return_type_detail return_vtype size_opt_params size_params to_s visible?

Public Class methods

WIN32OLE_METHOD.new(ole_type, method) → WIN32OLE_METHOD object

Returns a new WIN32OLE_METHOD object which represents the information about OLE method. The first argument ole_type specifies WIN32OLE_TYPE object. The second argument method specifies OLE method name defined OLE class which represents WIN32OLE_TYPE object.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')

Public Instance methods

WIN32OLE_METHOD#dispid

Returns dispatch ID.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.dispid # => 181
WIN32OLE_METHOD#event?

Returns true if the method is event.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SheetActivate')
   puts method.event? # => true
WIN32OLE_METHOD#event_interface

Returns event interface name if the method is event.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
  method = WIN32OLE_METHOD.new(tobj, 'SheetActivate')
  puts method.event_interface # =>  WorkbookEvents
WIN32OLE_METHOD#helpcontext

Returns help context.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.helpcontext # => 65717
WIN32OLE_METHOD#helpfile

Returns help file. If help file is not found, then the method returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.helpfile # => C:\...\VBAXL9.CHM
WIN32OLE_METHOD#helpstring

Returns help string of OLE method. If the help string is not found, then the method returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
   method = WIN32OLE_METHOD.new(tobj, 'Navigate')
   puts method.helpstring # => Navigates to a URL or file.
WIN32OLE_MTHOD#invkind

Returns the method invoke kind.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
  method = WIN32OLE_METHOD.new(tobj, 'Add')
  puts method.invkind # => 1
WIN32OLE_METHOD#invoke_kind

Returns the method kind string. The string is "UNKNOWN" or "PROPERTY" or "PROPERTY" or "PROPERTYGET" or "PROPERTYPUT" or "PROPERTYPPUTREF" or "FUNC".

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.invoke_kind # => "FUNC"
name()

call-seq

   WIN32OLE_METHOD#name

Returns the name of the method.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   puts method.name # => SaveAs
WIN32OLE_METHOD#offset_vtbl

Returns the offset ov VTBL.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.offset_vtbl # => 40
WIN32OLE_METHOD#params

returns array of WIN32OLE_PARAM object corresponding with method parameters.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   p method.params # => [Filename, FileFormat, Password, WriteResPassword,
                         ReadOnlyRecommended, CreateBackup, AccessMode,
                         ConflictResolution, AddToMru, TextCodepage,
                         TextVisualLayout]
WIN32OLE_METHOD#return_type

Returns string of return value type of method.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.return_type # => Workbook
WIN32OLE_METHOD#return_type_detail

Returns detail information of return value type of method. The information is array.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   p method.return_type_detail # => ["PTR", "USERDEFINED", "Workbook"]
WIN32OLE_METHOD#return_vtype

Returns number of return value type of method.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.return_vtype # => 26
WIN32OLE_METHOD#size_opt_params

Returns the size of optional parameters.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   puts method.size_opt_params # => 4
WIN32OLE_METHOD#size_params

Returns the size of arguments of the method.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   puts method.size_params # => 11
to_s()

Alias for name

WIN32OLE_METHOD#visible?

Returns true if the method is public.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
   method = WIN32OLE_METHOD.new(tobj, 'Add')
   puts method.visible? # => true


Class: WIN32OLE_PARAM

Class | WIN32OLE_PARAM
In: | ext/win32ole/win32ole.c
Parent: | Object

WIN32OLE_PARAM objects represent param information of the OLE method.

Methods

default input? name ole_type ole_type_detail optional? output? retval? to_s

Public Instance methods

WIN32OLE_PARAM#default

Returns default value. If the default value does not exist, this method returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   method.params.each do |param|
     if param.default
       puts "#{param.name} (= #{param.default})"
     else
       puts "#{param}"
     end
   end

   The above script result is following:
       Filename
       FileFormat
       Password
       WriteResPassword
       ReadOnlyRecommended
       CreateBackup
       AccessMode (= 1)
       ConflictResolution
       AddToMru
       TextCodepage
       TextVisualLayout
WIN32OLE_PARAM#input?

Returns true if the parameter is input.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   param1 = method.params[0]
   puts param1.input? # => true
WIN32OLE_PARAM#name

Returns name.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   param1 = method.params[0]
   puts param1.name # => Filename
WIN32OLE_PARAM#ole_type

Returns OLE type of WIN32OLE_PARAM object(parameter of OLE method).

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   param1 = method.params[0]
   puts param1.ole_type # => VARIANT
WIN32OLE_PARAM#ole_type_detail

Returns detail information of type of argument.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'IWorksheetFunction')
   method = WIN32OLE_METHOD.new(tobj, 'SumIf')
   param1 = method.params[0]
   p param1.ole_type_detail # => ["PTR", "USERDEFINED", "Range"]
WIN32OLE_PARAM#optional?

Returns true if argument is optional.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
   method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
   param1 = method.params[0]
   puts "#{param1.name} #{param1.optional?}" # => Filename true
WIN32OLE#output?

Returns true if argument is output.

   tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'DWebBrowserEvents')
   method = WIN32OLE_METHOD.new(tobj, 'NewWindow')
   method.params.each do |param|
     puts "#{param.name} #{param.output?}"
   end

   The result of above script is following:
     URL false
     Flags false
     TargetFrameName false
     PostData false
     Headers false
     Processed true
WIN32OLE_PARAM#retval?

Returns true if argument is return value.

   tobj = WIN32OLE_TYPE.new('DirectX 7 for Visual Basic Type Library',
                            'DirectPlayLobbyConnection')
   method = WIN32OLE_METHOD.new(tobj, 'GetPlayerShortName')
   param = method.params[0]
   puts "#{param.name} #{param.retval?}"  # => name true
to_s()

Alias for name


Class: WIN32OLE_TYPE

Class | WIN32OLE_TYPE
In: | ext/win32ole/win32ole.c
Parent: | Object

WIN32OLE_TYPE objects represent OLE type libarary information.

Methods

guid helpcontext helpfile helpstring major_version minor_version name new ole_classes ole_methods ole_type progid progids src_type to_s typekind typelibs variables visible?

Public Class methods

WIN32OLE_TYPE.new(typelib, ole_class) → WIN32OLE_TYPE object

Returns a new WIN32OLE_TYPE object. The first argument typelib specifies OLE type library name. The second argument specifies OLE class name.

    WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
        # => WIN32OLE_TYPE object of Application class of Excel.
WIN32OLE_TYPE.ole_classes(typelib)

Returns array of WIN32OLE_TYPE objects defined by the typelib type library.

WIN32OLE_TYPE.progids

Returns array of ProgID.

WIN32OLE_TYPE.typelibs

Returns array of type libraries.

Public Instance methods

WIN32OLE_TYPE#guid #=> GUID

Returns GUID.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
  puts tobj.guid  # => {00024500-0000-0000-C000-000000000046}
WIN32OLE_TYPE#helpcontext

Returns helpcontext. If helpcontext is not found, then returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
   puts tobj.helpfile # => 131185
WIN32OLE_TYPE#helpfile

Returns helpfile path. If helpfile is not found, then returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
   puts tobj.helpfile # => C:\...\VBAXL9.CHM
WIN32OLE_TYPE#helpstring #=> help string.

Returns help string.

  tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
  puts tobj.helpstring # => Web Browser interface
WIN32OLE_TYPE#major_version

Returns major version.

   tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
   puts tobj.major_version # => 8
WIN32OLE_TYPE#minor_version #=> OLE minor version

Returns minor version.

   tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
   puts tobj.minor_version # => 2
WIN32OLE_TYPE#name #=> OLE type name

Returns OLE type name.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
   puts tobj.name  # => Application
WIN32OLE_TYPE#ole_methods # the array of WIN32OLE_METHOD objects.

Returns array of WIN32OLE_METHOD objects which represent OLE method defined in OLE type library.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
  methods = tobj.ole_methods.collect{|m|
    m.name
  }
  # => ['Activate', 'Copy', 'Delete',....]
WIN32OLE_TYPE#ole_type #=> OLE type string.

returns type of OLE class.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
  puts tobj.ole_type  # => Class
WIN32OLE_TYPE#progid #=> ProgID

Returns ProgID if it exists. If not found, then returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
   puts tobj.progid  # =>   Excel.Application.9
WIN32OLE_TYPE#src_type #=> OLE source class

Returns source class when the OLE class is ‘Alias’.

   tobj =  WIN32OLE_TYPE.new('Microsoft Office 9.0 Object Library', 'MsoRGBType')
   puts tobj.src_type # => I4
to_s()

Alias for name

WIN32OLE_TYPE#typekind #=> number of type.

Returns number which represents type.

  tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
  puts tobj.typekind # => 4
WIN32OLE_TYPE#variables

Returns array of WIN32OLE_VARIABLE objects which represent variables defined in OLE class.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
   vars = tobj.variables
   vars.each do |v|
     puts "#{v.name} = #{v.value}"
   end

   The result of above sample script is follows:
     xlChart = -4109
     xlDialogSheet = -4116
     xlExcel4IntlMacroSheet = 4
     xlExcel4MacroSheet = 3
     xlWorksheet = -4167
WIN32OLE_TYPE#visible #=> true or false

Returns true if the OLE class is public.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
  puts tobj.visible  # => true


Class: WIN32OLE_VARIABLE

Class | WIN32OLE_VARIABLE
In: | ext/win32ole/win32ole.c
Parent: | Object

WIN32OLE_VARIABLE objects represent OLE variable information.

Methods

name ole_type ole_type_detail to_s value variable_kind varkind visible?

Public Instance methods

WIN32OLE_VARIABLE#name

Returns the name of variable.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
   variables = tobj.variables
   variables.each do |variable|
     puts "#{variable.name}"
   end

   The result of above script is following:
     xlChart
     xlDialogSheet
     xlExcel4IntlMacroSheet
     xlExcel4MacroSheet
     xlWorksheet
WIN32OLE_VARIABLE#ole_type

Returns OLE type string.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
  variables = tobj.variables
  variables.each do |variable|
    puts "#{variable.ole_type} #{variable.name}"
  end

  The result of above script is following:
    INT xlChart
    INT xlDialogSheet
    INT xlExcel4IntlMacroSheet
    INT xlExcel4MacroSheet
    INT xlWorksheet
WIN32OLE_VARIABLE#ole_type_detail

Returns detail information of type. The information is array of type.

   tobj = WIN32OLE_TYPE.new('DirectX 7 for Visual Basic Type Library', 'D3DCLIPSTATUS')
   variable = tobj.variables.find {|variable| variable.name == 'lFlags'}
   tdetail  = variable.ole_type_detail
   p tdetail # => ["USERDEFINED", "CONST_D3DCLIPSTATUSFLAGS"]
to_s()

Alias for name

WIN32OLE_VARIABLE#value

Returns value if value is exists. If the value does not exist, this method returns nil.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
   variables = tobj.variables
   variables.each do |variable|
     puts "#{variable.name} = #{variable.value}"
   end

   The result of above script is following:
     xlChart = -4109
     xlDialogSheet = -4116
     xlExcel4IntlMacroSheet = 4
     xlExcel4MacroSheet = 3
     xlWorksheet = -4167
WIN32OLE_VARIABLE#variable_kind

Returns variable kind string.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
   variables = tobj.variables
   variables.each do |variable|
     puts "#{variable.name} #{variable.variable_kind}"
   end

   The result of above script is following:
     xlChart CONSTANT
     xlDialogSheet CONSTANT
     xlExcel4IntlMacroSheet CONSTANT
     xlExcel4MacroSheet CONSTANT
     xlWorksheet CONSTANT
WIN32OLE_VARIABLE#varkind

Returns the number which represents variable kind.

  tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
  variables = tobj.variables
  variables.each do |variable|
    puts "#{variable.name} #{variable.varkind}"
  end

  The result of above script is following:
     xlChart 2
     xlDialogSheet 2
     xlExcel4IntlMacroSheet 2
     xlExcel4MacroSheet 2
     xlWorksheet 2
WIN32OLE_VARIABLE#visible?

Returns true if the variable is public.

   tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
   variables = tobj.variables
   variables.each do |variable|
     puts "#{variable.name} #{variable.visible?}"
   end

   The result of above script is following:
     xlChart true
     xlDialogSheet true
     xlExcel4IntlMacroSheet true
     xlExcel4MacroSheet true
     xlWorksheet true


Module: WSDL
In: lib/wsdl/param.rb
lib/wsdl/part.rb
lib/wsdl/binding.rb
lib/wsdl/service.rb
lib/wsdl/portType.rb
lib/wsdl/import.rb
lib/wsdl/definitions.rb
lib/wsdl/operationBinding.rb
lib/wsdl/types.rb
lib/wsdl/xmlSchema/simpleContent.rb
lib/wsdl/xmlSchema/sequence.rb
lib/wsdl/xmlSchema/length.rb
lib/wsdl/xmlSchema/annotation.rb
lib/wsdl/xmlSchema/import.rb
lib/wsdl/xmlSchema/attribute.rb
lib/wsdl/xmlSchema/choice.rb
lib/wsdl/xmlSchema/any.rb
lib/wsdl/xmlSchema/enumeration.rb
lib/wsdl/xmlSchema/element.rb
lib/wsdl/xmlSchema/include.rb
lib/wsdl/xmlSchema/content.rb
lib/wsdl/xmlSchema/complexType.rb
lib/wsdl/xmlSchema/xsd2ruby.rb
lib/wsdl/xmlSchema/parser.rb
lib/wsdl/xmlSchema/simpleExtension.rb
lib/wsdl/xmlSchema/all.rb
lib/wsdl/xmlSchema/pattern.rb
lib/wsdl/xmlSchema/complexContent.rb
lib/wsdl/xmlSchema/data.rb
lib/wsdl/xmlSchema/simpleRestriction.rb
lib/wsdl/xmlSchema/importer.rb
lib/wsdl/xmlSchema/schema.rb
lib/wsdl/xmlSchema/unique.rb
lib/wsdl/xmlSchema/simpleType.rb
lib/wsdl/operation.rb
lib/wsdl/soap/headerfault.rb
lib/wsdl/soap/cgiStubCreator.rb
lib/wsdl/soap/classDefCreator.rb
lib/wsdl/soap/binding.rb
lib/wsdl/soap/wsdl2ruby.rb
lib/wsdl/soap/definitions.rb
lib/wsdl/soap/body.rb
lib/wsdl/soap/classDefCreatorSupport.rb
lib/wsdl/soap/address.rb
lib/wsdl/soap/element.rb
lib/wsdl/soap/standaloneServerStubCreator.rb
lib/wsdl/soap/servantSkeltonCreator.rb
lib/wsdl/soap/clientSkeltonCreator.rb
lib/wsdl/soap/methodDefCreator.rb
lib/wsdl/soap/complexType.rb
lib/wsdl/soap/mappingRegistryCreator.rb
lib/wsdl/soap/operation.rb
lib/wsdl/soap/driverCreator.rb
lib/wsdl/soap/fault.rb
lib/wsdl/soap/header.rb
lib/wsdl/soap/data.rb
lib/wsdl/wsdl.rb
lib/wsdl/port.rb
lib/wsdl/parser.rb
lib/wsdl/documentation.rb
lib/wsdl/message.rb
lib/wsdl/data.rb
lib/wsdl/info.rb
lib/wsdl/importer.rb

This program is copyrighted free software by NAKAMURA, Hiroshi. You can redistribute it and/or modify it under the same terms of Ruby‘s license; either the dual license version in 2003, or any later version.

Classes and Modules

Module WSDL::SOAP
Module WSDL::XMLSchema
Class WSDL::Binding
Class WSDL::Definitions
Class WSDL::Documentation
Class WSDL::Error
Class WSDL::Import
Class WSDL::Importer
Class WSDL::Info
Class WSDL::Message
Class WSDL::Operation
Class WSDL::OperationBinding
Class WSDL::Param
Class WSDL::Parser
Class WSDL::Part
Class WSDL::Port
Class WSDL::PortType
Class WSDL::Service
Class WSDL::Types

Constants

Version | = | '0.0.2'
Namespace | = | 'http://schemas.xmlsoap.org/wsdl/'
SOAPBindingNamespace | = | 'http://schemas.xmlsoap.org/wsdl/soap/'
ArrayTypeAttrName | = | XSD::QName.new(Namespace, 'arrayType')
BindingName | = | XSD::QName.new(Namespace, 'binding')
DefinitionsName | = | XSD::QName.new(Namespace, 'definitions')
DocumentationName | = | XSD::QName.new(Namespace, 'documentation')
FaultName | = | XSD::QName.new(Namespace, 'fault')
ImportName | = | XSD::QName.new(Namespace, 'import')
InputName | = | XSD::QName.new(Namespace, 'input')
MessageName | = | XSD::QName.new(Namespace, 'message')
OperationName | = | XSD::QName.new(Namespace, 'operation')
OutputName | = | XSD::QName.new(Namespace, 'output')
PartName | = | XSD::QName.new(Namespace, 'part')
PortName | = | XSD::QName.new(Namespace, 'port')
PortTypeName | = | XSD::QName.new(Namespace, 'portType')
ServiceName | = | XSD::QName.new(Namespace, 'service')
TypesName | = | XSD::QName.new(Namespace, 'types')
SchemaName | = | XSD::QName.new(XSD::Namespace, 'schema')
SOAPAddressName | = | XSD::QName.new(SOAPBindingNamespace, 'address')
SOAPBindingName | = | XSD::QName.new(SOAPBindingNamespace, 'binding')
SOAPHeaderName | = | XSD::QName.new(SOAPBindingNamespace, 'header')
SOAPBodyName | = | XSD::QName.new(SOAPBindingNamespace, 'body')
SOAPFaultName | = | XSD::QName.new(SOAPBindingNamespace, 'fault')
SOAPOperationName | = | XSD::QName.new(SOAPBindingNamespace, 'operation')
BindingAttrName | = | XSD::QName.new(nil, 'binding')
ElementAttrName | = | XSD::QName.new(nil, 'element')
LocationAttrName | = | XSD::QName.new(nil, 'location')
MessageAttrName | = | XSD::QName.new(nil, 'message')
NameAttrName | = | XSD::QName.new(nil, 'name')
NamespaceAttrName | = | XSD::QName.new(nil, 'namespace')
ParameterOrderAttrName | = | XSD::QName.new(nil, 'parameterOrder')
TargetNamespaceAttrName | = | XSD::QName.new(nil, 'targetNamespace')
TypeAttrName | = | XSD::QName.new(nil, 'type')


Class: WSDL::Binding

Class | WSDL::Binding
In: | lib/wsdl/binding.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

name | [R]
operations | [R]
soapbinding | [R]
type | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::Definitions

Class | WSDL::Definitions
In: | lib/wsdl/definitions.rb lib/wsdl/soap/definitions.rb
Parent: | Info

Methods

add_type array_complextype binding bindings collect_attributes collect_complextypes collect_elements collect_faulttypes collect_simpletypes exception_complextype fault_complextype inspect message messages new parse_attr parse_element parse_element porttype porttype_binding porttypes service services soap_rpc_complextypes soap_rpc_complextypes targetnamespace=

Attributes

importedschema | [R]
imports | [R]
location | [RW]
name | [R]
targetnamespace | [R]

Public Class methods

array_complextype()
exception_complextype()
fault_complextype()
new()
parse_element(element)
soap_rpc_complextypes()

Public Instance methods

add_type(complextype)

ToDo: simpletype must be accepted…

binding(name)
bindings()
collect_attributes()
collect_complextypes()
collect_elements()
collect_faulttypes()
collect_simpletypes()
inspect()
message(name)
messages()
parse_attr(attr, value)
parse_element(element)
porttype(name)
porttype_binding(name)
porttypes()
service(name)
services()
soap_rpc_complextypes(binding)
targetnamespace=(targetnamespace)


Class: WSDL::Documentation

Class | WSDL::Documentation
In: | lib/wsdl/documentation.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::Error

Class | WSDL::Error
In: | lib/wsdl/wsdl.rb
Parent: | StandardError


Class: WSDL::Import

Class | WSDL::Import
In: | lib/wsdl/import.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

content | [R]
location | [R]
namespace | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::Importer

Class | WSDL::Importer
In: | lib/wsdl/importer.rb
Parent: | WSDL::XMLSchema::Importer

Methods

import

Public Class methods

import(location, originalroot = nil)


Class: WSDL::Info

Class | WSDL::Info
In: | lib/wsdl/info.rb
Parent: | Object

Methods

inspect new parse_attr parse_element parse_epilogue

Attributes

id | [RW]
parent | [RW]
root | [RW]

Public Class methods

new()

Public Instance methods

inspect()
parse_attr(attr, value)
parse_element(element)
parse_epilogue()


Class: WSDL::Message

Class | WSDL::Message
In: | lib/wsdl/message.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

name | [R]
parts | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::Operation

Class | WSDL::Operation
In: | lib/wsdl/operation.rb
Parent: | Info

Methods

input_info inputname inputparts new output_info outputname outputparts parse_attr parse_element targetnamespace

Classes and Modules

Class WSDL::Operation::NameInfo

Attributes

fault | [R]
input | [R]
name | [R]
output | [R]
parameter_order | [R]
type | [R]

Public Class methods

new()

Public Instance methods

input_info()
inputname()
inputparts()
output_info()
outputname()
outputparts()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::Operation::NameInfo

Class | WSDL::Operation::NameInfo
In: | lib/wsdl/operation.rb
Parent: | Object

Methods

new

Attributes

op_name | [R]
optype_name | [R]
parts | [R]

Public Class methods

new(op_name, optype_name, parts)


Class: WSDL::OperationBinding

Class | WSDL::OperationBinding
In: | lib/wsdl/operationBinding.rb
Parent: | Info

Methods

find_operation new parse_attr parse_element porttype soapaction soapoperation_name soapoperation_style targetnamespace

Attributes

fault | [R]
input | [R]
name | [R]
output | [R]
soapoperation | [R]

Public Class methods

new()

Public Instance methods

find_operation()
parse_attr(attr, value)
parse_element(element)
porttype()
soapaction()
soapoperation_name()
soapoperation_style()
targetnamespace()


Class: WSDL::Param

Class | WSDL::Param
In: | lib/wsdl/param.rb
Parent: | Info

Methods

find_message new parse_attr parse_element soapbody_use targetnamespace

Attributes

message | [R]
name | [R]
soapbody | [R]
soapfault | [R]
soapheader | [R]

Public Class methods

new()

Public Instance methods

find_message()
parse_attr(attr, value)
parse_element(element)
soapbody_use()
targetnamespace()


Class: WSDL::Parser

Class | WSDL::Parser
In: | lib/wsdl/parser.rb
Parent: | Object

Methods

characters charset end_element new parse start_element

Included Modules

WSDL

Classes and Modules

Class WSDL::Parser::AttributeConstraintError
Class WSDL::Parser::ElementConstraintError
Class WSDL::Parser::FormatDecodeError
Class WSDL::Parser::ParseError
Class WSDL::Parser::ParseFrame
Class WSDL::Parser::UnexpectedElementError
Class WSDL::Parser::UnknownAttributeError
Class WSDL::Parser::UnknownElementError

Public Class methods

new(opt = {})

Public Instance methods

characters(text)
charset()
end_element(name)
parse(string_or_readable)
start_element(name, attrs)


Class: WSDL::Parser::AttributeConstraintError

Class | WSDL::Parser::AttributeConstraintError
In: | lib/wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::ElementConstraintError

Class | WSDL::Parser::ElementConstraintError
In: | lib/wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::FormatDecodeError

Class | WSDL::Parser::FormatDecodeError
In: | lib/wsdl/parser.rb
Parent: | ParseError


Class: WSDL::Parser::ParseError

Class | WSDL::Parser::ParseError
In: | lib/wsdl/parser.rb
Parent: | Error


Class: WSDL::Parser::ParseFrame

Class | WSDL::Parser::ParseFrame
In: | lib/wsdl/parser.rb
Parent: | Object

Methods

new

Attributes

name | [R]
node | [RW]
ns | [R]

Public Class methods

new(ns, name, node)


Class: WSDL::Parser::UnexpectedElementError

Class | WSDL::Parser::UnexpectedElementError
In: | lib/wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::UnknownAttributeError

Class | WSDL::Parser::UnknownAttributeError
In: | lib/wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Parser::UnknownElementError

Class | WSDL::Parser::UnknownElementError
In: | lib/wsdl/parser.rb
Parent: | FormatDecodeError


Class: WSDL::Part

Class | WSDL::Part
In: | lib/wsdl/part.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

element | [R]
name | [R]
type | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::Port

Class | WSDL::Port
In: | lib/wsdl/port.rb
Parent: | Info

Methods

find_binding inputoperation_map new outputoperation_map parse_attr parse_element porttype targetnamespace

Attributes

binding | [R]
name | [R]
soap_address | [R]

Public Class methods

new()

Public Instance methods

find_binding()
inputoperation_map()
outputoperation_map()
parse_attr(attr, value)
parse_element(element)
porttype()
targetnamespace()


Class: WSDL::PortType

Class | WSDL::PortType
In: | lib/wsdl/portType.rb
Parent: | Info

Methods

find_binding locations new parse_attr parse_element targetnamespace

Attributes

name | [R]
operations | [R]

Public Class methods

new()

Public Instance methods

find_binding()
locations()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Module: WSDL::SOAP

Module | WSDL::SOAP
In: | lib/wsdl/soap/headerfault.rb lib/wsdl/soap/cgiStubCreator.rb lib/wsdl/soap/classDefCreator.rb lib/wsdl/soap/binding.rb lib/wsdl/soap/wsdl2ruby.rb lib/wsdl/soap/body.rb lib/wsdl/soap/classDefCreatorSupport.rb lib/wsdl/soap/address.rb lib/wsdl/soap/standaloneServerStubCreator.rb lib/wsdl/soap/servantSkeltonCreator.rb lib/wsdl/soap/clientSkeltonCreator.rb lib/wsdl/soap/methodDefCreator.rb lib/wsdl/soap/mappingRegistryCreator.rb lib/wsdl/soap/operation.rb lib/wsdl/soap/driverCreator.rb lib/wsdl/soap/fault.rb lib/wsdl/soap/header.rb lib/wsdl/soap/data.rb

Classes and Modules

Module WSDL::SOAP::ClassDefCreatorSupport
Class WSDL::SOAP::Address
Class WSDL::SOAP::Binding
Class WSDL::SOAP::Body
Class WSDL::SOAP::CGIStubCreator
Class WSDL::SOAP::ClassDefCreator
Class WSDL::SOAP::ClientSkeltonCreator
Class WSDL::SOAP::DriverCreator
Class WSDL::SOAP::Fault
Class WSDL::SOAP::Header
Class WSDL::SOAP::HeaderFault
Class WSDL::SOAP::MappingRegistryCreator
Class WSDL::SOAP::MethodDefCreator
Class WSDL::SOAP::Operation
Class WSDL::SOAP::ServantSkeltonCreator
Class WSDL::SOAP::StandaloneServerStubCreator
Class WSDL::SOAP::WSDL2Ruby

Constants

HeaderFaultName | = | XSD::QName.new(SOAPBindingNamespace, 'headerfault')
LocationAttrName | = | XSD::QName.new(nil, 'location')
StyleAttrName | = | XSD::QName.new(nil, 'style')
TransportAttrName | = | XSD::QName.new(nil, 'transport')
UseAttrName | = | XSD::QName.new(nil, 'use')
PartsAttrName | = | XSD::QName.new(nil, 'parts')
PartAttrName | = | XSD::QName.new(nil, 'part')
NameAttrName | = | XSD::QName.new(nil, 'name')
MessageAttrName | = | XSD::QName.new(nil, 'message')
EncodingStyleAttrName | = | XSD::QName.new(nil, 'encodingStyle')
NamespaceAttrName | = | XSD::QName.new(nil, 'namespace')
SOAPActionAttrName | = | XSD::QName.new(nil, 'soapAction')


Class: WSDL::SOAP::Address

Class | WSDL::SOAP::Address
In: | lib/wsdl/soap/address.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

location [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::SOAP::Binding

Class | WSDL::SOAP::Binding
In: | lib/wsdl/soap/binding.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

style | [R]
transport | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::SOAP::Body

Class | WSDL::SOAP::Body
In: | lib/wsdl/soap/body.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

encodingstyle | [R]
namespace | [R]
parts | [R]
use | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::SOAP::CGIStubCreator

Class | WSDL::SOAP::CGIStubCreator
In: | lib/wsdl/soap/cgiStubCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

dump(service_name)


Class: WSDL::SOAP::ClassDefCreator

Class | WSDL::SOAP::ClassDefCreator
In: | lib/wsdl/soap/classDefCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Constants

DEFAULT_ITEM_NAME = XSD::QName.new(nil, 'item')

Public Class methods

new(definitions)

Public Instance methods

dump(type = nil)


Module: WSDL::SOAP::ClassDefCreatorSupport

Module | WSDL::SOAP::ClassDefCreatorSupport
In: | lib/wsdl/soap/classDefCreatorSupport.rb

Methods

basetype_mapped_class create_class_name dq dqname dump_method_signature ndq sym

Included Modules

XSD::CodeGen::GenSupport

Public Instance methods

basetype_mapped_class(name)
create_class_name(qname)
dq(ele)
dqname(qname)
dump_method_signature(operation)
ndq(ele)
sym(ele)


Class: WSDL::SOAP::ClientSkeltonCreator

Class | WSDL::SOAP::ClientSkeltonCreator
In: | lib/wsdl/soap/clientSkeltonCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

dump(service_name)


Class: WSDL::SOAP::DriverCreator

Class | WSDL::SOAP::DriverCreator
In: | lib/wsdl/soap/driverCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

dump(porttype = nil)


Class: WSDL::SOAP::Fault

Class | WSDL::SOAP::Fault
In: | lib/wsdl/soap/fault.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

encodingstyle | [R]
name | [R]
namespace | [R]
use | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::SOAP::Header

Class | WSDL::SOAP::Header
In: | lib/wsdl/soap/header.rb
Parent: | Info

Methods

find_message find_part new parse_attr parse_element targetnamespace

Attributes

encodingstyle | [R]
headerfault | [R]
message | [R]
namespace | [R]
part | [R]
use | [R]

Public Class methods

new()

Public Instance methods

find_message()
find_part()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::SOAP::HeaderFault

Class | WSDL::SOAP::HeaderFault
In: | lib/wsdl/soap/headerfault.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

encodingstyle | [R]
message | [R]
namespace | [R]
part | [R]
use | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::SOAP::MappingRegistryCreator

Class | WSDL::SOAP::MappingRegistryCreator
In: | lib/wsdl/soap/mappingRegistryCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

dump(types)


Class: WSDL::SOAP::MethodDefCreator

Class | WSDL::SOAP::MethodDefCreator
In: | lib/wsdl/soap/methodDefCreator.rb
Parent: | Object

Methods

collect_documentparameter collect_rpcparameter dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

collect_documentparameter(operation)
collect_rpcparameter(operation)
dump(porttype)


Class: WSDL::SOAP::Operation

Class | WSDL::SOAP::Operation
In: | lib/wsdl/soap/operation.rb
Parent: | Info

Methods

input_info new operation_style output_info parse_attr parse_element

Classes and Modules

Class WSDL::SOAP::Operation::OperationInfo

Attributes

soapaction | [R]
style | [R]

Public Class methods

new()

Public Instance methods

input_info()
operation_style()
output_info()
parse_attr(attr, value)
parse_element(element)


Class: WSDL::SOAP::Operation::OperationInfo

Class | WSDL::SOAP::Operation::OperationInfo
In: | lib/wsdl/soap/operation.rb
Parent: | Object

Methods

new

Attributes

bodyparts | [R]
faultpart | [R]
headerparts | [R]
op_name | [R]
optype_name | [R]
soapaction | [R]
style | [R]

Public Class methods

new(style, op_name, optype_name, headerparts, bodyparts, faultpart, soapaction)


Class: WSDL::SOAP::ServantSkeltonCreator

Class | WSDL::SOAP::ServantSkeltonCreator
In: | lib/wsdl/soap/servantSkeltonCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport XSD::CodeGen::GenSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

dump(porttype = nil)


Class: WSDL::SOAP::StandaloneServerStubCreator

Class | WSDL::SOAP::StandaloneServerStubCreator
In: | lib/wsdl/soap/standaloneServerStubCreator.rb
Parent: | Object

Methods

dump new

Included Modules

ClassDefCreatorSupport

Attributes

definitions [R]

Public Class methods

new(definitions)

Public Instance methods

dump(service_name)


Class: WSDL::SOAP::WSDL2Ruby

Class | WSDL::SOAP::WSDL2Ruby
In: | lib/wsdl/soap/wsdl2ruby.rb
Parent: | Object

Methods

new run

Attributes

basedir | [RW]
location | [RW]
logger | [RW]
opt | [R]

Public Class methods

new()

Public Instance methods

run()


Class: WSDL::Service

Class | WSDL::Service
In: | lib/wsdl/service.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

name | [R]
ports | [R]
soap_address | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::Types

Class | WSDL::Types
In: | lib/wsdl/types.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

schemas [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Module: WSDL::XMLSchema

Module | WSDL::XMLSchema
In: | lib/wsdl/xmlSchema/simpleContent.rb lib/wsdl/xmlSchema/sequence.rb lib/wsdl/xmlSchema/length.rb lib/wsdl/xmlSchema/annotation.rb lib/wsdl/xmlSchema/import.rb lib/wsdl/xmlSchema/attribute.rb lib/wsdl/xmlSchema/choice.rb lib/wsdl/xmlSchema/any.rb lib/wsdl/xmlSchema/enumeration.rb lib/wsdl/xmlSchema/element.rb lib/wsdl/xmlSchema/include.rb lib/wsdl/xmlSchema/content.rb lib/wsdl/xmlSchema/complexType.rb lib/wsdl/xmlSchema/xsd2ruby.rb lib/wsdl/xmlSchema/parser.rb lib/wsdl/xmlSchema/simpleExtension.rb lib/wsdl/xmlSchema/all.rb lib/wsdl/xmlSchema/pattern.rb lib/wsdl/xmlSchema/complexContent.rb lib/wsdl/xmlSchema/data.rb lib/wsdl/xmlSchema/simpleRestriction.rb lib/wsdl/xmlSchema/importer.rb lib/wsdl/xmlSchema/schema.rb lib/wsdl/xmlSchema/unique.rb lib/wsdl/xmlSchema/simpleType.rb lib/wsdl/soap/element.rb lib/wsdl/soap/complexType.rb

Classes and Modules

Class WSDL::XMLSchema::All
Class WSDL::XMLSchema::Annotation
Class WSDL::XMLSchema::Any
Class WSDL::XMLSchema::Attribute
Class WSDL::XMLSchema::Choice
Class WSDL::XMLSchema::ComplexContent
Class WSDL::XMLSchema::ComplexType
Class WSDL::XMLSchema::Content
Class WSDL::XMLSchema::Element
Class WSDL::XMLSchema::Enumeration
Class WSDL::XMLSchema::Import
Class WSDL::XMLSchema::Importer
Class WSDL::XMLSchema::Include
Class WSDL::XMLSchema::Length
Class WSDL::XMLSchema::Parser
Class WSDL::XMLSchema::Pattern
Class WSDL::XMLSchema::Schema
Class WSDL::XMLSchema::Sequence
Class WSDL::XMLSchema::SimpleContent
Class WSDL::XMLSchema::SimpleExtension
Class WSDL::XMLSchema::SimpleRestriction
Class WSDL::XMLSchema::SimpleType
Class WSDL::XMLSchema::Unique
Class WSDL::XMLSchema::XSD2Ruby

Constants

AllName | = | XSD::QName.new(XSD::Namespace, 'all')
AnnotationName | = | XSD::QName.new(XSD::Namespace, 'annotation')
AnyName | = | XSD::QName.new(XSD::Namespace, 'any')
AttributeName | = | XSD::QName.new(XSD::Namespace, 'attribute')
ChoiceName | = | XSD::QName.new(XSD::Namespace, 'choice')
ComplexContentName | = | XSD::QName.new(XSD::Namespace, 'complexContent')
ComplexTypeName | = | XSD::QName.new(XSD::Namespace, 'complexType')
ElementName | = | XSD::QName.new(XSD::Namespace, 'element')
EnumerationName | = | XSD::QName.new(XSD::Namespace, 'enumeration')
ExtensionName | = | XSD::QName.new(XSD::Namespace, 'extension')
ImportName | = | XSD::QName.new(XSD::Namespace, 'import')
IncludeName | = | XSD::QName.new(XSD::Namespace, 'include')
LengthName | = | XSD::QName.new(XSD::Namespace, 'length')
PatternName | = | XSD::QName.new(XSD::Namespace, 'pattern')
RestrictionName | = | XSD::QName.new(XSD::Namespace, 'restriction')
SequenceName | = | XSD::QName.new(XSD::Namespace, 'sequence')
SchemaName | = | XSD::QName.new(XSD::Namespace, 'schema')
SimpleContentName | = | XSD::QName.new(XSD::Namespace, 'simpleContent')
SimpleTypeName | = | XSD::QName.new(XSD::Namespace, 'simpleType')
UniqueName | = | XSD::QName.new(XSD::Namespace, 'unique')
AttributeFormDefaultAttrName | = | XSD::QName.new(nil, 'attributeFormDefault')
BaseAttrName | = | XSD::QName.new(nil, 'base')
DefaultAttrName | = | XSD::QName.new(nil, 'default')
ElementFormDefaultAttrName | = | XSD::QName.new(nil, 'elementFormDefault')
FinalAttrName | = | XSD::QName.new(nil, 'final')
FixedAttrName | = | XSD::QName.new(nil, 'fixed')
FormAttrName | = | XSD::QName.new(nil, 'form')
IdAttrName | = | XSD::QName.new(nil, 'id')
MaxOccursAttrName | = | XSD::QName.new(nil, 'maxOccurs')
MinOccursAttrName | = | XSD::QName.new(nil, 'minOccurs')
MixedAttrName | = | XSD::QName.new(nil, 'mixed')
NameAttrName | = | XSD::QName.new(nil, 'name')
NamespaceAttrName | = | XSD::QName.new(nil, 'namespace')
NillableAttrName | = | XSD::QName.new(nil, 'nillable')
ProcessContentsAttrName | = | XSD::QName.new(nil, 'processContents')
RefAttrName | = | XSD::QName.new(nil, 'ref')
SchemaLocationAttrName | = | XSD::QName.new(nil, 'schemaLocation')
TargetNamespaceAttrName | = | XSD::QName.new(nil, 'targetNamespace')
TypeAttrName | = | XSD::QName.new(nil, 'type')
UseAttrName | = | XSD::QName.new(nil, 'use')
ValueAttrName | = | XSD::QName.new(nil, 'value')


Class: WSDL::XMLSchema::All

Class | WSDL::XMLSchema::All
In: | lib/wsdl/xmlSchema/all.rb
Parent: | Info

Methods

<< elementformdefault new parse_attr parse_element targetnamespace

Attributes

elements | [R]
maxoccurs | [R]
minoccurs | [R]

Public Class methods

new()

Public Instance methods

<<(element)
elementformdefault()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::Annotation

Class | WSDL::XMLSchema::Annotation
In: | lib/wsdl/xmlSchema/annotation.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Any

Class | WSDL::XMLSchema::Any
In: | lib/wsdl/xmlSchema/any.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace

Attributes

maxoccurs | [RW]
minoccurs | [RW]
namespace | [RW]
process_contents | [RW]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::Attribute

Class | WSDL::XMLSchema::Attribute
In: | lib/wsdl/xmlSchema/attribute.rb
Parent: | Info

Methods

attr_reader_ref attr_reader_ref new parse_attr parse_element refelement targetnamespace

Attributes

arytype | [RW]
default | [W]
fixed | [W]
form | [W]
local_simpletype | [W]
name | [W]
ref | [RW]
type | [W]
use | [W]

Public Class methods

attr_reader_ref(symbol)
attr_reader_ref(symbol)
new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
refelement()
targetnamespace()


Class: WSDL::XMLSchema::Choice

Class | WSDL::XMLSchema::Choice
In: | lib/wsdl/xmlSchema/choice.rb
Parent: | Info

Methods

<< elementformdefault new parse_attr parse_element targetnamespace

Attributes

elements | [R]
maxoccurs | [R]
minoccurs | [R]

Public Class methods

new()

Public Instance methods

<<(element)
elementformdefault()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::ComplexContent

Class | WSDL::XMLSchema::ComplexContent
In: | lib/wsdl/xmlSchema/complexContent.rb
Parent: | Info

Methods

basetype elementformdefault new parse_attr parse_element targetnamespace

Attributes

attributes | [R]
base | [RW]
content | [R]
derivetype | [R]

Public Class methods

new()

Public Instance methods

basetype()
elementformdefault()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::ComplexType

Class | WSDL::XMLSchema::ComplexType
In: | lib/wsdl/xmlSchema/complexType.rb lib/wsdl/soap/complexType.rb
Parent: | Info

Methods

all_elements= check_type child_defined_complextype child_type compoundtype each_element elementformdefault find_aryelement find_arytype find_element find_element_by_name new parse_attr parse_element sequence_elements= targetnamespace

Constants

AnyAsElement = Element.new(XSD::QName.new(nil, 'any'), XSD::AnyTypeName)

Attributes

attributes | [R]
complexcontent | [RW]
content | [R]
final | [RW]
mixed | [RW]
name | [RW]
simplecontent | [RW]

Public Class methods

new(name = nil)

Public Instance methods

all_elements=(elements)
check_type()
child_defined_complextype(name)
child_type(name = nil)
compoundtype()
each_element() {|AnyAsElement| ...}
elementformdefault()
find_aryelement()
find_arytype()
find_element(name)
find_element_by_name(name)
parse_attr(attr, value)
parse_element(element)
sequence_elements=(elements)
targetnamespace()


Class: WSDL::XMLSchema::Content

Class | WSDL::XMLSchema::Content
In: | lib/wsdl/xmlSchema/content.rb
Parent: | Info

Methods

<< each new parse_attr parse_element parse_epilogue targetnamespace

Attributes

contents | [R]
elements | [R]
final | [RW]
mixed | [RW]
type | [RW]

Public Class methods

new()

Public Instance methods

<<(content)
each() {|content| ...}
parse_attr(attr, value)
parse_element(element)
parse_epilogue()
targetnamespace()


Class: WSDL::XMLSchema::Element

Class | WSDL::XMLSchema::Element
In: | lib/wsdl/xmlSchema/element.rb lib/wsdl/soap/element.rb
Parent: | Info

Methods

attr_reader_ref attr_reader_ref attributes elementform elementformdefault map_as_array? new parse_attr parse_element refelement targetnamespace

Attributes

constraint | [W]
form | [W]
local_complextype | [W]
local_simpletype | [W]
maxoccurs | [W]
minoccurs | [W]
name | [W]
nillable | [W]
ref | [RW]
type | [W]

Public Class methods

attr_reader_ref(symbol)
attr_reader_ref(symbol)
new(name = nil, type = nil)

Public Instance methods

attributes()
elementform()
elementformdefault()
map_as_array?()
parse_attr(attr, value)
parse_element(element)
refelement()
targetnamespace()


Class: WSDL::XMLSchema::Enumeration

Class | WSDL::XMLSchema::Enumeration
In: | lib/wsdl/xmlSchema/enumeration.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Import

Class | WSDL::XMLSchema::Import
In: | lib/wsdl/xmlSchema/import.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

content | [R]
namespace | [R]
schemalocation | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Importer

Class | WSDL::XMLSchema::Importer
In: | lib/wsdl/xmlSchema/importer.rb
Parent: | Object

Methods

import import new

Public Class methods

import(location, originalroot = nil)
new()

Public Instance methods

import(location, originalroot = nil)


Class: WSDL::XMLSchema::Include

Class | WSDL::XMLSchema::Include
In: | lib/wsdl/xmlSchema/include.rb
Parent: | Info

Methods

new parse_attr parse_element

Attributes

content | [R]
schemalocation | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Length

Class | WSDL::XMLSchema::Length
In: | lib/wsdl/xmlSchema/length.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Parser

Class | WSDL::XMLSchema::Parser
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | Object

Methods

characters charset end_element new parse start_element

Included Modules

XSD

Classes and Modules

Class WSDL::XMLSchema::Parser::AttributeConstraintError
Class WSDL::XMLSchema::Parser::ElementConstraintError
Class WSDL::XMLSchema::Parser::FormatDecodeError
Class WSDL::XMLSchema::Parser::ParseError
Class WSDL::XMLSchema::Parser::ParseFrame
Class WSDL::XMLSchema::Parser::UnexpectedElementError
Class WSDL::XMLSchema::Parser::UnknownAttributeError
Class WSDL::XMLSchema::Parser::UnknownElementError

Public Class methods

new(opt = {})

Public Instance methods

characters(text)
charset()
end_element(name)
parse(string_or_readable)
start_element(name, attrs)


Class: WSDL::XMLSchema::Parser::AttributeConstraintError

Class | WSDL::XMLSchema::Parser::AttributeConstraintError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::ElementConstraintError

Class | WSDL::XMLSchema::Parser::ElementConstraintError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::FormatDecodeError

Class | WSDL::XMLSchema::Parser::FormatDecodeError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | ParseError


Class: WSDL::XMLSchema::Parser::ParseError

Class | WSDL::XMLSchema::Parser::ParseError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | Error


Class: WSDL::XMLSchema::Parser::ParseFrame

Class | WSDL::XMLSchema::Parser::ParseFrame
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | Object

Methods

new

Attributes

name | [R]
node | [RW]
ns | [R]

Public Class methods

new(ns, name, node)


Class: WSDL::XMLSchema::Parser::UnexpectedElementError

Class | WSDL::XMLSchema::Parser::UnexpectedElementError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::UnknownAttributeError

Class | WSDL::XMLSchema::Parser::UnknownAttributeError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Parser::UnknownElementError

Class | WSDL::XMLSchema::Parser::UnknownElementError
In: | lib/wsdl/xmlSchema/parser.rb
Parent: | FormatDecodeError


Class: WSDL::XMLSchema::Pattern

Class | WSDL::XMLSchema::Pattern
In: | lib/wsdl/xmlSchema/pattern.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Schema

Class | WSDL::XMLSchema::Schema
In: | lib/wsdl/xmlSchema/schema.rb
Parent: | Info

Methods

collect_attributes collect_complextypes collect_elements collect_simpletypes location location= new parse_attr parse_element parse_element

Attributes

attributeformdefault | [RW]
attributes | [R]
complextypes | [R]
elementformdefault | [RW]
elements | [R]
importedschema | [R]
imports | [R]
simpletypes | [R]
targetnamespace | [R]

Public Class methods

new()
parse_element(element)

Public Instance methods

collect_attributes()
collect_complextypes()
collect_elements()
collect_simpletypes()
location()
location=(location)
parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::Sequence

Class | WSDL::XMLSchema::Sequence
In: | lib/wsdl/xmlSchema/sequence.rb
Parent: | Info

Methods

<< elementformdefault new parse_attr parse_element targetnamespace

Attributes

elements | [R]
maxoccurs | [R]
minoccurs | [R]

Public Class methods

new()

Public Instance methods

<<(element)
elementformdefault()
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::SimpleContent

Class | WSDL::XMLSchema::SimpleContent
In: | lib/wsdl/xmlSchema/simpleContent.rb
Parent: | Info

Methods

base check_lexical_format new parse_element targetnamespace

Attributes

extension | [R]
restriction | [R]

Public Class methods

new()

Public Instance methods

base()
check_lexical_format(value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::SimpleExtension

Class | WSDL::XMLSchema::SimpleExtension
In: | lib/wsdl/xmlSchema/simpleExtension.rb
Parent: | Info

Methods

new parse_attr parse_element targetnamespace valid?

Attributes

attributes | [R]
base | [R]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
targetnamespace()
valid?(value)


Class: WSDL::XMLSchema::SimpleRestriction

Class | WSDL::XMLSchema::SimpleRestriction
In: | lib/wsdl/xmlSchema/simpleRestriction.rb
Parent: | Info

Methods

new parse_attr parse_element valid?

Attributes

base | [R]
enumeration | [R]
length | [RW]
pattern | [RW]

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)
valid?(value)


Class: WSDL::XMLSchema::SimpleType

Class | WSDL::XMLSchema::SimpleType
In: | lib/wsdl/xmlSchema/simpleType.rb
Parent: | Info

Methods

base check_lexical_format new parse_attr parse_element targetnamespace

Attributes

name | [RW]
restriction | [R]

Public Class methods

new(name = nil)

Public Instance methods

base()
check_lexical_format(value)
parse_attr(attr, value)
parse_element(element)
targetnamespace()


Class: WSDL::XMLSchema::Unique

Class | WSDL::XMLSchema::Unique
In: | lib/wsdl/xmlSchema/unique.rb
Parent: | Info

Methods

new parse_attr parse_element

Public Class methods

new()

Public Instance methods

parse_attr(attr, value)
parse_element(element)


Class: WSDL::XMLSchema::XSD2Ruby

Class | WSDL::XMLSchema::XSD2Ruby
In: | lib/wsdl/xmlSchema/xsd2ruby.rb
Parent: | Object

Methods

new run

Attributes

basedir | [RW]
location | [RW]
logger | [RW]
opt | [R]

Public Class methods

new()

Public Instance methods

run()


Class: WeakRef

Class | WeakRef
In: | lib/weakref.rb
Parent: | Delegator

WeakRef is a class to represent a reference to an object that is not seen by the tracing phase of the garbage collector. This allows the referenced object to be garbage collected as if nothing is referring to it. Because WeakRef delegates method calls to the referenced object, it may be used in place of that object, i.e. it is of the same duck type.

Usage:

  foo = Object.new
  foo = Object.new
  p foo.to_s                  # original's class
  foo = WeakRef.new(foo)
  p foo.to_s                  # should be same class
  ObjectSpace.garbage_collect
  p foo.to_s                  # should raise exception (recycled)

Methods

__getobj__ __setobj__ new weakref_alive?

Classes and Modules

Class WeakRef::RefError

Public Class methods

new(orig)

Create a new WeakRef from orig.

Public Instance methods

__getobj__()

Return the object this WeakRef references. Raises RefError if the object has been garbage collected. The object returned is the object to which method calls are delegated (see Delegator).

__setobj__(obj)
weakref_alive?()

Returns true if the referenced object still exists, and false if it has been garbage collected.


Class: WeakRef::RefError

Class | WeakRef::RefError
In: | lib/weakref.rb
Parent: | StandardError

RefError is raised if an object cannot be referenced by a WeakRef.


Module: XML

Module | XML
In: | lib/rss/xmlparser.rb

Classes and Modules

Class XML::Parser


Class: XML::Parser

Class | XML::Parser
In: | lib/rss/xmlparser.rb
Parent: | Object

Constants

Error = ::XMLParserError


Module: XMLEncoding_ja

Module | XMLEncoding_ja
In: | lib/rss/xmlparser.rb

Classes and Modules

Class XMLEncoding_ja::SJISHandler


Class: XMLEncoding_ja::SJISHandler

Class | XMLEncoding_ja::SJISHandler
In: | lib/rss/xmlparser.rb
Parent: | Object

Included Modules

Kconv


Class: XMP

Class | XMP
In: | lib/irb/xmp.rb
Parent: | Object

Methods

new puts

Classes and Modules

Class XMP::StringInputMethod

Public Class methods

new(bind = nil)

Public Instance methods

puts(exps)


Class: XMP::StringInputMethod

Class | XMP::StringInputMethod
In: | lib/irb/xmp.rb
Parent: | IRB::InputMethod

Methods

eof? gets new puts

Public Class methods

new()

Public Instance methods

eof?()
gets()
puts(exps)


Module: XSD

Module | XSD
In: | lib/xsd/xmlparser.rb lib/xsd/mapping.rb lib/xsd/charset.rb lib/xsd/datatypes.rb lib/xsd/codegen/gensupport.rb lib/xsd/codegen/classdef.rb lib/xsd/codegen/moduledef.rb lib/xsd/codegen/methoddef.rb lib/xsd/codegen/commentdef.rb lib/xsd/xmlparser/xmlparser.rb lib/xsd/xmlparser/rexmlparser.rb lib/xsd/xmlparser/xmlscanner.rb lib/xsd/xmlparser/parser.rb lib/xsd/iconvcharset.rb lib/xsd/datatypes1999.rb lib/xsd/qname.rb lib/xsd/namedelements.rb lib/xsd/ns.rb

This program is copyrighted free software by NAKAMURA, Hiroshi. You can redistribute it and/or modify it under the same terms of Ruby‘s license; either the dual license version in 2003, or any later version.

Classes and Modules

Module XSD::Charset
Module XSD::CodeGen
Module XSD::FloatConstants
Module XSD::Mapping
Module XSD::XMLParser
Module XSD::XSDDateTimeImpl
Class XSD::Error
Class XSD::IconvCharset
Class XSD::NS
Class XSD::NSDBase
Class XSD::NamedElements
Class XSD::QName
Class XSD::ValueSpaceError
Class XSD::XSDAnySimpleType
Class XSD::XSDAnyURI
Class XSD::XSDBase64Binary
Class XSD::XSDBoolean
Class XSD::XSDByte
Class XSD::XSDDate
Class XSD::XSDDateTime
Class XSD::XSDDecimal
Class XSD::XSDDouble
Class XSD::XSDDuration
Class XSD::XSDFloat
Class XSD::XSDGDay
Class XSD::XSDGMonth
Class XSD::XSDGMonthDay
Class XSD::XSDGYear
Class XSD::XSDGYearMonth
Class XSD::XSDHexBinary
Class XSD::XSDInt
Class XSD::XSDInteger
Class XSD::XSDLong
Class XSD::XSDNegativeInteger
Class XSD::XSDNil
Class XSD::XSDNonNegativeInteger
Class XSD::XSDNonPositiveInteger
Class XSD::XSDNormalizedString
Class XSD::XSDPositiveInteger
Class XSD::XSDQName
Class XSD::XSDShort
Class XSD::XSDString
Class XSD::XSDTime
Class XSD::XSDUnsignedByte
Class XSD::XSDUnsignedInt
Class XSD::XSDUnsignedLong
Class XSD::XSDUnsignedShort

Constants

Namespace | = | 'http://www.w3.org/2001/XMLSchema'
InstanceNamespace | = | 'http://www.w3.org/2001/XMLSchema-instance'
AttrType | = | 'type'
NilValue | = | 'true'
AnyTypeLiteral | = | 'anyType'
AnySimpleTypeLiteral | = | 'anySimpleType'
NilLiteral | = | 'nil'
StringLiteral | = | 'string'
BooleanLiteral | = | 'boolean'
DecimalLiteral | = | 'decimal'
FloatLiteral | = | 'float'
DoubleLiteral | = | 'double'
DurationLiteral | = | 'duration'
DateTimeLiteral | = | 'dateTime'
TimeLiteral | = | 'time'
DateLiteral | = | 'date'
GYearMonthLiteral | = | 'gYearMonth'
GYearLiteral | = | 'gYear'
GMonthDayLiteral | = | 'gMonthDay'
GDayLiteral | = | 'gDay'
GMonthLiteral | = | 'gMonth'
HexBinaryLiteral | = | 'hexBinary'
Base64BinaryLiteral | = | 'base64Binary'
AnyURILiteral | = | 'anyURI'
QNameLiteral | = | 'QName'
NormalizedStringLiteral | = | 'normalizedString'
IntegerLiteral | = | 'integer' | 3.3.2 token 3.3.3 language 3.3.4 NMTOKEN 3.3.5 NMTOKENS 3.3.6 Name 3.3.7 NCName 3.3.8 ID 3.3.9 IDREF 3.3.10 IDREFS 3.3.11 ENTITY 3.3.12 ENTITIES
NonPositiveIntegerLiteral | = | 'nonPositiveInteger'
NegativeIntegerLiteral | = | 'negativeInteger'
LongLiteral | = | 'long'
IntLiteral | = | 'int'
ShortLiteral | = | 'short'
ByteLiteral | = | 'byte'
NonNegativeIntegerLiteral | = | 'nonNegativeInteger'
UnsignedLongLiteral | = | 'unsignedLong'
UnsignedIntLiteral | = | 'unsignedInt'
UnsignedShortLiteral | = | 'unsignedShort'
UnsignedByteLiteral | = | 'unsignedByte'
PositiveIntegerLiteral | = | 'positiveInteger'
AttrTypeName | = | QName.new(InstanceNamespace, AttrType)
AttrNilName | = | QName.new(InstanceNamespace, NilLiteral)
AnyTypeName | = | QName.new(Namespace, AnyTypeLiteral)
AnySimpleTypeName | = | QName.new(Namespace, AnySimpleTypeLiteral)


Module: XSD::Charset

Module | XSD::Charset
In: | lib/xsd/charset.rb

Methods

charset_label charset_str encoding encoding= encoding_conv encoding_from_xml encoding_to_xml init is_ces is_euc is_sjis is_us_ascii is_utf8 xml_encoding_label

Classes and Modules

Class XSD::Charset::CharsetConversionError
Class XSD::Charset::CharsetError
Class XSD::Charset::UnknownCharsetError
Class XSD::Charset::XSDError

Constants

EncodingConvertMap | = | {} | Maps
CharsetMap | = | { 'NONE' => 'us-ascii', 'EUC' => 'euc-jp', 'SJIS' => 'shift_jis', 'UTF8' => 'utf-8', 'X_ISO_8859_1' => 'iso-8859-1', 'X_UNKNOWN' => nil, }
USASCIIRegexp | = | Regexp.new("\\A#{us_ascii}*\\z", nil, "NONE")
EUCRegexp | = | Regexp.new("\\A#{character_euc}*\\z", nil, "NONE")
SJISRegexp | = | Regexp.new("\\A#{character_sjis}*\\z", nil, "NONE")
UTF8Regexp | = | Regexp.new("\\A#{character_utf8}*\\z", nil, "NONE")

Public Class methods

charset_label(encoding)
charset_str(label)
encoding()

handlers

encoding=(encoding)
encoding_conv(str, enc_from, enc_to)
encoding_from_xml(str, charset)
encoding_to_xml(str, charset)
init()
is_ces(str, code = $KCODE)
is_euc(str)
is_sjis(str)
is_us_ascii(str)
is_utf8(str)
xml_encoding_label()


Class: XSD::Charset::CharsetConversionError

Class | XSD::Charset::CharsetConversionError
In: | lib/xsd/charset.rb
Parent: | CharsetError


Class: XSD::Charset::CharsetError

Class | XSD::Charset::CharsetError
In: | lib/xsd/charset.rb
Parent: | XSDError


Class: XSD::Charset::UnknownCharsetError

Class | XSD::Charset::UnknownCharsetError
In: | lib/xsd/charset.rb
Parent: | CharsetError


Class: XSD::Charset::XSDError

Class | XSD::Charset::XSDError
In: | lib/xsd/charset.rb
Parent: | StandardError


Module: XSD::CodeGen

Module | XSD::CodeGen
In: | lib/xsd/codegen/gensupport.rb lib/xsd/codegen/classdef.rb lib/xsd/codegen/moduledef.rb lib/xsd/codegen/methoddef.rb lib/xsd/codegen/commentdef.rb

Classes and Modules

Module XSD::CodeGen::CommentDef
Module XSD::CodeGen::GenSupport
Class XSD::CodeGen::ClassDef
Class XSD::CodeGen::MethodDef
Class XSD::CodeGen::ModuleDef

Constants

KEYWORD = {} from the file ‘keywords’ in 1.9.


Class: XSD::CodeGen::ClassDef

Class | XSD::CodeGen::ClassDef
In: | lib/xsd/codegen/classdef.rb
Parent: | ModuleDef

Methods

def_attr def_classvar dump new

Included Modules

GenSupport

Public Class methods

new(name, baseclass = nil)

Public Instance methods

def_attr(attrname, writable = true, varname = nil)
def_classvar(var, value)
dump()


Module: XSD::CodeGen::CommentDef

Module | XSD::CodeGen::CommentDef
In: | lib/xsd/codegen/commentdef.rb

Included Modules

GenSupport

Attributes

comment [RW]


Module: XSD::CodeGen::GenSupport

Module | XSD::CodeGen::GenSupport
In: | lib/xsd/codegen/gensupport.rb

Methods

capitalize format keyword? safeconstname safeconstname? safemethodname safemethodname? safevarname safevarname? uncapitalize

Public Instance methods

capitalize(target)
format(str, indent = nil)
keyword?(word)
safeconstname(name)
safeconstname?(name)
safemethodname(name)
safemethodname?(name)
safevarname(name)
safevarname?(name)
uncapitalize(target)


Class: XSD::CodeGen::MethodDef

Class | XSD::CodeGen::MethodDef
In: | lib/xsd/codegen/methoddef.rb
Parent: | Object

Methods

dump new

Included Modules

GenSupport CommentDef

Attributes

definition [RW]

Public Class methods

new(name, *params) {|if block_given?| ...}

Public Instance methods

dump()


Class: XSD::CodeGen::ModuleDef

Class | XSD::CodeGen::ModuleDef
In: | lib/xsd/codegen/moduledef.rb
Parent: | Object

Methods

add_method def_code def_const def_method def_privatemethod def_protectedmethod def_publicmethod def_require dump new

Included Modules

GenSupport CommentDef

Public Class methods

new(name)

Public Instance methods

add_method(m, visibility = :public)
def_code(code)
def_const(const, value)
def_method(name, *params) {|if block_given?| ...}
def_privatemethod(name, *params) {|if block_given?| ...}
def_protectedmethod(name, *params) {|if block_given?| ...}
def_publicmethod(name, *params)

Alias for def_method

def_require(path)
dump()


Class: XSD::Error

Class | XSD::Error
In: | lib/xsd/datatypes.rb
Parent: | StandardError


Module: XSD::FloatConstants

Module | XSD::FloatConstants
In: | lib/xsd/datatypes.rb

Constants

NaN | = | 0.0/0.0
POSITIVE_INF | = | +1.0/0.0
NEGATIVE_INF | = | -1.0/0.0
POSITIVE_ZERO | = | +1.0/POSITIVE_INF
NEGATIVE_ZERO | = | -1.0/POSITIVE_INF
MIN_POSITIVE_SINGLE | = | 2.0 ** -149


Class: XSD::IconvCharset

Class | XSD::IconvCharset
In: | lib/xsd/iconvcharset.rb
Parent: | Object

Methods

safe_iconv

Public Class methods

safe_iconv(to, from, str)


Module: XSD::Mapping

Module | XSD::Mapping
In: | lib/xsd/mapping.rb

Methods

obj2xml xml2obj

Constants

MappingRegistry | = | SOAP::Mapping::WSDLLiteralRegistry.new
MappingOpt | = | {:default_encodingstyle => SOAP::LiteralNamespace}

Public Class methods

obj2xml(obj, elename = nil, io = nil)
xml2obj(stream)


Class: XSD::NS

Class | XSD::NS
In: | lib/xsd/ns.rb
Parent: | Object

Methods

assign assigned? assigned_tag? assigner= clone_ns compare each_ns name new parse parse_local

Classes and Modules

Class XSD::NS::Assigner
Class XSD::NS::FormatError

Constants

ParseRegexp = Regexp.new('^([^:]+)(?::(.+))?$') $1 and $2 are necessary.

Attributes

default_namespace [R]

Public Class methods

new(tag2ns = {})

Public Instance methods

assign(ns, tag = nil)
assigned?(ns)
assigned_tag?(tag)
clone_ns()
compare(ns, name, rhs)
each_ns() {|ns, tag| ...}
name(name)
parse(str, local = false)
parse_local(elem)

For local attribute key parsing

  <foo xmlns="urn:a" xmlns:n1="urn:a" bar="1" n1:baz="2" />
    =>
  {}bar, {urn:a}baz

Protected Instance methods

assigner=(assigner)


Class: XSD::NS::Assigner

Class | XSD::NS::Assigner
In: | lib/xsd/ns.rb
Parent: | Object

Methods

assign new

Public Class methods

new()

Public Instance methods

assign(ns)


Class: XSD::NS::FormatError

Class | XSD::NS::FormatError
In: | lib/xsd/ns.rb
Parent: | Error


Class: XSD::NSDBase

Class | XSD::NSDBase
In: | lib/xsd/datatypes.rb
Parent: | Object

The base class of all datatypes with Namespace.

Methods

inherited init new types

Attributes

type [RW]

Public Class methods

inherited(klass)
new()
types()

Public Instance methods

init(type)


Class: XSD::NamedElements

Class | XSD::NamedElements
In: | lib/xsd/namedelements.rb
Parent: | Object

Methods

+ << [] concat delete dup each elements elements= empty? find_name freeze keys new size

Included Modules

Enumerable

Constants

Empty = NamedElements.new.freeze

Public Class methods

new()

Public Instance methods

+(rhs)
<<(rhs)
[](idx)
concat(rhs)
delete(rhs)
dup()
each() {|element| ...}
empty?()
find_name(name)
freeze()
keys()
size()

Protected Instance methods

elements()
elements=(rhs)


Class: XSD::QName

Class | XSD::QName
In: | lib/xsd/qname.rb
Parent: | Object

Methods

== === dump dup_name eql? hash inspect match new parse to_s

Constants

NormalizedNameRegexp | = | /^\{([^}]*)\}(.*)$/
EMPTY | = | QName.new.freeze

Attributes

name | [RW]
namespace | [RW]
source | [RW]

Public Class methods

new(namespace = nil, name = nil)

Public Instance methods

==(rhs)
===(rhs)
dump()
dup_name(name)
eql?(rhs)
hash()
inspect()
match(rhs)
parse(str)
to_s()


Class: XSD::ValueSpaceError

Class | XSD::ValueSpaceError
In: | lib/xsd/datatypes.rb
Parent: | Error


Module: XSD::XMLParser

Module | XSD::XMLParser
In: | lib/xsd/xmlparser.rb lib/xsd/xmlparser/xmlparser.rb lib/xsd/xmlparser/rexmlparser.rb lib/xsd/xmlparser/xmlscanner.rb lib/xsd/xmlparser/parser.rb

Methods

create_parser filter_ns

Classes and Modules

Class XSD::XMLParser::Parser
Class XSD::XMLParser::REXMLParser
Class XSD::XMLParser::XMLParser
Class XSD::XMLParser::XMLScanner

Constants

NSParseRegexp = Regexp.new('^xmlns:?(.*)$') $1 is necessary.

Public Instance methods

create_parser(host, opt)
filter_ns(ns, attrs)


Class: XSD::XMLParser::Parser

Class | XSD::XMLParser::Parser
In: | lib/xsd/xmlparser/parser.rb
Parent: | Object

Methods

add_factory create_parser factory new parse

Classes and Modules

Class XSD::XMLParser::Parser::ElementConstraintError
Class XSD::XMLParser::Parser::FormatDecodeError
Class XSD::XMLParser::Parser::ParseError
Class XSD::XMLParser::Parser::UnexpectedElementError
Class XSD::XMLParser::Parser::UnknownAttributeError
Class XSD::XMLParser::Parser::UnknownElementError

Attributes

charset [RW]

Public Class methods

add_factory(factory)
create_parser(host, opt = {})
factory()
new(host, opt = {})

Public Instance methods

parse(string_or_readable)


Class: XSD::XMLParser::Parser::ElementConstraintError

Class | XSD::XMLParser::Parser::ElementConstraintError
In: | lib/xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::Parser::FormatDecodeError

Class | XSD::XMLParser::Parser::FormatDecodeError
In: | lib/xsd/xmlparser/parser.rb
Parent: | ParseError


Class: XSD::XMLParser::Parser::ParseError

Class | XSD::XMLParser::Parser::ParseError
In: | lib/xsd/xmlparser/parser.rb
Parent: | Error


Class: XSD::XMLParser::Parser::UnexpectedElementError

Class | XSD::XMLParser::Parser::UnexpectedElementError
In: | lib/xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::Parser::UnknownAttributeError

Class | XSD::XMLParser::Parser::UnknownAttributeError
In: | lib/xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::Parser::UnknownElementError

Class | XSD::XMLParser::Parser::UnknownElementError
In: | lib/xsd/xmlparser/parser.rb
Parent: | FormatDecodeError


Class: XSD::XMLParser::REXMLParser

Class | XSD::XMLParser::REXMLParser
In: | lib/xsd/xmlparser/rexmlparser.rb
Parent: | XSD::XMLParser::Parser

Methods

do_parse epilogue tag_end tag_start text xmldecl

Included Modules

REXML::StreamListener

Public Instance methods

do_parse(string_or_readable)
epilogue()
tag_end(name)
tag_start(name, attrs)
text(text)
xmldecl(version, encoding, standalone)


Class: XSD::XMLParser::XMLParser

Class | XSD::XMLParser::XMLParser
In: | lib/xsd/xmlparser/xmlparser.rb
Parent: | XSD::XMLParser::Parser

Methods

do_parse

Classes and Modules

Class XSD::XMLParser::XMLParser::Listener

Public Instance methods

do_parse(string_or_readable)


Class: XSD::XMLParser::XMLParser::Listener

Class | XSD::XMLParser::XMLParser::Listener
In: | lib/xsd/xmlparser/xmlparser.rb
Parent: | XML::Parser

Included Modules

XML::Encoding_ja


Class: XSD::XMLParser::XMLScanner

Class | XSD::XMLParser::XMLScanner
In: | lib/xsd/xmlparser/xmlscanner.rb
Parent: | XSD::XMLParser::Parser

Methods

do_parse on_attr_charref on_attr_charref_hex on_attr_entityref on_attr_value on_attribute on_chardata on_charref on_charref_hex on_entityref on_etag on_stag on_stag_end on_stag_end_empty on_xmldecl_encoding on_xmldecl_version parse_error scanner_kcode= valid_error warning wellformed_error

Included Modules

XMLScan::Visitor

Constants

ENTITY_REF_MAP = { 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '"', 'apos' => '\''

Public Instance methods

do_parse(string_or_readable)
on_attr_charref(code)
on_attr_charref_hex(code)
on_attr_entityref(ref)
on_attr_value(str)
on_attribute(name)
on_chardata(str)

def on_pi(target, pi); end

on_charref(code)
on_charref_hex(code)
on_entityref(ref)
on_etag(name)

def on_cdata(str); end

on_stag(name)

def on_end_document; end

on_stag_end(name)
on_stag_end_empty(name)

def on_attribute_end(name); end

on_xmldecl_encoding(str)
on_xmldecl_version(str)

def on_xmldecl; end

parse_error(msg)
scanner_kcode=(charset)
valid_error(msg)
warning(msg)
wellformed_error(msg)


Class: XSD::XSDAnySimpleType

Class | XSD::XSDAnySimpleType
In: | lib/xsd/datatypes.rb
Parent: | NSDBase

The base class of XSD datatypes.

Methods

check_lexical_format new set to_s

Included Modules

XSD

Constants

Type = QName.new(Namespace, AnySimpleTypeLiteral)

Attributes

data | [R] | @data represents canonical space (ex. Integer: 123).
is_nil | [RW] | @is_nil represents this data is nil or not.

Public Class methods

new(value = nil)

Public Instance methods

check_lexical_format(value)

true or raise

set(value)

set accepts a string which follows lexical space (ex. String: "+123"), or an object which follows canonical space (ex. Integer: 123).

to_s()

to_s creates a string which follows lexical space (ex. String: "123").


Class: XSD::XSDAnyURI

Class | XSD::XSDAnyURI
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, AnyURILiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDBase64Binary

Class | XSD::XSDBase64Binary
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new set_encoded string

Constants

Type = QName.new(Namespace, Base64BinaryLiteral)

Public Class methods

new(value = nil)

String in Ruby could be a binary.

Public Instance methods

set_encoded(value)
string()


Class: XSD::XSDBoolean

Class | XSD::XSDBoolean
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, BooleanLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDByte

Class | XSD::XSDByte
In: | lib/xsd/datatypes.rb
Parent: | XSDShort

Methods

new

Constants

Type = QName.new(Namespace, ByteLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDDate

Class | XSD::XSDDate
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, DateLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDDateTime

Class | XSD::XSDDateTime
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, DateTimeLiteral)

Public Class methods

new(value = nil)


Module: XSD::XSDDateTimeImpl

Module | XSD::XSDDateTimeImpl
In: | lib/xsd/datatypes.rb

Methods

add_tz of2tz screen_data to_date to_datetime to_obj to_time tz2of

Constants

SecInDay = 86400

Public Instance methods

add_tz(s)
of2tz(offset)
screen_data(t)
to_date()
to_datetime()
to_obj(klass)
to_time()
tz2of(str)


Class: XSD::XSDDecimal

Class | XSD::XSDDecimal
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new nonzero?

Constants

Type = QName.new(Namespace, DecimalLiteral)

Public Class methods

new(value = nil)

Public Instance methods

nonzero?()


Class: XSD::XSDDouble

Class | XSD::XSDDouble
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Ruby‘s Float is double-precision 64-bit floating point value.

Methods

new

Included Modules

FloatConstants

Constants

Type = QName.new(Namespace, DoubleLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDDuration

Class | XSD::XSDDuration
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, DurationLiteral)

Attributes

day | [RW]
hour | [RW]
min | [RW]
month | [RW]
sec | [RW]
sign | [RW]
year | [RW]

Public Class methods

new(value = nil)


Class: XSD::XSDFloat

Class | XSD::XSDFloat
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

FloatConstants

Constants

Type = QName.new(Namespace, FloatLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDGDay

Class | XSD::XSDGDay
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GDayLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDGMonth

Class | XSD::XSDGMonth
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GMonthLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDGMonthDay

Class | XSD::XSDGMonthDay
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GMonthDayLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDGYear

Class | XSD::XSDGYear
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GYearLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDGYearMonth

Class | XSD::XSDGYearMonth
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, GYearMonthLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDHexBinary

Class | XSD::XSDHexBinary
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new set_encoded string

Constants

Type = QName.new(Namespace, HexBinaryLiteral)

Public Class methods

new(value = nil)

String in Ruby could be a binary.

Public Instance methods

set_encoded(value)
string()


Class: XSD::XSDInt

Class | XSD::XSDInt
In: | lib/xsd/datatypes.rb
Parent: | XSDLong

Methods

new

Constants

Type = QName.new(Namespace, IntLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDInteger

Class | XSD::XSDInteger
In: | lib/xsd/datatypes.rb
Parent: | XSDDecimal

Methods

new

Constants

Type | = | QName.new(Namespace, IntegerLiteral)
PositiveMinInclusive | = | 1

Public Class methods

new(value = nil)


Class: XSD::XSDLong

Class | XSD::XSDLong
In: | lib/xsd/datatypes.rb
Parent: | XSDInteger

Methods

new

Constants

Type = QName.new(Namespace, LongLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDNegativeInteger

Class | XSD::XSDNegativeInteger
In: | lib/xsd/datatypes.rb
Parent: | XSDNonPositiveInteger

Methods

new

Constants

Type = QName.new(Namespace, NegativeIntegerLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDNil

Class | XSD::XSDNil
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type | = | QName.new(Namespace, NilLiteral)
Value | = | 'true'

Public Class methods

new(value = nil)


Class: XSD::XSDNonNegativeInteger

Class | XSD::XSDNonNegativeInteger
In: | lib/xsd/datatypes.rb
Parent: | XSDInteger

Methods

new

Constants

Type = QName.new(Namespace, NonNegativeIntegerLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDNonPositiveInteger

Class | XSD::XSDNonPositiveInteger
In: | lib/xsd/datatypes.rb
Parent: | XSDInteger

Methods

new

Constants

Type = QName.new(Namespace, NonPositiveIntegerLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDNormalizedString

Class | XSD::XSDNormalizedString
In: | lib/xsd/datatypes.rb
Parent: | XSDString

Derived types

Methods

new

Constants

Type = QName.new(Namespace, NormalizedStringLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDPositiveInteger

Class | XSD::XSDPositiveInteger
In: | lib/xsd/datatypes.rb
Parent: | XSDNonNegativeInteger

Methods

new

Constants

Type = QName.new(Namespace, PositiveIntegerLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDQName

Class | XSD::XSDQName
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Constants

Type = QName.new(Namespace, QNameLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDShort

Class | XSD::XSDShort
In: | lib/xsd/datatypes.rb
Parent: | XSDInt

Methods

new

Constants

Type = QName.new(Namespace, ShortLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDString

Class | XSD::XSDString
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Primitive datatypes.

Methods

new

Constants

Type = QName.new(Namespace, StringLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDTime

Class | XSD::XSDTime
In: | lib/xsd/datatypes.rb
Parent: | XSDAnySimpleType

Methods

new

Included Modules

XSDDateTimeImpl

Constants

Type = QName.new(Namespace, TimeLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDUnsignedByte

Class | XSD::XSDUnsignedByte
In: | lib/xsd/datatypes.rb
Parent: | XSDUnsignedShort

Methods

new

Constants

Type = QName.new(Namespace, UnsignedByteLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDUnsignedInt

Class | XSD::XSDUnsignedInt
In: | lib/xsd/datatypes.rb
Parent: | XSDUnsignedLong

Methods

new

Constants

Type = QName.new(Namespace, UnsignedIntLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDUnsignedLong

Class | XSD::XSDUnsignedLong
In: | lib/xsd/datatypes.rb
Parent: | XSDNonNegativeInteger

Methods

new

Constants

Type = QName.new(Namespace, UnsignedLongLiteral)

Public Class methods

new(value = nil)


Class: XSD::XSDUnsignedShort

Class | XSD::XSDUnsignedShort
In: | lib/xsd/datatypes.rb
Parent: | XSDUnsignedInt

Methods

new

Constants

Type = QName.new(Namespace, UnsignedShortLiteral)

Public Class methods

new(value = nil)


Module: YAML

Module | YAML
In: | lib/yaml/constants.rb lib/yaml/baseemitter.rb lib/yaml/loader.rb lib/yaml/ypath.rb lib/yaml/dbm.rb lib/yaml/types.rb lib/yaml/yamlnode.rb lib/yaml/stream.rb lib/yaml/syck.rb lib/yaml/encoding.rb lib/yaml/basenode.rb lib/yaml/tag.rb lib/yaml/error.rb lib/yaml.rb

YAML

YAML(tm) (rhymes with ‘camel’) is a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages such as Perl and Python. YAML is optimized for data serialization, formatted dumping, configuration files, log files, Internet messaging and filtering. This specification describes the YAML information model and serialization format. Together with the Unicode standard for characters, it provides all the information necessary to understand YAML Version 1.0 and construct computer programs to process it.

See yaml.org/ for more information. For a quick tutorial, please visit YAML In Five Minutes (yaml.kwiki.org/?YamlInFiveMinutes).

About This Library

The YAML 1.0 specification outlines four stages of YAML loading and dumping. This library honors all four of those stages, although data is really only available to you in three stages.

The four stages are: native, representation, serialization, and presentation.

The native stage refers to data which has been loaded completely into Ruby‘s own types. (See +YAML::load+.)

The representation stage means data which has been composed into +YAML::BaseNode+ objects. In this stage, the document is available as a tree of node objects. You can perform YPath queries and transformations at this level. (See +YAML::parse+.)

The serialization stage happens inside the parser. The YAML parser used in Ruby is called Syck. Serialized nodes are available in the extension as SyckNode structs.

The presentation stage is the YAML document itself. This is accessible to you as a string. (See +YAML::dump+.)

For more information about the various information models, see Chapter 3 of the YAML 1.0 Specification (yaml.org/spec/#id2491269).

The YAML module provides quick access to the most common loading (YAML::load) and dumping (YAML::dump) tasks. This module also provides an API for registering global types (YAML::add_domain_type).

Example

A simple round-trip (load and dump) of an object.

    require "yaml"

    test_obj = ["dogs", "cats", "badgers"]

    yaml_obj = YAML::dump( test_obj )
                        # -> ---
                             - dogs
                             - cats
                             - badgers
    ruby_obj = YAML::load( yaml_obj )
                        # => ["dogs", "cats", "badgers"]
    ruby_obj == test_obj
                        # => true

To register your custom types with the global resolver, use add_domain_type.

    YAML::add_domain_type( "your-site.com,2004", "widget" ) do |type, val|
        Widget.new( val )
    end

Methods

add_builtin_type add_domain_type add_private_type add_ruby_type detect_implicit dump dump_stream each_document each_node emitter escape generic_parser load load_documents load_file load_stream make_stream object_maker parse parse_documents parse_file parser quick_emit read_type_class resolver tag_class tagged_classes tagurize transfer try_implicit unescape

Classes and Modules

Module YAML::BaseEmitter
Module YAML::BaseNode
Module YAML::Syck
Class YAML::DBM
Class YAML::DomainType
Class YAML::Error
Class YAML::Loader
Class YAML::Mapping
Class YAML::Object
Class YAML::Omap
Class YAML::Pairs
Class YAML::ParseError
Class YAML::PrivateType
Class YAML::Sequence
Class YAML::Set
Class YAML::SpecialHash
Class YAML::Store
Class YAML::Stream
Class YAML::TypeError
Class YAML::YPath
Class YAML::YamlNode

Constants

VERSION | = | '0.60' | Constants
SUPPORTED_YAML_VERSIONS | = | ['1.0']
WORD_CHAR | = | 'A-Za-z0-9' | Parser tokens
PRINTABLE_CHAR | = | '-_A-Za-z0-9!?/()$\'". '
NOT_PLAIN_CHAR | = | '\x7f\x0-\x1f\x80-\x9f'
ESCAPE_CHAR | = | '[\\x00-\\x09\\x0b-\\x1f]'
INDICATOR_CHAR | = | '*&!|\\\\^@%{}[]='
SPACE_INDICATORS | = | '-#:,?'
RESTRICTED_INDICATORS | = | '#:,}]'
DNS_COMP_RE | = | "\\w(?:[-\\w]*\\w)?"
DNS_NAME_RE | = | "(?:(?:#{DNS_COMP_RE}\\.)+#{DNS_COMP_RE}|#{DNS_COMP_RE})"
ESCAPES | = | %w{\x00 \x01 \x02 \x03 \x04 \x05 \x06 \a \x08 \t \n \v \f \r \x0e \x0f \x10 \x11 \x12 \x13 \x14 \x15 \x16 \x17 \x18 \x19 \x1a \e \x1c \x1d \x1e \x1f }
UNESCAPES | = | { 'a' => "\x07", 'b' => "\x08", 't' => "\x09", 'n' => "\x0a", 'v' => "\x0b", 'f' => "\x0c", 'r' => "\x0d", 'e' => "\x1b", '\\' => '\\', }
DEFAULTS | = | { :Indent => 2, :UseHeader => false, :UseVersion => false, :Version => '1.0', :SortKeys => false, :AnchorFormat => 'id%03d', :ExplicitTypes => false, :WidthType => 'absolute', :BestWidth => 80, :UseBlock => false, :UseFold => false, :Encoding => :None | Default settings
ERROR_NO_HEADER_NODE | = | "With UseHeader=false, the node Array or Hash must have elements" | Error messages
ERROR_NEED_HEADER | = | "With UseHeader=false, the node must be an Array or Hash"
ERROR_BAD_EXPLICIT | = | "Unsupported explicit transfer: '%s'"
ERROR_MANY_EXPLICIT | = | "More than one explicit transfer"
ERROR_MANY_IMPLICIT | = | "More than one implicit request"
ERROR_NO_ANCHOR | = | "No anchor for alias '%s'"
ERROR_BAD_ANCHOR | = | "Invalid anchor: %s"
ERROR_MANY_ANCHOR | = | "More than one anchor"
ERROR_ANCHOR_ALIAS | = | "Can't define both an anchor and an alias"
ERROR_BAD_ALIAS | = | "Invalid alias: %s"
ERROR_MANY_ALIAS | = | "More than one alias"
ERROR_ZERO_INDENT | = | "Can't use zero as an indentation width"
ERROR_UNSUPPORTED_VERSION | = | "This release of YAML.rb does not support YAML version %s"
ERROR_UNSUPPORTED_ENCODING | = | "Attempt to use unsupported encoding: %s"
Resolver | = | YAML::Syck::Resolver
DefaultResolver | = | YAML::Syck::DefaultResolver
GenericResolver | = | YAML::Syck::GenericResolver
Parser | = | YAML::Syck::Parser
Emitter | = | YAML::Syck::Emitter

Public Class methods

add_builtin_type( type_tag, &transfer_proc )

Add a transfer method for a builtin type

add_domain_type( domain, type_tag, &transfer_proc )

Add a global handler for a YAML domain type.

add_private_type( type_re, &transfer_proc )

Add a private document type

add_ruby_type( type_tag, &transfer_proc )

Add a transfer method for a builtin type

detect_implicit( val )

Detect typing of a string

dump( obj, io = nil )

Converts obj to YAML and writes the YAML result to io.

  File.open( 'animals.yaml', 'w' ) do |out|
    YAML.dump( ['badger', 'elephant', 'tiger'], out )
  end

If no io is provided, a string containing the dumped YAML is returned.

  YAML.dump( :locked )
     #=> "--- :locked"
dump_stream( *objs )

Returns a YAML stream containing each of the items in objs, each having their own document.

  YAML.dump_stream( 0, [], {} )
    #=> --- 0
        --- []
        --- {}
each_document( io, &block )

Calls block with each consecutive document in the YAML stream contained in io.

  File.open( 'many-docs.yaml' ) do |yf|
    YAML.each_document( yf ) do |ydoc|
      ## ydoc contains the single object
      ## from the YAML document
    end
  end
each_node( io, &doc_proc )

Calls block with a tree of +YAML::BaseNodes+, one tree for each consecutive document in the YAML stream contained in io.

  File.open( 'many-docs.yaml' ) do |yf|
    YAML.each_node( yf ) do |ydoc|
      ## ydoc contains a tree of nodes
      ## from the YAML document
    end
  end
emitter()

Returns a new default emitter

escape( value, skip = "" )

Escape the string, condensing common escapes

generic_parser()

Returns a new generic parser

load( io )

Load a document from the current io stream.

  File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) }
     #=> ['badger', 'elephant', 'tiger']

Can also load from a string.

  YAML.load( "--- :locked" )
     #=> :locked
load_documents( io, &doc_proc )

Calls block with each consecutive document in the YAML stream contained in io.

  File.open( 'many-docs.yaml' ) do |yf|
    YAML.load_documents( yf ) do |ydoc|
      ## ydoc contains the single object
      ## from the YAML document
    end
  end
load_file( filepath )

Load a document from the file located at filepath.

  YAML.load_file( 'animals.yaml' )
     #=> ['badger', 'elephant', 'tiger']
load_stream( io )

Loads all documents from the current io stream, returning a +YAML::Stream+ object containing all loaded documents.

make_stream( io )

Class method for creating streams

object_maker( obj_class, val )

Allocate blank object

parse( io )

Parse the first document from the current io stream

  File.open( 'animals.yaml' ) { |yf| YAML::load( yf ) }
     #=> #<YAML::Syck::Node:0x82ccce0
          @kind=:seq,
          @value=
           [#<YAML::Syck::Node:0x82ccd94
             @kind=:scalar,
             @type_id="str",
             @value="badger">,
            #<YAML::Syck::Node:0x82ccd58
             @kind=:scalar,
             @type_id="str",
             @value="elephant">,
            #<YAML::Syck::Node:0x82ccd1c
             @kind=:scalar,
             @type_id="str",
             @value="tiger">]>

Can also load from a string.

  YAML.parse( "--- :locked" )
     #=> #<YAML::Syck::Node:0x82edddc
           @type_id="tag:ruby.yaml.org,2002:sym",
           @value=":locked", @kind=:scalar>
parse_documents( io, &doc_proc )

Calls block with a tree of +YAML::BaseNodes+, one tree for each consecutive document in the YAML stream contained in io.

  File.open( 'many-docs.yaml' ) do |yf|
    YAML.parse_documents( yf ) do |ydoc|
      ## ydoc contains a tree of nodes
      ## from the YAML document
    end
  end
parse_file( filepath )

Parse a document from the file located at filepath.

  YAML.parse_file( 'animals.yaml' )
     #=> #<YAML::Syck::Node:0x82ccce0
          @kind=:seq,
          @value=
           [#<YAML::Syck::Node:0x82ccd94
             @kind=:scalar,
             @type_id="str",
             @value="badger">,
            #<YAML::Syck::Node:0x82ccd58
             @kind=:scalar,
             @type_id="str",
             @value="elephant">,
            #<YAML::Syck::Node:0x82ccd1c
             @kind=:scalar,
             @type_id="str",
             @value="tiger">]>
parser()

Returns a new default parser

quick_emit( oid, opts = {}, &e )

Allocate an Emitter if needed

read_type_class( type, obj_class )

Method to extract colon-seperated type and class, returning the type and the constant of the class

resolver()

Returns the default resolver

tag_class( tag, cls )

Associates a taguri tag with a Ruby class cls. The taguri is used to give types to classes when loading YAML. Taguris are of the form:

  tag:authorityName,date:specific

The authorityName is a domain name or email address. The date is the date the type was issued in YYYY or YYYY-MM or YYYY-MM-DD format. The specific is a name for the type being added.

For example, built-in YAML types have ‘yaml.org’ as the authorityName and ‘2002’ as the date. The specific is simply the name of the type:

 tag:yaml.org,2002:int
 tag:yaml.org,2002:float
 tag:yaml.org,2002:timestamp

The domain must be owned by you on the date declared. If you don‘t own any domains on the date you declare the type, you can simply use an e-mail address.

 tag:why@ruby-lang.org,2004:notes/personal
tagged_classes()

Returns the complete dictionary of taguris, paired with classes. The key for the dictionary is the full taguri. The value for each key is the class constant associated to that taguri.

 YAML.tagged_classes["tag:yaml.org,2002:int"] => Integer
tagurize( val )

Convert a type_id to a taguri

transfer( type_id, obj )

Apply a transfer method to a Ruby object

try_implicit( obj )

Apply any implicit a node may qualify for

unescape( value )

Unescape the condenses escapes


Module: YAML::BaseEmitter

Module | YAML::BaseEmitter
In: | lib/yaml/baseemitter.rb

Methods

binary_base64 double fold indent indent! indent_text map node_text options options= seq seq_map_shortcut simple single

Public Instance methods

binary_base64( value )

Emit binary data

double( value )

Emit double-quoted string

fold( value )

Folding paragraphs within a column

indent( mod = nil )

Write a current indent

indent!()

Add indent to the buffer

indent_text( text, mod, first_line = true )

Write a text block with the current indent

map( type, &e )

Quick mapping

node_text( value, block = nil )

Emit plain, normal flowing text

options( opt = nil )
options=( opt )
seq( type, &e )

Quick sequence

seq_map_shortcut()
simple( value )

Emit a simple, unqouted string

single( value )

Emit single-quoted string


Module: YAML::BaseNode

Module | YAML::BaseNode
In: | lib/yaml/basenode.rb

YAML Generic Model container

Methods

[] at children children_with_index emit match_path match_segment search select select!

Public Instance methods

[]( *key )

We want the node to act like as Hash if it is.

at( seg )
children()
children_with_index()
emit()
match_path( ypath_str )

YPath search returning a complete depth array

match_segment( ypath, depth )

Search a node for a single YPath segment

search( ypath_str )

Search for YPath entry and return a list of qualified paths.

select( ypath_str )

Search for YPath entry and return qualified nodes.

select!( ypath_str )

Search for YPath entry and return transformed nodes.


Class: YAML::DBM

Class | YAML::DBM
In: | lib/yaml/dbm.rb
Parent: | ::DBM

Methods

[] []= delete delete_if each each_pair each_value fetch has_value? index invert reject replace select shift store to_a to_hash update values values_at

Constants

VERSION = "0.1"

Public Instance methods

[]( key )
[]=( key, val )
delete( key )
delete_if() {|k, fetch( k )| ...}
each()

Alias for each_pair

each_pair() {|k, fetch( k ) }| ...}
each_value() {|YAML::load( v ) }| ...}
fetch( keystr, ifnone = nil ) {|keystr| ...}
has_value?( val )
index( keystr )
invert()
reject() {|k, v| ...}
replace( hsh )
select( *keys ) {|k, v| ...}
shift()
store( key, val )
to_a()
to_hash()
update( hsh )
values()
values_at( *keys )


Class: YAML::DomainType

Class | YAML::DomainType
In: | lib/yaml/types.rb
Parent: | Object

Default domain type

Methods

new tag_subclasses? to_yaml

Attributes

domain | [RW]
type_id | [RW]
value | [RW]

Public Class methods

new( domain, type, val )
tag_subclasses?()

Public Instance methods

to_yaml( opts = {} )


Class: YAML::Error

Class | YAML::Error
In: | lib/yaml/error.rb
Parent: | StandardError

YAML Error classes


Class: YAML::Loader

Class | YAML::Loader
In: | lib/yaml/loader.rb
Parent: | Object

Constants

TRANSFER_DOMAINS | = | { 'yaml.org,2002' => {}, 'ruby.yaml.org,2002' => {}
PRIVATE_TYPES | = | {}
IMPLICIT_TYPES | = | [ 'null', 'bool', 'time', 'int', 'float' ]


Class: YAML::Mapping

Class | YAML::Mapping
In: | lib/yaml/baseemitter.rb
Parent: | Array

Emitter helper classes

Methods

add

Public Instance methods

add( k, v )


Class: YAML::Object

Class | YAML::Object
In: | lib/yaml/types.rb
Parent: | Object

Unresolved objects

Methods

tag_subclasses? to_yaml

Public Class methods

tag_subclasses?()

Public Instance methods

to_yaml( opts = {} )


Class: YAML::Omap

Class | YAML::Omap
In: | lib/yaml/types.rb
Parent: | ::Array

Builtin collection: !omap

Methods

[] [] []= has_key? is_complex_yaml? to_yaml yaml_initialize

Public Class methods

[]( *vals )

Public Instance methods

[]( k )
[]=( k, *rest )
has_key?( k )
is_complex_yaml?()
to_yaml( opts = {} )
yaml_initialize( tag, val )


Class: YAML::Pairs

Class | YAML::Pairs
In: | lib/yaml/types.rb
Parent: | ::Array

Builtin collection: !pairs

Methods

[] [] []= has_key? is_complex_yaml? to_yaml yaml_initialize

Public Class methods

[]( *vals )

Public Instance methods

[]( k )
[]=( k, val )
has_key?( k )
is_complex_yaml?()
to_yaml( opts = {} )
yaml_initialize( tag, val )


Class: YAML::ParseError

Class | YAML::ParseError
In: | lib/yaml/error.rb
Parent: | Error


Class: YAML::PrivateType

Class | YAML::PrivateType
In: | lib/yaml/types.rb
Parent: | Object

Default private type

Methods

new tag_subclasses? to_yaml

Attributes

type_id | [RW]
value | [RW]

Public Class methods

new( type, val )
tag_subclasses?()

Public Instance methods

to_yaml( opts = {} )


Class: YAML::Sequence

Class | YAML::Sequence
In: | lib/yaml/baseemitter.rb
Parent: | Array

Methods

add

Public Instance methods

add( v )


Class: YAML::Set

Class | YAML::Set
In: | lib/yaml/types.rb
Parent: | ::Hash

Builtin collection: !set


Class: YAML::SpecialHash

Class | YAML::SpecialHash
In: | lib/yaml/types.rb
Parent: | ::Hash

YAML Hash class to support comments and defaults

Methods

inspect to_s to_yaml update

Attributes

default [RW]

Public Instance methods

inspect()
to_s()
to_yaml( opts = {} )
update( h )


Class: YAML::Store

Class | YAML::Store
In: | lib/yaml/store.rb
Parent: | PStore

Methods

dump load load_file new

Public Class methods

new( *o )

Public Instance methods

dump(table)
load(content)
load_file(file)


Class: YAML::Stream

Class | YAML::Stream
In: | lib/yaml/stream.rb
Parent: | Object

YAML::Stream — for emitting many documents

Methods

[] add edit emit new

Attributes

documents | [RW]
options | [RW]

Public Class methods

new( opts = {} )

Public Instance methods

[]( i )
add( doc )
edit( doc_num, doc )
emit( io = nil )


Module: YAML::Syck

Module | YAML::Syck
In: | lib/yaml/syck.rb

Classes and Modules

Class YAML::Syck::Node


Class: YAML::Syck::Node

Class | YAML::Syck::Node
In: | lib/yaml/syck.rb
Parent: | Object

Mixin BaseNode functionality

Included Modules

YAML::BaseNode


Class: YAML::TypeError

Class | YAML::TypeError
In: | lib/yaml/error.rb
Parent: | StandardError


Class: YAML::YPath

Class | YAML::YPath
In: | lib/yaml/ypath.rb
Parent: | Object

Methods

each_path new

Attributes

flags | [RW]
predicates | [RW]
segments | [RW]

Public Class methods

each_path( str ) {|YPath.new( path )| ...}
new( str )


Class: YAML::YamlNode

Class | YAML::YamlNode
In: | lib/yaml/yamlnode.rb
Parent: | Object

YAML Generic Model container

Methods

new transform

Included Modules

BaseNode

Attributes

anchor | [RW]
kind | [RW]
type_id | [RW]
value | [RW]

Public Class methods

new( t, v )

Public Instance methods

transform()

Transform this node fully into a native type


Class: ZeroDivisionError

Class | ZeroDivisionError
In: | numeric.c
Parent: | StandardError


Module: Zlib

Module | Zlib
In: | ext/zlib/zlib.c

GZIP_SUPPORT

Methods

adler32 crc32 crc_table zlib_version

Classes and Modules

Class Zlib::BufError
Class Zlib::DataError
Class Zlib::Deflate
Class Zlib::Error
Class Zlib::GzipFile
Class Zlib::GzipReader
Class Zlib::GzipWriter
Class Zlib::Inflate
Class Zlib::MemError
Class Zlib::NeedDict
Class Zlib::StreamEnd
Class Zlib::StreamError
Class Zlib::VersionError
Class Zlib::ZStream

Constants

VERSION | = | rb_str_new2(RUBY_ZLIB_VERSION)
ZLIB_VERSION | = | rb_str_new2(ZLIB_VERSION)
BINARY | = | INT2FIX(Z_BINARY)
ASCII | = | INT2FIX(Z_ASCII)
UNKNOWN | = | INT2FIX(Z_UNKNOWN)
NO_COMPRESSION | = | INT2FIX(Z_NO_COMPRESSION)
BEST_SPEED | = | INT2FIX(Z_BEST_SPEED)
BEST_COMPRESSION | = | INT2FIX(Z_BEST_COMPRESSION)
DEFAULT_COMPRESSION | = | INT2FIX(Z_DEFAULT_COMPRESSION)
FILTERED | = | INT2FIX(Z_FILTERED)
HUFFMAN_ONLY | = | INT2FIX(Z_HUFFMAN_ONLY)
DEFAULT_STRATEGY | = | INT2FIX(Z_DEFAULT_STRATEGY)
MAX_WBITS | = | INT2FIX(MAX_WBITS)
DEF_MEM_LEVEL | = | INT2FIX(DEF_MEM_LEVEL)
MAX_MEM_LEVEL | = | INT2FIX(MAX_MEM_LEVEL)
NO_FLUSH | = | INT2FIX(Z_NO_FLUSH)
SYNC_FLUSH | = | INT2FIX(Z_SYNC_FLUSH)
FULL_FLUSH | = | INT2FIX(Z_FULL_FLUSH)
FINISH | = | INT2FIX(Z_FINISH)
OS_CODE | = | INT2FIX(OS_CODE)
OS_MSDOS | = | INT2FIX(OS_MSDOS)
OS_AMIGA | = | INT2FIX(OS_AMIGA)
OS_VMS | = | INT2FIX(OS_VMS)
OS_UNIX | = | INT2FIX(OS_UNIX)
OS_ATARI | = | INT2FIX(OS_ATARI)
OS_OS2 | = | INT2FIX(OS_OS2)
OS_MACOS | = | INT2FIX(OS_MACOS)
OS_TOPS20 | = | INT2FIX(OS_TOPS20)
OS_WIN32 | = | INT2FIX(OS_WIN32)
OS_VMCMS | = | INT2FIX(OS_VMCMS)
OS_ZSYSTEM | = | INT2FIX(OS_ZSYSTEM)
OS_CPM | = | INT2FIX(OS_CPM)
OS_QDOS | = | INT2FIX(OS_QDOS)
OS_RISCOS | = | INT2FIX(OS_RISCOS)
OS_UNKNOWN | = | INT2FIX(OS_UNKNOWN)

Public Class methods

Zlib.adler32(string, adler)

Calculates Alder-32 checksum for string, and returns updated value of adler. If string is omitted, it returns the Adler-32 initial value. If adler is omitted, it assumes that the initial value is given to adler.

FIXME: expression.

Zlib.crc32(string, adler)

Calculates CRC checksum for string, and returns updated value of crc. If string is omitted, it returns the CRC initial value. If crc is omitted, it assumes that the initial value is given to crc.

FIXME: expression.

crc_table()

Returns the table for calculating CRC checksum as an array.

zlib_version()

Returns the string which represents the version of zlib library.


Class: Zlib::BufError

Class | Zlib::BufError
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::DataError

Class | Zlib::DataError
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::Deflate

Class | Zlib::Deflate
In: | ext/zlib/zlib.c
Parent: | Zlib::ZStream

Zlib::Deflate is the class for compressing data. See Zlib::Stream for more information.

Methods

<< deflate deflate flush initialize_copy new params set_dictionary

Public Class methods

Zlib::Deflate.deflate(string[, level])

Compresses the given string. Valid values of level are Zlib::NO_COMPRESSION, Zlib::BEST_SPEED, Zlib::BEST_COMPRESSION, Zlib::DEFAULT_COMPRESSION, and an integer from 0 to 9.

This method is almost equivalent to the following code:

  def deflate(string, level)
    z = Zlib::Deflate.new(level)
    dst = z.deflate(string, Zlib::FINISH)
    z.close
    dst
  end

TODO: what‘s default value of level?

Zlib::Deflate.new(level=nil, windowBits=nil, memlevel=nil, strategy=nil)

Creates a new deflate stream for compression. See zlib.h for details of each argument. If an argument is nil, the default value of that argument is used.

TODO: document better!

Public Instance methods

<<(p1)

Same as IO.

deflate(string[, flush])

Inputs string into the deflate stream and returns the output from the stream. On calling this method, both the input and the output buffers of the stream are flushed. If string is nil, this method finishes the stream, just like Zlib::ZStream#finish.

The value of flush should be either Zlib::NO_FLUSH, Zlib::SYNC_FLUSH, Zlib::FULL_FLUSH, or Zlib::FINISH. See zlib.h for details.

TODO: document better!

flush(flush)

This method is equivalent to deflate(’’, flush). If flush is omitted, Zlib::SYNC_FLUSH is used as flush. This method is just provided to improve the readability of your Ruby program.

TODO: document better!

initialize_copy()

Duplicates the deflate stream.

params(level, strategy)

Changes the parameters of the deflate stream. See zlib.h for details. The output from the stream by changing the params is preserved in output buffer.

TODO: document better!

set_dictionary(string)

Sets the preset dictionary and returns string. This method is available just only after Zlib::Deflate.new or Zlib::ZStream#reset method was called. See zlib.h for details.

TODO: document better!


Class: Zlib::Error

Class | Zlib::Error
In: | ext/zlib/zlib.c
Parent: | StandardError

The superclass for all exceptions raised by Ruby/zlib.

The following exceptions are defined as subclasses of Zlib::Error. These exceptions are raised when zlib library functions return with an error status.

  • Zlib::StreamEnd
  • Zlib::NeedDict
  • Zlib::DataError
  • Zlib::StreamError
  • Zlib::MemError
  • Zlib::BufError
  • Zlib::VersionError


Class: Zlib::GzipFile

Class | Zlib::GzipFile
In: | ext/zlib/zlib.c
Parent: | Object

Zlib::GzipFile is an abstract class for handling a gzip formatted compressed file. The operations are defined in the subclasses, Zlib::GzipReader for reading, and Zlib::GzipWriter for writing.

GzipReader should be used by associating an IO, or IO-like, object.

Methods

close closed? comment crc finish level mtime orig_name os_code sync sync= to_io wrap

Classes and Modules

Class Zlib::GzipFile::CRCError
Class Zlib::GzipFile::Error
Class Zlib::GzipFile::LengthError
Class Zlib::GzipFile::NoFooter

Public Class methods

wrap(...)

See Zlib::GzipReader#wrap and Zlib::GzipWriter#wrap.

Public Instance methods

close()

Closes the GzipFile object. This method calls close method of the associated IO object. Returns the associated IO object.

closed?()

Same as IO.

comment()

Returns comments recorded in the gzip file header, or nil if the comments is not present.

crc()

Returns CRC value of the uncompressed data.

finish()

Closes the GzipFile object. Unlike Zlib::GzipFile#close, this method never calls the close method of the associated IO object. Returns the associated IO object.

level()

Returns compression level.

mtime()

Returns last modification time recorded in the gzip file header.

orig_name()

Returns original filename recorded in the gzip file header, or nil if original filename is not present.

os_code()

Returns OS code number recorded in the gzip file header.

sync()

Same as IO.

sync = flag

Same as IO. If flag is true, the associated IO object must respond to the flush method. While sync mode is true, the compression ratio decreases sharply.

to_io()

Same as IO.


Class: Zlib::GzipFile::CRCError

Class | Zlib::GzipFile::CRCError
In: | ext/zlib/zlib.c
Parent: | Zlib::GzipFile::Error

Raised when the CRC checksum recorded in gzip file footer is not equivalent to the CRC checksum of the actual uncompressed data.


Class: Zlib::GzipFile::Error

Class | Zlib::GzipFile::Error
In: | ext/zlib/zlib.c
Parent: | Zlib::Error

Base class of errors that occur when processing GZIP files.


Class: Zlib::GzipFile::LengthError

Class | Zlib::GzipFile::LengthError
In: | ext/zlib/zlib.c
Parent: | Zlib::GzipFile::Error

Raised when the data length recorded in the gzip file footer is not equivalent to the length of the actual uncompressed data.


Class: Zlib::GzipFile::NoFooter

Class | Zlib::GzipFile::NoFooter
In: | ext/zlib/zlib.c
Parent: | Zlib::GzipFile::Error

Raised when gzip file footer is not found.


Class: Zlib::GzipReader

Class | Zlib::GzipReader
In: | ext/zlib/zlib.c
Parent: | Zlib::GzipFile

Zlib::GzipReader is the class for reading a gzipped file. GzipReader should be used an IO, or -IO-lie, object.

  Zlib::GzipReader.open('hoge.gz') {|gz|
    print gz.read
  }

  File.open('hoge.gz') do |f|
    gz = Zlib::GzipReader.new(f)
    print gz.read
    gz.close
  end

  # TODO: test these.  Are they equivalent?  Can GzipReader.new take a
  # block?

Method Catalogue

The following methods in Zlib::GzipReader are just like their counterparts in IO, but they raise Zlib::Error or Zlib::GzipFile::Error exception if an error was found in the gzip file.

  • each
  • each_line
  • each_byte
  • gets
  • getc
  • lineno
  • lineno=
  • read
  • readchar
  • readline
  • readlines
  • ungetc

Be careful of the footer of the gzip file. A gzip file has the checksum of pre-compressed data in its footer. GzipReader checks all uncompressed data against that checksum at the following cases, and if it fails, raises Zlib::GzipFile::NoFooter, Zlib::GzipFile::CRCError, or Zlib::GzipFile::LengthError exception.

  • When an reading request is received beyond the end of file (the end of compressed data). That is, when Zlib::GzipReader#read, Zlib::GzipReader#gets, or some other methods for reading returns nil.
  • When Zlib::GzipFile#close method is called after the object reaches the end of file.
  • When Zlib::GzipReader#unused method is called after the object reaches the end of file.

The rest of the methods are adequately described in their own documentation.

Methods

each each_byte each_line eof eof? getc gets lineno lineno= new open pos read readchar readline readlines rewind tell ungetc unused

Included Modules

Enumerable

Public Class methods

Zlib::GzipReader.new(io)

Creates a GzipReader object associated with io. The GzipReader object reads gzipped data from io, and parses/decompresses them. At least, io must have a read method that behaves same as the read method in IO class.

If the gzip file header is incorrect, raises an Zlib::GzipFile::Error exception.

Zlib::GzipReader.open(filename) {|gz| ... }

Opens a file specified by filename as a gzipped file, and returns a GzipReader object associated with that file. Further details of this method are in Zlib::GzipReader.new and ZLib::GzipReader.wrap.

Public Instance methods

each(...)

See Zlib::GzipReader documentation for a description.

each_byte()

See Zlib::GzipReader documentation for a description.

each_line(...)

See Zlib::GzipReader documentation for a description.

eof()

???

eof?()

???

getc()

See Zlib::GzipReader documentation for a description.

gets(...)

See Zlib::GzipReader documentation for a description.

lineno()

???

lineno=(p1)

???

pos()

???

read(...)

See Zlib::GzipReader documentation for a description.

readchar()

See Zlib::GzipReader documentation for a description.

readline(...)

See Zlib::GzipReader documentation for a description.

readlines(...)

See Zlib::GzipReader documentation for a description.

rewind()

Resets the position of the file pointer to the point created the GzipReader object. The associated IO object needs to respond to the seek method.

tell()

???

ungetc(p1)

See Zlib::GzipReader documentation for a description.

unused()

Returns the rest of the data which had read for parsing gzip format, or nil if the whole gzip file is not parsed yet.


Class: Zlib::GzipWriter

Class | Zlib::GzipWriter
In: | ext/zlib/zlib.c
Parent: | Zlib::GzipFile

Zlib::GzipWriter is a class for writing gzipped files. GzipWriter should be used with an instance of IO, or IO-like, object.

For example:

  Zlib::GzipWriter.open('hoge.gz') do |gz|
    gz.write 'jugemu jugemu gokou no surikire...'
  end

  File.open('hoge.gz', 'w') do |f|
    gz = Zlib::GzipWriter.new(f)
    gz.write 'jugemu jugemu gokou no surikire...'
    gz.close
  end

  # TODO: test these.  Are they equivalent?  Can GzipWriter.new take a
  # block?

NOTE: Due to the limitation of Ruby‘s finalizer, you must explicitly close GzipWriter objects by Zlib::GzipWriter#close etc. Otherwise, GzipWriter will be not able to write the gzip footer and will generate a broken gzip file.

Methods

<< comment= flush mtime= new open orig_name= pos print printf putc puts tell write

Public Class methods

Zlib::GzipWriter.new(io, level, strategy)

Creates a GzipWriter object associated with io. level and strategy should be the same as the arguments of Zlib::Deflate.new. The GzipWriter object writes gzipped data to io. At least, io must respond to the write method that behaves same as write method in IO class.

Zlib::GzipWriter.open(filename, level=nil, strategy=nil) { |gz| ... }

Opens a file specified by filename for writing gzip compressed data, and returns a GzipWriter object associated with that file. Further details of this method are found in Zlib::GzipWriter.new and Zlib::GzipWriter#wrap.

Public Instance methods

<<(p1)

Document-method: << Same as IO.

Same as IO.

comment=(p1)

???

flush(flush=nil)

Flushes all the internal buffers of the GzipWriter object. The meaning of flush is same as in Zlib::Deflate#deflate. Zlib::SYNC_FLUSH is used if flush is omitted. It is no use giving flush Zlib::NO_FLUSH.

mtime=(p1)

???

orig_name=(p1)

???

pos()

???

print(...)

Document-method: print Same as IO.

Same as IO.

printf(...)

Document-method: printf Same as IO.

Same as IO.

putc(p1)

Same as IO.

puts(...)

Document-method: puts Same as IO.

Same as IO.

tell()

???

write(p1)

Same as IO.


Class: Zlib::Inflate

Class | Zlib::Inflate
In: | ext/zlib/zlib.c
Parent: | Zlib::ZStream

Zlib:Inflate is the class for decompressing compressed data. Unlike Zlib::Deflate, an instance of this class is not able to duplicate (clone, dup) itself.

Methods

<< inflate inflate new set_dictionary sync sync_point?

Public Class methods

Zlib::Inflate.inflate(string)

Decompresses string. Raises a Zlib::NeedDict exception if a preset dictionary is needed for decompression.

This method is almost equivalent to the following code:

  def inflate(string)
    zstream = Zlib::Inflate.new
    buf = zstream.inflate(string)
    zstream.finish
    zstream.close
    buf
  end
Zlib::Inflate.new(window_bits)

Creates a new inflate stream for decompression. See zlib.h for details of the argument. If window_bits is nil, the default value is used.

TODO: document better!

Public Instance methods

<<(p1)

Same as IO.

inflate(string)

Inputs string into the inflate stream and returns the output from the stream. Calling this method, both the input and the output buffer of the stream are flushed. If string is nil, this method finishes the stream, just like Zlib::ZStream#finish.

Raises a Zlib::NeedDict exception if a preset dictionary is needed to decompress. Set the dictionary by Zlib::Inflate#set_dictionary and then call this method again with an empty string. (???)

TODO: document better!

set_dictionary(p1)

Sets the preset dictionary and returns string. This method is available just only after a Zlib::NeedDict exception was raised. See zlib.h for details.

TODO: document better!

sync(string)

Inputs string into the end of input buffer and skips data until a full flush point can be found. If the point is found in the buffer, this method flushes the buffer and returns false. Otherwise it returns true and the following data of full flush point is preserved in the buffer.

sync_point?()

Quoted verbatim from original documentation:

  What is this?

:)


Class: Zlib::MemError

Class | Zlib::MemError
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::NeedDict

Class | Zlib::NeedDict
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::StreamEnd

Class | Zlib::StreamEnd
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::StreamError

Class | Zlib::StreamError
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::VersionError

Class | Zlib::VersionError
In: | ext/zlib/zlib.c
Parent: | Zlib::Error


Class: Zlib::ZStream

Class | Zlib::ZStream
In: | ext/zlib/zlib.c
Parent: | Object

Zlib::ZStream is the abstract class for the stream which handles the compressed data. The operations are defined in the subclasses: Zlib::Deflate for compression, and Zlib::Inflate for decompression.

An instance of Zlib::ZStream has one stream (struct zstream in the source) and two variable-length buffers which associated to the input (next_in) of the stream and the output (next_out) of the stream. In this document, "input buffer" means the buffer for input, and "output buffer" means the buffer for output.

Data input into an instance of Zlib::ZStream are temporally stored into the end of input buffer, and then data in input buffer are processed from the beginning of the buffer until no more output from the stream is produced (i.e. until avail_out > 0 after processing). During processing, output buffer is allocated and expanded automatically to hold all output data.

Some particular instance methods consume the data in output buffer and return them as a String.

Here is an ascii art for describing above:

   +================ an instance of Zlib::ZStream ================+
   ||                                                            ||
   ||     +--------+          +-------+          +--------+      ||
   ||  +--| output |<---------|zstream|<---------| input  |<--+  ||
   ||  |  | buffer |  next_out+-------+next_in   | buffer |   |  ||
   ||  |  +--------+                             +--------+   |  ||
   ||  |                                                      |  ||
   +===|======================================================|===+
       |                                                      |
       v                                                      |
   "output data"                                         "input data"

If an error occurs during processing input buffer, an exception which is a subclass of Zlib::Error is raised. At that time, both input and output buffer keep their conditions at the time when the error occurs.

Method Catalogue

Many of the methods in this class are fairly low-level and unlikely to be of interest to users. In fact, users are unlikely to use this class directly; rather they will be interested in Zlib::Inflate and Zlib::Deflate.

The higher level methods are listed below.

  • total_in
  • total_out
  • data_type
  • adler
  • reset
  • finish
  • finished?
  • close
  • closed?

Methods

adler avail_in avail_out avail_out= close closed? data_type end ended? finish finished? flush_next_in flush_next_out reset stream_end? total_in total_out

Public Instance methods

adler()

Returns the adler-32 checksum.

avail_in()

Returns bytes of data in the input buffer. Normally, returns 0.

avail_out()

Returns number of bytes of free spaces in output buffer. Because the free space is allocated automatically, this method returns 0 normally.

avail_out=(p1)

Allocates size bytes of free space in the output buffer. If there are more than size bytes already in the buffer, the buffer is truncated. Because free space is allocated automatically, you usually don‘t need to use this method.

close()

Closes the stream. All operations on the closed stream will raise an exception.

closed?()

Returns true if the stream is closed.

data_type()

Guesses the type of the data which have been inputed into the stream. The returned value is either Zlib::BINARY, Zlib::ASCII, or Zlib::UNKNOWN.

end()

Closes the stream. All operations on the closed stream will raise an exception.

ended?()

Returns true if the stream is closed.

finish()

Finishes the stream and flushes output buffer. See Zlib::Deflate#finish and Zlib::Inflate#finish for details of this behavior.

finished?()

Returns true if the stream is finished.

flush_next_in()

Flushes input buffer and returns all data in that buffer.

flush_next_out()

Flushes output buffer and returns all data in that buffer.

reset()

Resets and initializes the stream. All data in both input and output buffer are discarded.

stream_end?()

Returns true if the stream is finished.

total_in()

Returns the total bytes of the input data to the stream. FIXME

total_out()

Returns the total bytes of the output data from the stream. FIXME


Class: fatal

Class | fatal
In: | error.c
Parent: | Exception


abbrev (Abbrev)

# File lib/abbrev.rb, line 44
  def abbrev(words, pattern = nil)
    table = {}
    seen = Hash.new(0)

    if pattern.is_a?(String)
      pattern = /^#{Regexp.quote(pattern)}/     # regard as a prefix
    end

    words.each do |word|
      next if (abbrev = word).empty?
      while (len = abbrev.rindex(/[\w\W]\z/)) > 0
        abbrev = word[0,len]

        next if pattern && pattern !~ abbrev

        case seen[abbrev] += 1
        when 1
          table[abbrev] = word
        when 2
          table.delete(abbrev)
        else
          break
        end
      end
    end

    words.each do |word|
      next if pattern && pattern !~ word

      table[word] = word
    end

    table
  end


new (ACL::ACLEntry)

# File lib/drb/acl.rb, line 13
    def initialize(str)
      if str == '*' or str == 'all'
        @pat = [:all]
      elsif str.include?('*')
        @pat = [:name, dot_pat(str)]
      else
        begin
          @pat = [:ip, IPAddr.new(str)]
        rescue ArgumentError
          @pat = [:name, dot_pat(str)]
        end
      end
    end


match (ACL::ACLEntry)

# File lib/drb/acl.rb, line 42
    def match(addr)
      case @pat[0]
      when :all
        true
      when :ip
        begin
          ipaddr = IPAddr.new(addr[3])
          ipaddr = ipaddr.ipv4_mapped if @pat[1].ipv6? && ipaddr.ipv4?
        rescue ArgumentError
          return false
        end
        (@pat[1].include?(ipaddr)) ? true : false
      when :name
        (@pat[1] =~ addr[2]) ? true : false
      else
        false
      end
    end


new (ACL::ACLList)

# File lib/drb/acl.rb, line 63
    def initialize
      @list = []
    end


match (ACL::ACLList)

# File lib/drb/acl.rb, line 68
    def match(addr)
      @list.each do |e|
        return true if e.match(addr)
      end
      false
    end


add (ACL::ACLList)

# File lib/drb/acl.rb, line 76
    def add(str)
      @list.push(ACLEntry.new(str))
    end


new (ACL)

# File lib/drb/acl.rb, line 84
  def initialize(list=nil, order = DENY_ALLOW)
    @order = order
    @deny = ACLList.new
    @allow = ACLList.new
    install_list(list) if list
  end


allow_socket? (ACL)

# File lib/drb/acl.rb, line 92
  def allow_socket?(soc)
    allow_addr?(soc.peeraddr)
  end


allow_addr? (ACL)

# File lib/drb/acl.rb, line 97
  def allow_addr?(addr)
    case @order
    when DENY_ALLOW
      return true if @allow.match(addr)
      return false if @deny.match(addr)
      return true
    when ALLOW_DENY
      return false if @deny.match(addr)
      return true if @allow.match(addr)
      return false
    else
      false
    end
  end


install_list (ACL)

# File lib/drb/acl.rb, line 113
  def install_list(list)
    i = 0
    while i < list.size
      permission, domain = list.slice(i,2)
      case permission.downcase
      when 'allow'
        @allow.add(domain)
      when 'deny'
        @deny.add(domain)
      else
        raise "Invalid ACL entry #{list.to_s}"
      end
      i += 2
    end
  end


options= (Arguable)

# File lib/optparse.rb, line 1694
    def options=(opt)
      unless @optparse = opt
        class << self
          undef_method(:options)
          undef_method(:options=)
        end
      end
    end


options (Arguable)

# File lib/optparse.rb, line 1711
    def options
      @optparse ||= OptionParser.new
      @optparse.default_argv = self
      block_given? or return @optparse
      begin
        yield @optparse
      rescue ParseError
        @optparse.warn $!
        nil
      end
    end


order! (Arguable)

# File lib/optparse.rb, line 1727
    def order!(&blk) options.order!(self, &blk) end


permute! (Arguable)

# File lib/optparse.rb, line 1733
    def permute!() options.permute!(self) end


parse! (Arguable)

# File lib/optparse.rb, line 1739
    def parse!() options.parse!(self) end


getopts (Arguable)

# File lib/optparse.rb, line 1752
    def getopts(*args)
      options.getopts(self, *args)
    end


extend_object (Arguable)

# File lib/optparse.rb, line 1759
    def self.extend_object(obj)
      super
      obj.instance_eval {@optparse = nil}
    end


new (Arguable)

# File lib/optparse.rb, line 1763
    def initialize(*args)
      super
      @optparse = nil
    end


[] (Array)

/*
* Returns a new array populated with the given objects.
*
*   Array.[]( 1, 'a', /^A/ )
*   Array[ 1, 'a', /^A/ ]
*   [ 1, 'a', /^A/ ]
*/

static VALUE
rb_ary_s_create(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE ary = ary_alloc(klass);

    if (argc > 0) {
        RARRAY(ary)->ptr = ALLOC_N(VALUE, argc);
        MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc);
    }
    RARRAY(ary)->len = RARRAY(ary)->aux.capa = argc;

    return ary;
}


new (Array)

/*
 *  call-seq:
 *     Array.new(size=0, obj=nil)
 *     Array.new(array)
 *     Array.new(size) {|index| block }
 *
 *  Returns a new array. In the first form, the new array is
 *  empty. In the second it is created with _size_ copies of _obj_
 *  (that is, _size_ references to the same
 *  _obj_). The third form creates a copy of the array
 *  passed as a parameter (the array is generated by calling
 *  to_ary  on the parameter). In the last form, an array
 *  of the given size is created. Each element in this array is
 *  calculated by passing the element's index to the given block and
 *  storing the return value.
 *
 *     Array.new
 *     Array.new(2)
 *     Array.new(5, "A")
 *
 *     # only one copy of the object is created
 *     a = Array.new(2, Hash.new)
 *     a[0]['cat'] = 'feline'
 *     a
 *     a[1]['cat'] = 'Felix'
 *     a
 *
 *     # here multiple copies are created
 *     a = Array.new(2) { Hash.new }
 *     a[0]['cat'] = 'feline'
 *     a
 *
 *     squares = Array.new(5) {|i| i*i}
 *     squares
 *
 *     copy = Array.new(squares)
 */

static VALUE
rb_ary_initialize(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    long len;
    VALUE size, val;

    rb_ary_modify(ary);
    if (rb_scan_args(argc, argv, "02", &size, &val) == 0) {
        RARRAY(ary)->len = 0;
        if (rb_block_given_p()) {
            rb_warning("given block not used");
        }
        return ary;
    }

    if (argc == 1 && !FIXNUM_P(size)) {
        val = rb_check_array_type(size);
        if (!NIL_P(val)) {
            rb_ary_replace(ary, val);
            return ary;
        }
    }

    len = NUM2LONG(size);
    if (len < 0) {
        rb_raise(rb_eArgError, "negative array size");
    }
    if (len > 0 && len * (long)sizeof(VALUE) <= len) {
        rb_raise(rb_eArgError, "array size too big");
    }
    if (len > RARRAY(ary)->aux.capa) {
        REALLOC_N(RARRAY(ary)->ptr, VALUE, len);
        RARRAY(ary)->aux.capa = len;
    }
    if (rb_block_given_p()) {
        long i;

        if (argc == 2) {
            rb_warn("block supersedes default value argument");
        }
        for (i=0; i<len; i++) {
            rb_ary_store(ary, i, rb_yield(LONG2NUM(i)));
            RARRAY(ary)->len = i + 1;
        }
    }
    else {
        memfill(RARRAY(ary)->ptr, len, val);
        RARRAY(ary)->len = len;
    }

    return ary;
}


initialize_copy (Array)

/*
 *  call-seq:
 *     array.replace(other_array)  -> array
 *
 *  Replaces the contents of <i>self</i> with the contents of
 *  <i>other_array</i>, truncating or expanding if necessary.
 *
 *     a = [ "a", "b", "c", "d", "e" ]
 *     a.replace([ "x", "y", "z" ])   #=> ["x", "y", "z"]
 *     a                              #=> ["x", "y", "z"]
 */

static VALUE
rb_ary_replace(copy, orig)
    VALUE copy, orig;
{
    VALUE shared;

    rb_ary_modify(copy);
    orig = to_ary(orig);
    if (copy == orig) return copy;
    shared = ary_make_shared(orig);
    if (RARRAY(copy)->ptr && !FL_TEST(copy, ELTS_SHARED))
        free(RARRAY(copy)->ptr);
    RARRAY(copy)->ptr = RARRAY(orig)->ptr;
    RARRAY(copy)->len = RARRAY(orig)->len;
    RARRAY(copy)->aux.shared = shared;
    FL_SET(copy, ELTS_SHARED);

    return copy;
}


to_s (Array)

/*
 *  call-seq:
 *     array.to_s -> string
 *
 *  Returns _self_<code>.join</code>.
 *
 *     [ "a", "e", "i", "o" ].to_s   #=> "aeio"
 *
 */

VALUE
rb_ary_to_s(ary)
    VALUE ary;
{
    if (RARRAY(ary)->len == 0) return rb_str_new(0, 0);

    return rb_ary_join(ary, rb_output_fs);
}


inspect (Array)

/*
 *  call-seq:
 *     array.inspect  -> string
 *
 *  Create a printable version of <i>array</i>.
 */

static VALUE
rb_ary_inspect(ary)
    VALUE ary;
{
    if (RARRAY(ary)->len == 0) return rb_str_new2("[]");
    if (rb_inspecting_p(ary)) return rb_str_new2("[...]");
    return rb_protect_inspect(inspect_ary, ary, 0);
}


to_a (Array)

/*
 *  call-seq:
 *     array.to_a     -> array
 *
 *  Returns _self_. If called on a subclass of Array, converts
 *  the receiver to an Array object.
 */

static VALUE
rb_ary_to_a(ary)
    VALUE ary;
{
    if (rb_obj_class(ary) != rb_cArray) {
        VALUE dup = rb_ary_new2(RARRAY(ary)->len);
        rb_ary_replace(dup, ary);
        return dup;
    }
    return ary;
}


to_ary (Array)

/*
 *  call-seq:
 *     array.to_ary -> array
 *
 *  Returns _self_.
 */

static VALUE
rb_ary_to_ary_m(ary)
    VALUE ary;
{
    return ary;
}


frozen? (Array)

/*
 *  call-seq:
 *     array.frozen?  -> true or false
 *
 *  Return <code>true</code> if this array is frozen (or temporarily frozen
 *  while being sorted).
 */

static VALUE
rb_ary_frozen_p(ary)
    VALUE ary;
{
    if (OBJ_FROZEN(ary)) return Qtrue;
    if (FL_TEST(ary, ARY_TMPLOCK)) return Qtrue;
    return Qfalse;
}


== (Array)

/*
 *  call-seq:
 *     array == other_array   ->   bool
 *
 *  Equality---Two arrays are equal if they contain the same number
 *  of elements and if each element is equal to (according to
 *  Object.==) the corresponding element in the other array.
 *
 *     [ "a", "c" ]    == [ "a", "c", 7 ]     #=> false
 *     [ "a", "c", 7 ] == [ "a", "c", 7 ]     #=> true
 *     [ "a", "c", 7 ] == [ "a", "d", "f" ]   #=> false
 *
 */

static VALUE
rb_ary_equal(ary1, ary2)
    VALUE ary1, ary2;
{
    long i;

    if (ary1 == ary2) return Qtrue;
    if (TYPE(ary2) != T_ARRAY) {
        if (!rb_respond_to(ary2, rb_intern("to_ary"))) {
            return Qfalse;
        }
        return rb_equal(ary2, ary1);
    }
    if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse;
    for (i=0; i<RARRAY(ary1)->len; i++) {
        if (!rb_equal(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
            return Qfalse;
    }
    return Qtrue;
}


eql? (Array)

/*
 *  call-seq:
 *     array.eql?(other)  -> true or false
 *
 *  Returns <code>true</code> if _array_ and _other_ are the same object,
 *  or are both arrays with the same content.
 */

static VALUE
rb_ary_eql(ary1, ary2)
    VALUE ary1, ary2;
{
    long i;

    if (ary1 == ary2) return Qtrue;
    if (TYPE(ary2) != T_ARRAY) return Qfalse;
    if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse;
    for (i=0; i<RARRAY(ary1)->len; i++) {
        if (!rb_eql(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
            return Qfalse;
    }
    return Qtrue;
}


hash (Array)

/*
 *  call-seq:
 *     array.hash   -> fixnum
 *
 *  Compute a hash-code for this array. Two arrays with the same content
 *  will have the same hash code (and will compare using <code>eql?</code>).
 */

static VALUE
rb_ary_hash(ary)
    VALUE ary;
{
    long i, h;
    VALUE n;

    h = RARRAY(ary)->len;
    for (i=0; i<RARRAY(ary)->len; i++) {
        h = (h << 1) | (h<0 ? 1 : 0);
        n = rb_hash(RARRAY(ary)->ptr[i]);
        h ^= NUM2LONG(n);
    }
    return LONG2FIX(h);
}


[] (Array)

/*
 *  call-seq:
 *     array[index]                -> obj      or nil
 *     array[start, length]        -> an_array or nil
 *     array[range]                -> an_array or nil
 *     array.slice(index)          -> obj      or nil
 *     array.slice(start, length)  -> an_array or nil
 *     array.slice(range)          -> an_array or nil
 *
 *  Element Reference---Returns the element at _index_,
 *  or returns a subarray starting at _start_ and
 *  continuing for _length_ elements, or returns a subarray
 *  specified by _range_.
 *  Negative indices count backward from the end of the
 *  array (-1 is the last element). Returns nil if the index
 *  (or starting index) are out of range.
 *
 *     a = [ "a", "b", "c", "d", "e" ]
 *     a[2] +  a[0] + a[1]    #=> "cab"
 *     a[6]                   #=> nil
 *     a[1, 2]                #=> [ "b", "c" ]
 *     a[1..3]                #=> [ "b", "c", "d" ]
 *     a[4..7]                #=> [ "e" ]
 *     a[6..10]               #=> nil
 *     a[-3, 3]               #=> [ "c", "d", "e" ]
 *     # special cases
 *     a[5]                   #=> nil
 *     a[5, 1]                #=> []
 *     a[5..10]               #=> []
 *
 */

VALUE
rb_ary_aref(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE arg;
    long beg, len;

    if (argc == 2) {
        if (SYMBOL_P(argv[0])) {
            rb_raise(rb_eTypeError, "Symbol as array index");
        }
        beg = NUM2LONG(argv[0]);
        len = NUM2LONG(argv[1]);
        if (beg < 0) {
            beg += RARRAY(ary)->len;
        }
        return rb_ary_subseq(ary, beg, len);
    }
    if (argc != 1) {
        rb_scan_args(argc, argv, "11", 0, 0);
    }
    arg = argv[0];
    /* special case - speeding up */
    if (FIXNUM_P(arg)) {
        return rb_ary_entry(ary, FIX2LONG(arg));
    }
    if (SYMBOL_P(arg)) {
        rb_raise(rb_eTypeError, "Symbol as array index");
    }
    /* check if idx is Range */
    switch (rb_range_beg_len(arg, &beg, &len, RARRAY(ary)->len, 0)) {
      case Qfalse:
        break;
      case Qnil:
        return Qnil;
      default:
        return rb_ary_subseq(ary, beg, len);
    }
    return rb_ary_entry(ary, NUM2LONG(arg));
}


[]= (Array)

/*
 *  call-seq:
 *     array[index]         = obj                     ->  obj
 *     array[start, length] = obj or an_array or nil  ->  obj or an_array or nil
 *     array[range]         = obj or an_array or nil  ->  obj or an_array or nil
 *
 *  Element Assignment---Sets the element at _index_,
 *  or replaces a subarray starting at _start_ and
 *  continuing for _length_ elements, or replaces a subarray
 *  specified by _range_.  If indices are greater than
 *  the current capacity of the array, the array grows
 *  automatically. A negative indices will count backward
 *  from the end of the array. Inserts elements if _length_ is
 *  zero. If +nil+ is used in the second and third form,
 *  deletes elements from _self_. An +IndexError+ is raised if a
 *  negative index points past the beginning of the array. See also
 *  <code>Array#push</code>, and <code>Array#unshift</code>.
 *
 *     a = Array.new
 *     a[4] = "4";                 #=> [nil, nil, nil, nil, "4"]
 *     a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"]
 *     a[1..2] = [ 1, 2 ]          #=> ["a", 1, 2, nil, "4"]
 *     a[0, 2] = "?"               #=> ["?", 2, nil, "4"]
 *     a[0..2] = "A"               #=> ["A", "4"]
 *     a[-1]   = "Z"               #=> ["A", "Z"]
 *     a[1..-1] = nil              #=> ["A"]
 */

static VALUE
rb_ary_aset(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    long offset, beg, len;

    if (argc == 3) {
        if (SYMBOL_P(argv[0])) {
            rb_raise(rb_eTypeError, "Symbol as array index");
        }
        if (SYMBOL_P(argv[1])) {
            rb_raise(rb_eTypeError, "Symbol as subarray length");
        }
        rb_ary_splice(ary, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
        return argv[2];
    }
    if (argc != 2) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc);
    }
    if (FIXNUM_P(argv[0])) {
        offset = FIX2LONG(argv[0]);
        goto fixnum;
    }
    if (SYMBOL_P(argv[0])) {
        rb_raise(rb_eTypeError, "Symbol as array index");
    }
    if (rb_range_beg_len(argv[0], &beg, &len, RARRAY(ary)->len, 1)) {
        /* check if idx is Range */
        rb_ary_splice(ary, beg, len, argv[1]);
        return argv[1];
    }

    offset = NUM2LONG(argv[0]);
fixnum:
    rb_ary_store(ary, offset, argv[1]);
    return argv[1];
}


at (Array)

/*
 *  call-seq:
 *     array.at(index)   ->   obj  or nil
 *
 *  Returns the element at _index_. A
 *  negative index counts from the end of _self_.  Returns +nil+
 *  if the index is out of range. See also <code>Array#[]</code>.
 *  (<code>Array#at</code> is slightly faster than <code>Array#[]</code>,
 *  as it does not accept ranges and so on.)
 *
 *     a = [ "a", "b", "c", "d", "e" ]
 *     a.at(0)     #=> "a"
 *     a.at(-1)    #=> "e"
 */

static VALUE
rb_ary_at(ary, pos)
    VALUE ary, pos;
{
    return rb_ary_entry(ary, NUM2LONG(pos));
}


fetch (Array)

/*
 *  call-seq:
 *     array.fetch(index)                    -> obj
 *     array.fetch(index, default )          -> obj
 *     array.fetch(index) {|index| block }   -> obj
 *
 *  Tries to return the element at position <i>index</i>. If the index
 *  lies outside the array, the first form throws an
 *  <code>IndexError</code> exception, the second form returns
 *  <i>default</i>, and the third form returns the value of invoking
 *  the block, passing in the index. Negative values of <i>index</i>
 *  count from the end of the array.
 *
 *     a = [ 11, 22, 33, 44 ]
 *     a.fetch(1)               #=> 22
 *     a.fetch(-1)              #=> 44
 *     a.fetch(4, 'cat')        #=> "cat"
 *     a.fetch(4) { |i| i*i }   #=> 16
 */

static VALUE
rb_ary_fetch(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE pos, ifnone;
    long block_given;
    long idx;

    rb_scan_args(argc, argv, "11", &pos, &ifnone);
    block_given = rb_block_given_p();
    if (block_given && argc == 2) {
        rb_warn("block supersedes default value argument");
    }
    idx = NUM2LONG(pos);

    if (idx < 0) {
        idx +=  RARRAY(ary)->len;
    }
    if (idx < 0 || RARRAY(ary)->len <= idx) {
        if (block_given) return rb_yield(pos);
        if (argc == 1) {
            rb_raise(rb_eIndexError, "index %ld out of array", idx);
        }
        return ifnone;
    }
    return RARRAY(ary)->ptr[idx];
}


first (Array)

/*
 *  call-seq:
 *     array.first   ->   obj or nil
 *     array.first(n) -> an_array
 *
 *  Returns the first element, or the first +n+ elements, of the array.
 *  If the array is empty, the first form returns <code>nil</code>, and the
 *  second form returns an empty array.
 *
 *     a = [ "q", "r", "s", "t" ]
 *     a.first    #=> "q"
 *     a.first(1) #=> ["q"]
 *     a.first(3) #=> ["q", "r", "s"]
 */

static VALUE
rb_ary_first(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    if (argc == 0) {
        if (RARRAY(ary)->len == 0) return Qnil;
        return RARRAY(ary)->ptr[0];
    }
    else {
        VALUE nv, result;
        long n, i;

        rb_scan_args(argc, argv, "01", &nv);
        n = NUM2LONG(nv);
        if (n > RARRAY(ary)->len) n = RARRAY(ary)->len;
        result = rb_ary_new2(n);
        for (i=0; i<n; i++) {
            rb_ary_push(result, RARRAY(ary)->ptr[i]);
        }
        return result;
    }
}


last (Array)

/*
 *  call-seq:
 *     array.last     ->  obj or nil
 *     array.last(n)  ->  an_array
 *
 *  Returns the last element(s) of <i>self</i>. If the array is empty,
 *  the first form returns <code>nil</code>.
 *
 *     [ "w", "x", "y", "z" ].last   #=> "z"
 */

static VALUE
rb_ary_last(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    if (argc == 0) {
        if (RARRAY(ary)->len == 0) return Qnil;
        return RARRAY(ary)->ptr[RARRAY(ary)->len-1];
    }
    else {
        VALUE nv, result;
        long n, i;

        rb_scan_args(argc, argv, "01", &nv);
        n = NUM2LONG(nv);
        if (n > RARRAY(ary)->len) n = RARRAY(ary)->len;
        result = rb_ary_new2(n);
        for (i=RARRAY(ary)->len-n; n--; i++) {
            rb_ary_push(result, RARRAY(ary)->ptr[i]);
        }
        return result;
    }
}


concat (Array)

/*
 *  call-seq:
 *     array.concat(other_array)   ->  array
 *
 *  Appends the elements in other_array to _self_.
 *
 *     [ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]
 */

VALUE
rb_ary_concat(x, y)
    VALUE x, y;
{
    y = to_ary(y);
    if (RARRAY(y)->len > 0) {
        rb_ary_splice(x, RARRAY(x)->len, 0, y);
    }
    return x;
}


<< (Array)

/*
 *  call-seq:
 *     array << obj            -> array
 *
 *  Append---Pushes the given object on to the end of this array. This
 *  expression returns the array itself, so several appends
 *  may be chained together.
 *
 *     [ 1, 2 ] << "c" << "d" << [ 3, 4 ]
 *             #=>  [ 1, 2, "c", "d", [ 3, 4 ] ]
 *
 */

VALUE
rb_ary_push(ary, item)
    VALUE ary;
    VALUE item;
{
    rb_ary_store(ary, RARRAY(ary)->len, item);
    return ary;
}


push (Array)

/*
 *  call-seq:
 *     array.push(obj, ... )   -> array
 *
 *  Append---Pushes the given object(s) on to the end of this array. This
 *  expression returns the array itself, so several appends
 *  may be chained together.
 *
 *     a = [ "a", "b", "c" ]
 *     a.push("d", "e", "f")
 *             #=> ["a", "b", "c", "d", "e", "f"]
 */

static VALUE
rb_ary_push_m(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    while (argc--) {
        rb_ary_push(ary, *argv++);
    }
    return ary;
}


pop (Array)

/*
 *  call-seq:
 *     array.pop  -> obj or nil
 *
 *  Removes the last element from <i>self</i> and returns it, or
 *  <code>nil</code> if the array is empty.
 *
 *     a = [ "a", "m", "z" ]
 *     a.pop   #=> "z"
 *     a       #=> ["a", "m"]
 */

VALUE
rb_ary_pop(ary)
    VALUE ary;
{
    rb_ary_modify_check(ary);
    if (RARRAY(ary)->len == 0) return Qnil;
    if (!FL_TEST(ary, ELTS_SHARED) &&
            RARRAY(ary)->len * 2 < RARRAY(ary)->aux.capa &&
            RARRAY(ary)->aux.capa > ARY_DEFAULT_SIZE) {
        RARRAY(ary)->aux.capa = RARRAY(ary)->len * 2;
        REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa);
    }
    return RARRAY(ary)->ptr[--RARRAY(ary)->len];
}


shift (Array)

/*
 *  call-seq:
 *     array.shift   ->   obj or nil
 *
 *  Returns the first element of <i>self</i> and removes it (shifting all
 *  other elements down by one). Returns <code>nil</code> if the array
 *  is empty.
 *
 *     args = [ "-m", "-q", "filename" ]
 *     args.shift   #=> "-m"
 *     args         #=> ["-q", "filename"]
 */

VALUE
rb_ary_shift(ary)
    VALUE ary;
{
    VALUE top;

    rb_ary_modify_check(ary);
    if (RARRAY(ary)->len == 0) return Qnil;
    top = RARRAY(ary)->ptr[0];
    if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE && !FL_TEST(ary, ELTS_SHARED)) {
        MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+1, VALUE, RARRAY_LEN(ary)-1);
    }
    else {
        if (!FL_TEST(ary, ELTS_SHARED)) {
            RARRAY(ary)->ptr[0] = Qnil;
        }
        ary_make_shared(ary);
        RARRAY(ary)->ptr++;            /* shift ptr */
    }
    RARRAY(ary)->len--;

    return top;
}


unshift (Array)

/*
 *  call-seq:
 *     array.unshift(obj, ...)  -> array
 *
 *  Prepends objects to the front of <i>array</i>.
 *  other elements up one.
 *
 *     a = [ "b", "c", "d" ]
 *     a.unshift("a")   #=> ["a", "b", "c", "d"]
 *     a.unshift(1, 2)  #=> [ 1, 2, "a", "b", "c", "d"]
 */

static VALUE
rb_ary_unshift_m(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    long len = RARRAY(ary)->len;

    if (argc == 0) return ary;

    /* make rooms by setting the last item */
    rb_ary_store(ary, len + argc - 1, Qnil);

    /* sliding items */
    MEMMOVE(RARRAY(ary)->ptr + argc, RARRAY(ary)->ptr, VALUE, len);
    MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc);

    return ary;
}


insert (Array)

/*
 *  call-seq:
 *     array.insert(index, obj...)  -> array
 *
 *  Inserts the given values before the element with the given index
 *  (which may be negative).
 *
 *     a = %w{ a b c d }
 *     a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
 *     a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
 */

static VALUE
rb_ary_insert(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    long pos;

    if (argc == 1) return ary;
    if (argc < 1) {
        rb_raise(rb_eArgError, "wrong number of arguments (at least 1)");
    }
    pos = NUM2LONG(argv[0]);
    if (pos == -1) {
        pos = RARRAY(ary)->len;
    }
    if (pos < 0) {
        pos++;
    }
    rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
    return ary;
}


each (Array)

/*
 *  call-seq:
 *     array.each {|item| block }   ->   array
 *
 *  Calls <i>block</i> once for each element in <i>self</i>, passing that
 *  element as a parameter.
 *
 *     a = [ "a", "b", "c" ]
 *     a.each {|x| print x, " -- " }
 *
 *  produces:
 *
 *     a -- b -- c --
 */

VALUE
rb_ary_each(ary)
    VALUE ary;
{
    long i;

    for (i=0; i<RARRAY(ary)->len; i++) {
        rb_yield(RARRAY(ary)->ptr[i]);
    }
    return ary;
}


each_index (Array)

/*
 *  call-seq:
 *     array.each_index {|index| block }  ->  array
 *
 *  Same as <code>Array#each</code>, but passes the index of the element
 *  instead of the element itself.
 *
 *     a = [ "a", "b", "c" ]
 *     a.each_index {|x| print x, " -- " }
 *
 *  produces:
 *
 *     0 -- 1 -- 2 --
 */

static VALUE
rb_ary_each_index(ary)
    VALUE ary;
{
    long i;

    for (i=0; i<RARRAY(ary)->len; i++) {
        rb_yield(LONG2NUM(i));
    }
    return ary;
}


reverse_each (Array)

/*
 *  call-seq:
 *     array.reverse_each {|item| block }
 *
 *  Same as <code>Array#each</code>, but traverses <i>self</i> in reverse
 *  order.
 *
 *     a = [ "a", "b", "c" ]
 *     a.reverse_each {|x| print x, " " }
 *
 *  produces:
 *
 *     c b a
 */

static VALUE
rb_ary_reverse_each(ary)
    VALUE ary;
{
    long len = RARRAY(ary)->len;

    while (len--) {
        rb_yield(RARRAY(ary)->ptr[len]);
        if (RARRAY(ary)->len < len) {
            len = RARRAY(ary)->len;
        }
    }
    return ary;
}


length (Array)

/*
 *  call-seq:
 *     array.length -> int
 *
 *  Returns the number of elements in <i>self</i>. May be zero.
 *
 *     [ 1, 2, 3, 4, 5 ].length   #=> 5
 */

static VALUE
rb_ary_length(ary)
    VALUE ary;
{
    return LONG2NUM(RARRAY(ary)->len);
}


empty? (Array)

/*
 *  call-seq:
 *     array.empty?   -> true or false
 *
 *  Returns <code>true</code> if <i>self</i> array contains no elements.
 *
 *     [].empty?   #=> true
 */

static VALUE
rb_ary_empty_p(ary)
    VALUE ary;
{
    if (RARRAY(ary)->len == 0)
        return Qtrue;
    return Qfalse;
}


index (Array)

/*
 *  call-seq:
 *     array.index(obj)   ->  int or nil
 *
 *  Returns the index of the first object in <i>self</i> such that is
 *  <code>==</code> to <i>obj</i>. Returns <code>nil</code> if
 *  no match is found.
 *
 *     a = [ "a", "b", "c" ]
 *     a.index("b")   #=> 1
 *     a.index("z")   #=> nil
 */

static VALUE
rb_ary_index(ary, val)
    VALUE ary;
    VALUE val;
{
    long i;

    for (i=0; i<RARRAY(ary)->len; i++) {
        if (rb_equal(RARRAY(ary)->ptr[i], val))
            return LONG2NUM(i);
    }
    return Qnil;
}


rindex (Array)

/*
 *  call-seq:
 *     array.rindex(obj)    ->  int or nil
 *
 *  Returns the index of the last object in <i>array</i>
 *  <code>==</code> to <i>obj</i>. Returns <code>nil</code> if
 *  no match is found.
 *
 *     a = [ "a", "b", "b", "b", "c" ]
 *     a.rindex("b")   #=> 3
 *     a.rindex("z")   #=> nil
 */

static VALUE
rb_ary_rindex(ary, val)
    VALUE ary;
    VALUE val;
{
    long i = RARRAY(ary)->len;

    while (i--) {
        if (i > RARRAY(ary)->len) {
            i = RARRAY(ary)->len;
            continue;
        }
        if (rb_equal(RARRAY(ary)->ptr[i], val))
            return LONG2NUM(i);
    }
    return Qnil;
}


indexes (Array)

/*
 *  call-seq:
 *     array.indexes( i1, i2, ... iN )   -> an_array
 *     array.indices( i1, i2, ... iN )   -> an_array
 *
 *  Deprecated; use <code>Array#values_at</code>.
 */

static VALUE
rb_ary_indexes(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE new_ary;
    long i;

    rb_warn("Array#%s is deprecated; use Array#values_at", rb_id2name(rb_frame_last_func()));
    new_ary = rb_ary_new2(argc);
    for (i=0; i<argc; i++) {
        rb_ary_push(new_ary, rb_ary_aref(1, argv+i, ary));
    }

    return new_ary;
}


indices (Array)

/*
 *  call-seq:
 *     array.indexes( i1, i2, ... iN )   -> an_array
 *     array.indices( i1, i2, ... iN )   -> an_array
 *
 *  Deprecated; use <code>Array#values_at</code>.
 */

static VALUE
rb_ary_indexes(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE new_ary;
    long i;

    rb_warn("Array#%s is deprecated; use Array#values_at", rb_id2name(rb_frame_last_func()));
    new_ary = rb_ary_new2(argc);
    for (i=0; i<argc; i++) {
        rb_ary_push(new_ary, rb_ary_aref(1, argv+i, ary));
    }

    return new_ary;
}


join (Array)

/*
 *  call-seq:
 *     array.join(sep=$,)    -> str
 *
 *  Returns a string created by converting each element of the array to
 *  a string, separated by <i>sep</i>.
 *
 *     [ "a", "b", "c" ].join        #=> "abc"
 *     [ "a", "b", "c" ].join("-")   #=> "a-b-c"
 */

static VALUE
rb_ary_join_m(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE sep;

    rb_scan_args(argc, argv, "01", &sep);
    if (NIL_P(sep)) sep = rb_output_fs;

    return rb_ary_join(ary, sep);
}


reverse (Array)

/*
 *  call-seq:
 *     array.reverse -> an_array
 *
 *  Returns a new array containing <i>self</i>'s elements in reverse order.
 *
 *     [ "a", "b", "c" ].reverse   #=> ["c", "b", "a"]
 *     [ 1 ].reverse               #=> [1]
 */

static VALUE
rb_ary_reverse_m(ary)
    VALUE ary;
{
    return rb_ary_reverse(rb_ary_dup(ary));
}


reverse! (Array)

/*
 *  call-seq:
 *     array.reverse!   -> array
 *
 *  Reverses _self_ in place.
 *
 *     a = [ "a", "b", "c" ]
 *     a.reverse!       #=> ["c", "b", "a"]
 *     a                #=> ["c", "b", "a"]
 */

static VALUE
rb_ary_reverse_bang(ary)
    VALUE ary;
{
    return rb_ary_reverse(ary);
}


sort (Array)

/*
 *  call-seq:
 *     array.sort                   -> an_array
 *     array.sort {| a,b | block }  -> an_array
 *
 *  Returns a new array created by sorting <i>self</i>. Comparisons for
 *  the sort will be done using the <code><=></code> operator or using
 *  an optional code block. The block implements a comparison between
 *  <i>a</i> and <i>b</i>, returning -1, 0, or +1. See also
 *  <code>Enumerable#sort_by</code>.
 *
 *     a = [ "d", "a", "e", "c", "b" ]
 *     a.sort                    #=> ["a", "b", "c", "d", "e"]
 *     a.sort {|x,y| y <=> x }   #=> ["e", "d", "c", "b", "a"]
 */

VALUE
rb_ary_sort(ary)
    VALUE ary;
{
    ary = rb_ary_dup(ary);
    rb_ary_sort_bang(ary);
    return ary;
}


sort! (Array)

/*
 *  call-seq:
 *     array.sort!                   -> array
 *     array.sort! {| a,b | block }  -> array
 *
 *  Sorts _self_. Comparisons for
 *  the sort will be done using the <code><=></code> operator or using
 *  an optional code block. The block implements a comparison between
 *  <i>a</i> and <i>b</i>, returning -1, 0, or +1. See also
 *  <code>Enumerable#sort_by</code>.
 *
 *     a = [ "d", "a", "e", "c", "b" ]
 *     a.sort                    #=> ["a", "b", "c", "d", "e"]
 *     a.sort {|x,y| y <=> x }   #=> ["e", "d", "c", "b", "a"]
 */

VALUE
rb_ary_sort_bang(ary)
    VALUE ary;
{
    rb_ary_modify(ary);
    if (RARRAY(ary)->len > 1) {
        FL_SET(ary, ARY_TMPLOCK);      /* prohibit modification during sort */
        rb_ensure(sort_internal, ary, sort_unlock, ary);
    }
    return ary;
}


collect (Array)

/*
 *  call-seq:
 *     array.collect {|item| block }  -> an_array
 *     array.map     {|item| block }  -> an_array
 *
 *  Invokes <i>block</i> once for each element of <i>self</i>. Creates a
 *  new array containing the values returned by the block.
 *  See also <code>Enumerable#collect</code>.
 *
 *     a = [ "a", "b", "c", "d" ]
 *     a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
 *     a                          #=> ["a", "b", "c", "d"]
 */

static VALUE
rb_ary_collect(ary)
    VALUE ary;
{
    long i;
    VALUE collect;

    if (!rb_block_given_p()) {
        return rb_ary_new4(RARRAY(ary)->len, RARRAY(ary)->ptr);
    }

    collect = rb_ary_new2(RARRAY(ary)->len);
    for (i = 0; i < RARRAY(ary)->len; i++) {
        rb_ary_push(collect, rb_yield(RARRAY(ary)->ptr[i]));
    }
    return collect;
}


collect! (Array)

/*
 *  call-seq:
 *     array.collect! {|item| block }   ->   array
 *     array.map!     {|item| block }   ->   array
 *
 *  Invokes the block once for each element of _self_, replacing the
 *  element with the value returned by _block_.
 *  See also <code>Enumerable#collect</code>.
 *
 *     a = [ "a", "b", "c", "d" ]
 *     a.collect! {|x| x + "!" }
 *     a             #=>  [ "a!", "b!", "c!", "d!" ]
 */

static VALUE
rb_ary_collect_bang(ary)
    VALUE ary;
{
    long i;

    rb_ary_modify(ary);
    for (i = 0; i < RARRAY(ary)->len; i++) {
        rb_ary_store(ary, i, rb_yield(RARRAY(ary)->ptr[i]));
    }
    return ary;
}


map (Array)

/*
 *  call-seq:
 *     array.collect {|item| block }  -> an_array
 *     array.map     {|item| block }  -> an_array
 *
 *  Invokes <i>block</i> once for each element of <i>self</i>. Creates a
 *  new array containing the values returned by the block.
 *  See also <code>Enumerable#collect</code>.
 *
 *     a = [ "a", "b", "c", "d" ]
 *     a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
 *     a                          #=> ["a", "b", "c", "d"]
 */

static VALUE
rb_ary_collect(ary)
    VALUE ary;
{
    long i;
    VALUE collect;

    if (!rb_block_given_p()) {
        return rb_ary_new4(RARRAY(ary)->len, RARRAY(ary)->ptr);
    }

    collect = rb_ary_new2(RARRAY(ary)->len);
    for (i = 0; i < RARRAY(ary)->len; i++) {
        rb_ary_push(collect, rb_yield(RARRAY(ary)->ptr[i]));
    }
    return collect;
}


map! (Array)

/*
 *  call-seq:
 *     array.collect! {|item| block }   ->   array
 *     array.map!     {|item| block }   ->   array
 *
 *  Invokes the block once for each element of _self_, replacing the
 *  element with the value returned by _block_.
 *  See also <code>Enumerable#collect</code>.
 *
 *     a = [ "a", "b", "c", "d" ]
 *     a.collect! {|x| x + "!" }
 *     a             #=>  [ "a!", "b!", "c!", "d!" ]
 */

static VALUE
rb_ary_collect_bang(ary)
    VALUE ary;
{
    long i;

    rb_ary_modify(ary);
    for (i = 0; i < RARRAY(ary)->len; i++) {
        rb_ary_store(ary, i, rb_yield(RARRAY(ary)->ptr[i]));
    }
    return ary;
}


select (Array)

/*
 *  call-seq:
 *     array.select {|item| block } -> an_array
 *
 *  Invokes the block passing in successive elements from <i>array</i>,
 *  returning an array containing those elements for which the block
 *  returns a true value (equivalent to <code>Enumerable#select</code>).
 *
 *     a = %w{ a b c d e f }
 *     a.select {|v| v =~ /[aeiou]/}   #=> ["a", "e"]
 */

static VALUE
rb_ary_select(ary)
    VALUE ary;
{
    VALUE result;
    long i;

    result = rb_ary_new2(RARRAY(ary)->len);
    for (i = 0; i < RARRAY(ary)->len; i++) {
        if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) {
            rb_ary_push(result, rb_ary_elt(ary, i));
        }
    }
    return result;
}


values_at (Array)

/*
 *  call-seq:
 *     array.values_at(selector,... )  -> an_array
 *
 *  Returns an array containing the elements in
 *  _self_ corresponding to the given selector(s). The selectors
 *  may be either integer indices or ranges.
 *  See also <code>Array#select</code>.
 *
 *     a = %w{ a b c d e f }
 *     a.values_at(1, 3, 5)
 *     a.values_at(1, 3, 5, 7)
 *     a.values_at(-1, -3, -5, -7)
 *     a.values_at(1..3, 2...5)
 */

static VALUE
rb_ary_values_at(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    return rb_values_at(ary, RARRAY(ary)->len, argc, argv, rb_ary_entry);
}


delete (Array)

/*
 *  call-seq:
 *     array.delete(obj)            -> obj or nil
 *     array.delete(obj) { block }  -> obj or nil
 *
 *  Deletes items from <i>self</i> that are equal to <i>obj</i>. If
 *  the item is not found, returns <code>nil</code>. If the optional
 *  code block is given, returns the result of <i>block</i> if the item
 *  is not found.
 *
 *     a = [ "a", "b", "b", "b", "c" ]
 *     a.delete("b")                   #=> "b"
 *     a                               #=> ["a", "c"]
 *     a.delete("z")                   #=> nil
 *     a.delete("z") { "not found" }   #=> "not found"
 */

VALUE
rb_ary_delete(ary, item)
    VALUE ary;
    VALUE item;
{
    long i1, i2;

    for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) {
        VALUE e = RARRAY(ary)->ptr[i1];

        if (rb_equal(e, item)) continue;
        if (i1 != i2) {
            rb_ary_store(ary, i2, e);
        }
        i2++;
    }
    if (RARRAY(ary)->len == i2) {
        if (rb_block_given_p()) {
            return rb_yield(item);
        }
        return Qnil;
    }

    rb_ary_modify(ary);
    if (RARRAY(ary)->len > i2) {
        RARRAY(ary)->len = i2;
        if (i2 * 2 < RARRAY(ary)->aux.capa &&
            RARRAY(ary)->aux.capa > ARY_DEFAULT_SIZE) {
            REALLOC_N(RARRAY(ary)->ptr, VALUE, i2 * 2);
            RARRAY(ary)->aux.capa = i2 * 2;
        }
    }

    return item;
}


delete_at (Array)

/*
 *  call-seq:
 *     array.delete_at(index)  -> obj or nil
 *
 *  Deletes the element at the specified index, returning that element,
 *  or <code>nil</code> if the index is out of range. See also
 *  <code>Array#slice!</code>.
 *
 *     a = %w( ant bat cat dog )
 *     a.delete_at(2)    #=> "cat"
 *     a                 #=> ["ant", "bat", "dog"]
 *     a.delete_at(99)   #=> nil
 */

static VALUE
rb_ary_delete_at_m(ary, pos)
    VALUE ary, pos;
{
    return rb_ary_delete_at(ary, NUM2LONG(pos));
}


delete_if (Array)

/*
 *  call-seq:
 *     array.delete_if {|item| block }  -> array
 *
 *  Deletes every element of <i>self</i> for which <i>block</i> evaluates
 *  to <code>true</code>.
 *
 *     a = [ "a", "b", "c" ]
 *     a.delete_if {|x| x >= "b" }   #=> ["a"]
 */

static VALUE
rb_ary_delete_if(ary)
    VALUE ary;
{
    rb_ary_reject_bang(ary);
    return ary;
}


reject (Array)

/*
 *  call-seq:
 *     array.reject {|item| block }  -> an_array
 *
 *  Returns a new array containing the items in _self_
 *  for which the block is not true.
 */

static VALUE
rb_ary_reject(ary)
    VALUE ary;
{
    ary = rb_ary_dup(ary);
    rb_ary_reject_bang(ary);
    return ary;
}


reject! (Array)

/*
 *  call-seq:
 *     array.reject! {|item| block }  -> array or nil
 *
 *  Equivalent to <code>Array#delete_if</code>, deleting elements from
 *  _self_ for which the block evaluates to true, but returns
 *  <code>nil</code> if no changes were made. Also see
 *  <code>Enumerable#reject</code>.
 */

static VALUE
rb_ary_reject_bang(ary)
    VALUE ary;
{
    long i1, i2;

    rb_ary_modify(ary);
    for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) {
        VALUE v = RARRAY(ary)->ptr[i1];
        if (RTEST(rb_yield(v))) continue;
        if (i1 != i2) {
            rb_ary_store(ary, i2, v);
        }
        i2++;
    }
    if (RARRAY(ary)->len == i2) return Qnil;
    if (i2 < RARRAY(ary)->len)
        RARRAY(ary)->len = i2;

    return ary;
}


zip (Array)

/*
 *  call-seq:
 *     array.zip(arg, ...)                   -> an_array
 *     array.zip(arg, ...) {| arr | block }  -> nil
 *
 *  Converts any arguments to arrays, then merges elements of
 *  <i>self</i> with corresponding elements from each argument. This
 *  generates a sequence of <code>self.size</code> <em>n</em>-element
 *  arrays, where <em>n</em> is one more that the count of arguments. If
 *  the size of any argument is less than <code>enumObj.size</code>,
 *  <code>nil</code> values are supplied. If a block given, it is
 *  invoked for each output array, otherwise an array of arrays is
 *  returned.
 *
 *     a = [ 4, 5, 6 ]
 *     b = [ 7, 8, 9 ]
 *
 *     [1,2,3].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
 *     [1,2].zip(a,b)         #=> [[1, 4, 7], [2, 5, 8]]
 *     a.zip([1,2],[8])       #=> [[4,1,8], [5,2,nil], [6,nil,nil]]
 */

static VALUE
rb_ary_zip(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    int i, j;
    long len;
    VALUE result;

    for (i=0; i<argc; i++) {
        argv[i] = to_ary(argv[i]);
    }
    if (rb_block_given_p()) {
        for (i=0; i<RARRAY(ary)->len; i++) {
            VALUE tmp = rb_ary_new2(argc+1);

            rb_ary_push(tmp, rb_ary_elt(ary, i));
            for (j=0; j<argc; j++) {
                rb_ary_push(tmp, rb_ary_elt(argv[j], i));
            }
            rb_yield(tmp);
        }
        return Qnil;
    }
    len = RARRAY(ary)->len;
    result = rb_ary_new2(len);
    for (i=0; i<len; i++) {
        VALUE tmp = rb_ary_new2(argc+1);

        rb_ary_push(tmp, rb_ary_elt(ary, i));
        for (j=0; j<argc; j++) {
            rb_ary_push(tmp, rb_ary_elt(argv[j], i));
        }
        rb_ary_push(result, tmp);
    }
    return result;
}


transpose (Array)

/*
 *  call-seq:
 *     array.transpose -> an_array
 *
 *  Assumes that <i>self</i> is an array of arrays and transposes the
 *  rows and columns.
 *
 *     a = [[1,2], [3,4], [5,6]]
 *     a.transpose   #=> [[1, 3, 5], [2, 4, 6]]
 */

static VALUE
rb_ary_transpose(ary)
    VALUE ary;
{
    long elen = -1, alen, i, j;
    VALUE tmp, result = 0;

    alen = RARRAY(ary)->len;
    if (alen == 0) return rb_ary_dup(ary);
    for (i=0; i<alen; i++) {
        tmp = to_ary(rb_ary_elt(ary, i));
        if (elen < 0) {                /* first element */
            elen = RARRAY(tmp)->len;
            result = rb_ary_new2(elen);
            for (j=0; j<elen; j++) {
                rb_ary_store(result, j, rb_ary_new2(alen));
            }
        }
        else if (elen != RARRAY(tmp)->len) {
            rb_raise(rb_eIndexError, "element size differs (%d should be %d)",
                     RARRAY(tmp)->len, elen);
        }
        for (j=0; j<elen; j++) {
            rb_ary_store(rb_ary_elt(result, j), i, rb_ary_elt(tmp, j));
        }
    }
    return result;
}


replace (Array)

/*
 *  call-seq:
 *     array.replace(other_array)  -> array
 *
 *  Replaces the contents of <i>self</i> with the contents of
 *  <i>other_array</i>, truncating or expanding if necessary.
 *
 *     a = [ "a", "b", "c", "d", "e" ]
 *     a.replace([ "x", "y", "z" ])   #=> ["x", "y", "z"]
 *     a                              #=> ["x", "y", "z"]
 */

static VALUE
rb_ary_replace(copy, orig)
    VALUE copy, orig;
{
    VALUE shared;

    rb_ary_modify(copy);
    orig = to_ary(orig);
    if (copy == orig) return copy;
    shared = ary_make_shared(orig);
    if (RARRAY(copy)->ptr && !FL_TEST(copy, ELTS_SHARED))
        free(RARRAY(copy)->ptr);
    RARRAY(copy)->ptr = RARRAY(orig)->ptr;
    RARRAY(copy)->len = RARRAY(orig)->len;
    RARRAY(copy)->aux.shared = shared;
    FL_SET(copy, ELTS_SHARED);

    return copy;
}


clear (Array)

/*
 *  call-seq:
 *     array.clear    ->  array
 *
 *  Removes all elements from _self_.
 *
 *     a = [ "a", "b", "c", "d", "e" ]
 *     a.clear    #=> [ ]
 */

VALUE
rb_ary_clear(ary)
    VALUE ary;
{
    rb_ary_modify(ary);
    RARRAY(ary)->len = 0;
    if (ARY_DEFAULT_SIZE * 2 < RARRAY(ary)->aux.capa) {
        REALLOC_N(RARRAY(ary)->ptr, VALUE, ARY_DEFAULT_SIZE * 2);
        RARRAY(ary)->aux.capa = ARY_DEFAULT_SIZE * 2;
    }
    return ary;
}


fill (Array)

/*
 *  call-seq:
 *     array.fill(obj)                                -> array
 *     array.fill(obj, start [, length])              -> array
 *     array.fill(obj, range )                        -> array
 *     array.fill {|index| block }                    -> array
 *     array.fill(start [, length] ) {|index| block } -> array
 *     array.fill(range) {|index| block }             -> array
 *
 *  The first three forms set the selected elements of <i>self</i> (which
 *  may be the entire array) to <i>obj</i>. A <i>start</i> of
 *  <code>nil</code> is equivalent to zero. A <i>length</i> of
 *  <code>nil</code> is equivalent to <i>self.length</i>. The last three
 *  forms fill the array with the value of the block. The block is
 *  passed the absolute index of each element to be filled.
 *
 *     a = [ "a", "b", "c", "d" ]
 *     a.fill("x")              #=> ["x", "x", "x", "x"]
 *     a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
 *     a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
 *     a.fill {|i| i*i}         #=> [0, 1, 4, 9]
 *     a.fill(-2) {|i| i*i*i}   #=> [0, 1, 8, 27]
 */

static VALUE
rb_ary_fill(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE item, arg1, arg2;
    long beg = 0, end = 0, len = 0;
    VALUE *p, *pend;
    int block_p = Qfalse;

    if (rb_block_given_p()) {
        block_p = Qtrue;
        rb_scan_args(argc, argv, "02", &arg1, &arg2);
        argc += 1;             /* hackish */
    }
    else {
        rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
    }
    switch (argc) {
      case 1:
        beg = 0;
        len = RARRAY(ary)->len;
        break;
      case 2:
        if (rb_range_beg_len(arg1, &beg, &len, RARRAY(ary)->len, 1)) {
            break;
        }
        /* fall through */
      case 3:
        beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1);
        if (beg < 0) {
            beg = RARRAY(ary)->len + beg;
            if (beg < 0) beg = 0;
        }
        len = NIL_P(arg2) ? RARRAY(ary)->len - beg : NUM2LONG(arg2);
        break;
    }
    rb_ary_modify(ary);
    end = beg + len;
    if (end < 0) {
        rb_raise(rb_eArgError, "argument too big");
    }
    if (end > RARRAY(ary)->len) {
        if (end >= RARRAY(ary)->aux.capa) {
            REALLOC_N(RARRAY(ary)->ptr, VALUE, end);
            RARRAY(ary)->aux.capa = end;
        }
        rb_mem_clear(RARRAY(ary)->ptr + RARRAY(ary)->len, end - RARRAY(ary)->len);
        RARRAY(ary)->len = end;
    }

    if (block_p) {
        VALUE v;
        long i;

        for (i=beg; i<end; i++) {
            v = rb_yield(LONG2NUM(i));
            if (i>=RARRAY(ary)->len) break;
            RARRAY(ary)->ptr[i] = v;
        }
    }
    else {
        p = RARRAY(ary)->ptr + beg;
        pend = p + len;
        while (p < pend) {
            *p++ = item;
        }
    }
    return ary;
}


include? (Array)

/*
 *  call-seq:
 *     array.include?(obj)   -> true or false
 *
 *  Returns <code>true</code> if the given object is present in
 *  <i>self</i> (that is, if any object <code>==</code> <i>anObject</i>),
 *  <code>false</code> otherwise.
 *
 *     a = [ "a", "b", "c" ]
 *     a.include?("b")   #=> true
 *     a.include?("z")   #=> false
 */

VALUE
rb_ary_includes(ary, item)
    VALUE ary;
    VALUE item;
{
    long i;

    for (i=0; i<RARRAY(ary)->len; i++) {
        if (rb_equal(RARRAY(ary)->ptr[i], item)) {
            return Qtrue;
        }
    }
    return Qfalse;
}


<=> (Array)

/*
 *  call-seq:
 *     array <=> other_array   ->  -1, 0, +1
 *
 *  Comparison---Returns an integer (-1, 0,
 *  or +1) if this array is less than, equal to, or greater than
 *  other_array.  Each object in each array is compared
 *  (using <=>). If any value isn't
 *  equal, then that inequality is the return value. If all the
 *  values found are equal, then the return is based on a
 *  comparison of the array lengths.  Thus, two arrays are
 *  ``equal'' according to <code>Array#<=></code> if and only if they have
 *  the same length and the value of each element is equal to the
 *  value of the corresponding element in the other array.
 *
 *     [ "a", "a", "c" ]    <=> [ "a", "b", "c" ]   #=> -1
 *     [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]            #=> +1
 *
 */

VALUE
rb_ary_cmp(ary1, ary2)
    VALUE ary1, ary2;
{
    long i, len;

    ary2 = to_ary(ary2);
    len = RARRAY(ary1)->len;
    if (len > RARRAY(ary2)->len) {
        len = RARRAY(ary2)->len;
    }
    for (i=0; i<len; i++) {
        VALUE v = rb_funcall(rb_ary_elt(ary1, i), id_cmp, 1, rb_ary_elt(ary2, i));
        if (v != INT2FIX(0)) {
            return v;
        }
    }
    len = RARRAY(ary1)->len - RARRAY(ary2)->len;
    if (len == 0) return INT2FIX(0);
    if (len > 0) return INT2FIX(1);
    return INT2FIX(-1);
}


slice (Array)

/*
 *  call-seq:
 *     array[index]                -> obj      or nil
 *     array[start, length]        -> an_array or nil
 *     array[range]                -> an_array or nil
 *     array.slice(index)          -> obj      or nil
 *     array.slice(start, length)  -> an_array or nil
 *     array.slice(range)          -> an_array or nil
 *
 *  Element Reference---Returns the element at _index_,
 *  or returns a subarray starting at _start_ and
 *  continuing for _length_ elements, or returns a subarray
 *  specified by _range_.
 *  Negative indices count backward from the end of the
 *  array (-1 is the last element). Returns nil if the index
 *  (or starting index) are out of range.
 *
 *     a = [ "a", "b", "c", "d", "e" ]
 *     a[2] +  a[0] + a[1]    #=> "cab"
 *     a[6]                   #=> nil
 *     a[1, 2]                #=> [ "b", "c" ]
 *     a[1..3]                #=> [ "b", "c", "d" ]
 *     a[4..7]                #=> [ "e" ]
 *     a[6..10]               #=> nil
 *     a[-3, 3]               #=> [ "c", "d", "e" ]
 *     # special cases
 *     a[5]                   #=> nil
 *     a[5, 1]                #=> []
 *     a[5..10]               #=> []
 *
 */

VALUE
rb_ary_aref(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE arg;
    long beg, len;

    if (argc == 2) {
        if (SYMBOL_P(argv[0])) {
            rb_raise(rb_eTypeError, "Symbol as array index");
        }
        beg = NUM2LONG(argv[0]);
        len = NUM2LONG(argv[1]);
        if (beg < 0) {
            beg += RARRAY(ary)->len;
        }
        return rb_ary_subseq(ary, beg, len);
    }
    if (argc != 1) {
        rb_scan_args(argc, argv, "11", 0, 0);
    }
    arg = argv[0];
    /* special case - speeding up */
    if (FIXNUM_P(arg)) {
        return rb_ary_entry(ary, FIX2LONG(arg));
    }
    if (SYMBOL_P(arg)) {
        rb_raise(rb_eTypeError, "Symbol as array index");
    }
    /* check if idx is Range */
    switch (rb_range_beg_len(arg, &beg, &len, RARRAY(ary)->len, 0)) {
      case Qfalse:
        break;
      case Qnil:
        return Qnil;
      default:
        return rb_ary_subseq(ary, beg, len);
    }
    return rb_ary_entry(ary, NUM2LONG(arg));
}


slice! (Array)

/*
 *  call-seq:
 *     array.slice!(index)         -> obj or nil
 *     array.slice!(start, length) -> sub_array or nil
 *     array.slice!(range)         -> sub_array or nil
 *
 *  Deletes the element(s) given by an index (optionally with a length)
 *  or by a range. Returns the deleted object, subarray, or
 *  <code>nil</code> if the index is out of range. Equivalent to:
 *
 *     def slice!(*args)
 *       result = self[*args]
 *       self[*args] = nil
 *       result
 *     end
 *
 *     a = [ "a", "b", "c" ]
 *     a.slice!(1)     #=> "b"
 *     a               #=> ["a", "c"]
 *     a.slice!(-1)    #=> "c"
 *     a               #=> ["a"]
 *     a.slice!(100)   #=> nil
 *     a               #=> ["a"]
 */

static VALUE
rb_ary_slice_bang(argc, argv, ary)
    int argc;
    VALUE *argv;
    VALUE ary;
{
    VALUE arg1, arg2;
    long pos, len;

    if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) {
        pos = NUM2LONG(arg1);
        len = NUM2LONG(arg2);
      delete_pos_len:
        if (pos < 0) {
            pos = RARRAY(ary)->len + pos;
        }
        arg2 = rb_ary_subseq(ary, pos, len);
        rb_ary_splice(ary, pos, len, Qnil);    /* Qnil/rb_ary_new2(0) */
        return arg2;
    }

    if (!FIXNUM_P(arg1) && rb_range_beg_len(arg1, &pos, &len, RARRAY(ary)->len, 1)) {
        goto delete_pos_len;
    }

    return rb_ary_delete_at(ary, NUM2LONG(arg1));
}


assoc (Array)

/*
 *  call-seq:
 *     array.assoc(obj)   ->  an_array  or  nil
 *
 *  Searches through an array whose elements are also arrays
 *  comparing _obj_ with the first element of each contained array
 *  using obj.==.
 *  Returns the first contained array that matches (that
 *  is, the first associated array),
 *  or +nil+ if no match is found.
 *  See also <code>Array#rassoc</code>.
 *
 *     s1 = [ "colors", "red", "blue", "green" ]
 *     s2 = [ "letters", "a", "b", "c" ]
 *     s3 = "foo"
 *     a  = [ s1, s2, s3 ]
 *     a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
 *     a.assoc("foo")      #=> nil
 */

VALUE
rb_ary_assoc(ary, key)
    VALUE ary, key;
{
    long i;
    VALUE v;

    for (i = 0; i < RARRAY(ary)->len; ++i) {
        v = RARRAY(ary)->ptr[i];
        if (TYPE(v) == T_ARRAY &&
            RARRAY(v)->len > 0 &&
            rb_equal(RARRAY(v)->ptr[0], key))
            return v;
    }
    return Qnil;
}


rassoc (Array)

/*
 *  call-seq:
 *     array.rassoc(key) -> an_array or nil
 *
 *  Searches through the array whose elements are also arrays. Compares
 *  <em>key</em> with the second element of each contained array using
 *  <code>==</code>. Returns the first contained array that matches. See
 *  also <code>Array#assoc</code>.
 *
 *     a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
 *     a.rassoc("two")    #=> [2, "two"]
 *     a.rassoc("four")   #=> nil
 */

VALUE
rb_ary_rassoc(ary, value)
    VALUE ary, value;
{
    long i;
    VALUE v;

    for (i = 0; i < RARRAY(ary)->len; ++i) {
        v = RARRAY(ary)->ptr[i];
        if (TYPE(v) == T_ARRAY &&
            RARRAY(v)->len > 1 &&
            rb_equal(RARRAY(v)->ptr[1], value))
            return v;
    }
    return Qnil;
}


+ (Array)

/*
 *  call-seq:
 *     array + other_array   -> an_array
 *
 *  Concatenation---Returns a new array built by concatenating the
 *  two arrays together to produce a third array.
 *
 *     [ 1, 2, 3 ] + [ 4, 5 ]    #=> [ 1, 2, 3, 4, 5 ]
 */

VALUE
rb_ary_plus(x, y)
    VALUE x, y;
{
    VALUE z;
    long len;

    y = to_ary(y);
    len = RARRAY(x)->len + RARRAY(y)->len;
    z = rb_ary_new2(len);
    MEMCPY(RARRAY(z)->ptr, RARRAY(x)->ptr, VALUE, RARRAY(x)->len);
    MEMCPY(RARRAY(z)->ptr + RARRAY(x)->len, RARRAY(y)->ptr, VALUE, RARRAY(y)->len);
    RARRAY(z)->len = len;
    return z;
}


* (Array)

/*
 *  call-seq:
 *     array * int     ->    an_array
 *     array * str     ->    a_string
 *
 *  Repetition---With a String argument, equivalent to
 *  self.join(str). Otherwise, returns a new array
 *  built by concatenating the _int_ copies of _self_.
 *
 *
 *     [ 1, 2, 3 ] * 3    #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
 *     [ 1, 2, 3 ] * ","  #=> "1,2,3"
 *
 */

static VALUE
rb_ary_times(ary, times)
    VALUE ary, times;
{
    VALUE ary2, tmp;
    long i, len;

    tmp = rb_check_string_type(times);
    if (!NIL_P(tmp)) {
        return rb_ary_join(ary, tmp);
    }

    len = NUM2LONG(times);
    if (len == 0) return ary_new(rb_obj_class(ary), 0);
    if (len < 0) {
        rb_raise(rb_eArgError, "negative argument");
    }
    if (LONG_MAX/len < RARRAY(ary)->len) {
        rb_raise(rb_eArgError, "argument too big");
    }
    len *= RARRAY(ary)->len;

    ary2 = ary_new(rb_obj_class(ary), len);
    RARRAY(ary2)->len = len;

    for (i=0; i<len; i+=RARRAY(ary)->len) {
        MEMCPY(RARRAY(ary2)->ptr+i, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);
    }
    OBJ_INFECT(ary2, ary);

    return ary2;
}


- (Array)

/*
 *  call-seq:
 *     array - other_array    -> an_array
 *
 *  Array Difference---Returns a new array that is a copy of
 *  the original array, removing any items that also appear in
 *  other_array. (If you need set-like behavior, see the
 *  library class Set.)
 *
 *     [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]
 */

static VALUE
rb_ary_diff(ary1, ary2)
    VALUE ary1, ary2;
{
    VALUE ary3;
    volatile VALUE hash;
    long i;

    hash = ary_make_hash(to_ary(ary2), 0);
    ary3 = rb_ary_new();

    for (i=0; i<RARRAY(ary1)->len; i++) {
        if (st_lookup(RHASH(hash)->tbl, RARRAY(ary1)->ptr[i], 0)) continue;
        rb_ary_push(ary3, rb_ary_elt(ary1, i));
    }
    return ary3;
}


& (Array)

/*
 *  call-seq:
 *     array & other_array
 *
 *  Set Intersection---Returns a new array
 *  containing elements common to the two arrays, with no duplicates.
 *
 *     [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
 */

static VALUE
rb_ary_and(ary1, ary2)
    VALUE ary1, ary2;
{
    VALUE hash, ary3, v, vv;
    long i;

    ary2 = to_ary(ary2);
    ary3 = rb_ary_new2(RARRAY(ary1)->len < RARRAY(ary2)->len ?
            RARRAY(ary1)->len : RARRAY(ary2)->len);
    hash = ary_make_hash(ary2, 0);

    for (i=0; i<RARRAY(ary1)->len; i++) {
        v = vv = rb_ary_elt(ary1, i);
        if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) {
            rb_ary_push(ary3, v);
        }
    }

    return ary3;
}


| (Array)

/*
 *  call-seq:
 *     array | other_array     ->  an_array
 *
 *  Set Union---Returns a new array by joining this array with
 *  other_array, removing duplicates.
 *
 *     [ "a", "b", "c" ] | [ "c", "d", "a" ]
 *            #=> [ "a", "b", "c", "d" ]
 */

static VALUE
rb_ary_or(ary1, ary2)
    VALUE ary1, ary2;
{
    VALUE hash, ary3;
    VALUE v, vv;
    long i;

    ary2 = to_ary(ary2);
    ary3 = rb_ary_new2(RARRAY(ary1)->len+RARRAY(ary2)->len);
    hash = ary_make_hash(ary1, ary2);

    for (i=0; i<RARRAY(ary1)->len; i++) {
        v = vv = rb_ary_elt(ary1, i);
        if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) {
            rb_ary_push(ary3, v);
        }
    }
    for (i=0; i<RARRAY(ary2)->len; i++) {
        v = vv = rb_ary_elt(ary2, i);
        if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) {
            rb_ary_push(ary3, v);
        }
    }
    return ary3;
}


uniq (Array)

/*
 *  call-seq:
 *     array.uniq   -> an_array
 *
 *  Returns a new array by removing duplicate values in <i>self</i>.
 *
 *     a = [ "a", "a", "b", "b", "c" ]
 *     a.uniq   #=> ["a", "b", "c"]
 */

static VALUE
rb_ary_uniq(ary)
    VALUE ary;
{
    ary = rb_ary_dup(ary);
    rb_ary_uniq_bang(ary);
    return ary;
}


uniq! (Array)

/*
 *  call-seq:
 *     array.uniq! -> array or nil
 *
 *  Removes duplicate elements from _self_.
 *  Returns <code>nil</code> if no changes are made (that is, no
 *  duplicates are found).
 *
 *     a = [ "a", "a", "b", "b", "c" ]
 *     a.uniq!   #=> ["a", "b", "c"]
 *     b = [ "a", "b", "c" ]
 *     b.uniq!   #=> nil
 */

static VALUE
rb_ary_uniq_bang(ary)
    VALUE ary;
{
    VALUE hash, v, vv;
    long i, j;

    hash = ary_make_hash(ary, 0);

    if (RARRAY(ary)->len == RHASH(hash)->tbl->num_entries) {
        return Qnil;
    }
    for (i=j=0; i<RARRAY(ary)->len; i++) {
        v = vv = rb_ary_elt(ary, i);
        if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) {
            rb_ary_store(ary, j++, v);
        }
    }
    RARRAY(ary)->len = j;

    return ary;
}


compact (Array)

/*
 *  call-seq:
 *     array.compact     ->  an_array
 *
 *  Returns a copy of _self_ with all +nil+ elements removed.
 *
 *     [ "a", nil, "b", nil, "c", nil ].compact
 *                       #=> [ "a", "b", "c" ]
 */

static VALUE
rb_ary_compact(ary)
    VALUE ary;
{
    ary = rb_ary_dup(ary);
    rb_ary_compact_bang(ary);
    return ary;
}


compact! (Array)

/*
 *  call-seq:
 *     array.compact!    ->   array  or  nil
 *
 *  Removes +nil+ elements from array.
 *  Returns +nil+ if no changes were made.
 *
 *     [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
 *     [ "a", "b", "c" ].compact!           #=> nil
 */

static VALUE
rb_ary_compact_bang(ary)
    VALUE ary;
{
    VALUE *p, *t, *end;

    rb_ary_modify(ary);
    p = t = RARRAY(ary)->ptr;
    end = p + RARRAY(ary)->len;

    while (t < end) {
        if (NIL_P(*t)) t++;
        else *p++ = *t++;
    }
    if (RARRAY(ary)->len == (p - RARRAY(ary)->ptr)) {
        return Qnil;
    }
    RARRAY(ary)->len = RARRAY(ary)->aux.capa = (p - RARRAY(ary)->ptr);
    REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);

    return ary;
}


flatten (Array)

/*
 *  call-seq:
 *     array.flatten -> an_array
 *
 *  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(ary)
    VALUE ary;
{
    ary = rb_ary_dup(ary);
    rb_ary_flatten_bang(ary);
    return ary;
}


flatten! (Array)

/*
 *  call-seq:
 *     array.flatten! -> array or nil
 *
 *  Flattens _self_ in place.
 *  Returns <code>nil</code> if no modifications were made (i.e.,
 *  <i>array</i> contains no subarrays.)
 *
 *     a = [ 1, 2, [3, [4, 5] ] ]
 *     a.flatten!   #=> [1, 2, 3, 4, 5]
 *     a.flatten!   #=> nil
 *     a            #=> [1, 2, 3, 4, 5]
 */

static VALUE
rb_ary_flatten_bang(ary)
    VALUE ary;
{
    long i = 0;
    int mod = 0;
    VALUE memo = Qnil;

    while (i<RARRAY(ary)->len) {
        VALUE ary2 = RARRAY(ary)->ptr[i];
        VALUE tmp;

        tmp = rb_check_array_type(ary2);
        if (!NIL_P(tmp)) {
            if (NIL_P(memo)) {
                memo = rb_ary_new();
            }
            i += flatten(ary, i, tmp, memo);
            mod = 1;
        }
        i++;
    }
    if (mod == 0) return Qnil;
    return ary;
}


nitems (Array)

/*
 *  call-seq:
 *     array.nitems -> int
 *
 *  Returns the number of non-<code>nil</code> elements in _self_.
 *  May be zero.
 *
 *     [ 1, nil, 3, nil, 5 ].nitems   #=> 3
 */

static VALUE
rb_ary_nitems(ary)
    VALUE ary;
{
    long n = 0;
    VALUE *p, *pend;

    p = RARRAY(ary)->ptr;
    pend = p + RARRAY(ary)->len;

    while (p < pend) {
        if (!NIL_P(*p)) n++;
        p++;
    }
    return LONG2NUM(n);
}


pack (Array)

/*
 *  call-seq:
 *     arr.pack ( aTemplateString ) -> aBinaryString
 *
 *  Packs the contents of <i>arr</i> into a binary sequence according to
 *  the directives in <i>aTemplateString</i> (see the table below)
 *  Directives ``A,'' ``a,'' and ``Z'' may be followed by a count,
 *  which gives the width of the resulting field. The remaining
 *  directives also may take a count, indicating the number of array
 *  elements to convert. If the count is an asterisk
 *  (``<code>*</code>''), all remaining array elements will be
 *  converted. Any of the directives ``<code>sSiIlL</code>'' may be
 *  followed by an underscore (``<code>_</code>'') to use the underlying
 *  platform's native size for the specified type; otherwise, they use a
 *  platform-independent size. Spaces are ignored in the template
 *  string. See also <code>String#unpack</code>.
 *
 *     a = [ "a", "b", "c" ]
 *     n = [ 65, 66, 67 ]
 *     a.pack("A3A3A3")   #=> "a  b  c  "
 *     a.pack("a3a3a3")   #=> "a\000\000b\000\000c\000\000"
 *     n.pack("ccc")      #=> "ABC"
 *
 *  Directives for +pack+.
 *
 *   Directive    Meaning
 *   ---------------------------------------------------------------
 *       @     |  Moves to absolute position
 *       A     |  ASCII string (space padded, count is width)
 *       a     |  ASCII string (null padded, count is width)
 *       B     |  Bit string (descending bit order)
 *       b     |  Bit string (ascending bit order)
 *       C     |  Unsigned char
 *       c     |  Char
 *       D, d  |  Double-precision float, native format
 *       E     |  Double-precision float, little-endian byte order
 *       e     |  Single-precision float, little-endian byte order
 *       F, f  |  Single-precision float, native format
 *       G     |  Double-precision float, network (big-endian) byte order
 *       g     |  Single-precision float, network (big-endian) byte order
 *       H     |  Hex string (high nibble first)
 *       h     |  Hex string (low nibble first)
 *       I     |  Unsigned integer
 *       i     |  Integer
 *       L     |  Unsigned long
 *       l     |  Long
 *       M     |  Quoted printable, MIME encoding (see RFC2045)
 *       m     |  Base64 encoded string
 *       N     |  Long, network (big-endian) byte order
 *       n     |  Short, network (big-endian) byte-order
 *       P     |  Pointer to a structure (fixed-length string)
 *       p     |  Pointer to a null-terminated string
 *       Q, q  |  64-bit number
 *       S     |  Unsigned short
 *       s     |  Short
 *       U     |  UTF-8
 *       u     |  UU-encoded string
 *       V     |  Long, little-endian byte order
 *       v     |  Short, little-endian byte order
 *       w     |  BER-compressed integer\fnm
 *       X     |  Back up a byte
 *       x     |  Null byte
 *       Z     |  Same as ``a'', except that null is added with *
 */

static VALUE
pack_pack(ary, fmt)
    VALUE ary, fmt;
{
    static char *nul10 = "\0\0\0\0\0\0\0\0\0\0";
    static char *spc10 = "          ";
    char *p, *pend;
    VALUE res, from, associates = 0;
    char type;
    long items, len, idx, plen;
    char *ptr;
#ifdef NATINT_PACK
    int natint;         /* native integer */
#endif

    StringValue(fmt);
    p = RSTRING(fmt)->ptr;
    pend = p + RSTRING(fmt)->len;
    res = rb_str_buf_new(0);

    items = RARRAY(ary)->len;
    idx = 0;

#define TOO_FEW (rb_raise(rb_eArgError, toofew), 0)
#define THISFROM (items > 0 ? RARRAY(ary)->ptr[idx] : TOO_FEW)
#define NEXTFROM (items-- > 0 ? RARRAY(ary)->ptr[idx++] : TOO_FEW)

    while (p < pend) {
        if (RSTRING(fmt)->ptr + RSTRING(fmt)->len != pend) {
            rb_raise(rb_eRuntimeError, "format string modified");
        }
        type = *p++;           /* get data type */
#ifdef NATINT_PACK
        natint = 0;
#endif

        if (ISSPACE(type)) continue;
        if (type == '#') {
            while ((p < pend) && (*p != '\n')) {
                p++;
            }
            continue;
        }
        if (*p == '_' || *p == '!') {
            const char *natstr = "sSiIlL";

            if (strchr(natstr, type)) {
#ifdef NATINT_PACK
                natint = 1;
#endif
                p++;
            }
            else {
                rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
            }
        }
        if (*p == '*') {       /* set data length */
            len = strchr("@Xxu", type) ? 0 : items;
            p++;
        }
        else if (ISDIGIT(*p)) {
            len = strtoul(p, (char**)&p, 10);
        }
        else {
            len = 1;
        }

        switch (type) {
          case 'A': case 'a': case 'Z':
          case 'B': case 'b':
          case 'H': case 'h':
            from = NEXTFROM;
            if (NIL_P(from)) {
                ptr = "";
                plen = 0;
            }
            else {
                StringValue(from);
                ptr = RSTRING(from)->ptr;
                plen = RSTRING(from)->len;
                OBJ_INFECT(res, from);
            }

            if (p[-1] == '*')
                len = plen;

            switch (type) {
              case 'a':                /* arbitrary binary string (null padded)  */
              case 'A':                /* ASCII string (space padded) */
              case 'Z':                /* null terminated ASCII string  */
                if (plen >= len) {
                    rb_str_buf_cat(res, ptr, len);
                    if (p[-1] == '*' && type == 'Z')
                        rb_str_buf_cat(res, nul10, 1);
                }
                else {
                    rb_str_buf_cat(res, ptr, plen);
                    len -= plen;
                    while (len >= 10) {
                        rb_str_buf_cat(res, (type == 'A')?spc10:nul10, 10);
                        len -= 10;
                    }
                    rb_str_buf_cat(res, (type == 'A')?spc10:nul10, len);
                }
                break;

              case 'b':                /* bit string (ascending) */
                {
                    int byte = 0;
                    long i, j = 0;

                    if (len > plen) {
                        j = (len - plen + 1)/2;
                        len = plen;
                    }
                    for (i=0; i++ < len; ptr++) {
                        if (*ptr & 1)
                            byte |= 128;
                        if (i & 7)
                            byte >>= 1;
                        else {
                            char c = byte & 0xff;
                            rb_str_buf_cat(res, &c, 1);
                            byte = 0;
                        }
                    }
                    if (len & 7) {
                        char c;
                        byte >>= 7 - (len & 7);
                        c = byte & 0xff;
                        rb_str_buf_cat(res, &c, 1);
                    }
                    len = j;
                    goto grow;
                }
                break;

              case 'B':                /* bit string (descending) */
                {
                    int byte = 0;
                    long i, j = 0;

                    if (len > plen) {
                        j = (len - plen + 1)/2;
                        len = plen;
                    }
                    for (i=0; i++ < len; ptr++) {
                        byte |= *ptr & 1;
                        if (i & 7)
                            byte <<= 1;
                        else {
                            char c = byte & 0xff;
                            rb_str_buf_cat(res, &c, 1);
                            byte = 0;
                        }
                    }
                    if (len & 7) {
                        char c;
                        byte <<= 7 - (len & 7);
                        c = byte & 0xff;
                        rb_str_buf_cat(res, &c, 1);
                    }
                    len = j;
                    goto grow;
                }
                break;

              case 'h':                /* hex string (low nibble first) */
                {
                    int byte = 0;
                    long i, j = 0;

                    if (len > plen) {
                        j = (len - plen + 1)/2;
                        len = plen;
                    }
                    for (i=0; i++ < len; ptr++) {
                        if (ISALPHA(*ptr))
                            byte |= (((*ptr & 15) + 9) & 15) << 4;
                        else
                            byte |= (*ptr & 15) << 4;
                        if (i & 1)
                            byte >>= 4;
                        else {
                            char c = byte & 0xff;
                            rb_str_buf_cat(res, &c, 1);
                            byte = 0;
                        }
                    }
                    if (len & 1) {
                        char c = byte & 0xff;
                        rb_str_buf_cat(res, &c, 1);
                    }
                    len = j;
                    goto grow;
                }
                break;

              case 'H':                /* hex string (high nibble first) */
                {
                    int byte = 0;
                    long i, j = 0;

                    if (len > plen) {
                        j = (len - plen + 1)/2;
                        len = plen;
                    }
                    for (i=0; i++ < len; ptr++) {
                        if (ISALPHA(*ptr))
                            byte |= ((*ptr & 15) + 9) & 15;
                        else
                            byte |= *ptr & 15;
                        if (i & 1)
                            byte <<= 4;
                        else {
                            char c = byte & 0xff;
                            rb_str_buf_cat(res, &c, 1);
                            byte = 0;
                        }
                    }
                    if (len & 1) {
                        char c = byte & 0xff;
                        rb_str_buf_cat(res, &c, 1);
                    }
                    len = j;
                    goto grow;
                }
                break;
            }
            break;

          case 'c':            /* signed char */
          case 'C':            /* unsigned char */
            while (len-- > 0) {
                char c;

                from = NEXTFROM;
                c = num2i32(from);
                rb_str_buf_cat(res, &c, sizeof(char));
            }
            break;

          case 's':            /* signed short */
          case 'S':            /* unsigned short */
            while (len-- > 0) {
                short s;

                from = NEXTFROM;
                s = num2i32(from);
                rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
            }
            break;

          case 'i':            /* signed int */
          case 'I':            /* unsigned int */
            while (len-- > 0) {
                long i;

                from = NEXTFROM;
                i = num2i32(from);
                rb_str_buf_cat(res, OFF32(&i), NATINT_LEN(int,4));
            }
            break;

          case 'l':            /* signed long */
          case 'L':            /* unsigned long */
            while (len-- > 0) {
                long l;

                from = NEXTFROM;
                l = num2i32(from);
                rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
            }
            break;

          case 'q':            /* signed quad (64bit) int */
          case 'Q':            /* unsigned quad (64bit) int */
            while (len-- > 0) {
                char tmp[QUAD_SIZE];

                from = NEXTFROM;
                rb_quad_pack(tmp, from);
                rb_str_buf_cat(res, (char*)&tmp, QUAD_SIZE);
            }
            break;

          case 'n':            /* unsigned short (network byte-order)  */
            while (len-- > 0) {
                unsigned short s;

                from = NEXTFROM;
                s = num2i32(from);
                s = NATINT_HTONS(s);
                rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
            }
            break;

          case 'N':            /* unsigned long (network byte-order) */
            while (len-- > 0) {
                unsigned long l;

                from = NEXTFROM;
                l = num2i32(from);
                l = NATINT_HTONL(l);
                rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
            }
            break;

          case 'v':            /* unsigned short (VAX byte-order) */
            while (len-- > 0) {
                unsigned short s;

                from = NEXTFROM;
                s = num2i32(from);
                s = NATINT_HTOVS(s);
                rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
            }
            break;

          case 'V':            /* unsigned long (VAX byte-order) */
            while (len-- > 0) {
                unsigned long l;

                from = NEXTFROM;
                l = num2i32(from);
                l = NATINT_HTOVL(l);
                rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
            }
            break;

          case 'f':            /* single precision float in native format */
          case 'F':            /* ditto */
            while (len-- > 0) {
                float f;

                from = NEXTFROM;
                f = RFLOAT(rb_Float(from))->value;
                rb_str_buf_cat(res, (char*)&f, sizeof(float));
            }
            break;

          case 'e':            /* single precision float in VAX byte-order */
            while (len-- > 0) {
                float f;
                FLOAT_CONVWITH(ftmp);

                from = NEXTFROM;
                f = RFLOAT(rb_Float(from))->value;
                f = HTOVF(f,ftmp);
                rb_str_buf_cat(res, (char*)&f, sizeof(float));
            }
            break;

          case 'E':            /* double precision float in VAX byte-order */
            while (len-- > 0) {
                double d;
                DOUBLE_CONVWITH(dtmp);

                from = NEXTFROM;
                d = RFLOAT(rb_Float(from))->value;
                d = HTOVD(d,dtmp);
                rb_str_buf_cat(res, (char*)&d, sizeof(double));
            }
            break;

          case 'd':            /* double precision float in native format */
          case 'D':            /* ditto */
            while (len-- > 0) {
                double d;

                from = NEXTFROM;
                d = RFLOAT(rb_Float(from))->value;
                rb_str_buf_cat(res, (char*)&d, sizeof(double));
            }
            break;

          case 'g':            /* single precision float in network byte-order */
            while (len-- > 0) {
                float f;
                FLOAT_CONVWITH(ftmp);

                from = NEXTFROM;
                f = RFLOAT(rb_Float(from))->value;
                f = HTONF(f,ftmp);
                rb_str_buf_cat(res, (char*)&f, sizeof(float));
            }
            break;

          case 'G':            /* double precision float in network byte-order */
            while (len-- > 0) {
                double d;
                DOUBLE_CONVWITH(dtmp);

                from = NEXTFROM;
                d = RFLOAT(rb_Float(from))->value;
                d = HTOND(d,dtmp);
                rb_str_buf_cat(res, (char*)&d, sizeof(double));
            }
            break;

          case 'x':            /* null byte */
          grow:
            while (len >= 10) {
                rb_str_buf_cat(res, nul10, 10);
                len -= 10;
            }
            rb_str_buf_cat(res, nul10, len);
            break;

          case 'X':            /* back up byte */
          shrink:
            plen = RSTRING(res)->len;
            if (plen < len)
                rb_raise(rb_eArgError, "X outside of string");
            RSTRING(res)->len = plen - len;
            RSTRING(res)->ptr[plen - len] = '\0';
            break;

          case '@':            /* null fill to absolute position */
            len -= RSTRING(res)->len;
            if (len > 0) goto grow;
            len = -len;
            if (len > 0) goto shrink;
            break;

          case '%':
            rb_raise(rb_eArgError, "%% is not supported");
            break;

          case 'U':            /* Unicode character */
            while (len-- > 0) {
                long l;
                char buf[8];
                int le;

                from = NEXTFROM;
                from = rb_to_int(from);
                l = NUM2INT(from);
                if (l < 0) {
                    rb_raise(rb_eRangeError, "pack(U): value out of range");
                }
                le = uv_to_utf8(buf, l);
                rb_str_buf_cat(res, (char*)buf, le);
            }
            break;

          case 'u':            /* uuencoded string */
          case 'm':            /* base64 encoded string */
            from = NEXTFROM;
            StringValue(from);
            ptr = RSTRING(from)->ptr;
            plen = RSTRING(from)->len;

            if (len <= 2)
                len = 45;
            else
                len = len / 3 * 3;
            while (plen > 0) {
                long todo;

                if (plen > len)
                    todo = len;
                else
                    todo = plen;
                encodes(res, ptr, todo, type);
                plen -= todo;
                ptr += todo;
            }
            break;

          case 'M':            /* quoted-printable encoded string */
            from = rb_obj_as_string(NEXTFROM);
            if (len <= 1)
                len = 72;
            qpencode(res, from, len);
            break;

          case 'P':            /* pointer to packed byte string */
            from = THISFROM;
            if (!NIL_P(from)) {
                StringValue(from);
                if (RSTRING(from)->len < len) {
                    rb_raise(rb_eArgError, "too short buffer for P(%ld for %ld)",
                             RSTRING(from)->len, len);
                }
            }
            len = 1;
            /* FALL THROUGH */
          case 'p':            /* pointer to string */
            while (len-- > 0) {
                char *t;
                from = NEXTFROM;
                if (NIL_P(from)) {
                    t = 0;
                }
                else {
                    t = StringValuePtr(from);
                }
                if (!associates) {
                    associates = rb_ary_new();
                }
                rb_ary_push(associates, from);
                rb_obj_taint(from);
                rb_str_buf_cat(res, (char*)&t, sizeof(char*));
            }
            break;

          case 'w':            /* BER compressed integer  */
            while (len-- > 0) {
                unsigned long ul;
                VALUE buf = rb_str_new(0, 0);
                char c, *bufs, *bufe;

                from = NEXTFROM;
                if (TYPE(from) == T_BIGNUM) {
                    VALUE big128 = rb_uint2big(128);
                    while (TYPE(from) == T_BIGNUM) {
                        from = rb_big_divmod(from, big128);
                        c = NUM2INT(RARRAY(from)->ptr[1]) | 0x80; /* mod */
                        rb_str_buf_cat(buf, &c, sizeof(char));
                        from = RARRAY(from)->ptr[0]; /* div */
                    }
                }

                {
                    long l = NUM2LONG(from);
                    if (l < 0) {
                        rb_raise(rb_eArgError, "can't compress negative numbers");
                    }
                    ul = l;
                }

                while (ul) {
                    c = ((ul & 0x7f) | 0x80);
                    rb_str_buf_cat(buf, &c, sizeof(char));
                    ul >>=  7;
                }

                if (RSTRING(buf)->len) {
                    bufs = RSTRING(buf)->ptr;
                    bufe = bufs + RSTRING(buf)->len - 1;
                    *bufs &= 0x7f; /* clear continue bit */
                    while (bufs < bufe) { /* reverse */
                        c = *bufs;
                        *bufs++ = *bufe;
                        *bufe-- = c;
                    }
                    rb_str_buf_cat(res, RSTRING(buf)->ptr, RSTRING(buf)->len);
                }
                else {
                    c = 0;
                    rb_str_buf_cat(res, &c, sizeof(char));
                }
            }
            break;

          default:
            break;
        }
    }

    if (associates) {
        rb_str_associate(res, associates);
    }
    return res;
}


abbrev (Array)

# File lib/abbrev.rb, line 90
  def abbrev(pattern = nil)
    Abbrev::abbrev(self, pattern)
  end


quote (Array)

# File lib/mkmf.rb, line 137
  def quote
    map {|s| s.quote}
  end


pretty_print (Array)

# File lib/pp.rb, line 301
  def pretty_print(q)
    q.group(1, '[', ']') {
      q.seplist(self) {|v|
        q.pp v
      }
    }
  end


pretty_print_cycle (Array)

# File lib/pp.rb, line 309
  def pretty_print_cycle(q)
    q.text(empty? ? '[]' : '[...]')
  end


dclone (Array)

# File lib/rexml/xpath_parser.rb, line 22
  def dclone
    klone = self.clone
    klone.clear
    self.each{|v| klone << v.dclone}
    klone
  end


yaml_initialize (Array)

# File lib/yaml/rubytypes.rb, line 105
    def yaml_initialize( tag, val ); concat( val.to_a ); end


to_yaml (Array)

# File lib/yaml/rubytypes.rb, line 106
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            out.seq( taguri, to_yaml_style ) do |seq|
                each do |x|
                    seq.add( x )
                end
            end
        end
        end


decode64 (Base64)

# File lib/base64.rb, line 58
  def decode64(str)
    str.unpack("m")[0]
  end


decode_b (Base64)

# File lib/base64.rb, line 72
  def decode_b(str)
    str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) {
      decode64($1)
    }
    str = Kconv::toeuc(str)
    str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) {
      decode64($1)
    }
    str = Kconv::toeuc(str)
    str.gsub!(/\n/, ' ')
    str.gsub!(/\0/, '')
    str
  end


encode64 (Base64)

# File lib/base64.rb, line 96
  def encode64(bin)
    [bin].pack("m")
  end


b64encode (Base64)

# File lib/base64.rb, line 112
  def b64encode(bin, len = 60)
    encode64(bin).scan(/.{1,#{len}}/) do
      print $&, "\n"
    end
  end


setsockopt (BasicSocket)

/*
 * Document-method: setsockopt
 * call-seq: setsockopt(level, optname, optval)
 *
 * Sets a socket option. These are protocol and system specific, see your
 * local sytem documentation for details.
 *
 * === Parameters
 * * +level+ is an integer, usually one of the SOL_ constants such as
 *   Socket::SOL_SOCKET, or a protocol level.
 * * +optname+ is an integer, usually one of the SO_ constants, such
 *   as Socket::SO_REUSEADDR.
 * * +optval+ is the value of the option, it is passed to the underlying
 *   setsockopt() as a pointer to a certain number of bytes. How this is
 *   done depends on the type:
 *   - Fixnum: value is assigned to an int, and a pointer to the int is
 *     passed, with length of sizeof(int).
 *   - true or false: 1 or 0 (respectively) is assigned to an int, and the
 *     int is passed as for a Fixnum. Note that +false+ must be passed,
 *     not +nil+.
 *   - String: the string's data and length is passed to the socket.
 *
 * === Examples
 *
 * Some socket options are integers with boolean values, in this case
 * #setsockopt could be called like this:
 *   sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
 *
 * Some socket options are integers with numeric values, in this case
 * #setsockopt could be called like this:
 *   sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255)
 *
 * Option values may be structs. Passing them can be complex as it involves
 * examining your system headers to determine the correct definition. An
 * example is an +ip_mreq+, which may be defined in your system headers as:
 *   struct ip_mreq {
 *     struct  in_addr imr_multiaddr;
 *     struct  in_addr imr_interface;
 *   };
 *
 * In this case #setsockopt could be called like this:
 *   optval =  IPAddr.new("224.0.0.251") + Socket::INADDR_ANY
 *   sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval)
 *
*/
static VALUE
bsock_setsockopt(sock, lev, optname, val)
    VALUE sock, lev, optname, val;
{
    int level, option;
    OpenFile *fptr;
    int i;
    char *v;
    int vlen;

    rb_secure(2);
    level = NUM2INT(lev);
    option = NUM2INT(optname);

    switch (TYPE(val)) {
      case T_FIXNUM:
        i = FIX2INT(val);
        goto numval;
      case T_FALSE:
        i = 0;
        goto numval;
      case T_TRUE:
        i = 1;
      numval:
        v = (char*)&i; vlen = sizeof(i);
        break;
      default:
        StringValue(val);
        v = RSTRING(val)->ptr;
        vlen = RSTRING(val)->len;
        break;
    }

    GetOpenFile(sock, fptr);
    if (setsockopt(fileno(fptr->f), level, option, v, vlen) < 0)
        rb_sys_fail(fptr->path);

    return INT2FIX(0);
}


getsockopt (BasicSocket)

/*
 * Document-method: getsockopt
 * call-seq: getsockopt(level, optname)
 *
 * Gets a socket option. These are protocol and system specific, see your
 * local sytem documentation for details. The option is returned as
 * a String with the data being the binary value of the socket option.
 *
 * === Parameters
 * * +level+ is an integer, usually one of the SOL_ constants such as
 *   Socket::SOL_SOCKET, or a protocol level.
 * * +optname+ is an integer, usually one of the SO_ constants, such
 *   as Socket::SO_REUSEADDR.
 *
 * === Examples
 *
 * Some socket options are integers with boolean values, in this case
 * #getsockopt could be called like this:
 *   optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
 *   optval = optval.unpack "i"
 *   reuseaddr = optval[0] == 0 ? false : true
 *
 * Some socket options are integers with numeric values, in this case
 * #getsockopt could be called like this:
 *   optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL)
 *   ipttl = optval.unpack("i")[0]
 *
 * Option values may be structs. Decoding them can be complex as it involves
 * examining your system headers to determine the correct definition. An
 * example is a +struct linger+, which may be defined in your system headers
 * as:
 *   struct linger {
 *     int l_onoff;
 *     int l_linger;
 *   };
 *
 * In this case #getsockopt could be called like this:
 *   optval =  sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER)
 *   onoff, linger = optval.unpack "ii"
*/
static VALUE
bsock_getsockopt(sock, lev, optname)
    VALUE sock, lev, optname;
{
#if !defined(__BEOS__)
    int level, option;
    socklen_t len;
    char *buf;
    OpenFile *fptr;

    level = NUM2INT(lev);
    option = NUM2INT(optname);
    len = 256;
    buf = ALLOCA_N(char,len);
    GetOpenFile(sock, fptr);

    GetOpenFile(sock, fptr);
    if (getsockopt(fileno(fptr->f), level, option, buf, &len) < 0)
        rb_sys_fail(fptr->path);

    return rb_str_new(buf, len);
#else
    rb_notimplement();
#endif
}


recv_nonblock (BasicSocket)

/*
 * call-seq:
 *      basicsocket.recv_nonblock(maxlen) => mesg
 *      basicsocket.recv_nonblock(maxlen, flags) => mesg
 *
 * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
 * O_NONBLOCK is set for the underlying file descriptor.
 * _flags_ is zero or more of the +MSG_+ options.
 * The result, _mesg_, is the data received.
 *
 * When recvfrom(2) returns 0, Socket#recv_nonblock returns
 * an empty string as data.
 * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
 *
 * === Parameters
 * * +maxlen+ - the number of bytes to receive from the socket
 * * +flags+ - zero or more of the +MSG_+ options
 *
 * === Example
 *      serv = TCPServer.new("127.0.0.1", 0)
 *      af, port, host, addr = serv.addr
 *      c = TCPSocket.new(addr, port)
 *      s = serv.accept
 *      c.send "aaa", 0
 *      IO.select([s])
 *      p s.recv_nonblock(10) #=> "aaa"
 *
 * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
 * to _recv_nonblock_ fails.
 *
 * BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure,
 * including Errno::EAGAIN.
 *
 * === See
 * * Socket#recvfrom
 */

static VALUE
bsock_recv_nonblock(argc, argv, sock)
    int argc;
    VALUE *argv;
    VALUE sock;
{
    return s_recvfrom_nonblock(sock, argc, argv, RECV_RECV);
}


new (Benchmark::Tms)

# File lib/benchmark.rb, line 423
    def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
      @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
      @total = @utime + @stime + @cutime + @cstime
    end


add (Benchmark::Tms)

# File lib/benchmark.rb, line 432
    def add(&blk) # :yield:
      self + Benchmark::measure(&blk)
    end


add! (Benchmark::Tms)

# File lib/benchmark.rb, line 439
    def add!
      t = Benchmark::measure(&blk)
      @utime  = utime + t.utime
      @stime  = stime + t.stime
      @cutime = cutime + t.cutime
      @cstime = cstime + t.cstime
      @real   = real + t.real
      self
    end


+ (Benchmark::Tms)

# File lib/benchmark.rb, line 455
    def +(other); memberwise(:+, other) end


- (Benchmark::Tms)

# File lib/benchmark.rb, line 462
    def -(other); memberwise(:-, other) end


* (Benchmark::Tms)

# File lib/benchmark.rb, line 468
    def *(x); memberwise(:*, x) end


/ (Benchmark::Tms)

# File lib/benchmark.rb, line 475
    def /(x); memberwise(:/, x) end


format (Benchmark::Tms)

# File lib/benchmark.rb, line 494
    def format(arg0 = nil, *args)
      fmtstr = (arg0 || FMTSTR).dup
      fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
      fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
      fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
      fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
      fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
      fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
      fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
      arg0 ? Kernel::format(fmtstr, *args) : fmtstr
    end


to_s (Benchmark::Tms)

# File lib/benchmark.rb, line 509
    def to_s
      format
    end


to_a (Benchmark::Tms)

# File lib/benchmark.rb, line 519
    def to_a
      [@label, @utime, @stime, @cutime, @cstime, @real]
    end


memberwise (Benchmark::Tms)

# File lib/benchmark.rb, line 524
    def memberwise(op, x)
      case x
      when Benchmark::Tms
        Benchmark::Tms.new(utime.__send__(op, x.utime),
                           stime.__send__(op, x.stime),
                           cutime.__send__(op, x.cutime),
                           cstime.__send__(op, x.cstime),
                           real.__send__(op, x.real)
                           )
      else
        Benchmark::Tms.new(utime.__send__(op, x),
                           stime.__send__(op, x),
                           cutime.__send__(op, x),
                           cstime.__send__(op, x),
                           real.__send__(op, x)
                           )
      end
    end


benchmark (Benchmark)

# File lib/benchmark.rb, line 170
  def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
    sync = STDOUT.sync
    STDOUT.sync = true
    label_width ||= 0
    fmtstr ||= FMTSTR
    raise ArgumentError, "no block" unless iterator?
    print caption
    results = yield(Report.new(label_width, fmtstr))
    Array === results and results.grep(Tms).each {|t|
      print((labels.shift || t.label || "").ljust(label_width),
            t.format(fmtstr))
    }
    STDOUT.sync = sync
  end


bm (Benchmark)

# File lib/benchmark.rb, line 206
  def bm(label_width = 0, *labels, &blk) # :yield: report
    benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
  end


bmbm (Benchmark)

# File lib/benchmark.rb, line 248
  def bmbm(width = 0, &blk) # :yield: job
    job = Job.new(width)
    yield(job)
    width = job.width
    sync = STDOUT.sync
    STDOUT.sync = true

    # rehearsal
    print "Rehearsal "
    puts '-'*(width+CAPTION.length - "Rehearsal ".length)
    list = []
    job.list.each{|label,item|
      print(label.ljust(width))
      res = Benchmark::measure(&item)
      print res.format()
      list.push res
    }
    sum = Tms.new; list.each{|i| sum += i}
    ets = sum.format("total: %tsec")
    printf("%s %s\n\n",
           "-"*(width+CAPTION.length-ets.length-1), ets)

    # take
    print ' '*width, CAPTION
    list = []
    ary = []
    job.list.each{|label,item|
      GC::start
      print label.ljust(width)
      res = Benchmark::measure(&item)
      print res.format()
      ary.push res
      list.push [label, res]
    }

    STDOUT.sync = sync
    ary
  end


measure (Benchmark)

# File lib/benchmark.rb, line 291
  def measure(label = "") # :yield:
    t0, r0 = Benchmark.times, Time.now
    yield
    t1, r1 = Benchmark.times, Time.now
    Benchmark::Tms.new(t1.utime  - t0.utime,
                       t1.stime  - t0.stime,
                       t1.cutime - t0.cutime,
                       t1.cstime - t0.cstime,
                       r1.to_f - r0.to_f,
                       label)
  end


realtime (Benchmark)

# File lib/benchmark.rb, line 306
  def realtime(&blk) # :yield:
    Benchmark::measure(&blk).real
  end


to_s (Bignum)

/*
 *  call-seq:
 *     big.to_s(base=10)   =>  string
 *
 *  Returns a string containing the representation of <i>big</i> radix
 *  <i>base</i> (2 through 36).
 *
 *     12345654321.to_s         #=> "12345654321"
 *     12345654321.to_s(2)      #=> "1011011111110110111011110000110001"
 *     12345654321.to_s(8)      #=> "133766736061"
 *     12345654321.to_s(16)     #=> "2dfdbbc31"
 *     78546939656932.to_s(36)  #=> "rubyrules"
 */

static VALUE
rb_big_to_s(argc, argv, x)
    int argc;
    VALUE *argv;
    VALUE x;
{
    VALUE b;
    int base;

    rb_scan_args(argc, argv, "01", &b);
    if (argc == 0) base = 10;
    else base = NUM2INT(b);
    return rb_big2str(x, base);
}


coerce (Bignum)

/*
 * MISSING: documentation
 */

static VALUE
rb_big_coerce(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        return rb_assoc_new(rb_int2big(FIX2LONG(y)), x);
    }
    else if (TYPE(y) == T_BIGNUM) {
       return rb_assoc_new(y, x);
    }
    else {
        rb_raise(rb_eTypeError, "can't coerce %s to Bignum",
                 rb_obj_classname(y));
    }
    /* not reached */
    return Qnil;
}


-@ (Bignum)

/*
 * call-seq:
 *    -big   =>  other_big
 *
 * Unary minus (returns a new Bignum whose value is 0-big)
 */

static VALUE
rb_big_uminus(x)
    VALUE x;
{
    VALUE z = rb_big_clone(x);

    RBIGNUM(z)->sign = !RBIGNUM(x)->sign;

    return bignorm(z);
}


+ (Bignum)

/*
 *  call-seq:
 *     big + other  => Numeric
 *
 *  Adds big and other, returning the result.
 */

VALUE
rb_big_plus(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        /* fall through */
      case T_BIGNUM:
        return bignorm(bigadd(x, y, 1));

      case T_FLOAT:
        return rb_float_new(rb_big2dbl(x) + RFLOAT(y)->value);

      default:
        return rb_num_coerce_bin(x, y);
    }
}


- (Bignum)

/*
 *  call-seq:
 *     big - other  => Numeric
 *
 *  Subtracts other from big, returning the result.
 */

VALUE
rb_big_minus(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        /* fall through */
      case T_BIGNUM:
        return bignorm(bigadd(x, y, 0));

      case T_FLOAT:
        return rb_float_new(rb_big2dbl(x) - RFLOAT(y)->value);

      default:
        return rb_num_coerce_bin(x, y);
    }
}


* (Bignum)

/*
 *  call-seq:
 *     big * other  => Numeric
 *
 *  Multiplies big and other, returning the result.
 */

VALUE
rb_big_mul(x, y)
    VALUE x, y;
{
    return bignorm(rb_big_mul0(x, y));
}


/ (Bignum)

/*
 *  call-seq:
 *     big / other     => Numeric
 *     big.div(other)  => Numeric
 *
 *  Divides big by other, returning the result.
 */

static VALUE
rb_big_div(x, y)
    VALUE x, y;
{
    VALUE z;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      case T_FLOAT:
        return rb_float_new(rb_big2dbl(x) / RFLOAT(y)->value);

      default:
        return rb_num_coerce_bin(x, y);
    }
    bigdivmod(x, y, &z, 0);

    return bignorm(z);
}


% (Bignum)

/*
 *  call-seq:
 *     big % other         => Numeric
 *     big.modulo(other)   => Numeric
 *
 *  Returns big modulo other. See Numeric.divmod for more
 *  information.
 */

static VALUE
rb_big_modulo(x, y)
    VALUE x, y;
{
    VALUE z;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      default:
        return rb_num_coerce_bin(x, y);
    }
    bigdivmod(x, y, 0, &z);

    return bignorm(z);
}


div (Bignum)

/*
 *  call-seq:
 *     big / other     => Numeric
 *     big.div(other)  => Numeric
 *
 *  Divides big by other, returning the result.
 */

static VALUE
rb_big_div(x, y)
    VALUE x, y;
{
    VALUE z;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      case T_FLOAT:
        return rb_float_new(rb_big2dbl(x) / RFLOAT(y)->value);

      default:
        return rb_num_coerce_bin(x, y);
    }
    bigdivmod(x, y, &z, 0);

    return bignorm(z);
}


divmod (Bignum)

/*
 *  call-seq:
 *     big.divmod(numeric)   => array
 *
 *  See <code>Numeric#divmod</code>.
 *
 */
VALUE
rb_big_divmod(x, y)
    VALUE x, y;
{
    VALUE div, mod;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      default:
        return rb_num_coerce_bin(x, y);
    }
    bigdivmod(x, y, &div, &mod);

    return rb_assoc_new(bignorm(div), bignorm(mod));
}


modulo (Bignum)

/*
 *  call-seq:
 *     big % other         => Numeric
 *     big.modulo(other)   => Numeric
 *
 *  Returns big modulo other. See Numeric.divmod for more
 *  information.
 */

static VALUE
rb_big_modulo(x, y)
    VALUE x, y;
{
    VALUE z;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      default:
        return rb_num_coerce_bin(x, y);
    }
    bigdivmod(x, y, 0, &z);

    return bignorm(z);
}


remainder (Bignum)

/*
 *  call-seq:
 *     big.remainder(numeric)    => number
 *
 *  Returns the remainder after dividing <i>big</i> by <i>numeric</i>.
 *
 *     -1234567890987654321.remainder(13731)      #=> -6966
 *     -1234567890987654321.remainder(13731.24)   #=> -9906.22531493148
 */
static VALUE
rb_big_remainder(x, y)
    VALUE x, y;
{
    VALUE z;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      default:
        return rb_num_coerce_bin(x, y);
    }
    bigdivrem(x, y, 0, &z);

    return bignorm(z);
}


quo (Bignum)

/*
 *  call-seq:
 *     big.quo(numeric) -> float
 *
 *  Returns the floating point result of dividing <i>big</i> by
 *  <i>numeric</i>.
 *
 *     -1234567890987654321.quo(13731)      #=> -89910996357705.5
 *     -1234567890987654321.quo(13731.24)   #=> -89909424858035.7
 *
 */

static VALUE
rb_big_quo(x, y)
    VALUE x, y;
{
    double dx = rb_big2dbl(x);
    double dy;

    switch (TYPE(y)) {
      case T_FIXNUM:
        dy = (double)FIX2LONG(y);
        break;

      case T_BIGNUM:
        dy = rb_big2dbl(y);
        break;

      case T_FLOAT:
        dy = RFLOAT(y)->value;
        break;

      default:
        return rb_num_coerce_bin(x, y);
    }
    return rb_float_new(dx / dy);
}


** (Bignum)

/*
 *  call-seq:
 *     big ** exponent   #=> numeric
 *
 *  Raises _big_ to the _exponent_ power (which may be an integer, float,
 *  or anything that will coerce to a number). The result may be
 *  a Fixnum, Bignum, or Float
 *
 *    123456789 ** 2      #=> 15241578750190521
 *    123456789 ** 1.2    #=> 5126464716.09932
 *    123456789 ** -2     #=> 6.5610001194102e-17
 */

VALUE
rb_big_pow(x, y)
    VALUE x, y;
{
    double d;
    long yy;

    if (y == INT2FIX(0)) return INT2FIX(1);
    switch (TYPE(y)) {
      case T_FLOAT:
        d = RFLOAT(y)->value;
        break;

      case T_BIGNUM:
        rb_warn("in a**b, b may be too big");
        d = rb_big2dbl(y);
        break;

      case T_FIXNUM:
        yy = FIX2LONG(y);
        if (yy > 0) {
            VALUE z = x;
            const long BIGLEN_LIMIT = 1024*1024 / SIZEOF_BDIGITS;

            if ((RBIGNUM(x)->len > BIGLEN_LIMIT) ||
                (RBIGNUM(x)->len > BIGLEN_LIMIT / yy)) {
                rb_warn("in a**b, b may be too big");
                d = (double)yy;
                break;
            }
            for (;;) {
                yy -= 1;
                if (yy == 0) break;
                while (yy % 2 == 0) {
                    yy /= 2;
                    x = rb_big_mul0(x, x);
                    bigtrunc(x);
                }
                z = rb_big_mul0(z, x);
                bigtrunc(z);
            }
            return bignorm(z);
        }
        d = (double)yy;
        break;

      default:
        return rb_num_coerce_bin(x, y);
    }
    return rb_float_new(pow(rb_big2dbl(x), d));
}


& (Bignum)

/*
 * call-seq:
 *     big & numeric   =>  integer
 *
 * Performs bitwise +and+ between _big_ and _numeric_.
 */

VALUE
rb_big_and(xx, yy)
    VALUE xx, yy;
{
    volatile VALUE x, y, z;
    BDIGIT *ds1, *ds2, *zds;
    long i, l1, l2;
    char sign;

    x = xx;
    y = rb_to_int(yy);
    if (FIXNUM_P(y)) {
        y = rb_int2big(FIX2LONG(y));
    }
    if (!RBIGNUM(y)->sign) {
        y = rb_big_clone(y);
        get2comp(y);
    }
    if (!RBIGNUM(x)->sign) {
        x = rb_big_clone(x);
        get2comp(x);
    }
    if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
        l1 = RBIGNUM(y)->len;
        l2 = RBIGNUM(x)->len;
        ds1 = BDIGITS(y);
        ds2 = BDIGITS(x);
        sign = RBIGNUM(y)->sign;
    }
    else {
        l1 = RBIGNUM(x)->len;
        l2 = RBIGNUM(y)->len;
        ds1 = BDIGITS(x);
        ds2 = BDIGITS(y);
        sign = RBIGNUM(x)->sign;
    }
    z = bignew(l2, RBIGNUM(x)->sign || RBIGNUM(y)->sign);
    zds = BDIGITS(z);

    for (i=0; i<l1; i++) {
        zds[i] = ds1[i] & ds2[i];
    }
    for (; i<l2; i++) {
        zds[i] = sign?0:ds2[i];
    }
    if (!RBIGNUM(z)->sign) get2comp(z);
    return bignorm(z);
}


| (Bignum)

/*
 * call-seq:
 *     big | numeric   =>  integer
 *
 * Performs bitwise +or+ between _big_ and _numeric_.
 */

VALUE
rb_big_or(xx, yy)
    VALUE xx, yy;
{
    volatile VALUE x, y, z;
    BDIGIT *ds1, *ds2, *zds;
    long i, l1, l2;
    char sign;

    x = xx;
    y = rb_to_int(yy);
    if (FIXNUM_P(y)) {
        y = rb_int2big(FIX2LONG(y));
    }
    if (!RBIGNUM(y)->sign) {
        y = rb_big_clone(y);
        get2comp(y);
    }
    if (!RBIGNUM(x)->sign) {
        x = rb_big_clone(x);
        get2comp(x);
    }
    if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
        l1 = RBIGNUM(y)->len;
        l2 = RBIGNUM(x)->len;
        ds1 = BDIGITS(y);
        ds2 = BDIGITS(x);
        sign = RBIGNUM(y)->sign;
    }
    else {
        l1 = RBIGNUM(x)->len;
        l2 = RBIGNUM(y)->len;
        ds1 = BDIGITS(x);
        ds2 = BDIGITS(y);
        sign = RBIGNUM(x)->sign;
    }
    z = bignew(l2, RBIGNUM(x)->sign && RBIGNUM(y)->sign);
    zds = BDIGITS(z);

    for (i=0; i<l1; i++) {
        zds[i] = ds1[i] | ds2[i];
    }
    for (; i<l2; i++) {
        zds[i] = sign?ds2[i]:(BIGRAD-1);
    }
    if (!RBIGNUM(z)->sign) get2comp(z);

    return bignorm(z);
}


^ (Bignum)

/*
 * call-seq:
 *     big ^ numeric   =>  integer
 *
 * Performs bitwise +exclusive or+ between _big_ and _numeric_.
 */

VALUE
rb_big_xor(xx, yy)
    VALUE xx, yy;
{
    volatile VALUE x, y;
    VALUE z;
    BDIGIT *ds1, *ds2, *zds;
    long i, l1, l2;
    char sign;

    x = xx;
    y = rb_to_int(yy);
    if (FIXNUM_P(y)) {
        y = rb_int2big(FIX2LONG(y));
    }
    if (!RBIGNUM(y)->sign) {
        y = rb_big_clone(y);
        get2comp(y);
    }
    if (!RBIGNUM(x)->sign) {
        x = rb_big_clone(x);
        get2comp(x);
    }
    if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
        l1 = RBIGNUM(y)->len;
        l2 = RBIGNUM(x)->len;
        ds1 = BDIGITS(y);
        ds2 = BDIGITS(x);
        sign = RBIGNUM(y)->sign;
    }
    else {
        l1 = RBIGNUM(x)->len;
        l2 = RBIGNUM(y)->len;
        ds1 = BDIGITS(x);
        ds2 = BDIGITS(y);
        sign = RBIGNUM(x)->sign;
    }
    RBIGNUM(x)->sign = RBIGNUM(x)->sign?1:0;
    RBIGNUM(y)->sign = RBIGNUM(y)->sign?1:0;
    z = bignew(l2, !(RBIGNUM(x)->sign ^ RBIGNUM(y)->sign));
    zds = BDIGITS(z);

    for (i=0; i<l1; i++) {
        zds[i] = ds1[i] ^ ds2[i];
    }
    for (; i<l2; i++) {
        zds[i] = sign?ds2[i]:~ds2[i];
    }
    if (!RBIGNUM(z)->sign) get2comp(z);

    return bignorm(z);
}


~ (Bignum)

/*
 * call-seq:
 *     ~big  =>  integer
 *
 * Inverts the bits in big. As Bignums are conceptually infinite
 * length, the result acts as if it had an infinite number of one
 * bits to the left. In hex representations, this is displayed
 * as two periods to the left of the digits.
 *
 *   sprintf("%X", ~0x1122334455)    #=> "..FEEDDCCBBAA"
 */

static VALUE
rb_big_neg(x)
    VALUE x;
{
    VALUE z = rb_big_clone(x);
    long i;
    BDIGIT *ds;

    if (!RBIGNUM(x)->sign) get2comp(z);
    ds = BDIGITS(z);
    i = RBIGNUM(x)->len;
    if (!i) return INT2FIX(~0);
    while (i--) ds[i] = ~ds[i];
    RBIGNUM(z)->sign = !RBIGNUM(z)->sign;
    if (RBIGNUM(x)->sign) get2comp(z);

    return bignorm(z);
}


<< (Bignum)

/*
 * call-seq:
 *     big << numeric   =>  integer
 *
 * Shifts big left _numeric_ positions (right if _numeric_ is negative).
 */

VALUE
rb_big_lshift(x, y)
    VALUE x, y;
{
    long shift;
    int neg = 0;

    for (;;) {
        if (FIXNUM_P(y)) {
            shift = FIX2LONG(y);
            if (shift < 0) {
                neg = 1;
                shift = -shift;
            }
            break;
        }
        else if (TYPE(y) == T_BIGNUM) {
            if (!RBIGNUM(y)->sign) {
                VALUE t = check_shiftdown(y, x);
                if (!NIL_P(t)) return t;
                neg = 1;
            }
            shift = big2ulong(y, "long", Qtrue);
            break;
        }
        y = rb_to_int(y);
    }

    if (neg) return big_rshift(x, shift);
    return big_lshift(x, shift);
}


>> (Bignum)

/*
 * call-seq:
 *     big >> numeric   =>  integer
 *
 * Shifts big right _numeric_ positions (left if _numeric_ is negative).
 */

VALUE
rb_big_rshift(x, y)
    VALUE x, y;
{
    long shift;
    int neg = 0;

    for (;;) {
        if (FIXNUM_P(y)) {
            shift = FIX2LONG(y);
            if (shift < 0) {
                neg = 1;
                shift = -shift;
            }
            break;
        }
        else if (TYPE(y) == T_BIGNUM) {
            if (RBIGNUM(y)->sign) {
                VALUE t = check_shiftdown(y, x);
                if (!NIL_P(t)) return t;
            }
            else {
                neg = 1;
            }
            shift = big2ulong(y, "long", Qtrue);
            break;
        }
        y = rb_to_int(y);
    }

    if (neg) return big_lshift(x, shift);
    return big_rshift(x, shift);
}


[] (Bignum)

/*
 *  call-seq:
 *     big[n] -> 0, 1
 *
 *  Bit Reference---Returns the <em>n</em>th bit in the (assumed) binary
 *  representation of <i>big</i>, where <i>big</i>[0] is the least
 *  significant bit.
 *
 *     a = 9**15
 *     50.downto(0) do |n|
 *       print a[n]
 *     end
 *
 *  <em>produces:</em>
 *
 *     000101110110100000111000011110010100111100010111001
 *
 */

static VALUE
rb_big_aref(x, y)
    VALUE x, y;
{
    BDIGIT *xds;
    BDIGIT_DBL num;
    unsigned long shift;
    long i, s1, s2;

    if (TYPE(y) == T_BIGNUM) {
        if (!RBIGNUM(y)->sign)
            return INT2FIX(0);
        if (RBIGNUM(bigtrunc(y))->len > SIZEOF_LONG/SIZEOF_BDIGITS) {
          out_of_range:
            return RBIGNUM(x)->sign ? INT2FIX(0) : INT2FIX(1);
        }
        shift = big2ulong(y, "long", Qfalse);
    }
    else {
        i = NUM2LONG(y);
        if (i < 0) return INT2FIX(0);
        shift = (VALUE)i;
    }
    s1 = shift/BITSPERDIG;
    s2 = shift%BITSPERDIG;

    if (s1 >= RBIGNUM(x)->len) goto out_of_range;
    if (!RBIGNUM(x)->sign) {
        xds = BDIGITS(x);
        i = 0; num = 1;
        while (num += ~xds[i], ++i <= s1) {
            num = BIGDN(num);
        }
    }
    else {
        num = BDIGITS(x)[s1];
    }
    if (num & ((BDIGIT_DBL)1<<s2))
        return INT2FIX(1);
    return INT2FIX(0);
}


<=> (Bignum)

/*
 *  call-seq:
 *     big <=> numeric   => -1, 0, +1
 *
 *  Comparison---Returns -1, 0, or +1 depending on whether <i>big</i> is
 *  less than, equal to, or greater than <i>numeric</i>. This is the
 *  basis for the tests in <code>Comparable</code>.
 *
 */

static VALUE
rb_big_cmp(x, y)
    VALUE x, y;
{
    long xlen = RBIGNUM(x)->len;

    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;

      case T_BIGNUM:
        break;

      case T_FLOAT:
        return rb_dbl_cmp(rb_big2dbl(x), RFLOAT(y)->value);

      default:
        return rb_num_coerce_cmp(x, y);
    }

    if (RBIGNUM(x)->sign > RBIGNUM(y)->sign) return INT2FIX(1);
    if (RBIGNUM(x)->sign < RBIGNUM(y)->sign) return INT2FIX(-1);
    if (xlen < RBIGNUM(y)->len)
        return (RBIGNUM(x)->sign) ? INT2FIX(-1) : INT2FIX(1);
    if (xlen > RBIGNUM(y)->len)
        return (RBIGNUM(x)->sign) ? INT2FIX(1) : INT2FIX(-1);

    while(xlen-- && (BDIGITS(x)[xlen]==BDIGITS(y)[xlen]));
    if (-1 == xlen) return INT2FIX(0);
    return (BDIGITS(x)[xlen] > BDIGITS(y)[xlen]) ?
        (RBIGNUM(x)->sign ? INT2FIX(1) : INT2FIX(-1)) :
            (RBIGNUM(x)->sign ? INT2FIX(-1) : INT2FIX(1));
}


== (Bignum)

/*
 *  call-seq:
 *     big == obj  => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> has the same value
 *  as <i>big</i>. Contrast this with <code>Bignum#eql?</code>, which
 *  requires <i>obj</i> to be a <code>Bignum</code>.
 *
 *     68719476736 == 68719476736.0   #=> true
 */

static VALUE
rb_big_eq(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        y = rb_int2big(FIX2LONG(y));
        break;
      case T_BIGNUM:
        break;
      case T_FLOAT:
        {
            volatile double a, b;

            a = RFLOAT(y)->value;
            if (isnan(a)) return Qfalse;
            b = rb_big2dbl(x);
            return (a == b)?Qtrue:Qfalse;
        }
      default:
        return rb_equal(y, x);
    }
    if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse;
    if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse;
    if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse;
    return Qtrue;
}


eql? (Bignum)

/*
 *  call-seq:
 *     big.eql?(obj)   => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> is a
 *  <code>Bignum</code> with the same value as <i>big</i>. Contrast this
 *  with <code>Bignum#==</code>, which performs type conversions.
 *
 *     68719476736.eql?(68719476736.0)   #=> false
 */

static VALUE
rb_big_eql(x, y)
    VALUE x, y;
{
    if (TYPE(y) != T_BIGNUM) return Qfalse;
    if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse;
    if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse;
    if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse;
    return Qtrue;
}


hash (Bignum)

/*
 * call-seq:
 *   big.hash   => fixnum
 *
 * Compute a hash based on the value of _big_.
 */

static VALUE
rb_big_hash(x)
    VALUE x;
{
    long i, len, key;
    BDIGIT *digits;

    key = 0; digits = BDIGITS(x); len = RBIGNUM(x)->len;
    for (i=0; i<len; i++) {
        key ^= *digits++;
    }
    return LONG2FIX(key);
}


to_f (Bignum)

/*
 *  call-seq:
 *     big.to_f -> float
 *
 *  Converts <i>big</i> to a <code>Float</code>. If <i>big</i> doesn't
 *  fit in a <code>Float</code>, the result is infinity.
 *
 */

static VALUE
rb_big_to_f(x)
    VALUE x;
{
    return rb_float_new(rb_big2dbl(x));
}


abs (Bignum)

/*
 *  call-seq:
 *     big.abs -> aBignum
 *
 *  Returns the absolute value of <i>big</i>.
 *
 *     -1234567890987654321.abs   #=> 1234567890987654321
 */

static VALUE
rb_big_abs(x)
    VALUE x;
{
    if (!RBIGNUM(x)->sign) {
        x = rb_big_clone(x);
        RBIGNUM(x)->sign = 1;
    }
    return x;
}


size (Bignum)

/*
 *  call-seq:
 *     big.size -> integer
 *
 *  Returns the number of bytes in the machine representation of
 *  <i>big</i>.
 *
 *     (256**10 - 1).size   #=> 12
 *     (256**20 - 1).size   #=> 20
 *     (256**40 - 1).size   #=> 40
 */

static VALUE
rb_big_size(big)
    VALUE big;
{
    return LONG2FIX(RBIGNUM(big)->len*SIZEOF_BDIGITS);
}


quo (Bignum)

# File lib/rational.rb, line 513
  def quo(other)
    Rational.new!(self,1) / other
  end


rpower (Bignum)

# File lib/rational.rb, line 519
  def rpower (other)
    if other >= 0
      self.power!(other)
    else
      Rational.new!(self, 1)**other
    end
  end


clone (Binding)

/*
 * MISSING: documentation
 */

static VALUE
proc_clone(self)
    VALUE self;
{
    struct BLOCK *orig, *data;
    VALUE bind;

    Data_Get_Struct(self, struct BLOCK, orig);
    bind = Data_Make_Struct(rb_obj_class(self),struct BLOCK,blk_mark,blk_free,data);
    CLONESETUP(bind, self);
    blk_dup(data, orig);

    return bind;
}


dup (Binding)

/*
 * MISSING: documentation
 */

static VALUE
proc_dup(self)
    VALUE self;
{
    struct BLOCK *orig, *data;
    VALUE bind;

    Data_Get_Struct(self, struct BLOCK, orig);
    bind = Data_Make_Struct(rb_obj_class(self),struct BLOCK,blk_mark,blk_free,data);
    blk_dup(data, orig);

    return bind;
}


new (CGI::Cookie)

# File lib/cgi.rb, line 794
    def initialize(name = "", *value)
      options = if name.kind_of?(String)
                  { "name" => name, "value" => value }
                else
                  name
                end
      unless options.has_key?("name")
        raise ArgumentError, "`name' required"
      end

      @name = options["name"]
      @value = Array(options["value"])
      # simple support for IE
      if options["path"]
        @path = options["path"]
      else
        %r|^(.*/)|.match(ENV["SCRIPT_NAME"])
        @path = ($1 or "")
      end
      @domain = options["domain"]
      @expires = options["expires"]
      @secure = options["secure"] == true ? true : false

      super(@value)
    end


secure= (CGI::Cookie)

# File lib/cgi.rb, line 826
    def secure=(val)
      @secure = val if val == true or val == false
      @secure
    end


to_s (CGI::Cookie)

# File lib/cgi.rb, line 832
    def to_s
      buf = ""
      buf += @name + '='

      if @value.kind_of?(String)
        buf += CGI::escape(@value)
      else
        buf += @value.collect{|v| CGI::escape(v) }.join("&")
      end

      if @domain
        buf += '; domain=' + @domain
      end

      if @path
        buf += '; path=' + @path
      end

      if @expires
        buf += '; expires=' + CGI::rfc1123_date(@expires)
      end

      if @secure == true
        buf += '; secure'
      end

      buf
    end


parse (CGI::Cookie)

# File lib/cgi.rb, line 870
  def Cookie::parse(raw_cookie)
    cookies = Hash.new([])
    return cookies unless raw_cookie

    raw_cookie.split(/[;,]\s?/).each do |pairs|
      name, values = pairs.split('=',2)
      next unless name and values
      name = CGI::unescape(name)
      values ||= ""
      values = values.split('&').collect{|v| CGI::unescape(v) }
      if cookies.has_key?(name)
        values = cookies[name].value + values
      end
      cookies[name] = Cookie::new({ "name" => name, "value" => values })
    end

    cookies
  end


a (CGI::HtmlExtension)

# File lib/cgi.rb, line 1317
    def a(href = "") # :yield:
      attributes = if href.kind_of?(String)
                     { "HREF" => href }
                   else
                     href
                   end
      if block_given?
        super(attributes){ yield }
      else
        super(attributes)
      end
    end


base (CGI::HtmlExtension)

# File lib/cgi.rb, line 1339
    def base(href = "") # :yield:
      attributes = if href.kind_of?(String)
                     { "HREF" => href }
                   else
                     href
                   end
      if block_given?
        super(attributes){ yield }
      else
        super(attributes)
      end
    end


blockquote (CGI::HtmlExtension)

# File lib/cgi.rb, line 1362
    def blockquote(cite = nil)  # :yield:
      attributes = if cite.kind_of?(String)
                     { "CITE" => cite }
                   else
                     cite or ""
                   end
      if block_given?
        super(attributes){ yield }
      else
        super(attributes)
      end
    end


caption (CGI::HtmlExtension)

# File lib/cgi.rb, line 1386
    def caption(align = nil) # :yield:
      attributes = if align.kind_of?(String)
                     { "ALIGN" => align }
                   else
                     align or ""
                   end
      if block_given?
        super(attributes){ yield }
      else
        super(attributes)
      end
    end


checkbox (CGI::HtmlExtension)

# File lib/cgi.rb, line 1416
    def checkbox(name = "", value = nil, checked = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "checkbox", "NAME" => name,
                       "VALUE" => value, "CHECKED" => checked }
                   else
                     name["TYPE"] = "checkbox"
                     name
                   end
      input(attributes)
    end


checkbox_group (CGI::HtmlExtension)

# File lib/cgi.rb, line 1470
    def checkbox_group(name = "", *values)
      if name.kind_of?(Hash)
        values = name["VALUES"]
        name = name["NAME"]
      end
      values.collect{|value|
        if value.kind_of?(String)
          checkbox(name, value) + value
        else
          if value[value.size - 1] == true
            checkbox(name, value[0], true) +
            value[value.size - 2]
          else
            checkbox(name, value[0]) +
            value[value.size - 1]
          end
        end
      }.to_s
    end


file_field (CGI::HtmlExtension)

# File lib/cgi.rb, line 1512
    def file_field(name = "", size = 20, maxlength = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "file", "NAME" => name,
                       "SIZE" => size.to_s }
                   else
                     name["TYPE"] = "file"
                     name
                   end
      attributes["MAXLENGTH"] = maxlength.to_s if maxlength
      input(attributes)
    end


form (CGI::HtmlExtension)

# File lib/cgi.rb, line 1546
    def form(method = "post", action = script_name, enctype = "application/x-www-form-urlencoded")
      attributes = if method.kind_of?(String)
                     { "METHOD" => method, "ACTION" => action,
                       "ENCTYPE" => enctype }
                   else
                     unless method.has_key?("METHOD")
                       method["METHOD"] = "post"
                     end
                     unless method.has_key?("ENCTYPE")
                       method["ENCTYPE"] = enctype
                     end
                     method
                   end
      if block_given?
        body = yield
      else
        body = ""
      end
      if @output_hidden
        body += @output_hidden.collect{|k,v|
          "<INPUT TYPE=\"HIDDEN\" NAME=\"#{k}\" VALUE=\"#{v}\">"
        }.to_s
      end
      super(attributes){body}
    end


hidden (CGI::HtmlExtension)

# File lib/cgi.rb, line 1587
    def hidden(name = "", value = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "hidden", "NAME" => name, "VALUE" => value }
                   else
                     name["TYPE"] = "hidden"
                     name
                   end
      input(attributes)
    end


html (CGI::HtmlExtension)

# File lib/cgi.rb, line 1639
    def html(attributes = {}) # :yield:
      if nil == attributes
        attributes = {}
      elsif "PRETTY" == attributes
        attributes = { "PRETTY" => true }
      end
      pretty = attributes.delete("PRETTY")
      pretty = "  " if true == pretty
      buf = ""

      if attributes.has_key?("DOCTYPE")
        if attributes["DOCTYPE"]
          buf += attributes.delete("DOCTYPE")
        else
          attributes.delete("DOCTYPE")
        end
      else
        buf += doctype
      end

      if block_given?
        buf += super(attributes){ yield }
      else
        buf += super(attributes)
      end

      if pretty
        CGI::pretty(buf, pretty)
      else
        buf
      end

    end


image_button (CGI::HtmlExtension)

# File lib/cgi.rb, line 1688
    def image_button(src = "", name = nil, alt = nil)
      attributes = if src.kind_of?(String)
                     { "TYPE" => "image", "SRC" => src, "NAME" => name,
                       "ALT" => alt }
                   else
                     src["TYPE"] = "image"
                     src["SRC"] ||= ""
                     src
                   end
      input(attributes)
    end


img (CGI::HtmlExtension)

# File lib/cgi.rb, line 1714
    def img(src = "", alt = "", width = nil, height = nil)
      attributes = if src.kind_of?(String)
                     { "SRC" => src, "ALT" => alt }
                   else
                     src
                   end
      attributes["WIDTH"] = width.to_s if width
      attributes["HEIGHT"] = height.to_s if height
      super(attributes)
    end


multipart_form (CGI::HtmlExtension)

# File lib/cgi.rb, line 1740
    def multipart_form(action = nil, enctype = "multipart/form-data")
      attributes = if action == nil
                     { "METHOD" => "post", "ENCTYPE" => enctype }
                   elsif action.kind_of?(String)
                     { "METHOD" => "post", "ACTION" => action,
                       "ENCTYPE" => enctype }
                   else
                     unless action.has_key?("METHOD")
                       action["METHOD"] = "post"
                     end
                     unless action.has_key?("ENCTYPE")
                       action["ENCTYPE"] = enctype
                     end
                     action
                   end
      if block_given?
        form(attributes){ yield }
      else
        form(attributes)
      end
    end


password_field (CGI::HtmlExtension)

# File lib/cgi.rb, line 1782
    def password_field(name = "", value = nil, size = 40, maxlength = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "password", "NAME" => name,
                       "VALUE" => value, "SIZE" => size.to_s }
                   else
                     name["TYPE"] = "password"
                     name
                   end
      attributes["MAXLENGTH"] = maxlength.to_s if maxlength
      input(attributes)
    end


popup_menu (CGI::HtmlExtension)

# File lib/cgi.rb, line 1837
    def popup_menu(name = "", *values)

      if name.kind_of?(Hash)
        values   = name["VALUES"]
        size     = name["SIZE"].to_s if name["SIZE"]
        multiple = name["MULTIPLE"]
        name     = name["NAME"]
      else
        size = nil
        multiple = nil
      end

      select({ "NAME" => name, "SIZE" => size,
               "MULTIPLE" => multiple }){
        values.collect{|value|
          if value.kind_of?(String)
            option({ "VALUE" => value }){ value }
          else
            if value[value.size - 1] == true
              option({ "VALUE" => value[0], "SELECTED" => true }){
                value[value.size - 2]
              }
            else
              option({ "VALUE" => value[0] }){
                value[value.size - 1]
              }
            end
          end
        }.to_s
      }

    end


radio_button (CGI::HtmlExtension)

# File lib/cgi.rb, line 1886
    def radio_button(name = "", value = nil, checked = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "radio", "NAME" => name,
                       "VALUE" => value, "CHECKED" => checked }
                   else
                     name["TYPE"] = "radio"
                     name
                   end
      input(attributes)
    end


radio_group (CGI::HtmlExtension)

# File lib/cgi.rb, line 1925
    def radio_group(name = "", *values)
      if name.kind_of?(Hash)
        values = name["VALUES"]
        name = name["NAME"]
      end
      values.collect{|value|
        if value.kind_of?(String)
          radio_button(name, value) + value
        else
          if value[value.size - 1] == true
            radio_button(name, value[0], true) +
            value[value.size - 2]
          else
            radio_button(name, value[0]) +
            value[value.size - 1]
          end
        end
      }.to_s
    end


reset (CGI::HtmlExtension)

# File lib/cgi.rb, line 1960
    def reset(value = nil, name = nil)
      attributes = if (not value) or value.kind_of?(String)
                     { "TYPE" => "reset", "VALUE" => value, "NAME" => name }
                   else
                     value["TYPE"] = "reset"
                     value
                   end
      input(attributes)
    end


submit (CGI::HtmlExtension)

# File lib/cgi.rb, line 1990
    def submit(value = nil, name = nil)
      attributes = if (not value) or value.kind_of?(String)
                     { "TYPE" => "submit", "VALUE" => value, "NAME" => name }
                   else
                     value["TYPE"] = "submit"
                     value
                   end
      input(attributes)
    end


text_field (CGI::HtmlExtension)

# File lib/cgi.rb, line 2022
    def text_field(name = "", value = nil, size = 40, maxlength = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "text", "NAME" => name, "VALUE" => value,
                       "SIZE" => size.to_s }
                   else
                     name["TYPE"] = "text"
                     name
                   end
      attributes["MAXLENGTH"] = maxlength.to_s if maxlength
      input(attributes)
    end


textarea (CGI::HtmlExtension)

# File lib/cgi.rb, line 2048
    def textarea(name = "", cols = 70, rows = 10)  # :yield:
      attributes = if name.kind_of?(String)
                     { "NAME" => name, "COLS" => cols.to_s,
                       "ROWS" => rows.to_s }
                   else
                     name
                   end
      if block_given?
        super(attributes){ yield }
      else
        super(attributes)
      end
    end


raw_cookie (CGI::QueryExtension)

# File lib/cgi.rb, line 946
    def raw_cookie
      env_table["HTTP_COOKIE"]
    end


raw_cookie2 (CGI::QueryExtension)

# File lib/cgi.rb, line 951
    def raw_cookie2
      env_table["HTTP_COOKIE2"]
    end


params= (CGI::QueryExtension)

# File lib/cgi.rb, line 963
    def params=(hash)
      @params.clear
      @params.update(hash)
    end


multipart? (CGI::QueryExtension)

# File lib/cgi.rb, line 1133
    def multipart?
      @multipart
    end


[] (CGI::QueryExtension)

# File lib/cgi.rb, line 1164
    def [](key)
      params = @params[key]
      return '' unless params
      value = params[0]
      if @multipart
        if value
          return value
        elsif defined? StringIO
          StringIO.new("")
        else
          Tempfile.new("CGI")
        end
      else
        str = if value then value.dup else "" end
        str.extend(Value)
        str.set_params(params)
        str
      end
    end


keys (CGI::QueryExtension)

# File lib/cgi.rb, line 1185
    def keys(*args)
      @params.keys(*args)
    end


has_key? (CGI::QueryExtension)

# File lib/cgi.rb, line 1190
    def has_key?(*args)
      @params.has_key?(*args)
    end


new (CGI::Session::FileStore)

# File lib/cgi/session.rb, line 369
      def initialize(session, option={})
        dir = option['tmpdir'] || Dir::tmpdir
        prefix = option['prefix'] || ''
        suffix = option['suffix'] || ''
        id = session.session_id
        require 'digest/md5'
        md5 = Digest::MD5.hexdigest(id)[0,16]
        @path = dir+"/"+prefix+md5+suffix
        if File::exist? @path
          @hash = nil
        else
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          @hash = {}
        end
      end


restore (CGI::Session::FileStore)

# File lib/cgi/session.rb, line 390
      def restore
        unless @hash
          @hash = {}
          begin
            f = File.open(@path, 'r')
            f.flock File::LOCK_SH
            for line in f
              line.chomp!
              k, v = line.split('=',2)
              @hash[CGI::unescape(k)] = CGI::unescape(v)
            end
          ensure
            f.close unless f.nil?
          end
        end
        @hash
      end


update (CGI::Session::FileStore)

# File lib/cgi/session.rb, line 409
      def update
        return unless @hash
        begin
          f = File.open(@path, File::CREAT|File::TRUNC|File::RDWR, 0600)
          f.flock File::LOCK_EX
          for k,v in @hash
            f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(v))
          end
        ensure
          f.close unless f.nil?
        end
      end


close (CGI::Session::FileStore)

# File lib/cgi/session.rb, line 423
      def close
        update
      end


delete (CGI::Session::FileStore)

# File lib/cgi/session.rb, line 428
      def delete
        File::unlink @path
      rescue Errno::ENOENT
      end


new (CGI::Session::MemoryStore)

# File lib/cgi/session.rb, line 447
      def initialize(session, option=nil)
        @session_id = session.session_id
        unless GLOBAL_HASH_TABLE.key?(@session_id)
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          GLOBAL_HASH_TABLE[@session_id] = {}
        end
      end


restore (CGI::Session::MemoryStore)

# File lib/cgi/session.rb, line 460
      def restore
        GLOBAL_HASH_TABLE[@session_id]
      end


update (CGI::Session::MemoryStore)

# File lib/cgi/session.rb, line 467
      def update
        # don't need to update; hash is shared
      end


close (CGI::Session::MemoryStore)

# File lib/cgi/session.rb, line 474
      def close
        # don't need to close
      end


delete (CGI::Session::MemoryStore)

# File lib/cgi/session.rb, line 479
      def delete
        GLOBAL_HASH_TABLE.delete(@session_id)
      end


new (CGI::Session)

# File lib/cgi/session.rb, line 246
    def initialize(request, option={})
      @new_session = false
      session_key = option['session_key'] || '_session_id'
      session_id = option['session_id']
      unless session_id
        if option['new_session']
          session_id = create_new_id
        end
      end
      unless session_id
        if request.key?(session_key)
          session_id = request[session_key]
          session_id = session_id.read if session_id.respond_to?(:read)
        end
        unless session_id
          session_id, = request.cookies[session_key]
        end
        unless session_id
          unless option.fetch('new_session', true)
            raise ArgumentError, "session_key `%s' should be supplied"%session_key
          end
          session_id = create_new_id
        end
      end
      @session_id = session_id
      dbman = option['database_manager'] || FileStore
      begin
        @dbman = dbman::new(self, option)
      rescue NoSession
        unless option.fetch('new_session', true)
          raise ArgumentError, "invalid session_id `%s'"%session_id
        end
        session_id = @session_id = create_new_id
        retry
      end
      request.instance_eval do
        @output_hidden = {session_key => session_id} unless option['no_hidden']
        @output_cookies =  [
          Cookie::new("name" => session_key,
                      "value" => session_id,
                      "expires" => option['session_expires'],
                      "domain" => option['session_domain'],
                      "secure" => option['session_secure'],
                      "path" => if option['session_path'] then
                                  option['session_path']
                                elsif ENV["SCRIPT_NAME"] then
                                  File::dirname(ENV["SCRIPT_NAME"])
                                else
                                  ""
                                end)
        ] unless option['no_cookies']
      end
      @dbprot = [@dbman]
      ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
    end


[] (CGI::Session)

# File lib/cgi/session.rb, line 303
    def [](key)
      @data ||= @dbman.restore
      @data[key]
    end


[]= (CGI::Session)

# File lib/cgi/session.rb, line 309
    def []=(key, val)
      @write_lock ||= true
      @data ||= @dbman.restore
      @data[key] = val
    end


update (CGI::Session)

# File lib/cgi/session.rb, line 317
    def update
      @dbman.update
    end


close (CGI::Session)

# File lib/cgi/session.rb, line 323
    def close
      @dbman.close
      @dbprot.clear
    end


delete (CGI::Session)

# File lib/cgi/session.rb, line 332
    def delete
      @dbman.delete
      @dbprot.clear
    end


escape (CGI)

# File lib/cgi.rb, line 341
  def CGI::escape(string)
    string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
      '%' + $1.unpack('H2' * $1.size).join('%').upcase
    end.tr(' ', '+')
  end


unescape (CGI)

# File lib/cgi.rb, line 351
  def CGI::unescape(string)
    string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
      [$1.delete('%')].pack('H*')
    end
  end


escapeHTML (CGI)

# File lib/cgi.rb, line 361
  def CGI::escapeHTML(string)
    string.gsub(/&/n, '&amp;').gsub(/\"/n, '&quot;').gsub(/>/n, '&gt;').gsub(/</n, '&lt;')
  end


unescapeHTML (CGI)

# File lib/cgi.rb, line 369
  def CGI::unescapeHTML(string)
    string.gsub(/&(amp|quot|gt|lt|\#[0-9]+|\#x[0-9A-Fa-f]+);/n) do
      match = $1.dup
      case match
      when 'amp'                 then '&'
      when 'quot'                then '"'
      when 'gt'                  then '>'
      when 'lt'                  then '<'
      when /\A#0*(\d+)\z/n       then
        if Integer($1) < 256
          Integer($1).chr
        else
          if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
            [Integer($1)].pack("U")
          else
            "&##{$1};"
          end
        end
      when /\A#x([0-9a-f]+)\z/ni then
        if $1.hex < 256
          $1.hex.chr
        else
          if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
            [$1.hex].pack("U")
          else
            "&#x#{$1};"
          end
        end
      else
        "&#{match};"
      end
    end
  end


escapeElement (CGI)

# File lib/cgi.rb, line 417
  def CGI::escapeElement(string, *elements)
    elements = elements[0] if elements[0].kind_of?(Array)
    unless elements.empty?
      string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
        CGI::escapeHTML($&)
      end
    else
      string
    end
  end


unescapeElement (CGI)

# File lib/cgi.rb, line 438
  def CGI::unescapeElement(string, *elements)
    elements = elements[0] if elements[0].kind_of?(Array)
    unless elements.empty?
      string.gsub(/&lt;\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?&gt;/ni) do
        CGI::unescapeHTML($&)
      end
    else
      string
    end
  end


rfc1123_date (CGI)

# File lib/cgi.rb, line 454
  def CGI::rfc1123_date(time)
    t = time.clone.gmtime
    return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
                RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
                t.hour, t.min, t.sec)
  end


header (CGI)

# File lib/cgi.rb, line 539
  def header(options = "text/html")

    buf = ""

    case options
    when String
      options = { "type" => options }
    when Hash
      options = options.dup
    end

    unless options.has_key?("type")
      options["type"] = "text/html"
    end

    if options.has_key?("charset")
      options["type"] += "; charset=" + options.delete("charset")
    end

    options.delete("nph") if defined?(MOD_RUBY)
    if options.delete("nph") or
        (/IIS\/(\d+)/n.match(env_table['SERVER_SOFTWARE']) and $1.to_i < 5)
      buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0")  + " " +
             (HTTP_STATUS[options["status"]] or options["status"] or "200 OK") +
             EOL +
             "Date: " + CGI::rfc1123_date(Time.now) + EOL

      unless options.has_key?("server")
        options["server"] = (env_table['SERVER_SOFTWARE'] or "")
      end

      unless options.has_key?("connection")
        options["connection"] = "close"
      end

      options.delete("status")
    end

    if options.has_key?("status")
      buf += "Status: " +
             (HTTP_STATUS[options["status"]] or options["status"]) + EOL
      options.delete("status")
    end

    if options.has_key?("server")
      buf += "Server: " + options.delete("server") + EOL
    end

    if options.has_key?("connection")
      buf += "Connection: " + options.delete("connection") + EOL
    end

    buf += "Content-Type: " + options.delete("type") + EOL

    if options.has_key?("length")
      buf += "Content-Length: " + options.delete("length").to_s + EOL
    end

    if options.has_key?("language")
      buf += "Content-Language: " + options.delete("language") + EOL
    end

    if options.has_key?("expires")
      buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL
    end

    if options.has_key?("cookie")
      if options["cookie"].kind_of?(String) or
           options["cookie"].kind_of?(Cookie)
        buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL
      elsif options["cookie"].kind_of?(Array)
        options.delete("cookie").each{|cookie|
          buf += "Set-Cookie: " + cookie.to_s + EOL
        }
      elsif options["cookie"].kind_of?(Hash)
        options.delete("cookie").each_value{|cookie|
          buf += "Set-Cookie: " + cookie.to_s + EOL
        }
      end
    end
    if @output_cookies
      for cookie in @output_cookies
        buf += "Set-Cookie: " + cookie.to_s + EOL
      end
    end

    options.each{|key, value|
      buf += key + ": " + value.to_s + EOL
    }

    if defined?(MOD_RUBY)
      table = Apache::request.headers_out
      buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value|
        warn sprintf("name:%s value:%s\n", name, value) if $DEBUG
        case name
        when 'Set-Cookie'
          table.add(name, value)
        when /^status$/ni
          Apache::request.status_line = value
          Apache::request.status = value.to_i
        when /^content-type$/ni
          Apache::request.content_type = value
        when /^content-encoding$/ni
          Apache::request.content_encoding = value
        when /^location$/ni
          if Apache::request.status == 200
            Apache::request.status = 302
          end
          Apache::request.headers_out[name] = value
        else
          Apache::request.headers_out[name] = value
        end
      }
      Apache::request.send_http_header
      ''
    else
      buf + EOL
    end

  end


out (CGI)

# File lib/cgi.rb, line 703
  def out(options = "text/html") # :yield:

    options = { "type" => options } if options.kind_of?(String)
    content = yield

    if options.has_key?("charset")
      require "nkf"
      case options["charset"]
      when /iso-2022-jp/ni
        content = NKF::nkf('-m0 -x -j', content)
        options["language"] = "ja" unless options.has_key?("language")
      when /euc-jp/ni
        content = NKF::nkf('-m0 -x -e', content)
        options["language"] = "ja" unless options.has_key?("language")
      when /shift_jis/ni
        content = NKF::nkf('-m0 -x -s', content)
        options["language"] = "ja" unless options.has_key?("language")
      end
    end

    options["length"] = content.length.to_s
    output = stdoutput
    output.binmode if defined? output.binmode
    output.print header(options)
    output.print content unless "HEAD" == env_table['REQUEST_METHOD']
  end


print (CGI)

# File lib/cgi.rb, line 735
  def print(*options)
    stdoutput.print(*options)
  end


parse (CGI)

# File lib/cgi.rb, line 895
  def CGI::parse(query)
    params = Hash.new([].freeze)

    query.split(/[&;]/n).each do |pairs|
      key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
      if params.has_key?(key)
        params[key].push(value)
      else
        params[key] = [value]
      end
    end

    params
  end


pretty (CGI)

# File lib/cgi.rb, line 1216
  def CGI::pretty(string, shift = "  ")
    lines = string.gsub(/(?!\A)<(?:.|\n)*?>/n, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
    end_pos = 0
    while end_pos = lines.index(/^<\/(\w+)/n, end_pos)
      element = $1.dup
      start_pos = lines.rindex(/^\s*<#{element}/ni, end_pos)
      lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/n, "\n" + shift) + "__"
    end
    lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/n, '\1')
  end


new (CGI)

# File lib/cgi.rb, line 2289
  def initialize(type = "query")
    if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
      Apache.request.setup_cgi_env
    end

    extend QueryExtension
    @multipart = false
    if defined?(CGI_PARAMS)
      warn "do not use CGI_PARAMS and CGI_COOKIES"
      @params = CGI_PARAMS.dup
      @cookies = CGI_COOKIES.dup
    else
      initialize_query()  # set @params, @cookies
    end
    @output_cookies = nil
    @output_hidden = nil

    case type
    when "html3"
      extend Html3
      element_init()
      extend HtmlExtension
    when "html4"
      extend Html4
      element_init()
      extend HtmlExtension
    when "html4Tr"
      extend Html4Tr
      element_init()
      extend HtmlExtension
    when "html4Fr"
      extend Html4Tr
      element_init()
      extend Html4Fr
      element_init()
      extend HtmlExtension
    end
  end


rfc1123_date (CGI)

# File lib/cgi-lib.rb, line 126
  def CGI::rfc1123_date(time)
    t = time.clone.gmtime
    return format("%s, %.2d %s %d %.2d:%.2d:%.2d GMT",
                RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
                t.hour, t.min, t.sec)
  end


escape (CGI)

# File lib/cgi-lib.rb, line 134
  def CGI::escape(str)
    str.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
  end


unescape (CGI)

# File lib/cgi-lib.rb, line 139
  def CGI::unescape(str)
    str.gsub(/\+/, ' ').gsub(/%([0-9a-fA-F]{2})/){ [$1.hex].pack("c") }
  end


escapeHTML (CGI)

# File lib/cgi-lib.rb, line 144
  def CGI::escapeHTML(str)
    str.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
  end


read_from_cmdline (CGI)

# File lib/cgi-lib.rb, line 149
  def read_from_cmdline
    require "shellwords.rb"
    words = Shellwords.shellwords(
              if not ARGV.empty?
                ARGV.join(' ')
              else
                STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty?
                readlines.join(' ').gsub(/\n/, '')
              end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26'))

    if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end
  end


new (CGI)

# File lib/cgi-lib.rb, line 162
  def initialize(input = $stdin)

    @inputs = {}
    @cookie = {}

    case ENV['REQUEST_METHOD']
    when "GET"
      ENV['QUERY_STRING'] or ""
    when "POST"
      input.read(Integer(ENV['CONTENT_LENGTH'])) or ""
    else
      read_from_cmdline
    end.split(/[&;]/).each do |x|
      key, val = x.split(/=/,2).collect{|x|CGI::unescape(x)}
      if @inputs.include?(key)
        @inputs[key] += "\0" + (val or "")
      else
        @inputs[key] = (val or "")
      end
    end

    super(@inputs)

    if ENV.has_key?('HTTP_COOKIE') or ENV.has_key?('COOKIE')
      (ENV['HTTP_COOKIE'] or ENV['COOKIE']).split(/; /).each do |x|
        key, val = x.split(/=/,2)
        key = CGI::unescape(key)
        val = val.split(/&/).collect{|x|CGI::unescape(x)}.join("\0")
        if @cookie.include?(key)
          @cookie[key] += "\0" + val
        else
          @cookie[key] = val
        end
      end
    end
  end


tag (CGI)

# File lib/cgi-lib.rb, line 203
  def CGI::tag(element, attributes = {})
    "<" + escapeHTML(element) + attributes.collect{|name, value|
      " " + escapeHTML(name) + '="' + escapeHTML(value) + '"'
    }.to_s + ">" +
    (iterator? ? yield.to_s + "</" + escapeHTML(element) + ">" : "")
  end


cookie (CGI)

# File lib/cgi-lib.rb, line 211
  def CGI::cookie(options)
    "Set-Cookie: " + options['name'] + '=' + escape(options['value']) +
    (options['domain']  ? '; domain='  + options['domain'] : '') +
    (options['path']    ? '; path='    + options['path']   : '') +
    (options['expires'] ? '; expires=' + rfc1123_date(options['expires']) : '') +
    (options['secure']  ? '; secure' : '')
  end


header (CGI)

# File lib/cgi-lib.rb, line 220
  def CGI::header(*options)
    if defined?(MOD_RUBY)
      options.each{|option|
        option.sub(/(.*?): (.*)/){
          Apache::request.headers_out[$1] = $2
        }
      }
      Apache::request.send_http_header
      ''
    else
      if options.delete("nph") or (ENV['SERVER_SOFTWARE'] =~ /IIS/)
        [(ENV['SERVER_PROTOCOL'] or "HTTP/1.0") + " 200 OK",
         "Date: " + rfc1123_date(Time.now),
         "Server: " + (ENV['SERVER_SOFTWARE'] or ""),
         "Connection: close"] +
        (options.empty? ? ["Content-Type: text/html"] : options)
      else
        options.empty? ? ["Content-Type: text/html"] : options
      end.join(EOL) + EOL + EOL
    end
  end


print (CGI)

# File lib/cgi-lib.rb, line 243
  def CGI::print(*options)
    $>.print CGI::header(*options) + yield.to_s
  end


message (CGI)

# File lib/cgi-lib.rb, line 248
  def CGI::message(message, title = "", header = ["Content-Type: text/html"])
    if message.kind_of?(Hash)
      title   = message['title']
      header  = message['header']
      message = message['body']
    end
    CGI::print(*header){
      CGI::tag("HTML"){
        CGI::tag("HEAD"){ CGI.tag("TITLE"){ title } } +
        CGI::tag("BODY"){ message }
      }
    }
    true
  end


error (CGI)

# File lib/cgi-lib.rb, line 264
  def CGI::error
    CGI::message({'title'=>'ERROR', 'body'=>
      CGI::tag("PRE"){
        "ERROR: " + CGI::tag("STRONG"){ escapeHTML($!.to_s) } + "\n" + escapeHTML($@.join("\n"))
      }
    })
    exit
  end


inherited (Class)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


allocate (Class)

/*
 *  call-seq:
 *     class.allocate()   =>   obj
 *
 *  Allocates space for a new object of <i>class</i>'s class. The
 *  returned object must be an instance of <i>class</i>.
 *
 */

VALUE
rb_obj_alloc(klass)
    VALUE klass;
{
    VALUE obj;

    if (RCLASS(klass)->super == 0) {
        rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
    }
    if (FL_TEST(klass, FL_SINGLETON)) {
        rb_raise(rb_eTypeError, "can't create instance of virtual class");
    }
    obj = rb_funcall(klass, ID_ALLOCATOR, 0, 0);
    if (rb_obj_class(obj) != rb_class_real(klass)) {
        rb_raise(rb_eTypeError, "wrong instance allocation");
    }
    return obj;
}


new (Class)

/*
 *  call-seq:
 *     class.new(args, ...)    =>  obj
 *
 *  Calls <code>allocate</code> to create a new object of
 *  <i>class</i>'s class, then invokes that object's
 *  <code>initialize</code> method, passing it <i>args</i>.
 *  This is the method that ends up getting called whenever
 *  an object is constructed using .new.
 *
 */

VALUE
rb_class_new_instance(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE obj;

    obj = rb_obj_alloc(klass);
    rb_obj_call_init(obj, argc, argv);

    return obj;
}


new (Class)

/*
 *  call-seq:
 *     Class.new(super_class=Object)   =>    a_class
 *
 *  Creates a new anonymous (unnamed) class with the given superclass
 *  (or <code>Object</code> if no parameter is given). You can give a
 *  class a name by assigning the class object to a constant.
 *
 */

static VALUE
rb_class_initialize(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE super;

    if (RCLASS(klass)->super != 0) {
        rb_raise(rb_eTypeError, "already initialized class");
    }
    if (rb_scan_args(argc, argv, "01", &super) == 0) {
        super = rb_cObject;
    }
    else {
        rb_check_inheritable(super);
    }
    RCLASS(klass)->super = super;
    rb_make_metaclass(klass, RBASIC(super)->klass);
    rb_mod_initialize(klass);
    rb_class_inherited(super, klass);

    return klass;
}


superclass (Class)

/*
 *  call-seq:
 *     class.superclass -> a_super_class or nil
 *
 *  Returns the superclass of <i>class</i>, or <code>nil</code>.
 *
 *     File.superclass     #=> IO
 *     IO.superclass       #=> Object
 *     Object.superclass   #=> nil
 *
 */

static VALUE
rb_class_superclass(klass)
    VALUE klass;
{
    VALUE super = RCLASS(klass)->super;

    if (!super) {
        rb_raise(rb_eTypeError, "uninitialized class");
    }
    if (FL_TEST(klass, FL_SINGLETON)) {
        super = RBASIC(klass)->klass;
    }
    while (TYPE(super) == T_ICLASS) {
        super = RCLASS(super)->super;
    }
    if (!super) {
        return Qnil;
    }
    return super;
}


to_yaml (Class)

# File lib/yaml/rubytypes.rb, line 5
        def to_yaml( opts = {} )
                raise TypeError, "can't dump anonymous class %s" % self.class
        end


== (Comparable)

/*
 *  call-seq:
 *     obj == other    => true or false
 *
 *  Compares two objects based on the receiver's <code><=></code>
 *  method, returning true if it returns 0. Also returns true if
 *  _obj_ and _other_ are the same object.
 */

static VALUE
cmp_equal(x, y)
    VALUE x, y;
{
    VALUE a[2];

    if (x == y) return Qtrue;

    a[0] = x; a[1] = y;
    return rb_rescue(cmp_eq, (VALUE)a, cmp_failed, 0);
}


> (Comparable)

/*
 *  call-seq:
 *     obj > other    => true or false
 *
 *  Compares two objects based on the receiver's <code><=></code>
 *  method, returning true if it returns 1.
 */

static VALUE
cmp_gt(x, y)
    VALUE x, y;
{
    VALUE c = rb_funcall(x, cmp, 1, y);

    if (NIL_P(c)) return cmperr();
    if (rb_cmpint(c, x, y) > 0) return Qtrue;
    return Qfalse;
}


>= (Comparable)

/*
 *  call-seq:
 *     obj >= other    => true or false
 *
 *  Compares two objects based on the receiver's <code><=></code>
 *  method, returning true if it returns 0 or 1.
 */

static VALUE
cmp_ge(x, y)
    VALUE x, y;
{
    VALUE c = rb_funcall(x, cmp, 1, y);

    if (NIL_P(c)) return cmperr();
    if (rb_cmpint(c, x, y) >= 0) return Qtrue;
    return Qfalse;
}


< (Comparable)

/*
 *  call-seq:
 *     obj < other    => true or false
 *
 *  Compares two objects based on the receiver's <code><=></code>
 *  method, returning true if it returns -1.
 */

static VALUE
cmp_lt(x, y)
    VALUE x, y;
{
    VALUE c = rb_funcall(x, cmp, 1, y);

    if (NIL_P(c)) return cmperr();
    if (rb_cmpint(c, x, y) < 0) return Qtrue;
    return Qfalse;
}


<= (Comparable)

/*
 *  call-seq:
 *     obj <= other    => true or false
 *
 *  Compares two objects based on the receiver's <code><=></code>
 *  method, returning true if it returns -1 or 0.
 */

static VALUE
cmp_le(x, y)
    VALUE x, y;
{
    VALUE c = rb_funcall(x, cmp, 1, y);

    if (NIL_P(c)) return cmperr();
    if (rb_cmpint(c, x, y) <= 0) return Qtrue;
    return Qfalse;
}


between? (Comparable)

/*
 *  call-seq:
 *     obj.between?(min, max)    => true or false
 *
 *  Returns <code>false</code> if <i>obj</i> <code><=></code>
 *  <i>min</i> is less than zero or if <i>anObject</i> <code><=></code>
 *  <i>max</i> is greater than zero, <code>true</code> otherwise.
 *
 *     3.between?(1, 5)               #=> true
 *     6.between?(1, 5)               #=> false
 *     'cat'.between?('ant', 'dog')   #=> true
 *     'gnu'.between?('ant', 'dog')   #=> false
 *
 */

static VALUE
cmp_between(x, min, max)
    VALUE x, min, max;
{
    if (RTEST(cmp_lt(x, min))) return Qfalse;
    if (RTEST(cmp_gt(x, max))) return Qfalse;
    return Qtrue;
}


match (CompletingHash)

# File lib/optparse.rb, line 663
    def match(key)
      return key, *fetch(key) {
        raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
      }
    end


polar (Complex)

# File lib/complex.rb, line 115
  def Complex.polar(r, theta)
    Complex(r*Math.cos(theta), r*Math.sin(theta))
  end


new! (Complex)

# File lib/complex.rb, line 122
  def Complex.new!(a, b=0)
    new(a,b)
  end


new (Complex)

# File lib/complex.rb, line 126
  def initialize(a, b)
    raise TypeError, "non numeric 1st arg `#{a.inspect}'" if !a.kind_of? Numeric
    raise TypeError, "`#{a.inspect}' for 1st arg" if a.kind_of? Complex
    raise TypeError, "non numeric 2nd arg `#{b.inspect}'" if !b.kind_of? Numeric
    raise TypeError, "`#{b.inspect}' for 2nd arg" if b.kind_of? Complex
    @real = a
    @image = b
  end


+ (Complex)

# File lib/complex.rb, line 138
  def + (other)
    if other.kind_of?(Complex)
      re = @real + other.real
      im = @image + other.image
      Complex(re, im)
    elsif Complex.generic?(other)
      Complex(@real + other, @image)
    else
      x , y = other.coerce(self)
      x + y
    end
  end


- (Complex)

# File lib/complex.rb, line 154
  def - (other)
    if other.kind_of?(Complex)
      re = @real - other.real
      im = @image - other.image
      Complex(re, im)
    elsif Complex.generic?(other)
      Complex(@real - other, @image)
    else
      x , y = other.coerce(self)
      x - y
    end
  end


* (Complex)

# File lib/complex.rb, line 170
  def * (other)
    if other.kind_of?(Complex)
      re = @real*other.real - @image*other.image
      im = @real*other.image + @image*other.real
      Complex(re, im)
    elsif Complex.generic?(other)
      Complex(@real * other, @image * other)
    else
      x , y = other.coerce(self)
      x * y
    end
  end


/ (Complex)

# File lib/complex.rb, line 186
  def / (other)
    if other.kind_of?(Complex)
      self*other.conjugate/other.abs2
    elsif Complex.generic?(other)
      Complex(@real/other, @image/other)
    else
      x, y = other.coerce(self)
      x/y
    end
  end


** (Complex)

# File lib/complex.rb, line 200
  def ** (other)
    if other == 0
      return Complex(1)
    end
    if other.kind_of?(Complex)
      r, theta = polar
      ore = other.real
      oim = other.image
      nr = Math.exp!(ore*Math.log!(r) - oim * theta)
      ntheta = theta*ore + oim*Math.log!(r)
      Complex.polar(nr, ntheta)
    elsif other.kind_of?(Integer)
      if other > 0
        x = self
        z = x
        n = other - 1
        while n != 0
          while (div, mod = n.divmod(2)
                 mod == 0)
            x = Complex(x.real*x.real - x.image*x.image, 2*x.real*x.image)
            n = div
          end
          z *= x
          n -= 1
        end
        z
      else
        if defined? Rational
          (Rational(1) / self) ** -other
        else
          self ** Float(other)
        end
      end
    elsif Complex.generic?(other)
      r, theta = polar
      Complex.polar(r**other, theta*other)
    else
      x, y = other.coerce(self)
      x**y
    end
  end


% (Complex)

# File lib/complex.rb, line 245
  def % (other)
    if other.kind_of?(Complex)
      Complex(@real % other.real, @image % other.image)
    elsif Complex.generic?(other)
      Complex(@real % other, @image % other)
    else
      x , y = other.coerce(self)
      x % y
    end
  end


abs (Complex)

# File lib/complex.rb, line 275
  def abs
    Math.hypot(@real, @image)
  end


abs2 (Complex)

# File lib/complex.rb, line 282
  def abs2
    @real*@real + @image*@image
  end


arg (Complex)

# File lib/complex.rb, line 289
  def arg
    Math.atan2!(@image, @real)
  end


polar (Complex)

# File lib/complex.rb, line 297
  def polar
    return abs, arg
  end


conjugate (Complex)

# File lib/complex.rb, line 304
  def conjugate
    Complex(@real, -@image)
  end


<=> (Complex)

# File lib/complex.rb, line 312
  def <=> (other)
    self.abs <=> other.abs
  end


== (Complex)

# File lib/complex.rb, line 319
  def == (other)
    if other.kind_of?(Complex)
      @real == other.real and @image == other.image
    elsif Complex.generic?(other)
      @real == other and @image == 0
    else
      other == self
    end
  end


coerce (Complex)

# File lib/complex.rb, line 332
  def coerce(other)
    if Complex.generic?(other)
      return Complex.new!(other), self
    else
      super
    end
  end


denominator (Complex)

# File lib/complex.rb, line 343
  def denominator
    @real.denominator.lcm(@image.denominator)
  end


numerator (Complex)

# File lib/complex.rb, line 350
  def numerator
    cd = denominator
    Complex(@real.numerator*(cd/@real.denominator),
            @image.numerator*(cd/@image.denominator))
  end


to_s (Complex)

# File lib/complex.rb, line 359
  def to_s
    if @real != 0
      if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1
        if @image >= 0
          @real.to_s+"+("+@image.to_s+")i"
        else
          @real.to_s+"-("+(-@image).to_s+")i"
        end
      else
        if @image >= 0
          @real.to_s+"+"+@image.to_s+"i"
        else
          @real.to_s+"-"+(-@image).to_s+"i"
        end
      end
    else
      if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1
        "("+@image.to_s+")i"
      else
        @image.to_s+"i"
      end
    end
  end


hash (Complex)

# File lib/complex.rb, line 386
  def hash
    @real.hash ^ @image.hash
  end


inspect (Complex)

# File lib/complex.rb, line 393
  def inspect
    sprintf("Complex(%s, %s)", @real.inspect, @image.inspect)
  end


new (ConditionVariable)

# File lib/thread.rb, line 187
  def initialize
    @waiters = []
  end


wait (ConditionVariable)

# File lib/thread.rb, line 194
  def wait(mutex)
    begin
      mutex.exclusive_unlock do
        @waiters.push(Thread.current)
        Thread.stop
      end
    ensure
      mutex.lock
    end
  end


signal (ConditionVariable)

# File lib/thread.rb, line 208
  def signal
    begin
      t = @waiters.shift
      t.run if t
    rescue ThreadError
      retry
    end
  end


broadcast (ConditionVariable)

# File lib/thread.rb, line 220
  def broadcast
    waiters0 = nil
    Thread.exclusive do
      waiters0 = @waiters.dup
      @waiters.clear
    end
    for t in waiters0
      begin
        t.run
      rescue ThreadError
      end
    end
  end


call (Continuation)

/*
 *  call-seq:
 *     cont.call(args, ...)
 *     cont[args, ...]
 *
 *  Invokes the continuation. The program continues from the end of the
 *  <code>callcc</code> block. If no arguments are given, the original
 *  <code>callcc</code> returns <code>nil</code>. If one argument is
 *  given, <code>callcc</code> returns it. Otherwise, an array
 *  containing <i>args</i> is returned.
 *
 *     callcc {|cont|  cont.call }           #=> nil
 *     callcc {|cont|  cont.call 1 }         #=> 1
 *     callcc {|cont|  cont.call 1, 2, 3 }   #=> [1, 2, 3]
 */

static VALUE
rb_cont_call(argc, argv, cont)
    int argc;
    VALUE *argv;
    VALUE cont;
{
    rb_thread_t th = rb_thread_check(cont);

    if (th->thread != curr_thread->thread) {
        rb_raise(rb_eRuntimeError, "continuation called across threads");
    }
    if (th->thgroup != cont_protect) {
        rb_raise(rb_eRuntimeError, "continuation called across trap");
    }
    switch (argc) {
      case 0:
        th->result = Qnil;
        break;
      case 1:
        th->result = argv[0];
        break;
      default:
        th->result = rb_ary_new4(argc, argv);
        break;
    }

    rb_thread_restore_context(th, RESTORE_NORMAL);
    return Qnil;
}


[] (Continuation)

/*
 *  call-seq:
 *     cont.call(args, ...)
 *     cont[args, ...]
 *
 *  Invokes the continuation. The program continues from the end of the
 *  <code>callcc</code> block. If no arguments are given, the original
 *  <code>callcc</code> returns <code>nil</code>. If one argument is
 *  given, <code>callcc</code> returns it. Otherwise, an array
 *  containing <i>args</i> is returned.
 *
 *     callcc {|cont|  cont.call }           #=> nil
 *     callcc {|cont|  cont.call 1 }         #=> 1
 *     callcc {|cont|  cont.call 1, 2, 3 }   #=> [1, 2, 3]
 */

static VALUE
rb_cont_call(argc, argv, cont)
    int argc;
    VALUE *argv;
    VALUE cont;
{
    rb_thread_t th = rb_thread_check(cont);

    if (th->thread != curr_thread->thread) {
        rb_raise(rb_eRuntimeError, "continuation called across threads");
    }
    if (th->thgroup != cont_protect) {
        rb_raise(rb_eRuntimeError, "continuation called across trap");
    }
    switch (argc) {
      case 0:
        th->result = Qnil;
        break;
      case 1:
        th->result = argv[0];
        break;
      default:
        th->result = rb_ary_new4(argc, argv);
        break;
    }

    rb_thread_restore_context(th, RESTORE_NORMAL);
    return Qnil;
}


new (CSV::BasicWriter)

# File lib/csv.rb, line 714
    def initialize(str_or_writable, fs = ',', rs = nil)
      @fs = fs
      @rs = rs
      @dev = str_or_writable
      @close_on_terminate = false
    end


close_on_terminate (CSV::BasicWriter)

# File lib/csv.rb, line 723
    def close_on_terminate
      @close_on_terminate = true
    end


new (CSV::Cell)

# File lib/csv.rb, line 16
    def initialize(data = "", is_null = false)
      super(is_null ? "" : data)
    end


data (CSV::Cell)

# File lib/csv.rb, line 20
    def data
      to_s
    end


new (CSV::IOBuf)

# File lib/csv.rb, line 973
    def initialize(s)
      @s = s
      super()
    end


close (CSV::IOBuf)

# File lib/csv.rb, line 978
    def close
      terminate
    end


new (CSV::IOReader)

# File lib/csv.rb, line 616
    def initialize(io, fs = ',', rs = nil)
      @io = io
      @fs = fs
      @rs = rs
      @dev = CSV::IOBuf.new(@io)
      @idx = 0
      if @dev[0] == 0xef and @dev[1] == 0xbb and @dev[2] == 0xbf
        @idx += 3
      end
      @close_on_terminate = false
    end


close_on_terminate (CSV::IOReader)

# File lib/csv.rb, line 630
    def close_on_terminate
      @close_on_terminate = true
    end


parse (CSV::Reader)

# File lib/csv.rb, line 528
    def Reader.parse(str_or_readable, fs = ',', rs = nil, &block)
      reader = Reader.create(str_or_readable, fs, rs)
      if block
        reader.each do |row|
          yield(row)
        end
        reader.close
        nil
      else
        reader
      end
    end


create (CSV::Reader)

# File lib/csv.rb, line 542
    def Reader.create(str_or_readable, fs = ',', rs = nil)
      case str_or_readable
      when IO
        IOReader.new(str_or_readable, fs, rs)
      when String
        StringReader.new(str_or_readable, fs, rs)
      else
        IOReader.new(str_or_readable, fs, rs)
      end
    end


each (CSV::Reader)

# File lib/csv.rb, line 553
    def each
      while true
        row = []
        parsed_cells = get_row(row)
        if parsed_cells == 0
          break
        end
        yield(row)
      end
      nil
    end


shift (CSV::Reader)

# File lib/csv.rb, line 565
    def shift
      row = []
      parsed_cells = get_row(row)
      row
    end


close (CSV::Reader)

# File lib/csv.rb, line 571
    def close
      terminate
    end


new (CSV::Reader)

# File lib/csv.rb, line 577
    def initialize(dev)
      raise RuntimeError.new('Do not instanciate this class directly.')
    end


[] (CSV::StreamBuf)

# File lib/csv.rb, line 803
    def [](idx, n = nil)
      if idx < 0
        return nil
      end
      if (idx_is_eos?(idx))
        if n and (@offset + idx == buf_size(@cur_buf))
          # Like a String, 'abc'[4, 1] returns nil and
          # 'abc'[3, 1] returns '' not nil.
          return ''
        else
          return nil
        end
      end
      my_buf = @cur_buf
      my_offset = @offset
      next_idx = idx
      while (my_offset + next_idx >= buf_size(my_buf))
        if (my_buf == @buf_tail_idx)
          unless add_buf
            break
          end
        end
        next_idx = my_offset + next_idx - buf_size(my_buf)
        my_buf += 1
        my_offset = 0
      end
      loc = my_offset + next_idx
      if !n
        return @buf_list[my_buf][loc]           # Fixnum of char code.
      elsif (loc + n - 1 < buf_size(my_buf))
        return @buf_list[my_buf][loc, n]        # String.
      else # should do loop insted of (tail) recursive call...
        res = @buf_list[my_buf][loc, BufSize]
        size_added = buf_size(my_buf) - loc
        if size_added > 0
          idx += size_added
          n -= size_added
          ret = self[idx, n]
          if ret
            res << ret
          end
        end
        return res
      end
    end


drop (CSV::StreamBuf)

# File lib/csv.rb, line 854
    def drop(n)
      if is_eos?
        return 0
      end
      size_dropped = 0
      while (n > 0)
        if !@is_eos or (@cur_buf != @buf_tail_idx)
          if (@offset + n < buf_size(@cur_buf))
            size_dropped += n
            @offset += n
            n = 0
          else
            size = buf_size(@cur_buf) - @offset
            size_dropped += size
            n -= size
            @offset = 0
            unless rel_buf
              unless add_buf
                break
              end
              @cur_buf = @buf_tail_idx
            end
          end
        end
      end
      size_dropped
    end


is_eos? (CSV::StreamBuf)

# File lib/csv.rb, line 882
    def is_eos?
      return idx_is_eos?(0)
    end


new (CSV::StreamBuf)

# File lib/csv.rb, line 888
    def initialize
      @buf_list = []
      @cur_buf = @buf_tail_idx = -1
      @offset = 0
      @is_eos = false
      add_buf
      @cur_buf = @buf_tail_idx
    end


terminate (CSV::StreamBuf)

# File lib/csv.rb, line 899
    def terminate
      while (rel_buf); end
    end


read (CSV::StreamBuf)

# File lib/csv.rb, line 907
    def read(size) # raise EOFError
      raise NotImplementedError.new('Method read must be defined in a derived class.')
    end


new (CSV::StringReader)

# File lib/csv.rb, line 592
    def initialize(string, fs = ',', rs = nil)
      @fs = fs
      @rs = rs
      @dev = string
      @idx = 0
      if @dev[0, 3] == "\xef\xbb\xbf"
        @idx += 3
      end
    end


generate (CSV::Writer)

# File lib/csv.rb, line 674
    def Writer.generate(str_or_writable, fs = ',', rs = nil, &block)
      writer = Writer.create(str_or_writable, fs, rs)
      if block
        yield(writer)
        writer.close
        nil
      else
        writer
      end
    end


create (CSV::Writer)

# File lib/csv.rb, line 686
    def Writer.create(str_or_writable, fs = ',', rs = nil)
      BasicWriter.new(str_or_writable, fs, rs)
    end


<< (CSV::Writer)

# File lib/csv.rb, line 691
    def <<(row)
      CSV.generate_row(row, row.size, @dev, @fs, @rs)
      self
    end


close (CSV::Writer)

# File lib/csv.rb, line 697
    def close
      terminate
    end


new (CSV::Writer)

# File lib/csv.rb, line 703
    def initialize(dev)
      raise RuntimeError.new('Do not instanciate this class directly.')
    end


open (CSV)

# File lib/csv.rb, line 83
  def CSV.open(path, mode, fs = nil, rs = nil, &block)
    if mode == 'r' or mode == 'rb'
      open_reader(path, mode, fs, rs, &block)
    elsif mode == 'w' or mode == 'wb'
      open_writer(path, mode, fs, rs, &block)
    else
      raise ArgumentError.new("'mode' must be 'r', 'rb', 'w', or 'wb'")
    end
  end


foreach (CSV)

# File lib/csv.rb, line 93
  def CSV.foreach(path, rs = nil, &block)
    open_reader(path, 'r', ',', rs, &block)
  end


read (CSV)

# File lib/csv.rb, line 97
  def CSV.read(path, length = nil, offset = nil)
    CSV.parse(IO.read(path, length, offset))
  end


readlines (CSV)

# File lib/csv.rb, line 101
  def CSV.readlines(path, rs = nil)
    reader = open_reader(path, 'r', ',', rs)
    begin
      reader.collect { |row| row }
    ensure
      reader.close
    end
  end


generate (CSV)

# File lib/csv.rb, line 110
  def CSV.generate(path, fs = nil, rs = nil, &block)
    open_writer(path, 'w', fs, rs, &block)
  end


parse (CSV)

# File lib/csv.rb, line 115
  def CSV.parse(str_or_readable, fs = nil, rs = nil, &block)
    if File.exist?(str_or_readable)
      STDERR.puts("CSV.parse(filename) is deprecated." +
        "  Use CSV.open(filename, 'r') instead.")
      return open_reader(str_or_readable, 'r', fs, rs, &block)
    end
    if block
      CSV::Reader.parse(str_or_readable, fs, rs) do |row|
        yield(row)
      end
      nil
    else
      CSV::Reader.create(str_or_readable, fs, rs).collect { |row| row }
    end
  end


parse_line (CSV)

# File lib/csv.rb, line 137
  def CSV.parse_line(src, fs = nil, rs = nil)
    fs ||= ','
    if fs.is_a?(Fixnum)
      fs = fs.chr
    end
    if !rs.nil? and rs.is_a?(Fixnum)
      rs = rs.chr
    end
    idx = 0
    res_type = :DT_COLSEP
    row = []
    begin
      while res_type == :DT_COLSEP
        res_type, idx, cell = parse_body(src, idx, fs, rs)
        row << cell
      end
    rescue IllegalFormatError
      return []
    end
    row
  end


generate_line (CSV)

# File lib/csv.rb, line 160
  def CSV.generate_line(row, fs = nil, rs = nil)
    if row.size == 0
      return ''
    end
    fs ||= ','
    if fs.is_a?(Fixnum)
      fs = fs.chr
    end
    if !rs.nil? and rs.is_a?(Fixnum)
      rs = rs.chr
    end
    res_type = :DT_COLSEP
    result_str = ''
    idx = 0
    while true
      generate_body(row[idx], result_str, fs, rs)
      idx += 1
      if (idx == row.size)
        break
      end
      generate_separator(:DT_COLSEP, result_str, fs, rs)
    end
    result_str
  end


parse_row (CSV)

# File lib/csv.rb, line 214
  def CSV.parse_row(src, idx, out_dev, fs = nil, rs = nil)
    fs ||= ','
    if fs.is_a?(Fixnum)
      fs = fs.chr
    end
    if !rs.nil? and rs.is_a?(Fixnum)
      rs = rs.chr
    end
    idx_backup = idx
    parsed_cells = 0
    res_type = :DT_COLSEP
    begin
      while res_type != :DT_ROWSEP
        res_type, idx, cell = parse_body(src, idx, fs, rs)
        if res_type == :DT_EOS
          if idx == idx_backup #((parsed_cells == 0) and cell.nil?)
            return 0, 0
          end
          res_type = :DT_ROWSEP
        end
        parsed_cells += 1
        out_dev << cell
      end
    rescue IllegalFormatError
      return 0, 0
    end
    return parsed_cells, idx
  end


generate_row (CSV)

# File lib/csv.rb, line 271
  def CSV.generate_row(src, cells, out_dev, fs = nil, rs = nil)
    fs ||= ','
    if fs.is_a?(Fixnum)
      fs = fs.chr
    end
    if !rs.nil? and rs.is_a?(Fixnum)
      rs = rs.chr
    end
    src_size = src.size
    if (src_size == 0)
      if cells == 0
        generate_separator(:DT_ROWSEP, out_dev, fs, rs)
      end
      return 0
    end
    res_type = :DT_COLSEP
    parsed_cells = 0
    generate_body(src[parsed_cells], out_dev, fs, rs)
    parsed_cells += 1
    while ((parsed_cells < cells) and (parsed_cells != src_size))
      generate_separator(:DT_COLSEP, out_dev, fs, rs)
      generate_body(src[parsed_cells], out_dev, fs, rs)
      parsed_cells += 1
    end
    if (parsed_cells == cells)
      generate_separator(:DT_ROWSEP, out_dev, fs, rs)
    else
      generate_separator(:DT_COLSEP, out_dev, fs, rs)
    end
    parsed_cells
  end


strftime (Date)

# File lib/date/format.rb, line 200
  def strftime(fmt='%F')
    fmt.gsub(/%([-_0^#]+)?(\d+)?[EO]?(:{1,3}z|.)/m) do |m|
      f = {}
      s, w, c = $1, $2, $3
      if s
        s.scan(/./) do |k|
          case k
          when '-'; f[:p] = '-'
          when '_'; f[:p] = "\s"
          when '0'; f[:p] = '0'
          when '^'; f[:u] = true
          when '#'; f[:x] = true
          end
        end
      end
      if w
        f[:w] = w.to_i
      end
      case c
      when 'A'; emit_ad(DAYNAMES[wday], 0, f)
      when 'a'; emit_ad(ABBR_DAYNAMES[wday], 0, f)
      when 'B'; emit_ad(MONTHNAMES[mon], 0, f)
      when 'b'; emit_ad(ABBR_MONTHNAMES[mon], 0, f)
      when 'C'; emit_sn((year / 100).floor, 2, f)
      when 'c'; emit_a(strftime('%a %b %e %H:%M:%S %Y'), 0, f)
      when 'D'; emit_a(strftime('%m/%d/%y'), 0, f)
      when 'd'; emit_n(mday, 2, f)
      when 'e'; emit_a(mday, 2, f)
      when 'F'
        if m == '%F'
          format('%.4d-%02d-%02d', year, mon, mday) # 4p
        else
          emit_a(strftime('%Y-%m-%d'), 0, f)
        end
      when 'G'; emit_sn(cwyear, 4, f)
      when 'g'; emit_n(cwyear % 100, 2, f)
      when 'H'; emit_n(hour, 2, f)
      when 'h'; emit_ad(strftime('%b'), 0, f)
      when 'I'; emit_n((hour % 12).nonzero? || 12, 2, f)
      when 'j'; emit_n(yday, 3, f)
      when 'k'; emit_a(hour, 2, f)
      when 'L'
        emit_n((sec_fraction / (1.to_r/86400/(10**3))).round, 3, f)
      when 'l'; emit_a((hour % 12).nonzero? || 12, 2, f)
      when 'M'; emit_n(min, 2, f)
      when 'm'; emit_n(mon, 2, f)
      when 'N'
        emit_n((sec_fraction / (1.to_r/86400/(10**9))).round, 9, f)
      when 'n'; "\n"
      when 'P'; emit_ad(strftime('%p').downcase, 0, f)
      when 'p'; emit_au(if hour < 12 then 'AM' else 'PM' end, 0, f)
      when 'Q'
        d = ajd - self.class.jd_to_ajd(self.class::UNIXEPOCH, 0)
        s = (d * 86400*10**3).to_i
        emit_sn(s, 1, f)
      when 'R'; emit_a(strftime('%H:%M'), 0, f)
      when 'r'; emit_a(strftime('%I:%M:%S %p'), 0, f)
      when 'S'; emit_n(sec, 2, f)
      when 's'
        d = ajd - self.class.jd_to_ajd(self.class::UNIXEPOCH, 0)
        s = (d * 86400).to_i
        emit_sn(s, 1, f)
      when 'T'
        if m == '%T'
          format('%02d:%02d:%02d', hour, min, sec) # 4p
        else
          emit_a(strftime('%H:%M:%S'), 0, f)
        end
      when 't'; "\t"
      when 'U', 'W'
        emit_n(if c == 'U' then wnum0 else wnum1 end, 2, f)
      when 'u'; emit_n(cwday, 1, f)
      when 'V'; emit_n(cweek, 2, f)
      when 'v'; emit_a(strftime('%e-%b-%Y'), 0, f)
      when 'w'; emit_n(wday, 1, f)
      when 'X'; emit_a(strftime('%H:%M:%S'), 0, f)
      when 'x'; emit_a(strftime('%m/%d/%y'), 0, f)
      when 'Y'; emit_sn(year, 4, f)
      when 'y'; emit_n(year % 100, 2, f)
      when 'Z'; emit_au(strftime('%:z'), 0, f)
      when /\A(:{0,3})z/
        t = $1.size
        sign = if offset < 0 then -1 else +1 end
        fr = offset.abs
        hh, fr = fr.divmod(1.to_r/24)
        mm, fr = fr.divmod(1.to_r/1440)
        ss, fr = fr.divmod(1.to_r/86400)
        if t == 3
          if    ss.nonzero? then t =  2
          elsif mm.nonzero? then t =  1
          else                   t = -1
          end
        end
        case t
        when -1
          tail = []
          sep = ''
        when 0
          f[:w] -= 2 if f[:w]
          tail = ['%02d' % mm]
          sep = ''
        when 1
          f[:w] -= 3 if f[:w]
          tail = ['%02d' % mm]
          sep = ':'
        when 2
          f[:w] -= 6 if f[:w]
          tail = ['%02d' % mm, '%02d' % ss]
          sep = ':'
        end
        ([emit_z(sign * hh, 2, f)] + tail).join(sep)
      when '%'; emit_a('%', 0, f)
      when '+'; emit_a(strftime('%a %b %e %H:%M:%S %Z %Y'), 0, f)
      when '1'
        if $VERBOSE
          warn("warning: strftime: %1 is deprecated; forget this")
        end
        emit_n(jd, 1, f)
      when '2'
        if $VERBOSE
          warn("warning: strftime: %2 is deprecated; use '%Y-%j'")
        end
        emit_a(strftime('%Y-%j'), 0, f)
      when '3'
        if $VERBOSE
          warn("warning: strftime: %3 is deprecated; use '%F'")
        end
        emit_a(strftime('%F'), 0, f)
      else
        c
      end
    end
  end


asctime (Date)

# File lib/date/format.rb, line 336
  def asctime() strftime('%c') end


_strptime (Date)

# File lib/date/format.rb, line 581
  def self._strptime(str, fmt='%F')
    e = Format::Bag.new
    return unless _strptime_i(str.dup, fmt, e)

    if e._cent
      if e.cwyear
        e.cwyear += e._cent * 100
      end
      if e.year
        e.  year += e._cent * 100
      end
    end

    if e._merid
      if e.hour
        e.hour %= 12
        e.hour += e._merid
      end
    end

    e.to_hash
  end


_parse (Date)

# File lib/date/format.rb, line 958
  def self._parse(str, comp=false)
    str = str.dup

    e = Format::Bag.new

    e._comp = comp

    str.gsub!(/[^-+',.\/:0-9@a-z\x80-\xff]+/in, ' ')

    _parse_time(str, e) # || _parse_beat(str, e)
    _parse_day(str, e)

    _parse_eu(str, e)     ||
    _parse_us(str, e)     ||
    _parse_iso(str, e)    ||
    _parse_jis(str, e)    ||
    _parse_vms(str, e)    ||
    _parse_sla_us(str, e) ||
    _parse_iso2(str, e)   ||
    _parse_year(str, e)   ||
    _parse_mon(str, e)    ||
    _parse_mday(str, e)   ||
    _parse_ddd(str, e)

    if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/in, ' ')
      if e.year
        e.year = -e.year + 1
      end
    end

    if str.sub!(/\A\s*(\d{1,2})\s*\z/n, ' ')
      if e.hour && !e.mday
        v = $1.to_i
        if (1..31) === v
          e.mday = v
        end
      end
      if e.mday && !e.hour
        v = $1.to_i
        if (0..24) === v
          e.hour = v
        end
      end
    end

    if e._comp and e.year
      if e.year >= 0 and e.year <= 99
        if e.year >= 69
          e.year += 1900
        else
          e.year += 2000
        end
      end
    end

    e.offset ||= zone_to_diff(e.zone) if e.zone

    e.to_hash
  end


julian? (Date)

# File lib/date.rb, line 327
  def self.julian? (jd, sg)
    case sg
    when Numeric
      jd < sg
    else
      if $VERBOSE
        warn("#{caller.shift.sub(/:in .*/, '')}: " \
"warning: do not use non-numerical object as julian day number anymore")
      end
      not sg
    end
  end


gregorian? (Date)

# File lib/date.rb, line 345
  def self.gregorian? (jd, sg) !julian?(jd, sg) end


ordinal_to_jd (Date)

# File lib/date.rb, line 361
  def self.ordinal_to_jd(y, d, sg=GREGORIAN)
    civil_to_jd(y, 1, d, sg)
  end


jd_to_ordinal (Date)

# File lib/date.rb, line 372
  def self.jd_to_ordinal(jd, sg=GREGORIAN)
    y = jd_to_civil(jd, sg)[0]
    doy = jd - civil_to_jd(y - 1, 12, 31, fix_style(jd, sg))
    return y, doy
  end


civil_to_jd (Date)

# File lib/date.rb, line 383
  def self.civil_to_jd(y, m, d, sg=GREGORIAN)
    if m <= 2
      y -= 1
      m += 12
    end
    a = (y / 100.0).floor
    b = 2 - a + (a / 4.0).floor
    jd = (365.25 * (y + 4716)).floor +
      (30.6001 * (m + 1)).floor +
      d + b - 1524
    if julian?(jd, sg)
      jd -= b
    end
    jd
  end


jd_to_civil (Date)

# File lib/date.rb, line 405
  def self.jd_to_civil(jd, sg=GREGORIAN)
    if julian?(jd, sg)
      a = jd
    else
      x = ((jd - 1867216.25) / 36524.25).floor
      a = jd + 1 + x - (x / 4.0).floor
    end
    b = a + 1524
    c = ((b - 122.1) / 365.25).floor
    d = (365.25 * c).floor
    e = ((b - d) / 30.6001).floor
    dom = b - d - (30.6001 * e).floor
    if e <= 13
      m = e - 1
      y = c - 4716
    else
      m = e - 13
      y = c - 4715
    end
    return y, m, dom
  end


commercial_to_jd (Date)

# File lib/date.rb, line 432
  def self.commercial_to_jd(y, w, d, ns=GREGORIAN)
    jd = civil_to_jd(y, 1, 4, ns)
    (jd - (((jd - 1) + 1) % 7)) +
      7 * (w - 1) +
      (d - 1)
  end


jd_to_commercial (Date)

# File lib/date.rb, line 446
  def self.jd_to_commercial(jd, sg=GREGORIAN)
    ns = fix_style(jd, sg)
    a = jd_to_civil(jd - 3, ns)[0]
    y = if jd >= commercial_to_jd(a + 1, 1, 1, ns) then a + 1 else a end
    w = 1 + ((jd - commercial_to_jd(y, 1, 1, ns)) / 7).floor
    d = (jd + 1) % 7
    d = 7 if d == 0
    return y, w, d
  end


ajd_to_jd (Date)

# File lib/date.rb, line 479
  def self.ajd_to_jd(ajd, of=0) (ajd + of + 1.to_r/2).divmod(1) end


jd_to_ajd (Date)

# File lib/date.rb, line 490
  def self.jd_to_ajd(jd, fr, of=0) jd + fr - of - 1.to_r/2 end


day_fraction_to_time (Date)

# File lib/date.rb, line 494
  def self.day_fraction_to_time(fr)
    h,   fr = fr.divmod(1.to_r/24)
    min, fr = fr.divmod(1.to_r/1440)
    s,   fr = fr.divmod(1.to_r/86400)
    return h, min, s, fr
  end


time_to_day_fraction (Date)

# File lib/date.rb, line 503
  def self.time_to_day_fraction(h, min, s)
    h.to_r/24 + min.to_r/1440 + s.to_r/86400
  end


amjd_to_ajd (Date)

# File lib/date.rb, line 509
  def self.amjd_to_ajd(amjd) amjd + 4800001.to_r/2 end


ajd_to_amjd (Date)

# File lib/date.rb, line 513
  def self.ajd_to_amjd(ajd) ajd - 4800001.to_r/2 end


mjd_to_jd (Date)

# File lib/date.rb, line 517
  def self.mjd_to_jd(mjd) mjd + 2400001 end


jd_to_mjd (Date)

# File lib/date.rb, line 521
  def self.jd_to_mjd(jd) jd - 2400001 end


ld_to_jd (Date)

# File lib/date.rb, line 525
  def self.ld_to_jd(ld) ld + 2299160 end


jd_to_ld (Date)

# File lib/date.rb, line 529
  def self.jd_to_ld(jd) jd - 2299160 end


jd_to_wday (Date)

# File lib/date.rb, line 534
  def self.jd_to_wday(jd) (jd + 1) % 7 end


julian_leap? (Date)

# File lib/date.rb, line 539
  def self.julian_leap? (y) y % 4 == 0 end


gregorian_leap? (Date)

# File lib/date.rb, line 545
  def self.gregorian_leap? (y) y % 4 == 0 && y % 100 != 0 || y % 400 == 0 end


valid_jd? (Date)

# File lib/date.rb, line 554
  def self.valid_jd? (jd, sg=ITALY) jd end


valid_ordinal? (Date)

# File lib/date.rb, line 569
  def self.valid_ordinal? (y, d, sg=ITALY)
    if d < 0
      ny, = (y + 1).divmod(1)
      jd = ordinal_to_jd(ny, d + 1, sg)
      ns = fix_style(jd, sg)
      return unless [y] == jd_to_ordinal(jd, sg)[0..0]
      return unless [ny, 1] == jd_to_ordinal(jd - d, ns)
    else
      jd = ordinal_to_jd(y, d, sg)
      return unless [y, d] == jd_to_ordinal(jd, sg)
    end
    jd
  end


valid_civil? (Date)

# File lib/date.rb, line 595
  def self.valid_civil? (y, m, d, sg=ITALY)
    if m < 0
      m += 13
    end
    if d < 0
      ny, nm = (y * 12 + m).divmod(12)
      nm,    = (nm + 1).divmod(1)
      jd = civil_to_jd(ny, nm, d + 1, sg)
      ns = fix_style(jd, sg)
      return unless [y, m] == jd_to_civil(jd, sg)[0..1]
      return unless [ny, nm, 1] == jd_to_civil(jd - d, ns)
    else
      jd = civil_to_jd(y, m, d, sg)
      return unless [y, m, d] == jd_to_civil(jd, sg)
    end
    jd
  end


valid_commercial? (Date)

# File lib/date.rb, line 629
  def self.valid_commercial? (y, w, d, sg=ITALY)
    if d < 0
      d += 8
    end
    if w < 0
      ny, nw, nd =
        jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7)
      return unless ny == y
      w = nw
    end
    jd = commercial_to_jd(y, w, d)
    return unless gregorian?(jd, sg)
    return unless [y, w, d] == jd_to_commercial(jd)
    jd
  end


valid_time? (Date)

# File lib/date.rb, line 672
  def self.valid_time? (h, min, s)
    h   += 24 if h   < 0
    min += 60 if min < 0
    s   += 60 if s   < 0
    return unless ((0..23) === h &&
                   (0..59) === min &&
                   (0..59) === s) ||
                  (24 == h &&
                    0 == min &&
                    0 == s)
    time_to_day_fraction(h, min, s)
  end


jd (Date)

# File lib/date.rb, line 690
  def self.jd(jd=0, sg=ITALY)
    jd = valid_jd?(jd, sg)
    new!(jd_to_ajd(jd, 0, 0), 0, sg)
  end


ordinal (Date)

# File lib/date.rb, line 705
  def self.ordinal(y=-4712, d=1, sg=ITALY)
    unless jd = valid_ordinal?(y, d, sg)
      raise ArgumentError, 'invalid date'
    end
    new!(jd_to_ajd(jd, 0, 0), 0, sg)
  end


civil (Date)

# File lib/date.rb, line 725
  def self.civil(y=-4712, m=1, d=1, sg=ITALY)
    unless jd = valid_civil?(y, m, d, sg)
      raise ArgumentError, 'invalid date'
    end
    new!(jd_to_ajd(jd, 0, 0), 0, sg)
  end


commercial (Date)

# File lib/date.rb, line 748
  def self.commercial(y=1582, w=41, d=5, sg=ITALY)
    unless jd = valid_commercial?(y, w, d, sg)
      raise ArgumentError, 'invalid date'
    end
    new!(jd_to_ajd(jd, 0, 0), 0, sg)
  end


strptime (Date)

# File lib/date.rb, line 953
  def self.strptime(str='-4712-01-01', fmt='%F', sg=ITALY)
    elem = _strptime(str, fmt)
    new_by_frags(elem, sg)
  end


parse (Date)

# File lib/date.rb, line 973
  def self.parse(str='-4712-01-01', comp=false, sg=ITALY)
    elem = _parse(str, comp)
    new_by_frags(elem, sg)
  end


new (Date)

# File lib/date.rb, line 1016
  def initialize(ajd=0, of=0, sg=ITALY) @ajd, @of, @sg = ajd, of, sg end


ajd (Date)

# File lib/date.rb, line 1019
  def ajd() @ajd end


amjd (Date)

# File lib/date.rb, line 1022
  def amjd() self.class.ajd_to_amjd(@ajd) end


jd (Date)

# File lib/date.rb, line 1027
  def jd() self.class.ajd_to_jd(@ajd, @of)[0] end


day_fraction (Date)

# File lib/date.rb, line 1030
  def day_fraction() self.class.ajd_to_jd(@ajd, @of)[1] end


mjd (Date)

# File lib/date.rb, line 1033
  def mjd() self.class.jd_to_mjd(jd) end


ld (Date)

# File lib/date.rb, line 1037
  def ld() self.class.jd_to_ld(jd) end


year (Date)

# File lib/date.rb, line 1057
  def year() civil[0] end


yday (Date)

# File lib/date.rb, line 1062
  def yday() ordinal[1] end


mon (Date)

# File lib/date.rb, line 1067
  def mon() civil[1] end


mday (Date)

# File lib/date.rb, line 1070
  def mday() civil[2] end


cwyear (Date)

# File lib/date.rb, line 1108
  def cwyear() commercial[0] end


cweek (Date)

# File lib/date.rb, line 1111
  def cweek() commercial[1] end


cwday (Date)

# File lib/date.rb, line 1115
  def cwday() commercial[2] end


wday (Date)

# File lib/date.rb, line 1119
  def wday() self.class.jd_to_wday(jd) end


julian? (Date)

# File lib/date.rb, line 1136
  def julian? () self.class.julian?(jd, @sg) end


gregorian? (Date)

# File lib/date.rb, line 1139
  def gregorian? () self.class.gregorian?(jd, @sg) end


leap? (Date)

# File lib/date.rb, line 1152
  def leap?
    self.class.jd_to_civil(self.class.civil_to_jd(year, 3, 1, fix_style) - 1,
                     fix_style)[-1] == 29
  end


start (Date)

# File lib/date.rb, line 1160
  def start() @sg end


new_start (Date)

# File lib/date.rb, line 1163
  def new_start(sg=self.class::ITALY) self.class.new!(@ajd, @of, sg) end


italy (Date)

# File lib/date.rb, line 1167
  def italy() new_start(self.class::ITALY) end


england (Date)

# File lib/date.rb, line 1171
  def england() new_start(self.class::ENGLAND) end


julian (Date)

# File lib/date.rb, line 1175
  def julian() new_start(self.class::JULIAN) end


gregorian (Date)

# File lib/date.rb, line 1179
  def gregorian() new_start(self.class::GREGORIAN) end


+ (Date)

# File lib/date.rb, line 1201
  def + (n)
    case n
    when Numeric; return self.class.new!(@ajd + n, @of, @sg)
    end
    raise TypeError, 'expected numeric'
  end


- (Date)

# File lib/date.rb, line 1216
  def - (x)
    case x
    when Numeric; return self.class.new!(@ajd - x, @of, @sg)
    when Date;    return @ajd - x.ajd
    end
    raise TypeError, 'expected numeric or date'
  end


<=> (Date)

# File lib/date.rb, line 1235
  def <=> (other)
    case other
    when Numeric; return @ajd <=> other
    when Date;    return @ajd <=> other.ajd
    end
    nil
  end


=== (Date)

# File lib/date.rb, line 1249
  def === (other)
    case other
    when Numeric; return jd == other
    when Date;    return jd == other.jd
    end
    false
  end


next (Date)

# File lib/date.rb, line 1263
  def next() next_day end


>> (Date)

# File lib/date.rb, line 1273
  def >> (n)
    y, m = (year * 12 + (mon - 1) + n).divmod(12)
    m,   = (m + 1)                    .divmod(1)
    d = mday
    d -= 1 until jd2 = self.class.valid_civil?(y, m, d, fix_style)
    self + (jd2 - jd)
  end


<< (Date)

# File lib/date.rb, line 1287
  def << (n) self >> -n end


step (Date)

# File lib/date.rb, line 1303
  def step(limit, step=1) # :yield: date
??
    da = self
    op = %w(- <= >=)[step <=> 0]
    while da.__send__(op, limit)
      yield da
      da += step
    end
    self
  end


upto (Date)

# File lib/date.rb, line 1320
  def upto(max, &block) # :yield: date
    step(max, +1, &block)
  end


downto (Date)

# File lib/date.rb, line 1326
  def downto(min, &block) # :yield: date
    step(min, -1, &block)
  end


eql? (Date)

# File lib/date.rb, line 1333
  def eql? (other) Date === other && self == other end


hash (Date)

# File lib/date.rb, line 1336
  def hash() @ajd.hash end


inspect (Date)

# File lib/date.rb, line 1339
  def inspect() format('#<%s: %s,%s,%s>', self.class, @ajd, @of, @sg) end


to_s (Date)

# File lib/date.rb, line 1344
  def to_s() strftime end


_dump (Date)

# File lib/date.rb, line 1347
  def _dump(limit) Marshal.dump([@ajd, @of, @sg], -1) end


_load (Date)

# File lib/date.rb, line 1352
  def self._load(str)
    a = Marshal.load(str)
    if a.size == 2
      ajd,     sg = a
           of = 0
      ajd -= 1.to_r/2
    else
      ajd, of, sg = a
    end
    new!(ajd, of, sg)
  end


today (Date)

# File lib/date.rb, line 1623
  def self.today(sg=ITALY) Time.now.__send__(:to_date)    .new_start(sg) end


to_yaml (Date)

# File lib/yaml/rubytypes.rb, line 349
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            out.scalar( "tag:yaml.org,2002:timestamp", self.to_s, :plain )
        end
        end


strftime (DateTime)

# File lib/date/format.rb, line 1056
  def strftime(fmt='%FT%T%:z')
    super(fmt)
  end


_strptime (DateTime)

# File lib/date/format.rb, line 1060
  def self._strptime(str, fmt='%FT%T%z')
    super(str, fmt)
  end


jd (DateTime)

# File lib/date.rb, line 1430
  def self.jd(jd=0, h=0, min=0, s=0, of=0, sg=ITALY)
    unless (jd = valid_jd?(jd, sg)) &&
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    if String === of
      of = (zone_to_diff(of) || 0).to_r/86400
    end
    new!(jd_to_ajd(jd, fr, of), of, sg)
  end


ordinal (DateTime)

# File lib/date.rb, line 1455
  def self.ordinal(y=-4712, d=1, h=0, min=0, s=0, of=0, sg=ITALY)
    unless (jd = valid_ordinal?(y, d, sg)) &&
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    if String === of
      of = (zone_to_diff(of) || 0).to_r/86400
    end
    new!(jd_to_ajd(jd, fr, of), of, sg)
  end


civil (DateTime)

# File lib/date.rb, line 1480
  def self.civil(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=ITALY)
    unless (jd = valid_civil?(y, m, d, sg)) &&
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    if String === of
      of = (zone_to_diff(of) || 0).to_r/86400
    end
    new!(jd_to_ajd(jd, fr, of), of, sg)
  end


commercial (DateTime)

# File lib/date.rb, line 1508
  def self.commercial(y=1582, w=41, d=5, h=0, min=0, s=0, of=0, sg=ITALY)
    unless (jd = valid_commercial?(y, w, d, sg)) &&
           (fr = valid_time?(h, min, s))
      raise ArgumentError, 'invalid date'
    end
    if String === of
      of = (zone_to_diff(of) || 0).to_r/86400
    end
    new!(jd_to_ajd(jd, fr, of), of, sg)
  end


strptime (DateTime)

# File lib/date.rb, line 1562
  def self.strptime(str='-4712-01-01T00:00:00+00:00', fmt='%FT%T%z', sg=ITALY)
    elem = _strptime(str, fmt)
    new_by_frags(elem, sg)
  end


parse (DateTime)

# File lib/date.rb, line 1582
  def self.parse(str='-4712-01-01T00:00:00+00:00', comp=false, sg=ITALY)
    elem = _parse(str, comp)
    new_by_frags(elem, sg)
  end


readline (DEBUGGER__::Context)

# File lib/debug.rb, line 68
    def readline(prompt, hist)
      Readline::readline(prompt, hist)
    end


readline (DEBUGGER__::Context)

# File lib/debug.rb, line 72
    def readline(prompt, hist)
      STDOUT.print prompt
      STDOUT.flush
      line = STDIN.gets
      exit unless line
      line.chomp!
      line
    end


new (DEBUGGER__::Context)

# File lib/debug.rb, line 83
  def initialize
    if Thread.current == Thread.main
      @stop_next = 1
    else
      @stop_next = 0
    end
    @last_file = nil
    @file = nil
    @line = nil
    @no_step = nil
    @frames = []
    @finish_pos = 0
    @trace = false
    @catch = "StandardError"
    @suspend_next = false
  end


stop_next (DEBUGGER__::Context)

# File lib/debug.rb, line 100
  def stop_next(n=1)
    @stop_next = n
  end


set_suspend (DEBUGGER__::Context)

# File lib/debug.rb, line 104
  def set_suspend
    @suspend_next = true
  end


clear_suspend (DEBUGGER__::Context)

# File lib/debug.rb, line 108
  def clear_suspend
    @suspend_next = false
  end


suspend_all (DEBUGGER__::Context)

# File lib/debug.rb, line 112
  def suspend_all
    DEBUGGER__.suspend
  end


resume_all (DEBUGGER__::Context)

# File lib/debug.rb, line 116
  def resume_all
    DEBUGGER__.resume
  end


check_suspend (DEBUGGER__::Context)

# File lib/debug.rb, line 120
  def check_suspend
    return if Thread.critical
    while (Thread.critical = true; @suspend_next)
      DEBUGGER__.waiting.push Thread.current
      @suspend_next = false
      Thread.stop
    end
    Thread.critical = false
  end


trace? (DEBUGGER__::Context)

# File lib/debug.rb, line 130
  def trace?
    @trace
  end


set_trace (DEBUGGER__::Context)

# File lib/debug.rb, line 134
  def set_trace(arg)
    @trace = arg
  end


stdout (DEBUGGER__::Context)

# File lib/debug.rb, line 138
  def stdout
    DEBUGGER__.stdout
  end


break_points (DEBUGGER__::Context)

# File lib/debug.rb, line 142
  def break_points
    DEBUGGER__.break_points
  end


display (DEBUGGER__::Context)

# File lib/debug.rb, line 146
  def display
    DEBUGGER__.display
  end


context (DEBUGGER__::Context)

# File lib/debug.rb, line 150
  def context(th)
    DEBUGGER__.context(th)
  end


set_trace_all (DEBUGGER__::Context)

# File lib/debug.rb, line 154
  def set_trace_all(arg)
    DEBUGGER__.set_trace(arg)
  end


set_last_thread (DEBUGGER__::Context)

# File lib/debug.rb, line 158
  def set_last_thread(th)
    DEBUGGER__.set_last_thread(th)
  end


debug_eval (DEBUGGER__::Context)

# File lib/debug.rb, line 162
  def debug_eval(str, binding)
    begin
      val = eval(str, binding)
    rescue StandardError, ScriptError => e
      at = eval("caller(1)", binding)
      stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '')
      for i in at
        stdout.printf "\tfrom %s\n", i
      end
      throw :debug_error
    end
  end


debug_silent_eval (DEBUGGER__::Context)

# File lib/debug.rb, line 175
  def debug_silent_eval(str, binding)
    begin
      eval(str, binding)
    rescue StandardError, ScriptError
      nil
    end
  end


var_list (DEBUGGER__::Context)

# File lib/debug.rb, line 183
  def var_list(ary, binding)
    ary.sort!
    for v in ary
      stdout.printf "  %s => %s\n", v, eval(v, binding).inspect
    end
  end


debug_variable_info (DEBUGGER__::Context)

# File lib/debug.rb, line 190
  def debug_variable_info(input, binding)
    case input
    when /^\s*g(?:lobal)?\s*$/
      var_list(global_variables, binding)

    when /^\s*l(?:ocal)?\s*$/
      var_list(eval("local_variables", binding), binding)

    when /^\s*i(?:nstance)?\s+/
      obj = debug_eval($', binding)
      var_list(obj.instance_variables, obj.instance_eval{binding()})

    when /^\s*c(?:onst(?:ant)?)?\s+/
      obj = debug_eval($', binding)
      unless obj.kind_of? Module
        stdout.print "Should be Class/Module: ", $', "\n"
      else
        var_list(obj.constants, obj.module_eval{binding()})
      end
    end
  end


debug_method_info (DEBUGGER__::Context)

# File lib/debug.rb, line 212
  def debug_method_info(input, binding)
    case input
    when /^i(:?nstance)?\s+/
      obj = debug_eval($', binding)

      len = 0
      for v in obj.methods.sort
        len += v.size + 1
        if len > 70
          len = v.size + 1
          stdout.print "\n"
        end
        stdout.print v, " "
      end
      stdout.print "\n"

    else
      obj = debug_eval(input, binding)
      unless obj.kind_of? Module
        stdout.print "Should be Class/Module: ", input, "\n"
      else
        len = 0
        for v in obj.instance_methods(false).sort
          len += v.size + 1
          if len > 70
            len = v.size + 1
            stdout.print "\n"
          end
          stdout.print v, " "
        end
        stdout.print "\n"
      end
    end
  end


thnum (DEBUGGER__::Context)

# File lib/debug.rb, line 247
  def thnum
    num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
    unless num
      DEBUGGER__.make_thread_list
      num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
    end
    num
  end


debug_command (DEBUGGER__::Context)

# File lib/debug.rb, line 256
  def debug_command(file, line, id, binding)
    MUTEX.lock
    unless defined?($debugger_restart) and $debugger_restart
      callcc{|c| $debugger_restart = c}
    end
    set_last_thread(Thread.current)
    frame_pos = 0
    binding_file = file
    binding_line = line
    previous_line = nil
    if ENV['EMACS']
      stdout.printf "\032\032%s:%d:\n", binding_file, binding_line
    else
      stdout.printf "%s:%d:%s", binding_file, binding_line,
        line_at(binding_file, binding_line)
    end
    @frames[0] = [binding, file, line, id]
    display_expressions(binding)
    prompt = true
    while prompt and input = readline("(rdb:%d) "%thnum(), true)
      catch(:debug_error) do
        if input == ""
          next unless DEBUG_LAST_CMD[0]
          input = DEBUG_LAST_CMD[0]
          stdout.print input, "\n"
        else
          DEBUG_LAST_CMD[0] = input
        end

        case input
        when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/
          if defined?( $2 )
            if $1 == 'on'
              set_trace_all true
            else
              set_trace_all false
            end
          elsif defined?( $1 )
            if $1 == 'on'
              set_trace true
            else
              set_trace false
            end
          end
          if trace?
            stdout.print "Trace on.\n"
          else
            stdout.print "Trace off.\n"
          end

        when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/
          pos = $2
          if $1
            klass = debug_silent_eval($1, binding)
            file = $1
          end
          if pos =~ /^\d+$/
            pname = pos
            pos = pos.to_i
          else
            pname = pos = pos.intern.id2name
          end
          break_points.push [true, 0, klass || file, pos]
          stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname

        when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/
          pos = $2.intern.id2name
          klass = debug_eval($1, binding)
          break_points.push [true, 0, klass, pos]
          stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos

        when /^\s*wat(?:ch)?\s+(.+)$/
          exp = $1
          break_points.push [true, 1, exp]
          stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp

        when /^\s*b(?:reak)?$/
          if break_points.find{|b| b[1] == 0}
            n = 1
            stdout.print "Breakpoints:\n"
            for b in break_points
              if b[0] and b[1] == 0
                stdout.printf "  %d %s:%s\n", n, b[2], b[3]
              end
              n += 1
            end
          end
          if break_points.find{|b| b[1] == 1}
            n = 1
            stdout.print "\n"
            stdout.print "Watchpoints:\n"
            for b in break_points
              if b[0] and b[1] == 1
                stdout.printf "  %d %s\n", n, b[2]
              end
              n += 1
            end
          end
          if break_points.size == 0
            stdout.print "No breakpoints\n"
          else
            stdout.print "\n"
          end

        when /^\s*del(?:ete)?(?:\s+(\d+))?$/
          pos = $1
          unless pos
            input = readline("Clear all breakpoints? (y/n) ", false)
            if input == "y"
              for b in break_points
                b[0] = false
              end
            end
          else
            pos = pos.to_i
            if break_points[pos-1]
              break_points[pos-1][0] = false
            else
              stdout.printf "Breakpoint %d is not defined\n", pos
            end
          end

        when /^\s*disp(?:lay)?\s+(.+)$/
          exp = $1
          display.push [true, exp]
          stdout.printf "%d: ", display.size
          display_expression(exp, binding)

        when /^\s*disp(?:lay)?$/
          display_expressions(binding)

        when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/
          pos = $1
          unless pos
            input = readline("Clear all expressions? (y/n) ", false)
            if input == "y"
              for d in display
                d[0] = false
              end
            end
          else
            pos = pos.to_i
            if display[pos-1]
              display[pos-1][0] = false
            else
              stdout.printf "Display expression %d is not defined\n", pos
            end
          end

        when /^\s*c(?:ont)?$/
          prompt = false

        when /^\s*s(?:tep)?(?:\s+(\d+))?$/
          if $1
            lev = $1.to_i
          else
            lev = 1
          end
          @stop_next = lev
          prompt = false

        when /^\s*n(?:ext)?(?:\s+(\d+))?$/
          if $1
            lev = $1.to_i
          else
            lev = 1
          end
          @stop_next = lev
          @no_step = @frames.size - frame_pos
          prompt = false

        when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
          display_frames(frame_pos)

        when /^\s*l(?:ist)?(?:\s+(.+))?$/
          if not $1
            b = previous_line ? previous_line + 10 : binding_line - 5
            e = b + 9
          elsif $1 == '-'
            b = previous_line ? previous_line - 10 : binding_line - 5
            e = b + 9
          else
            b, e = $1.split(/[-,]/)
            if e
              b = b.to_i
              e = e.to_i
            else
              b = b.to_i - 5
              e = b + 9
            end
          end
          previous_line = b
          display_list(b, e, binding_file, binding_line)

        when /^\s*up(?:\s+(\d+))?$/
          previous_line = nil
          if $1
            lev = $1.to_i
          else
            lev = 1
          end
          frame_pos += lev
          if frame_pos >= @frames.size
            frame_pos = @frames.size - 1
            stdout.print "At toplevel\n"
          end
          binding, binding_file, binding_line = @frames[frame_pos]
          stdout.print format_frame(frame_pos)

        when /^\s*down(?:\s+(\d+))?$/
          previous_line = nil
          if $1
            lev = $1.to_i
          else
            lev = 1
          end
          frame_pos -= lev
          if frame_pos < 0
            frame_pos = 0
            stdout.print "At stack bottom\n"
          end
          binding, binding_file, binding_line = @frames[frame_pos]
          stdout.print format_frame(frame_pos)

        when /^\s*fin(?:ish)?$/
          if frame_pos == @frames.size
            stdout.print "\"finish\" not meaningful in the outermost frame.\n"
          else
            @finish_pos = @frames.size - frame_pos
            frame_pos = 0
            prompt = false
          end

        when /^\s*cat(?:ch)?(?:\s+(.+))?$/
          if $1
            excn = $1
            if excn == 'off'
              @catch = nil
              stdout.print "Clear catchpoint.\n"
            else
              @catch = excn
              stdout.printf "Set catchpoint %s.\n", @catch
            end
          else
            if @catch
              stdout.printf "Catchpoint %s.\n", @catch
            else
              stdout.print "No catchpoint.\n"
            end
          end

        when /^\s*q(?:uit)?$/
          input = readline("Really quit? (y/n) ", false)
          if input == "y"
            exit!      # exit -> exit!: No graceful way to stop threads...
          end

        when /^\s*v(?:ar)?\s+/
          debug_variable_info($', binding)

        when /^\s*m(?:ethod)?\s+/
          debug_method_info($', binding)

        when /^\s*th(?:read)?\s+/
          if DEBUGGER__.debug_thread_info($', binding) == :cont
            prompt = false
          end

        when /^\s*pp\s+/
          PP.pp(debug_eval($', binding), stdout)

        when /^\s*p\s+/
          stdout.printf "%s\n", debug_eval($', binding).inspect

        when /^\s*r(?:estart)?$/
          $debugger_restart.call

        when /^\s*h(?:elp)?$/
          debug_print_help()

        else
          v = debug_eval(input, binding)
          stdout.printf "%s\n", v.inspect
        end
      end
    end
    MUTEX.unlock
    resume_all
  end


debug_print_help (DEBUGGER__::Context)

# File lib/debug.rb, line 546
  def debug_print_help
    stdout.print "Debugger help v.-0.002b\nCommands\n  b[reak] [file:|class:]<line|method>\n  b[reak] [class.]<line|method>\n                             set breakpoint to some position\n  wat[ch] <expression>       set watchpoint to some expression\n  cat[ch] (<exception>|off)  set catchpoint to an exception\n  b[reak]                    list breakpoints\n  cat[ch]                    show catchpoint\n  del[ete][ nnn]             delete some or all breakpoints\n  disp[lay] <expression>     add expression into display expression list\n  undisp[lay][ nnn]          delete one particular or all display expressions\n  c[ont]                     run until program ends or hit breakpoint\n  s[tep][ nnn]               step (into methods) one line or till line nnn\n  n[ext][ nnn]               go over one line or till line nnn\n  w[here]                    display frames\n  f[rame]                    alias for where\n  l[ist][ (-|nn-mm)]         list program, - lists backwards\n                             nn-mm lists given lines\n  up[ nn]                    move to higher frame\n  down[ nn]                  move to lower frame\n  fin[ish]                   return to outer frame\n  tr[ace] (on|off)           set trace mode of current thread\n  tr[ace] (on|off) all       set trace mode of all threads\n  q[uit]                     exit from debugger\n  v[ar] g[lobal]             show global variables\n  v[ar] l[ocal]              show local variables\n  v[ar] i[nstance] <object>  show instance variables of object\n  v[ar] c[onst] <object>     show constants of object\n  m[ethod] i[nstance] <obj>  show methods of object\n  m[ethod] <class|module>    show instance methods of class or module\n  th[read] l[ist]            list all threads\n  th[read] c[ur[rent]]       show current thread\n  th[read] [sw[itch]] <nnn>  switch thread context to nnn\n  th[read] stop <nnn>        stop thread nnn\n  th[read] resume <nnn>      resume thread nnn\n  p expression               evaluate expression and print its value\n  h[elp]                     print this help\n  <everything else>          evaluate\n"
  end


display_expressions (DEBUGGER__::Context)

# File lib/debug.rb, line 591
  def display_expressions(binding)
    n = 1
    for d in display
      if d[0]
        stdout.printf "%d: ", n
        display_expression(d[1], binding)
      end
      n += 1
    end
  end


display_expression (DEBUGGER__::Context)

# File lib/debug.rb, line 602
  def display_expression(exp, binding)
    stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
  end


frame_set_pos (DEBUGGER__::Context)

# File lib/debug.rb, line 606
  def frame_set_pos(file, line)
    if @frames[0]
      @frames[0][1] = file
      @frames[0][2] = line
    end
  end


display_frames (DEBUGGER__::Context)

# File lib/debug.rb, line 613
  def display_frames(pos)
    0.upto(@frames.size - 1) do |n|
      if n == pos
        stdout.print "--> "
      else
        stdout.print "    "
      end
      stdout.print format_frame(n)
    end
  end


format_frame (DEBUGGER__::Context)

# File lib/debug.rb, line 624
  def format_frame(pos)
    bind, file, line, id = @frames[pos]
    sprintf "#%d %s:%s%s\n", pos + 1, file, line,
      (id ? ":in `#{id.id2name}'" : "")
  end


display_list (DEBUGGER__::Context)

# File lib/debug.rb, line 630
  def display_list(b, e, file, line)
    stdout.printf "[%d, %d] in %s\n", b, e, file
    if lines = SCRIPT_LINES__[file] and lines != true
      n = 0
      b.upto(e) do |n|
        if n > 0 && lines[n-1]
          if n == line
            stdout.printf "=> %d  %s\n", n, lines[n-1].chomp
          else
            stdout.printf "   %d  %s\n", n, lines[n-1].chomp
          end
        end
      end
    else
      stdout.printf "No sourcefile available for %s\n", file
    end
  end


line_at (DEBUGGER__::Context)

# File lib/debug.rb, line 648
  def line_at(file, line)
    lines = SCRIPT_LINES__[file]
    if lines
      return "\n" if lines == true
      line = lines[line-1]
      return "\n" unless line
      return line
    end
    return "\n"
  end


debug_funcname (DEBUGGER__::Context)

# File lib/debug.rb, line 659
  def debug_funcname(id)
    if id.nil?
      "toplevel"
    else
      id.id2name
    end
  end


check_break_points (DEBUGGER__::Context)

# File lib/debug.rb, line 667
  def check_break_points(file, klass, pos, binding, id)
    return false if break_points.empty?
    n = 1
    for b in break_points
      if b[0]           # valid
        if b[1] == 0   # breakpoint
          if (b[2] == file and b[3] == pos) or
              (klass and b[2] == klass and b[3] == pos)
            stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
            return true
          end
        elsif b[1] == 1        # watchpoint
          if debug_silent_eval(b[2], binding)
            stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
            return true
          end
        end
      end
      n += 1
    end
    return false
  end


excn_handle (DEBUGGER__::Context)

# File lib/debug.rb, line 690
  def excn_handle(file, line, id, binding)
    if $!.class <= SystemExit
      set_trace_func nil
      exit
    end

    if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch })
      stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class
      fs = @frames.size
      tb = caller(0)[-fs..-1]
      if tb
        for i in tb
          stdout.printf "\tfrom %s\n", i
        end
      end
      suspend_all
      debug_command(file, line, id, binding)
    end
  end


trace_func (DEBUGGER__::Context)

# File lib/debug.rb, line 710
  def trace_func(event, file, line, id, binding, klass)
    Tracer.trace_func(event, file, line, id, binding, klass) if trace?
    context(Thread.current).check_suspend
    @file = file
    @line = line
    case event
    when 'line'
      frame_set_pos(file, line)
      if !@no_step or @frames.size == @no_step
        @stop_next -= 1
        @stop_next = -1 if @stop_next < 0
      elsif @frames.size < @no_step
        @stop_next = 0         # break here before leaving...
      else
        # nothing to do. skipped.
      end
      if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
        @no_step = nil
        suspend_all
        debug_command(file, line, id, binding)
      end

    when 'call'
      @frames.unshift [binding, file, line, id]
      if check_break_points(file, klass, id.id2name, binding, id)
        suspend_all
        debug_command(file, line, id, binding)
      end

    when 'c-call'
      frame_set_pos(file, line)

    when 'class'
      @frames.unshift [binding, file, line, id]

    when 'return', 'end'
      if @frames.size == @finish_pos
        @stop_next = 1
        @finish_pos = 0
      end
      @frames.shift

    when 'end'
      @frames.shift

    when 'raise'
      excn_handle(file, line, id, binding)

    end
    @last_file = file
  end


new (DEBUGGER__::Mutex)

# File lib/debug.rb, line 23
  def initialize
    @locker = nil
    @waiting = []
    @locked = false;
  end


locked? (DEBUGGER__::Mutex)

# File lib/debug.rb, line 29
  def locked?
    @locked
  end


lock (DEBUGGER__::Mutex)

# File lib/debug.rb, line 33
  def lock
    return if Thread.critical
    return if @locker == Thread.current
    while (Thread.critical = true; @locked)
      @waiting.push Thread.current
      Thread.stop
    end
    @locked = true
    @locker = Thread.current
    Thread.critical = false
    self
  end


unlock (DEBUGGER__::Mutex)

# File lib/debug.rb, line 46
  def unlock
    return if Thread.critical
    return unless @locked
    unless @locker == Thread.current
      raise RuntimeError, "unlocked by other"
    end
    Thread.critical = true
    t = @waiting.shift
    @locked = false
    @locker = nil
    Thread.critical = false
    t.run if t
    self
  end


stdout (DEBUGGER__)

# File lib/debug.rb, line 773
  def stdout
    @stdout
  end


stdout= (DEBUGGER__)

# File lib/debug.rb, line 777
  def stdout=(s)
    @stdout = s
  end


display (DEBUGGER__)

# File lib/debug.rb, line 781
  def display
    @display
  end


break_points (DEBUGGER__)

# File lib/debug.rb, line 785
  def break_points
    @break_points
  end


waiting (DEBUGGER__)

# File lib/debug.rb, line 789
  def waiting
    @waiting
  end


set_trace (DEBUGGER__)

# File lib/debug.rb, line 793
  def set_trace( arg )
    saved_crit = Thread.critical
    Thread.critical = true
    make_thread_list
    for th, in @thread_list
      context(th).set_trace arg
    end
    Thread.critical = saved_crit
    arg
  end


set_last_thread (DEBUGGER__)

# File lib/debug.rb, line 804
  def set_last_thread(th)
    @last_thread = th
  end


suspend (DEBUGGER__)

# File lib/debug.rb, line 808
  def suspend
    saved_crit = Thread.critical
    Thread.critical = true
    make_thread_list
    for th, in @thread_list
      next if th == Thread.current
      context(th).set_suspend
    end
    Thread.critical = saved_crit
    # Schedule other threads to suspend as soon as possible.
    Thread.pass unless Thread.critical
  end


resume (DEBUGGER__)

# File lib/debug.rb, line 821
  def resume
    saved_crit = Thread.critical
    Thread.critical = true
    make_thread_list
    for th, in @thread_list
      next if th == Thread.current
      context(th).clear_suspend
    end
    waiting.each do |th|
      th.run
    end
    waiting.clear
    Thread.critical = saved_crit
    # Schedule other threads to restart as soon as possible.
    Thread.pass
  end


context (DEBUGGER__)

# File lib/debug.rb, line 838
  def context(thread=Thread.current)
    c = thread[:__debugger_data__]
    unless c
      thread[:__debugger_data__] = c = Context.new
    end
    c
  end


interrupt (DEBUGGER__)

# File lib/debug.rb, line 846
  def interrupt
    context(@last_thread).stop_next
  end


get_thread (DEBUGGER__)

# File lib/debug.rb, line 850
  def get_thread(num)
    th = @thread_list.index(num)
    unless th
      @stdout.print "No thread ##{num}\n"
      throw :debug_error
    end
    th
  end


thread_list (DEBUGGER__)

# File lib/debug.rb, line 859
  def thread_list(num)
    th = get_thread(num)
    if th == Thread.current
      @stdout.print "+"
    else
      @stdout.print " "
    end
    @stdout.printf "%d ", num
    @stdout.print th.inspect, "\t"
    file = context(th).instance_eval{@file}
    if file
      @stdout.print file,":",context(th).instance_eval{@line}
    end
    @stdout.print "\n"
  end


thread_list_all (DEBUGGER__)

# File lib/debug.rb, line 875
  def thread_list_all
    for th in @thread_list.values.sort
      thread_list(th)
    end
  end


make_thread_list (DEBUGGER__)

# File lib/debug.rb, line 881
  def make_thread_list
    hash = {}
    for th in Thread::list
      if @thread_list.key? th
        hash[th] = @thread_list[th]
      else
        @max_thread += 1
        hash[th] = @max_thread
      end
    end
    @thread_list = hash
  end


debug_thread_info (DEBUGGER__)

# File lib/debug.rb, line 894
  def debug_thread_info(input, binding)
    case input
    when /^l(?:ist)?/
      make_thread_list
      thread_list_all

    when /^c(?:ur(?:rent)?)?$/
      make_thread_list
      thread_list(@thread_list[Thread.current])

    when /^(?:sw(?:itch)?\s+)?(\d+)/
      make_thread_list
      th = get_thread($1.to_i)
      if th == Thread.current
        @stdout.print "It's the current thread.\n"
      else
        thread_list(@thread_list[th])
        context(th).stop_next
        th.run
        return :cont
      end

    when /^stop\s+(\d+)/
      make_thread_list
      th = get_thread($1.to_i)
      if th == Thread.current
        @stdout.print "It's the current thread.\n"
      elsif th.stop?
        @stdout.print "Already stopped.\n"
      else
        thread_list(@thread_list[th])
        context(th).suspend
      end

    when /^resume\s+(\d+)/
      make_thread_list
      th = get_thread($1.to_i)
      if th == Thread.current
        @stdout.print "It's the current thread.\n"
      elsif !th.stop?
        @stdout.print "Already running."
      else
        thread_list(@thread_list[th])
        th.run
      end
    end
  end


new (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 41
  def initialize(options)
    @options = options
    @formatter = @options.formatter.new(@options, "     ")
  end


display_usage (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 49
  def display_usage
    page do
      RI::Options::OptionList.usage(short_form=true)
    end
  end


display_method_info (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 58
  def display_method_info(method)
    page do
      @formatter.draw_line(method.full_name)
      display_params(method)
      @formatter.draw_line
      display_flow(method.comment)
      if method.aliases && !method.aliases.empty?
        @formatter.blankline
        aka = "(also known as "
        aka << method.aliases.map {|a| a.name }.join(", ")
        aka << ")"
        @formatter.wrap(aka)
      end
    end
  end


display_class_info (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 76
  def display_class_info(klass, ri_reader)
    page do
      superclass = klass.superclass_string

      if superclass
        superclass = " < " + superclass
      else
        superclass = ""
      end

      @formatter.draw_line(klass.display_name + ": " +
                           klass.full_name + superclass)

      display_flow(klass.comment)
      @formatter.draw_line

      unless klass.includes.empty?
        @formatter.blankline
        @formatter.display_heading("Includes:", 2, "")
        incs = []
        klass.includes.each do |inc|
          inc_desc = ri_reader.find_class_by_name(inc.name)
          if inc_desc
            str = inc.name + "("
            str << inc_desc.instance_methods.map{|m| m.name}.join(", ")
            str << ")"
            incs << str
          else
            incs << inc.name
          end
      end
        @formatter.wrap(incs.sort.join(', '))
      end

      unless klass.constants.empty?
        @formatter.blankline
        @formatter.display_heading("Constants:", 2, "")
        len = 0
        klass.constants.each { |c| len = c.name.length if c.name.length > len }
        len += 2
        klass.constants.each do |c|
          @formatter.wrap(c.value,
                          @formatter.indent+((c.name+":").ljust(len)))
        end
      end

      unless klass.class_methods.empty?
        @formatter.blankline
        @formatter.display_heading("Class methods:", 2, "")
        @formatter.wrap(klass.class_methods.map{|m| m.name}.sort.join(', '))
      end

      unless klass.instance_methods.empty?
        @formatter.blankline
        @formatter.display_heading("Instance methods:", 2, "")
        @formatter.wrap(klass.instance_methods.map{|m| m.name}.sort.join(', '))
      end

      unless klass.attributes.empty?
        @formatter.blankline
        @formatter.wrap("Attributes:", "")
        @formatter.wrap(klass.attributes.map{|a| a.name}.sort.join(', '))
      end
    end
  end


display_method_list (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 146
  def display_method_list(methods)
    page do
      puts "More than one method matched your request. You can refine"
      puts "your search by asking for information on one of:\n\n"
      @formatter.wrap(methods.map {|m| m.full_name} .join(", "))
    end
  end


display_class_list (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 156
  def display_class_list(namespaces)
    page do
      puts "More than one class or module matched your request. You can refine"
      puts "your search by asking for information on one of:\n\n"
      @formatter.wrap(namespaces.map {|m| m.full_name}.join(", "))
    end
  end


list_known_classes (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 166
  def list_known_classes(classes)
    if classes.empty?
      warn_no_database
    else
      page do
        @formatter.draw_line("Known classes and modules")
        @formatter.blankline
        @formatter.wrap(classes.sort.join(", "))
      end
    end
  end


list_known_names (DefaultDisplay)

# File lib/rdoc/ri/ri_display.rb, line 180
  def list_known_names(names)
    if names.empty?
      warn_no_database
    else
      page do
        names.each {|n| @formatter.raw_print_line(n)}
      end
    end
  end


new (Delegator)

# File lib/delegate.rb, line 123
  def initialize(obj)
    preserved = ::Kernel.public_instance_methods(false)
    preserved -= ["to_s","to_a","inspect","==","=~","==="]
    for t in self.class.ancestors
      preserved |= t.public_instance_methods(false)
      preserved |= t.private_instance_methods(false)
      preserved |= t.protected_instance_methods(false)
      break if t == Delegator
    end
    preserved << "singleton_method_added"
    for method in obj.methods
      next if preserved.include? method
      begin
        eval "def self.\#{method}(*args, &block)\nbegin\n__getobj__.__send__(:\#{method}, *args, &block)\nrescue Exception\n$@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`\n$@.delete_if{|s| /^\\\\(eval\\\\):/ =~ s}\nKernel::raise\nend\nend\n"
      rescue SyntaxError
        raise NameError, "invalid identifier %s" % method, caller(4)
      end
    end
  end


method_missing (Delegator)

# File lib/delegate.rb, line 156
  def method_missing(m, *args)
    target = self.__getobj__
    unless target.respond_to?(m)
      super(m, *args)
    end
    target.__send__(m, *args)
  end


respond_to? (Delegator)

# File lib/delegate.rb, line 168
  def respond_to?(m)
    return true if super
    return self.__getobj__.respond_to?(m)
  end


__getobj__ (Delegator)

# File lib/delegate.rb, line 177
  def __getobj__
    raise NotImplementedError, "need to define `__getobj__'"
  end


marshal_dump (Delegator)

# File lib/delegate.rb, line 182
  def marshal_dump
    __getobj__
  end


marshal_load (Delegator)

# File lib/delegate.rb, line 186
  def marshal_load(obj)
    initialize_methods(obj)
    __setobj__(obj)
  end


open (Dir)

/*
 *  call-seq:
 *     Dir.open( string ) => aDir
 *     Dir.open( string ) {| aDir | block } => anObject
 *
 *  With no block, <code>open</code> is a synonym for
 *  <code>Dir::new</code>. If a block is present, it is passed
 *  <i>aDir</i> as a parameter. The directory is closed at the end of
 *  the block, and <code>Dir::open</code> returns the value of the
 *  block.
 */

static VALUE
dir_s_open(klass, dirname)
    VALUE klass, dirname;
{
    struct dir_data *dp;
    VALUE dir = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dp);

    dir_initialize(dir, dirname);
    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, dir, dir_close, dir);
    }

    return dir;
}


foreach (Dir)

/*
 *  call-seq:
 *     Dir.foreach( dirname ) {| filename | block }  => nil
 *
 *  Calls the block once for each entry in the named directory, passing
 *  the filename of each entry as a parameter to the block.
 *
 *     Dir.foreach("testdir") {|x| puts "Got #{x}" }
 *
 *  <em>produces:</em>
 *
 *     Got .
 *     Got ..
 *     Got config.h
 *     Got main.rb
 *
 */
static VALUE
dir_foreach(io, dirname)
    VALUE io, dirname;
{
    VALUE dir;

    dir = dir_open_dir(dirname);
    rb_ensure(dir_each, dir, dir_close, dir);
    return Qnil;
}


entries (Dir)

/*
 *  call-seq:
 *     Dir.entries( dirname ) => array
 *
 *  Returns an array containing all of the filenames in the given
 *  directory. Will raise a <code>SystemCallError</code> if the named
 *  directory doesn't exist.
 *
 *     Dir.entries("testdir")   #=> [".", "..", "config.h", "main.rb"]
 *
 */
static VALUE
dir_entries(io, dirname)
    VALUE io, dirname;
{
    VALUE dir;

    dir = dir_open_dir(dirname);
    return rb_ensure(rb_Array, dir, dir_close, dir);
}


new (Dir)

/*
 *  call-seq:
 *     Dir.new( string ) -> aDir
 *
 *  Returns a new directory object for the named directory.
 */
static VALUE
dir_initialize(dir, dirname)
    VALUE dir, dirname;
{
    struct dir_data *dp;

    SafeStringValue(dirname);
    Data_Get_Struct(dir, struct dir_data, dp);
    if (dp->dir) closedir(dp->dir);
    if (dp->path) free(dp->path);
    dp->dir = NULL;
    dp->path = NULL;
    dp->dir = opendir(RSTRING(dirname)->ptr);
    if (dp->dir == NULL) {
        if (errno == EMFILE || errno == ENFILE) {
            rb_gc();
            dp->dir = opendir(RSTRING(dirname)->ptr);
        }
        if (dp->dir == NULL) {
            rb_sys_fail(RSTRING(dirname)->ptr);
        }
    }
    dp->path = strdup(RSTRING(dirname)->ptr);

    return dir;
}


path (Dir)

/*
 *  call-seq:
 *     dir.path => string or nil
 *
 *  Returns the path parameter passed to <em>dir</em>'s constructor.
 *
 *     d = Dir.new("..")
 *     d.path   #=> ".."
 */
static VALUE
dir_path(dir)
    VALUE dir;
{
    struct dir_data *dirp;

    GetDIR(dir, dirp);
    if (!dirp->path) return Qnil;
    return rb_str_new2(dirp->path);
}


read (Dir)

/*
 *  call-seq:
 *     dir.read => string or nil
 *
 *  Reads the next entry from <em>dir</em> and returns it as a string.
 *  Returns <code>nil</code> at the end of the stream.
 *
 *     d = Dir.new("testdir")
 *     d.read   #=> "."
 *     d.read   #=> ".."
 *     d.read   #=> "config.h"
 */
static VALUE
dir_read(dir)
    VALUE dir;
{
    struct dir_data *dirp;
    struct dirent *dp;

    GetDIR(dir, dirp);
    errno = 0;
    dp = readdir(dirp->dir);
    if (dp) {
        return rb_tainted_str_new(dp->d_name, NAMLEN(dp));
    }
    else if (errno == 0) {      /* end of stream */
        return Qnil;
    }
    else {
        rb_sys_fail(0);
    }
    return Qnil;                /* not reached */
}


each (Dir)

/*
 *  call-seq:
 *     dir.each { |filename| block }  => dir
 *
 *  Calls the block once for each entry in this directory, passing the
 *  filename of each entry as a parameter to the block.
 *
 *     d = Dir.new("testdir")
 *     d.each  {|x| puts "Got #{x}" }
 *
 *  <em>produces:</em>
 *
 *     Got .
 *     Got ..
 *     Got config.h
 *     Got main.rb
 */
static VALUE
dir_each(dir)
    VALUE dir;
{
    struct dir_data *dirp;
    struct dirent *dp;

    GetDIR(dir, dirp);
    rewinddir(dirp->dir);
    for (dp = readdir(dirp->dir); dp != NULL; dp = readdir(dirp->dir)) {
        rb_yield(rb_tainted_str_new(dp->d_name, NAMLEN(dp)));
        if (dirp->dir == NULL) dir_closed();
    }
    return dir;
}


rewind (Dir)

/*
 *  call-seq:
 *     dir.rewind => dir
 *
 *  Repositions <em>dir</em> to the first entry.
 *
 *     d = Dir.new("testdir")
 *     d.read     #=> "."
 *     d.rewind   #=> #<Dir:0x401b3fb0>
 *     d.read     #=> "."
 */
static VALUE
dir_rewind(dir)
    VALUE dir;
{
    struct dir_data *dirp;

    if (rb_safe_level() >= 4 && !OBJ_TAINTED(dir)) {
        rb_raise(rb_eSecurityError, "Insecure: can't close");
    }
    GetDIR(dir, dirp);
    rewinddir(dirp->dir);
    return dir;
}


tell (Dir)

/*
 *  call-seq:
 *     dir.pos => integer
 *     dir.tell => integer
 *
 *  Returns the current position in <em>dir</em>. See also
 *  <code>Dir#seek</code>.
 *
 *     d = Dir.new("testdir")
 *     d.tell   #=> 0
 *     d.read   #=> "."
 *     d.tell   #=> 12
 */
static VALUE
dir_tell(dir)
    VALUE dir;
{
#ifdef HAVE_TELLDIR
    struct dir_data *dirp;
    long pos;

    GetDIR(dir, dirp);
    pos = telldir(dirp->dir);
    return rb_int2inum(pos);
#else
    rb_notimplement();
#endif
}


seek (Dir)

/*
 *  call-seq:
 *     dir.seek( integer ) => dir
 *
 *  Seeks to a particular location in <em>dir</em>. <i>integer</i>
 *  must be a value returned by <code>Dir#tell</code>.
 *
 *     d = Dir.new("testdir")   #=> #<Dir:0x401b3c40>
 *     d.read                   #=> "."
 *     i = d.tell               #=> 12
 *     d.read                   #=> ".."
 *     d.seek(i)                #=> #<Dir:0x401b3c40>
 *     d.read                   #=> ".."
 */
static VALUE
dir_seek(dir, pos)
    VALUE dir, pos;
{
    struct dir_data *dirp;
    off_t p = NUM2OFFT(pos);

    GetDIR(dir, dirp);
#ifdef HAVE_SEEKDIR
    seekdir(dirp->dir, p);
    return dir;
#else
    rb_notimplement();
#endif
}


pos (Dir)

/*
 *  call-seq:
 *     dir.pos => integer
 *     dir.tell => integer
 *
 *  Returns the current position in <em>dir</em>. See also
 *  <code>Dir#seek</code>.
 *
 *     d = Dir.new("testdir")
 *     d.tell   #=> 0
 *     d.read   #=> "."
 *     d.tell   #=> 12
 */
static VALUE
dir_tell(dir)
    VALUE dir;
{
#ifdef HAVE_TELLDIR
    struct dir_data *dirp;
    long pos;

    GetDIR(dir, dirp);
    pos = telldir(dirp->dir);
    return rb_int2inum(pos);
#else
    rb_notimplement();
#endif
}


pos= (Dir)

/*
 *  call-seq:
 *     dir.pos( integer ) => integer
 *
 *  Synonym for <code>Dir#seek</code>, but returns the position
 *  parameter.
 *
 *     d = Dir.new("testdir")   #=> #<Dir:0x401b3c40>
 *     d.read                   #=> "."
 *     i = d.pos                #=> 12
 *     d.read                   #=> ".."
 *     d.pos = i                #=> 12
 *     d.read                   #=> ".."
 */
static VALUE
dir_set_pos(dir, pos)
    VALUE dir, pos;
{
    dir_seek(dir, pos);
    return pos;
}


close (Dir)

/*
 *  call-seq:
 *     dir.close => nil
 *
 *  Closes the directory stream. Any further attempts to access
 *  <em>dir</em> will raise an <code>IOError</code>.
 *
 *     d = Dir.new("testdir")
 *     d.close   #=> nil
 */
static VALUE
dir_close(dir)
    VALUE dir;
{
    struct dir_data *dirp;

    GetDIR(dir, dirp);
    closedir(dirp->dir);
    dirp->dir = NULL;

    return Qnil;
}


chdir (Dir)

/*
 *  call-seq:
 *     Dir.chdir( [ string] ) => 0
 *     Dir.chdir( [ string] ) {| path | block }  => anObject
 *
 *  Changes the current working directory of the process to the given
 *  string. When called without an argument, changes the directory to
 *  the value of the environment variable <code>HOME</code>, or
 *  <code>LOGDIR</code>. <code>SystemCallError</code> (probably
 *  <code>Errno::ENOENT</code>) if the target directory does not exist.
 *
 *  If a block is given, it is passed the name of the new current
 *  directory, and the block is executed with that as the current
 *  directory. The original working directory is restored when the block
 *  exits. The return value of <code>chdir</code> is the value of the
 *  block. <code>chdir</code> blocks can be nested, but in a
 *  multi-threaded program an error will be raised if a thread attempts
 *  to open a <code>chdir</code> block while another thread has one
 *  open.
 *
 *     Dir.chdir("/var/spool/mail")
 *     puts Dir.pwd
 *     Dir.chdir("/tmp") do
 *       puts Dir.pwd
 *       Dir.chdir("/usr") do
 *         puts Dir.pwd
 *       end
 *       puts Dir.pwd
 *     end
 *     puts Dir.pwd
 *
 *  <em>produces:</em>
 *
 *     /var/spool/mail
 *     /tmp
 *     /usr
 *     /tmp
 *     /var/spool/mail
 */
static VALUE
dir_s_chdir(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE path = Qnil;

    rb_secure(2);
    if (rb_scan_args(argc, argv, "01", &path) == 1) {
        SafeStringValue(path);
    }
    else {
        const char *dist = getenv("HOME");
        if (!dist) {
            dist = getenv("LOGDIR");
            if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set");
        }
        path = rb_str_new2(dist);
    }

    if (chdir_blocking > 0) {
        if (!rb_block_given_p() || rb_thread_current() != chdir_thread)
            rb_warn("conflicting chdir during another chdir block");
    }

    if (rb_block_given_p()) {
        struct chdir_data args;
        char *cwd = my_getcwd();

        args.old_path = rb_tainted_str_new2(cwd); free(cwd);
        args.new_path = path;
        args.done = Qfalse;
        return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args);
    }
    dir_chdir(path);

    return INT2FIX(0);
}


getwd (Dir)

/*
 *  call-seq:
 *     Dir.getwd => string
 *     Dir.pwd => string
 *
 *  Returns the path to the current working directory of this process as
 *  a string.
 *
 *     Dir.chdir("/tmp")   #=> 0
 *     Dir.getwd           #=> "/tmp"
 */
static VALUE
dir_s_getwd(dir)
    VALUE dir;
{
    char *path;
    VALUE cwd;

    rb_secure(4);
    path = my_getcwd();
    cwd = rb_tainted_str_new2(path);

    free(path);
    return cwd;
}


pwd (Dir)

/*
 *  call-seq:
 *     Dir.getwd => string
 *     Dir.pwd => string
 *
 *  Returns the path to the current working directory of this process as
 *  a string.
 *
 *     Dir.chdir("/tmp")   #=> 0
 *     Dir.getwd           #=> "/tmp"
 */
static VALUE
dir_s_getwd(dir)
    VALUE dir;
{
    char *path;
    VALUE cwd;

    rb_secure(4);
    path = my_getcwd();
    cwd = rb_tainted_str_new2(path);

    free(path);
    return cwd;
}


chroot (Dir)

/*
 *  call-seq:
 *     Dir.chroot( string ) => 0
 *
 *  Changes this process's idea of the file system root. Only a
 *  privileged process may make this call. Not available on all
 *  platforms. On Unix systems, see <code>chroot(2)</code> for more
 *  information.
 */
static VALUE
dir_s_chroot(dir, path)
    VALUE dir, path;
{
#if defined(HAVE_CHROOT) && !defined(__CHECKER__)
    check_dirname(&path);

    if (chroot(RSTRING(path)->ptr) == -1)
        rb_sys_fail(RSTRING(path)->ptr);

    return INT2FIX(0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


mkdir (Dir)

/*
 *  call-seq:
 *     Dir.mkdir( string [, integer] ) => 0
 *
 *  Makes a new directory named by <i>string</i>, with permissions
 *  specified by the optional parameter <i>anInteger</i>. The
 *  permissions may be modified by the value of
 *  <code>File::umask</code>, and are ignored on NT. Raises a
 *  <code>SystemCallError</code> if the directory cannot be created. See
 *  also the discussion of permissions in the class documentation for
 *  <code>File</code>.
 *
 */
static VALUE
dir_s_mkdir(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE path, vmode;
    int mode;

    if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
        mode = NUM2INT(vmode);
    }
    else {
        mode = 0777;
    }

    check_dirname(&path);
    if (mkdir(RSTRING(path)->ptr, mode) == -1)
        rb_sys_fail(RSTRING(path)->ptr);

    return INT2FIX(0);
}


rmdir (Dir)

/*
 *  call-seq:
 *     Dir.delete( string ) => 0
 *     Dir.rmdir( string ) => 0
 *     Dir.unlink( string ) => 0
 *
 *  Deletes the named directory. Raises a subclass of
 *  <code>SystemCallError</code> if the directory isn't empty.
 */
static VALUE
dir_s_rmdir(obj, dir)
    VALUE obj, dir;
{
    check_dirname(&dir);
    if (rmdir(RSTRING(dir)->ptr) < 0)
        rb_sys_fail(RSTRING(dir)->ptr);

    return INT2FIX(0);
}


delete (Dir)

/*
 *  call-seq:
 *     Dir.delete( string ) => 0
 *     Dir.rmdir( string ) => 0
 *     Dir.unlink( string ) => 0
 *
 *  Deletes the named directory. Raises a subclass of
 *  <code>SystemCallError</code> if the directory isn't empty.
 */
static VALUE
dir_s_rmdir(obj, dir)
    VALUE obj, dir;
{
    check_dirname(&dir);
    if (rmdir(RSTRING(dir)->ptr) < 0)
        rb_sys_fail(RSTRING(dir)->ptr);

    return INT2FIX(0);
}


unlink (Dir)

/*
 *  call-seq:
 *     Dir.delete( string ) => 0
 *     Dir.rmdir( string ) => 0
 *     Dir.unlink( string ) => 0
 *
 *  Deletes the named directory. Raises a subclass of
 *  <code>SystemCallError</code> if the directory isn't empty.
 */
static VALUE
dir_s_rmdir(obj, dir)
    VALUE obj, dir;
{
    check_dirname(&dir);
    if (rmdir(RSTRING(dir)->ptr) < 0)
        rb_sys_fail(RSTRING(dir)->ptr);

    return INT2FIX(0);
}


glob (Dir)

/*
 *  call-seq:
 *     Dir.glob( pattern, [flags] ) => array
 *     Dir.glob( pattern, [flags] ) {| filename | block }  => nil
 *
 *  Returns the filenames found by expanding <i>pattern</i> which is
 *  an +Array+ of the patterns or the pattern +String+, either as an
 *  <i>array</i> or as parameters to the block. Note that this pattern
 *  is not a regexp (it's closer to a shell glob). See
 *  <code>File::fnmatch</code> for the meaning of the <i>flags</i>
 *  parameter. Note that case sensitivity depends on your system (so
 *  <code>File::FNM_CASEFOLD</code> is ignored)
 *
 *  <code>*</code>::        Matches any file. Can be restricted by
 *                          other values in the glob. <code>*</code>
 *                          will match all files; <code>c*</code> will
 *                          match all files beginning with
 *                          <code>c</code>; <code>*c</code> will match
 *                          all files ending with <code>c</code>; and
 *                          <code>*c*</code> will match all files that
 *                          have <code>c</code> in them (including at
 *                          the beginning or end). Equivalent to
 *                          <code>/ .* /x</code> in regexp.
 *  <code>**</code>::       Matches directories recursively.
 *  <code>?</code>::        Matches any one character. Equivalent to
 *                          <code>/.{1}/</code> in regexp.
 *  <code>[set]</code>::    Matches any one character in +set+.
 *                          Behaves exactly like character sets in
 *                          Regexp, including set negation
 *                          (<code>[^a-z]</code>).
 *  <code>{p,q}</code>::    Matches either literal <code>p</code> or
 *                          literal <code>q</code>. Matching literals
 *                          may be more than one character in length.
 *                          More than two literals may be specified.
 *                          Equivalent to pattern alternation in
 *                          regexp.
 *  <code>\</code>::        Escapes the next metacharacter.
 *
 *     Dir["config.?"]                     #=> ["config.h"]
 *     Dir.glob("config.?")                #=> ["config.h"]
 *     Dir.glob("*.[a-z][a-z]")            #=> ["main.rb"]
 *     Dir.glob("*.[^r]*")                 #=> ["config.h"]
 *     Dir.glob("*.{rb,h}")                #=> ["main.rb", "config.h"]
 *     Dir.glob("*")                       #=> ["config.h", "main.rb"]
 *     Dir.glob("*", File::FNM_DOTMATCH)   #=> [".", "..", "config.h", "main.rb"]
 *
 *     rbfiles = File.join("**", "*.rb")
 *     Dir.glob(rbfiles)                   #=> ["main.rb",
 *                                              "lib/song.rb",
 *                                              "lib/song/karaoke.rb"]
 *     libdirs = File.join("**", "lib")
 *     Dir.glob(libdirs)                   #=> ["lib"]
 *
 *     librbfiles = File.join("**", "lib", "**", "*.rb")
 *     Dir.glob(librbfiles)                #=> ["lib/song.rb",
 *                                              "lib/song/karaoke.rb"]
 *
 *     librbfiles = File.join("**", "lib", "*.rb")
 *     Dir.glob(librbfiles)                #=> ["lib/song.rb"]
 */
static VALUE
dir_s_glob(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE str, rflags, ary;
    int flags;

    if (rb_scan_args(argc, argv, "11", &str, &rflags) == 2)
        flags = NUM2INT(rflags);
    else
        flags = 0;

    ary = rb_check_array_type(str);
    if (NIL_P(ary)) {
        ary = rb_push_glob(str, flags);
    }
    else {
        volatile VALUE v = ary;
        ary = dir_globs(RARRAY_LEN(v), RARRAY_PTR(v), flags);
    }

    if (rb_block_given_p()) {
        rb_ary_each(ary);
        return Qnil;
    }
    return ary;
}


[] (Dir)

/*
 *  call-seq:
 *     Dir[ array ]                 => array
 *     Dir[ string [, string ...] ] => array
 *
 *  Equivalent to calling
 *  <code>Dir.glob(</code><i>array,</i><code>0)</code> and
 *  <code>Dir.glob([</code><i>string,...</i><code>],0)</code>.
 *
 */
static VALUE
dir_s_aref(int argc, VALUE *argv, VALUE obj)


tmpdir (Dir)

# File lib/tmpdir.rb, line 30
  def Dir::tmpdir
    tmp = '.'
    if $SAFE > 0
      tmp = @@systmpdir
    else
      for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'],
                  ENV['USERPROFILE'], @@systmpdir, '/tmp']
        if dir and File.directory?(dir) and File.writable?(dir)
          tmp = dir
          break
        end
      end
    end
    File.expand_path(tmp)
  end


new (DOT::DOTDigraph)

# File lib/rdoc/dot/dot.rb, line 228
        def initialize( params = {}, option_list = GRAPH_OPTS )
            super( params, option_list )
            @dot_string = 'digraph'
        end


new (DOT::DOTEdge)

# File lib/rdoc/dot/dot.rb, line 237
        def initialize( params = {}, option_list = EDGE_OPTS )
            super( params, option_list )
            @from = params['from'] ? params['from'] : nil
            @to = params['to'] ? params['to'] : nil
        end


to_s (DOT::DOTEdge)

# File lib/rdoc/dot/dot.rb, line 243
        def to_s( t = '' )
            t + "#{@from} -> #{to} [\n" +
            @options.to_a.collect{ |i|
                i[1] && i[0] != 'label' ?
                    t + $tab + "#{i[0]} = #{i[1]}" :
                    i[1] ? t + $tab + "#{i[0]} = \"#{i[1]}\"" : nil
            }.compact.join( "\n" ) + "\n" + t + "]\n"
        end


new (DOT::DOTElement)

# File lib/rdoc/dot/dot.rb, line 97
        def initialize( params = {}, option_list = [] )
            super( params )
            @name = params['name'] ? params['name'] : nil
            @parent = params['parent'] ? params['parent'] : nil
            @options = {}
            option_list.each{ |i|
                @options[i] = params[i] if params[i]
            }
            @options['label'] ||= @name if @name != 'node'
        end


each_option (DOT::DOTElement)

# File lib/rdoc/dot/dot.rb, line 108
        def each_option
            @options.each{ |i| yield i }
        end


each_option_pair (DOT::DOTElement)

# File lib/rdoc/dot/dot.rb, line 112
        def each_option_pair
            @options.each_pair{ |key, val| yield key, val }
        end


new (DOT::DOTNode)

# File lib/rdoc/dot/dot.rb, line 140
        def initialize( params = {}, option_list = NODE_OPTS )
            super( params, option_list )
            @ports = params['ports'] ? params['ports'] : []
        end


each_port (DOT::DOTNode)

# File lib/rdoc/dot/dot.rb, line 145
        def each_port
            @ports.each{ |i| yield i }
        end


<< (DOT::DOTNode)

# File lib/rdoc/dot/dot.rb, line 149
        def << ( thing )
            @ports << thing
        end


push (DOT::DOTNode)

# File lib/rdoc/dot/dot.rb, line 153
        def push ( thing )
            @ports.push( thing )
        end


pop (DOT::DOTNode)

# File lib/rdoc/dot/dot.rb, line 157
        def pop
            @ports.pop
        end


to_s (DOT::DOTNode)

# File lib/rdoc/dot/dot.rb, line 161
        def to_s( t = '' )

            label = @options['shape'] != 'record' && @ports.length == 0 ?
                @options['label'] ?
                    t + $tab + "label = \"#{@options['label']}\"\n" :
                    '' :
                t + $tab + 'label = "' + " \\\n" +
                t + $tab2 + "#{@options['label']}| \\\n" +
                @ports.collect{ |i|
                    t + $tab2 + i.to_s
                }.join( "| \\\n" ) + " \\\n" +
                t + $tab + '"' + "\n"

            t + "#{@name} [\n" +
            @options.to_a.collect{ |i|
                i[1] && i[0] != 'label' ?
                    t + $tab + "#{i[0]} = #{i[1]}" : nil
            }.compact.join( ",\n" ) + ( label != '' ? ",\n" : "\n" ) +
            label +
            t + "]\n"
        end


new (DOT::DOTPort)

# File lib/rdoc/dot/dot.rb, line 128
        def initialize( params = {} )
            super( params )
            @name = params['label'] ? params['label'] : ''
        end


to_s (DOT::DOTPort)

# File lib/rdoc/dot/dot.rb, line 132
        def to_s
            ( @name && @name != "" ? "<#{@name}>" : "" ) + "#{@label}"
        end


new (DOT::DOTSimpleElement)

# File lib/rdoc/dot/dot.rb, line 83
        def initialize( params = {} )
            @label = params['name'] ? params['name'] : ''
        end


to_s (DOT::DOTSimpleElement)

# File lib/rdoc/dot/dot.rb, line 87
        def to_s
            @name
        end


new (DOT::DOTSubgraph)

# File lib/rdoc/dot/dot.rb, line 188
        def initialize( params = {}, option_list = GRAPH_OPTS )
            super( params, option_list )
            @nodes = params['nodes'] ? params['nodes'] : []
            @dot_string = 'subgraph'
        end


each_node (DOT::DOTSubgraph)

# File lib/rdoc/dot/dot.rb, line 194
        def each_node
            @nodes.each{ |i| yield i }
        end


<< (DOT::DOTSubgraph)

# File lib/rdoc/dot/dot.rb, line 198
        def << ( thing )
            @nodes << thing
        end


push (DOT::DOTSubgraph)

# File lib/rdoc/dot/dot.rb, line 202
        def push( thing )
            @nodes.push( thing )
        end


pop (DOT::DOTSubgraph)

# File lib/rdoc/dot/dot.rb, line 206
        def pop
            @nodes.pop
        end


to_s (DOT::DOTSubgraph)

# File lib/rdoc/dot/dot.rb, line 210
        def to_s( t = '' )
          hdr = t + "#{@dot_string} #{@name} {\n"

          options = @options.to_a.collect{ |name, val|
            val && name != 'label' ?
            t + $tab + "#{name} = #{val}" :
              name ? t + $tab + "#{name} = \"#{val}\"" : nil
          }.compact.join( "\n" ) + "\n"

          nodes = @nodes.collect{ |i|
            i.to_s( t + $tab )
          }.join( "\n" ) + "\n"
          hdr + options + nodes + t + "}\n"
        end


change_tab (DOT)

# File lib/rdoc/dot/dot.rb, line 8
    def change_tab( t )
        $tab = t
        $tab2 = t * 2
    end


new (DRb::DRbArray)

# File lib/drb/drb.rb, line 515
    def initialize(ary)
      @ary = ary.collect { |obj|
        if obj.kind_of? DRbUndumped
          DRbObject.new(obj)
        else
          begin
            Marshal.dump(obj)
            obj
          rescue
            DRbObject.new(obj)
          end
        end
      }
    end


_load (DRb::DRbArray)

# File lib/drb/drb.rb, line 530
    def self._load(s)
      Marshal::load(s)
    end


_dump (DRb::DRbArray)

# File lib/drb/drb.rb, line 534
    def _dump(lv)
      Marshal.dump(@ary)
    end


to_obj (DRb::DRbIdConv)

# File lib/drb/drb.rb, line 374
    def to_obj(ref)
      ObjectSpace._id2ref(ref)
    end


to_id (DRb::DRbIdConv)

# File lib/drb/drb.rb, line 382
    def to_id(obj)
      obj.nil? ? nil : obj.__id__
    end


_load (DRb::DRbObject)

# File lib/drb/gw.rb, line 35
    def self._load(s)
      uri, ref = Marshal.load(s)
      if DRb.uri == uri
        return ref ? DRb.to_obj(ref) : DRb.front
      end

      self.new_with(DRb.uri, [:DRbObject, uri, ref])
    end


_dump (DRb::DRbObject)

# File lib/drb/gw.rb, line 44
    def _dump(lv)
      if DRb.uri == @uri
        if Array === @ref && @ref[0] == :DRbObject
          Marshal.dump([@ref[1], @ref[2]])
        else
          Marshal.dump([@uri, @ref]) # ??
        end
      else
        Marshal.dump([DRb.uri, [:DRbObject, @uri, @ref]])
      end
    end


== (DRb::DRbObject)

# File lib/drb/eq.rb, line 5
    def ==(other)
      return false unless DRbObject === other
     (@ref == other.__drbref) && (@uri == other.__drburi)
    end


hash (DRb::DRbObject)

# File lib/drb/eq.rb, line 10
    def hash
      [@uri, @ref].hash
    end


_load (DRb::DRbObject)

# File lib/drb/drb.rb, line 1001
    def self._load(s)
      uri, ref = Marshal.load(s)

      if DRb.here?(uri)
        obj = DRb.to_obj(ref)
        if ((! obj.tainted?) && Thread.current[:drb_untaint])
          Thread.current[:drb_untaint].push(obj)
        end
        return obj
      end

      self.new_with(uri, ref)
    end


new_with (DRb::DRbObject)

# File lib/drb/drb.rb, line 1015
    def self.new_with(uri, ref)
      it = self.allocate
      it.instance_variable_set('@uri', uri)
      it.instance_variable_set('@ref', ref)
      it
    end


new_with_uri (DRb::DRbObject)

# File lib/drb/drb.rb, line 1023
    def self.new_with_uri(uri)
      self.new(nil, uri)
    end


_dump (DRb::DRbObject)

# File lib/drb/drb.rb, line 1030
    def _dump(lv)
      Marshal.dump([@uri, @ref])
    end


new (DRb::DRbObject)

# File lib/drb/drb.rb, line 1039
    def initialize(obj, uri=nil)
      @uri = nil
      @ref = nil
      if obj.nil?
        return if uri.nil?
        @uri, option = DRbProtocol.uri_option(uri, DRb.config)
        @ref = DRbURIOption.new(option) unless option.nil?
      else
        @uri = uri ? uri : (DRb.uri rescue nil)
        @ref = obj ? DRb.to_id(obj) : nil
      end
    end


__drburi (DRb::DRbObject)

# File lib/drb/drb.rb, line 1053
    def __drburi
      @uri
    end


__drbref (DRb::DRbObject)

# File lib/drb/drb.rb, line 1058
    def __drbref
      @ref
    end


respond_to? (DRb::DRbObject)

# File lib/drb/drb.rb, line 1065
    def respond_to?(msg_id, priv=false)
      case msg_id
      when :_dump
        true
      when :marshal_dump
        false
      else
        method_missing(:respond_to?, msg_id, priv)
      end
    end


method_missing (DRb::DRbObject)

# File lib/drb/drb.rb, line 1077
    def method_missing(msg_id, *a, &b)
      if DRb.here?(@uri)
        obj = DRb.to_obj(@ref)
        DRb.current_server.check_insecure_method(obj, msg_id)
        return obj.__send__(msg_id, *a, &b)
      end

      succ, result = self.class.with_friend(@uri) do
        DRbConn.open(@uri) do |conn|
          conn.send_message(self, msg_id, a, b)
        end
      end

      if succ
        return result
      elsif DRbUnknown === result
        raise result
      else
        bt = self.class.prepare_backtrace(@uri, result)
        result.set_backtrace(bt + caller)
        raise result
      end
    end


with_friend (DRb::DRbObject)

# File lib/drb/drb.rb, line 1101
    def self.with_friend(uri)
      friend = DRb.fetch_server(uri)
      return yield() unless friend

      save = Thread.current['DRb']
      Thread.current['DRb'] = { 'server' => friend }
      return yield
    ensure
      Thread.current['DRb'] = save if friend
    end


prepare_backtrace (DRb::DRbObject)

# File lib/drb/drb.rb, line 1112
    def self.prepare_backtrace(uri, result)
      prefix = "(#{uri}) "
      bt = []
      result.backtrace.each do |x|
        break if /`__send__'$/ =~ x
        if /^\(druby:\/\// =~ x
          bt.push(x)
        else
          bt.push(prefix + x)
        end
      end
      bt
    end


notify_observers (DRb::DRbObservable)

# File lib/drb/observer.rb, line 7
    def notify_observers(*arg)
      if defined? @observer_state and @observer_state
        if defined? @observer_peers
          for i in @observer_peers.dup
            begin
              i.update(*arg)
            rescue
              delete_observer(i)
            end
          end
        end
        @observer_state = false
      end
    end


add_protocol (DRb::DRbProtocol)

# File lib/drb/drb.rb, line 716
    def add_protocol(prot)
      @protocol.push(prot)
    end


open (DRb::DRbProtocol)

# File lib/drb/drb.rb, line 728
    def open(uri, config, first=true)
      @protocol.each do |prot|
        begin
          return prot.open(uri, config)
        rescue DRbBadScheme
        rescue DRbConnError
          raise($!)
        rescue
          raise(DRbConnError, "#{uri} - #{$!.inspect}")
        end
      end
      if first && (config[:auto_load] != false)
        auto_load(uri, config)
        return open(uri, config, false)
      end
      raise DRbBadURI, 'can\'t parse uri:' + uri
    end


open_server (DRb::DRbProtocol)

# File lib/drb/drb.rb, line 756
    def open_server(uri, config, first=true)
      @protocol.each do |prot|
        begin
          return prot.open_server(uri, config)
        rescue DRbBadScheme
        end
      end
      if first && (config[:auto_load] != false)
        auto_load(uri, config)
        return open_server(uri, config, false)
      end
      raise DRbBadURI, 'can\'t parse uri:' + uri
    end


uri_option (DRb::DRbProtocol)

# File lib/drb/drb.rb, line 777
    def uri_option(uri, config, first=true)
      @protocol.each do |prot|
        begin
          uri, opt = prot.uri_option(uri, config)
          # opt = nil if opt == ''
          return uri, opt
        rescue DRbBadScheme
        end
      end
      if first && (config[:auto_load] != false)
        auto_load(uri, config)
        return uri_option(uri, config, false)
      end
      raise DRbBadURI, 'can\'t parse uri:' + uri
    end


new (DRb::DRbRemoteError)

# File lib/drb/drb.rb, line 435
    def initialize(error)
      @reason = error.class.to_s
      super("#{error.message} (#{error.class})")
      set_backtrace(error.backtrace)
    end


block_yield (DRb::DRbServer::InvokeMethod18Mixin)

# File lib/drb/invokemethod.rb, line 6
      def block_yield(x)
        if x.size == 1 && x[0].class == Array
          x[0] = DRbArray.new(x[0])
        end
        block_value = @block.call(*x)
      end


perform_with_block (DRb::DRbServer::InvokeMethod18Mixin)

# File lib/drb/invokemethod.rb, line 13
      def perform_with_block
        @obj.__send__(@msg_id, *@argv) do |*x|
          jump_error = nil
          begin
            block_value = block_yield(x)
          rescue LocalJumpError
            jump_error = $!
          end
          if jump_error
            case jump_error.reason
            when :retry
              retry
            when :break
              break(jump_error.exit_value)
            else
              raise jump_error
            end
          end
          block_value
        end
      end


default_argc_limit (DRb::DRbServer)

# File lib/drb/drb.rb, line 1231
    def self.default_argc_limit(argc)
      @@argc_limit = argc
    end


default_load_limit (DRb::DRbServer)

# File lib/drb/drb.rb, line 1238
    def self.default_load_limit(sz)
      @@load_limit = sz
    end


default_acl (DRb::DRbServer)

# File lib/drb/drb.rb, line 1245
    def self.default_acl(acl)
      @@acl = acl
    end


default_id_conv (DRb::DRbServer)

# File lib/drb/drb.rb, line 1252
    def self.default_id_conv(idconv)
      @@idconv = idconv
    end


default_safe_level (DRb::DRbServer)

# File lib/drb/drb.rb, line 1256
    def self.default_safe_level(level)
      @@safe_level = level
    end


verbose= (DRb::DRbServer)

# File lib/drb/drb.rb, line 1263
    def self.verbose=(on)
      @@verbose = on
    end


verbose (DRb::DRbServer)

# File lib/drb/drb.rb, line 1268
    def self.verbose
      @@verbose
    end


new (DRb::DRbServer)

# File lib/drb/drb.rb, line 1327
    def initialize(uri=nil, front=nil, config_or_acl=nil)
      if Hash === config_or_acl
        config = config_or_acl.dup
      else
        acl = config_or_acl || @@acl
        config = {
          :tcp_acl => acl
        }
      end

      @config = self.class.make_config(config)

      @protocol = DRbProtocol.open_server(uri, @config)
      @uri = @protocol.uri

      @front = front
      @idconv = @config[:idconv]
      @safe_level = @config[:safe_level]

      @grp = ThreadGroup.new
      @thread = run

      DRb.regist_server(self)
    end


verbose= (DRb::DRbServer)

# File lib/drb/drb.rb, line 1376
    def verbose=(v); @config[:verbose]=v; end


verbose (DRb::DRbServer)

# File lib/drb/drb.rb, line 1381
    def verbose; @config[:verbose]; end


alive? (DRb::DRbServer)

# File lib/drb/drb.rb, line 1384
    def alive?
      @thread.alive?
    end


stop_service (DRb::DRbServer)

# File lib/drb/drb.rb, line 1389
    def stop_service
      DRb.remove_server(self)
      if  Thread.current['DRb'] && Thread.current['DRb']['server'] == self
        Thread.current['DRb']['stop_service'] = true
      else
        @thread.kill
      end
    end


to_obj (DRb::DRbServer)

# File lib/drb/drb.rb, line 1399
    def to_obj(ref)
      return front if ref.nil?
      return front[ref.to_s] if DRbURIOption === ref
      @idconv.to_obj(ref)
    end


to_id (DRb::DRbServer)

# File lib/drb/drb.rb, line 1406
    def to_id(obj)
      return nil if obj.__id__ == front.__id__
      @idconv.to_id(obj)
    end


check_insecure_method (DRb::DRbServer)

# File lib/drb/drb.rb, line 1467
    def check_insecure_method(obj, msg_id)
      return true if Proc === obj && msg_id == :__drb_yield
      raise(ArgumentError, "#{any_to_s(msg_id)} is not a symbol") unless Symbol == msg_id.class
      raise(SecurityError, "insecure method `#{msg_id}'") if insecure_method?(msg_id)

      if obj.private_methods.include?(msg_id.to_s)
        desc = any_to_s(obj)
        raise NoMethodError, "private method `#{msg_id}' called for #{desc}"
      elsif obj.protected_methods.include?(msg_id.to_s)
        desc = any_to_s(obj)
        raise NoMethodError, "protected method `#{msg_id}' called for #{desc}"
      else
        true
      end
    end


new (DRb::DRbSSLSocket::SSLConfig)

# File lib/drb/ssl.rb, line 27
      def initialize(config)
        @config  = config
        @cert    = config[:SSLCertificate]
        @pkey    = config[:SSLPrivateKey]
        @ssl_ctx = nil
      end


[] (DRb::DRbSSLSocket::SSLConfig)

# File lib/drb/ssl.rb, line 34
      def [](key);
        @config[key] || DEFAULT[key]
      end


connect (DRb::DRbSSLSocket::SSLConfig)

# File lib/drb/ssl.rb, line 38
      def connect(tcp)
        ssl = ::OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
        ssl.sync = true
        ssl.connect
        ssl
      end


accept (DRb::DRbSSLSocket::SSLConfig)

# File lib/drb/ssl.rb, line 45
      def accept(tcp)
        ssl = OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
        ssl.sync = true
        ssl.accept
        ssl
      end


setup_certificate (DRb::DRbSSLSocket::SSLConfig)

# File lib/drb/ssl.rb, line 52
      def setup_certificate
        if @cert && @pkey
          return
        end

        rsa = OpenSSL::PKey::RSA.new(512){|p, n|
          next unless self[:verbose]
          case p
          when 0; $stderr.putc "."  # BN_generate_prime
          when 1; $stderr.putc "+"  # BN_generate_prime
          when 2; $stderr.putc "*"  # searching good prime,
                                    # n = #of try,
                                    # but also data from BN_generate_prime
          when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
                                    # but also data from BN_generate_prime
          else;   $stderr.putc "*"  # BN_generate_prime
          end
        }

        cert = OpenSSL::X509::Certificate.new
        cert.version = 3
        cert.serial = 0
        name = OpenSSL::X509::Name.new(self[:SSLCertName])
        cert.subject = name
        cert.issuer = name
        cert.not_before = Time.now
        cert.not_after = Time.now + (365*24*60*60)
        cert.public_key = rsa.public_key

        ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
        cert.extensions = [
          ef.create_extension("basicConstraints","CA:FALSE"),
          ef.create_extension("subjectKeyIdentifier", "hash") ]
        ef.issuer_certificate = cert
        cert.add_extension(ef.create_extension("authorityKeyIdentifier",
                                               "keyid:always,issuer:always"))
        if comment = self[:SSLCertComment]
          cert.add_extension(ef.create_extension("nsComment", comment))
        end
        cert.sign(rsa, OpenSSL::Digest::SHA1.new)

        @cert = cert
        @pkey = rsa
      end


setup_ssl_context (DRb::DRbSSLSocket::SSLConfig)

# File lib/drb/ssl.rb, line 97
      def setup_ssl_context
        ctx = ::OpenSSL::SSL::SSLContext.new
        ctx.cert            = @cert
        ctx.key             = @pkey
        ctx.client_ca       = self[:SSLClientCA]
        ctx.ca_path         = self[:SSLCACertificatePath]
        ctx.ca_file         = self[:SSLCACertificateFile]
        ctx.verify_mode     = self[:SSLVerifyMode]
        ctx.verify_depth    = self[:SSLVerifyDepth]
        ctx.verify_callback = self[:SSLVerifyCallback]
        ctx.cert_store      = self[:SSLCertificateStore]
        @ssl_ctx = ctx
      end


parse_uri (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 112
    def self.parse_uri(uri)
      if uri =~ /^drbssl:\/\/(.*?):(\d+)(\?(.*))?$/
        host = $1
        port = $2.to_i
        option = $4
        [host, port, option]
      else
        raise(DRbBadScheme, uri) unless uri =~ /^drbssl:/
        raise(DRbBadURI, 'can\'t parse uri:' + uri)
      end
    end


open (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 124
    def self.open(uri, config)
      host, port, option = parse_uri(uri)
      host.untaint
      port.untaint
      soc = TCPSocket.open(host, port)
      ssl_conf = SSLConfig::new(config)
      ssl_conf.setup_ssl_context
      ssl = ssl_conf.connect(soc)
      self.new(uri, ssl, ssl_conf, true)
    end


open_server (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 135
    def self.open_server(uri, config)
      uri = 'drbssl://:0' unless uri
      host, port, opt = parse_uri(uri)
      if host.size == 0
        host = getservername
        soc = open_server_inaddr_any(host, port)
      else
        soc = TCPServer.open(host, port)
      end
      port = soc.addr[1] if port == 0
      @uri = "drbssl://#{host}:#{port}"

      ssl_conf = SSLConfig.new(config)
      ssl_conf.setup_certificate
      ssl_conf.setup_ssl_context
      self.new(@uri, soc, ssl_conf, false)
    end


uri_option (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 153
    def self.uri_option(uri, config)
      host, port, option = parse_uri(uri)
      return "drbssl://#{host}:#{port}", option
    end


new (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 158
    def initialize(uri, soc, config, is_established)
      @ssl = is_established ? soc : nil
      super(uri, soc.to_io, config)
    end


stream (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 163
    def stream; @ssl; end


close (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 165
    def close
      if @ssl
        @ssl.close
        @ssl = nil
      end
      super
    end


accept (DRb::DRbSSLSocket)

# File lib/drb/ssl.rb, line 173
    def accept
      begin
      while true
        soc = @socket.accept
        break if (@acl ? @acl.allow_socket?(soc) : true)
        soc.close
      end
      ssl = @config.accept(soc)
      self.class.new(uri, ssl, @config, true)
      rescue OpenSSL::SSL::SSLError
        warn("#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})") if @config[:verbose]
        retry
      end
    end


open (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 822
    def self.open(uri, config)
      host, port, option = parse_uri(uri)
      host.untaint
      port.untaint
      soc = TCPSocket.open(host, port)
      self.new(uri, soc, config)
    end


getservername (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 830
    def self.getservername
      host = Socket::gethostname
      begin
        Socket::gethostbyname(host)[0]
      rescue
        'localhost'
      end
    end


open_server_inaddr_any (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 839
    def self.open_server_inaddr_any(host, port)
      infos = Socket::getaddrinfo(host, nil,
                                  Socket::AF_UNSPEC,
                                  Socket::SOCK_STREAM,
                                  0,
                                  Socket::AI_PASSIVE)
      family = infos.collect { |af, *_| af }.uniq
      case family
      when ['AF_INET']
        return TCPServer.open('0.0.0.0', port)
      when ['AF_INET6']
        return TCPServer.open('::', port)
      else
        return TCPServer.open(port)
      end
    end


open_server (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 858
    def self.open_server(uri, config)
      uri = 'druby://:0' unless uri
      host, port, opt = parse_uri(uri)
      if host.size == 0
        host = getservername
        soc = open_server_inaddr_any(host, port)
      else
        soc = TCPServer.open(host, port)
      end
      port = soc.addr[1] if port == 0
      uri = "druby://#{host}:#{port}"
      self.new(uri, soc, config)
    end


uri_option (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 873
    def self.uri_option(uri, config)
      host, port, option = parse_uri(uri)
      return "druby://#{host}:#{port}", option
    end


new (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 883
    def initialize(uri, soc, config={})
      @uri = uri
      @socket = soc
      @config = config
      @acl = config[:tcp_acl]
      @msg = DRbMessage.new(config)
      set_sockopt(@socket)
    end


peeraddr (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 897
    def peeraddr
      @socket.peeraddr
    end


stream (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 902
    def stream; @socket; end


send_request (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 905
    def send_request(ref, msg_id, arg, b)
      @msg.send_request(stream, ref, msg_id, arg, b)
    end


recv_request (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 910
    def recv_request
      @msg.recv_request(stream)
    end


send_reply (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 915
    def send_reply(succ, result)
      @msg.send_reply(stream, succ, result)
    end


recv_reply (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 920
    def recv_reply
      @msg.recv_reply(stream)
    end


close (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 932
    def close
      if @socket
        @socket.close
        @socket = nil
      end
    end


accept (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 942
    def accept
      while true
        s = @socket.accept
        break if (@acl ? @acl.allow_socket?(s) : true)
        s.close
      end
      self.class.new(nil, s, @config)
    end


alive? (DRb::DRbTCPSocket)

# File lib/drb/drb.rb, line 952
    def alive?
      return false unless @socket
      if IO.select([@socket], nil, nil, 0)
        close
        return false
      end
      true
    end


parse_uri (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 10
    def self.parse_uri(uri)
      if /^drbunix:(.*?)(\?(.*))?$/ =~ uri
        filename = $1
        option = $3
        [filename, option]
      else
        raise(DRbBadScheme, uri) unless uri =~ /^drbunix:/
        raise(DRbBadURI, 'can\'t parse uri:' + uri)
      end
    end


open (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 21
    def self.open(uri, config)
      filename, option = parse_uri(uri)
      filename.untaint
      soc = UNIXSocket.open(filename)
      self.new(uri, soc, config)
    end


open_server (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 28
    def self.open_server(uri, config)
      filename, option = parse_uri(uri)
      if filename.size == 0
        soc = temp_server
        filename = soc.path
        uri = 'drbunix:' + soc.path
      else
        soc = UNIXServer.open(filename)
      end
      owner = config[:UNIXFileOwner]
      group = config[:UNIXFileGroup]
      if owner || group
        require 'etc'
        owner = Etc.getpwnam( owner ).uid  if owner
        group = Etc.getgrnam( group ).gid  if group
        File.chown owner, group, filename
      end
      mode = config[:UNIXFileMode]
      File.chmod(mode, filename) if mode

      self.new(uri, soc, config, true)
    end


uri_option (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 51
    def self.uri_option(uri, config)
      filename, option = parse_uri(uri)
      return "drbunix:#{filename}", option
    end


new (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 56
    def initialize(uri, soc, config={}, server_mode = false)
      super(uri, soc, config)
      set_sockopt(@socket)
      @server_mode = server_mode
      @acl = nil
    end


close (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 89
    def close
      return unless @socket
      path = @socket.path if @server_mode
      @socket.close
      File.unlink(path) if @server_mode
      @socket = nil
    end


accept (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 97
    def accept
      s = @socket.accept
      self.class.new(nil, s, @config)
    end


set_sockopt (DRb::DRbUNIXSocket)

# File lib/drb/unix.rb, line 102
    def set_sockopt(soc)
      soc.fcntl(Fcntl::F_SETFL, Fcntl::FD_CLOEXEC) if defined? Fcntl::FD_CLOEXEC
    end


new (DRb::DRbUnknown)

# File lib/drb/drb.rb, line 466
    def initialize(err, buf)
      case err.to_s
      when /uninitialized constant (\S+)/
        @name = $1
      when /undefined class\/module (\S+)/
        @name = $1
      else
        @name = nil
      end
      @buf = buf
    end


reload (DRb::DRbUnknown)

# File lib/drb/drb.rb, line 504
    def reload
      self.class._load(@buf)
    end


exception (DRb::DRbUnknown)

# File lib/drb/drb.rb, line 509
    def exception
      DRbUnknownError.new(self)
    end


new (DRb::DRbUnknownError)

# File lib/drb/drb.rb, line 416
    def initialize(unknown)
      @unknown = unknown
      super(unknown.name)
    end


new (DRb::ExtServ)

# File lib/drb/extserv.rb, line 12
    def initialize(there, name, server=nil)
      @server = server || DRb::primary_server
      @name = name
      ro = DRbObject.new(nil, there)
      @invoker = ro.regist(name, DRbObject.new(self, @server.uri))
    end


front (DRb::ExtServ)

# File lib/drb/extserv.rb, line 20
    def front
      DRbObject.new(nil, @server.uri)
    end


stop_service (DRb::ExtServ)

# File lib/drb/extserv.rb, line 24
    def stop_service
      @invoker.unregist(@name)
      server = @server
      @server = nil
      server.stop_service
      true
    end


alive? (DRb::ExtServ)

# File lib/drb/extserv.rb, line 32
    def alive?
      @server ? @server.alive? : false
    end


command (DRb::ExtServManager)

# File lib/drb/extservm.rb, line 15
    def self.command
      @@command
    end


command= (DRb::ExtServManager)

# File lib/drb/extservm.rb, line 19
    def self.command=(cmd)
      @@command = cmd
    end


new (DRb::ExtServManager)

# File lib/drb/extservm.rb, line 23
    def initialize
      @servers = {}
      @waiting = []
      @queue = Queue.new
      @thread = invoke_thread
      @uri = nil
    end


service (DRb::ExtServManager)

# File lib/drb/extservm.rb, line 32
    def service(name)
      while true
        server = nil
        Thread.exclusive do
          server = @servers[name] if @servers[name]
        end
        return server if server && server.alive?
        invoke_service(name)
      end
    end


regist (DRb::ExtServManager)

# File lib/drb/extservm.rb, line 43
    def regist(name, ro)
      ary = nil
      Thread.exclusive do
        @servers[name] = ro
        ary = @waiting
        @waiting = []
      end
      ary.each do |th|
        begin
          th.run
        rescue ThreadError
        end
      end
      self
    end


unregist (DRb::ExtServManager)

# File lib/drb/extservm.rb, line 59
    def unregist(name)
      Thread.exclusive do
        @servers.delete(name)
      end
    end


new (DRb::GW)

# File lib/drb/gw.rb, line 16
    def initialize
      super()
      @hash = {}
    end


[] (DRb::GW)

# File lib/drb/gw.rb, line 21
    def [](key)
      synchronize do
        @hash[key]
      end
    end


[]= (DRb::GW)

# File lib/drb/gw.rb, line 27
    def []=(key, v)
      synchronize do
        @hash[key] = v
      end
    end


to_obj (DRb::GWIdConv)

# File lib/drb/gw.rb, line 6
    def to_obj(ref)
      if Array === ref && ref[0] == :DRbObject
        return DRbObject.new_with(ref[1], ref[2])
      end
      super(ref)
    end


new (DRb::TimerIdConv::TimerHolder2)

# File lib/drb/timeridconv.rb, line 11
      def initialize(timeout=600)
        super()
        @sentinel = Object.new
        @gc = {}
        @curr = {}
        @renew = {}
        @timeout = timeout
        @keeper = keeper
      end


add (DRb::TimerIdConv::TimerHolder2)

# File lib/drb/timeridconv.rb, line 21
      def add(obj)
        synchronize do
          key = obj.__id__
          @curr[key] = obj
          return key
        end
      end


fetch (DRb::TimerIdConv::TimerHolder2)

# File lib/drb/timeridconv.rb, line 29
      def fetch(key, dv=@sentinel)
        synchronize do
          obj = peek(key)
          if obj == @sentinel
            return dv unless dv == @sentinel
            raise InvalidIndexError
          end
          @renew[key] = obj # KeepIt
          return obj
        end
      end


include? (DRb::TimerIdConv::TimerHolder2)

# File lib/drb/timeridconv.rb, line 41
      def include?(key)
        synchronize do
          obj = peek(key)
          return false if obj == @sentinel
          true
        end
      end


peek (DRb::TimerIdConv::TimerHolder2)

# File lib/drb/timeridconv.rb, line 49
      def peek(key)
        synchronize do
          return @curr.fetch(key, @renew.fetch(key, @gc.fetch(key, @sentinel)))
        end
      end


new (DRb::TimerIdConv)

# File lib/drb/timeridconv.rb, line 74
    def initialize(timeout=600)
      @holder = TimerHolder2.new(timeout)
    end


to_obj (DRb::TimerIdConv)

# File lib/drb/timeridconv.rb, line 78
    def to_obj(ref)
      return super if ref.nil?
      @holder.fetch(ref)
    rescue TimerHolder2::InvalidIndexError
      raise "invalid reference"
    end


to_id (DRb::TimerIdConv)

# File lib/drb/timeridconv.rb, line 85
    def to_id(obj)
      return @holder.add(obj)
    end


start_service (DRb)

# File lib/drb/drb.rb, line 1626
  def start_service(uri=nil, front=nil, config=nil)
    @primary_server = DRbServer.new(uri, front, config)
  end


current_server (DRb)

# File lib/drb/drb.rb, line 1647
  def current_server
    drb = Thread.current['DRb']
    server = (drb && drb['server']) ? drb['server'] : @primary_server
    raise DRbServerNotFound unless server
    return server
  end


stop_service (DRb)

# File lib/drb/drb.rb, line 1659
  def stop_service
    @primary_server.stop_service if @primary_server
    @primary_server = nil
  end


uri (DRb)

# File lib/drb/drb.rb, line 1668
  def uri
    current_server.uri
  end


here? (DRb)

# File lib/drb/drb.rb, line 1674
  def here?(uri)
    (current_server.uri rescue nil) == uri
  end


config (DRb)

# File lib/drb/drb.rb, line 1683
  def config
    current_server.config
  rescue
    DRbServer.make_config
  end


front (DRb)

# File lib/drb/drb.rb, line 1694
  def front
    current_server.front
  end


to_obj (DRb)

# File lib/drb/drb.rb, line 1703
  def to_obj(ref)
    current_server.to_obj(ref)
  end


to_id (DRb)

# File lib/drb/drb.rb, line 1711
  def to_id(obj)
    current_server.to_id(obj)
  end


thread (DRb)

# File lib/drb/drb.rb, line 1720
  def thread
    @primary_server ? @primary_server.thread : nil
  end


install_id_conv (DRb)

# File lib/drb/drb.rb, line 1728
  def install_id_conv(idconv)
    DRbServer.default_id_conv(idconv)
  end


install_acl (DRb)

# File lib/drb/drb.rb, line 1736
  def install_acl(acl)
    DRbServer.default_acl(acl)
  end


regist_server (DRb)

# File lib/drb/drb.rb, line 1742
  def regist_server(server)
    @server[server.uri] = server
    Thread.exclusive do
      @primary_server = server unless @primary_server
    end
  end


remove_server (DRb)

# File lib/drb/drb.rb, line 1750
  def remove_server(server)
    @server.delete(server.uri)
  end


fetch_server (DRb)

# File lib/drb/drb.rb, line 1755
  def fetch_server(uri)
    @server[uri]
  end


new (Enumerable::Enumerator)

/*
 *  call-seq:
 *    Enumerable::Enumerator.new(obj, method = :each, *args)
 *
 *  Creates a new Enumerable::Enumerator object, which is to be
 *  used as an Enumerable object using the given object's given
 *  method with the given arguments.
 *
 *  e.g.:
 *      str = "xyz"
 *
 *      enum = Enumerable::Enumerator.new(str, :each_byte)
 *      a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
 *
 */
static VALUE
enumerator_initialize(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE enum_obj, enum_method, enum_args;

    rb_scan_args(argc, argv, "11*", &enum_obj, &enum_method, &enum_args);

    if (enum_method == Qnil)
        enum_method = sym_each;

    rb_ivar_set(obj, id_enum_obj, enum_obj);
    rb_ivar_set(obj, id_enum_method, enum_method);
    rb_ivar_set(obj, id_enum_args, enum_args);

    return Qnil;
}


each (Enumerable::Enumerator)

/*
 *  call-seq:
 *    enum.each {...}
 *
 *  Iterates the given block using the object and the method specified
 *  in the first place.
 *
 */
static VALUE
enumerator_each(obj)
    VALUE obj;
{
    VALUE val;

    obj = (VALUE)rb_node_newnode(NODE_MEMO,
                                 rb_ivar_get(obj, id_enum_obj),
                                 rb_to_id(rb_ivar_get(obj, id_enum_method)),
                                 rb_ivar_get(obj, id_enum_args));
    val = rb_iterate((VALUE (*)_((VALUE)))enumerator_iter, obj, rb_yield, 0);
    return val;
}


to_a (Enumerable)

/*
 *  call-seq:
 *     enum.to_a      =>    array
 *     enum.entries   =>    array
 *
 *  Returns an array containing the items in <i>enum</i>.
 *
 *     (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
 *     { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]
 */
static VALUE
enum_to_a(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, collect_all, ary);

    return ary;
}


entries (Enumerable)

/*
 *  call-seq:
 *     enum.to_a      =>    array
 *     enum.entries   =>    array
 *
 *  Returns an array containing the items in <i>enum</i>.
 *
 *     (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
 *     { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]
 */
static VALUE
enum_to_a(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, collect_all, ary);

    return ary;
}


sort (Enumerable)

/*
 *  call-seq:
 *     enum.sort                     => array
 *     enum.sort {| a, b | block }   => array
 *
 *  Returns an array containing the items in <i>enum</i> sorted,
 *  either according to their own <code><=></code> method, or by using
 *  the results of the supplied block. The block should return -1, 0, or
 *  +1 depending on the comparison between <i>a</i> and <i>b</i>. As of
 *  Ruby 1.8, the method <code>Enumerable#sort_by</code> implements a
 *  built-in Schwartzian Transform, useful when key computation or
 *  comparison is expensive..
 *
 *     %w(rhea kea flea).sort         #=> ["flea", "kea", "rhea"]
 *     (1..10).sort {|a,b| b <=> a}   #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
 */

static VALUE
enum_sort(obj)
    VALUE obj;
{
    return rb_ary_sort(enum_to_a(obj));
}


sort_by (Enumerable)

/*
 *  call-seq:
 *     enum.sort_by {| obj | block }    => array
 *
 *  Sorts <i>enum</i> using a set of keys generated by mapping the
 *  values in <i>enum</i> through the given block.
 *
 *     %w{ apple pear fig }.sort_by {|word| word.length}
                    #=> ["fig", "pear", "apple"]
 *
 *  The current implementation of <code>sort_by</code> generates an
 *  array of tuples containing the original collection element and the
 *  mapped value. This makes <code>sort_by</code> fairly expensive when
 *  the keysets are simple
 *
 *     require 'benchmark'
 *     include Benchmark
 *
 *     a = (1..100000).map {rand(100000)}
 *
 *     bm(10) do |b|
 *       b.report("Sort")    { a.sort }
 *       b.report("Sort by") { a.sort_by {|a| a} }
 *     end
 *
 *  <em>produces:</em>
 *
 *     user     system      total        real
 *     Sort        0.180000   0.000000   0.180000 (  0.175469)
 *     Sort by     1.980000   0.040000   2.020000 (  2.013586)
 *
 *  However, consider the case where comparing the keys is a non-trivial
 *  operation. The following code sorts some files on modification time
 *  using the basic <code>sort</code> method.
 *
 *     files = Dir["*"]
 *     sorted = files.sort {|a,b| File.new(a).mtime <=> File.new(b).mtime}
 *     sorted   #=> ["mon", "tues", "wed", "thurs"]
 *
 *  This sort is inefficient: it generates two new <code>File</code>
 *  objects during every comparison. A slightly better technique is to
 *  use the <code>Kernel#test</code> method to generate the modification
 *  times directly.
 *
 *     files = Dir["*"]
 *     sorted = files.sort { |a,b|
 *       test(?M, a) <=> test(?M, b)
 *     }
 *     sorted   #=> ["mon", "tues", "wed", "thurs"]
 *
 *  This still generates many unnecessary <code>Time</code> objects. A
 *  more efficient technique is to cache the sort keys (modification
 *  times in this case) before the sort. Perl users often call this
 *  approach a Schwartzian Transform, after Randal Schwartz. We
 *  construct a temporary array, where each element is an array
 *  containing our sort key along with the filename. We sort this array,
 *  and then extract the filename from the result.
 *
 *     sorted = Dir["*"].collect { |f|
 *        [test(?M, f), f]
 *     }.sort.collect { |f| f[1] }
 *     sorted   #=> ["mon", "tues", "wed", "thurs"]
 *
 *  This is exactly what <code>sort_by</code> does internally.
 *
 *     sorted = Dir["*"].sort_by {|f| test(?M, f)}
 *     sorted   #=> ["mon", "tues", "wed", "thurs"]
 */

static VALUE
enum_sort_by(obj)
    VALUE obj;
{
    VALUE ary;
    long i;

    if (TYPE(obj) == T_ARRAY) {
        ary  = rb_ary_new2(RARRAY(obj)->len);
    }
    else {
        ary = rb_ary_new();
    }
    RBASIC(ary)->klass = 0;
    rb_iterate(rb_each, obj, sort_by_i, ary);
    if (RARRAY(ary)->len > 1) {
        qsort(RARRAY(ary)->ptr, RARRAY(ary)->len, sizeof(VALUE), sort_by_cmp, 0);
    }
    if (RBASIC(ary)->klass) {
        rb_raise(rb_eRuntimeError, "sort_by reentered");
    }
    for (i=0; i<RARRAY(ary)->len; i++) {
        RARRAY(ary)->ptr[i] = RNODE(RARRAY(ary)->ptr[i])->u2.value;
    }
    RBASIC(ary)->klass = rb_cArray;
    return ary;
}


grep (Enumerable)

/*
 *  call-seq:
 *     enum.grep(pattern)                   => array
 *     enum.grep(pattern) {| obj | block }  => array
 *
 *  Returns an array of every element in <i>enum</i> for which
 *  <code>Pattern === element</code>. If the optional <em>block</em> is
 *  supplied, each matching element is passed to it, and the block's
 *  result is stored in the output array.
 *
 *     (1..100).grep 38..44   #=> [38, 39, 40, 41, 42, 43, 44]
 *     c = IO.constants
 *     c.grep(/SEEK/)         #=> ["SEEK_END", "SEEK_SET", "SEEK_CUR"]
 *     res = c.grep(/SEEK/) {|v| IO.const_get(v) }
 *     res                    #=> [2, 0, 1]
 *
 */

static VALUE
enum_grep(obj, pat)
    VALUE obj, pat;
{
    VALUE ary = rb_ary_new();
    VALUE arg[2];

    arg[0] = pat;
    arg[1] = ary;

    rb_iterate(rb_each, obj, rb_block_given_p() ? grep_iter_i : grep_i, (VALUE)arg);

    return ary;
}


find (Enumerable)

/*
 *  call-seq:
 *     enum.detect(ifnone = nil) {| obj | block }  => obj or nil
 *     enum.find(ifnone = nil)   {| obj | block }  => obj or nil
 *
 *  Passes each entry in <i>enum</i> to <em>block</em>. Returns the
 *  first for which <em>block</em> is not <code>false</code>.  If no
 *  object matches, calls <i>ifnone</i> and returns its result when it
 *  is specified, or returns <code>nil</code>
 *
 *     (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
 *     (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
 *
 */

static VALUE
enum_find(argc, argv, obj)
    int argc;
    VALUE* argv;
    VALUE obj;
{
    VALUE memo = Qundef;
    VALUE if_none;

    rb_scan_args(argc, argv, "01", &if_none);
    rb_iterate(rb_each, obj, find_i, (VALUE)&memo);
    if (memo != Qundef) {
        return memo;
    }
    if (!NIL_P(if_none)) {
        return rb_funcall(if_none, rb_intern("call"), 0, 0);
    }
    return Qnil;
}


detect (Enumerable)

/*
 *  call-seq:
 *     enum.detect(ifnone = nil) {| obj | block }  => obj or nil
 *     enum.find(ifnone = nil)   {| obj | block }  => obj or nil
 *
 *  Passes each entry in <i>enum</i> to <em>block</em>. Returns the
 *  first for which <em>block</em> is not <code>false</code>.  If no
 *  object matches, calls <i>ifnone</i> and returns its result when it
 *  is specified, or returns <code>nil</code>
 *
 *     (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
 *     (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
 *
 */

static VALUE
enum_find(argc, argv, obj)
    int argc;
    VALUE* argv;
    VALUE obj;
{
    VALUE memo = Qundef;
    VALUE if_none;

    rb_scan_args(argc, argv, "01", &if_none);
    rb_iterate(rb_each, obj, find_i, (VALUE)&memo);
    if (memo != Qundef) {
        return memo;
    }
    if (!NIL_P(if_none)) {
        return rb_funcall(if_none, rb_intern("call"), 0, 0);
    }
    return Qnil;
}


find_all (Enumerable)

/*
 *  call-seq:
 *     enum.find_all {| obj | block }  => array
 *     enum.select   {| obj | block }  => array
 *
 *  Returns an array containing all elements of <i>enum</i> for which
 *  <em>block</em> is not <code>false</code> (see also
 *  <code>Enumerable#reject</code>).
 *
 *     (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]
 *
 */

static VALUE
enum_find_all(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, find_all_i, ary);

    return ary;
}


select (Enumerable)

/*
 *  call-seq:
 *     enum.find_all {| obj | block }  => array
 *     enum.select   {| obj | block }  => array
 *
 *  Returns an array containing all elements of <i>enum</i> for which
 *  <em>block</em> is not <code>false</code> (see also
 *  <code>Enumerable#reject</code>).
 *
 *     (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]
 *
 */

static VALUE
enum_find_all(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, find_all_i, ary);

    return ary;
}


reject (Enumerable)

/*
 *  call-seq:
 *     enum.reject {| obj | block }  => array
 *
 *  Returns an array for all elements of <i>enum</i> for which
 *  <em>block</em> is false (see also <code>Enumerable#find_all</code>).
 *
 *     (1..10).reject {|i|  i % 3 == 0 }   #=> [1, 2, 4, 5, 7, 8, 10]
 *
 */

static VALUE
enum_reject(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, reject_i, ary);

    return ary;
}


collect (Enumerable)

/*
 *  call-seq:
 *     enum.collect {| obj | block }  => array
 *     enum.map     {| obj | block }  => array
 *
 *  Returns a new array with the results of running <em>block</em> once
 *  for every element in <i>enum</i>.
 *
 *     (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
 *     (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
 *
 */

static VALUE
enum_collect(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, rb_block_given_p() ? collect_i : collect_all, ary);

    return ary;
}


map (Enumerable)

/*
 *  call-seq:
 *     enum.collect {| obj | block }  => array
 *     enum.map     {| obj | block }  => array
 *
 *  Returns a new array with the results of running <em>block</em> once
 *  for every element in <i>enum</i>.
 *
 *     (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
 *     (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
 *
 */

static VALUE
enum_collect(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    rb_iterate(rb_each, obj, rb_block_given_p() ? collect_i : collect_all, ary);

    return ary;
}


inject (Enumerable)

/*
 *  call-seq:
 *     enum.inject(initial) {| memo, obj | block }  => obj
 *     enum.inject          {| memo, obj | block }  => obj
 *
 *  Combines the elements of <i>enum</i> by applying the block to an
 *  accumulator value (<i>memo</i>) and each element in turn. At each
 *  step, <i>memo</i> is set to the value returned by the block. The
 *  first form lets you supply an initial value for <i>memo</i>. The
 *  second form uses the first element of the collection as a the
 *  initial value (and skips that element while iterating).
 *
 *     # Sum some numbers
 *     (5..10).inject {|sum, n| sum + n }              #=> 45
 *     # Multiply some numbers
 *     (5..10).inject(1) {|product, n| product * n }   #=> 151200
 *
 *     # find the longest word
 *     longest = %w{ cat sheep bear }.inject do |memo,word|
 *        memo.length > word.length ? memo : word
 *     end
 *     longest                                         #=> "sheep"
 *
 *     # find the length of the longest word
 *     longest = %w{ cat sheep bear }.inject(0) do |memo,word|
 *        memo >= word.length ? memo : word.length
 *     end
 *     longest                                         #=> 5
 *
 */

static VALUE
enum_inject(argc, argv, obj)
    int argc;
    VALUE *argv, obj;
{
    VALUE memo = Qundef;

    if (rb_scan_args(argc, argv, "01", &memo) == 0)
        memo = Qundef;
    rb_iterate(rb_each, obj, inject_i, (VALUE)&memo);
    if (memo == Qundef) return Qnil;
    return memo;
}


partition (Enumerable)

/*
 *  call-seq:
 *     enum.partition {| obj | block }  => [ true_array, false_array ]
 *
 *  Returns two arrays, the first containing the elements of
 *  <i>enum</i> for which the block evaluates to true, the second
 *  containing the rest.
 *
 *     (1..6).partition {|i| (i&1).zero?}   #=> [[2, 4, 6], [1, 3, 5]]
 *
 */

static VALUE
enum_partition(obj)
    VALUE obj;
{
    VALUE ary[2];

    ary[0] = rb_ary_new();
    ary[1] = rb_ary_new();
    rb_iterate(rb_each, obj, partition_i, (VALUE)ary);

    return rb_assoc_new(ary[0], ary[1]);
}


all? (Enumerable)

/*
 *  call-seq:
 *     enum.all? [{|obj| block } ]   => true or false
 *
 *  Passes each element of the collection to the given block. The method
 *  returns <code>true</code> if the block never returns
 *  <code>false</code> or <code>nil</code>. If the block is not given,
 *  Ruby adds an implicit block of <code>{|obj| obj}</code> (that is
 *  <code>all?</code> will return <code>true</code> only if none of the
 *  collection members are <code>false</code> or <code>nil</code>.)
 *
 *     %w{ ant bear cat}.all? {|word| word.length >= 3}   #=> true
 *     %w{ ant bear cat}.all? {|word| word.length >= 4}   #=> false
 *     [ nil, true, 99 ].all?                             #=> false
 *
 */

static VALUE
enum_all(obj)
    VALUE obj;
{
    VALUE result = Qtrue;

    rb_iterate(rb_each, obj, rb_block_given_p() ? all_iter_i : all_i, (VALUE)&result);
    return result;
}


any? (Enumerable)

/*
 *  call-seq:
 *     enum.any? [{|obj| block } ]   => true or false
 *
 *  Passes each element of the collection to the given block. The method
 *  returns <code>true</code> if the block ever returns a value other
 *  than <code>false</code> or <code>nil</code>. If the block is not
 *  given, Ruby adds an implicit block of <code>{|obj| obj}</code> (that
 *  is <code>any?</code> will return <code>true</code> if at least one
 *  of the collection members is not <code>false</code> or
 *  <code>nil</code>.
 *
 *     %w{ ant bear cat}.any? {|word| word.length >= 3}   #=> true
 *     %w{ ant bear cat}.any? {|word| word.length >= 4}   #=> true
 *     [ nil, true, 99 ].any?                             #=> true
 *
 */

static VALUE
enum_any(obj)
    VALUE obj;
{
    VALUE result = Qfalse;

    rb_iterate(rb_each, obj, rb_block_given_p() ? any_iter_i : any_i, (VALUE)&result);
    return result;
}


min (Enumerable)

/*
 *  call-seq:
 *     enum.min                    => obj
 *     enum.min {| a,b | block }   => obj
 *
 *  Returns the object in <i>enum</i> with the minimum value. The
 *  first form assumes all objects implement <code>Comparable</code>;
 *  the second uses the block to return <em>a <=> b</em>.
 *
 *     a = %w(albatross dog horse)
 *     a.min                                  #=> "albatross"
 *     a.min {|a,b| a.length <=> b.length }   #=> "dog"
 */

static VALUE
enum_min(obj)
    VALUE obj;
{
    VALUE result = Qundef;

    rb_iterate(rb_each, obj, rb_block_given_p() ? min_ii : min_i, (VALUE)&result);
    if (result == Qundef) return Qnil;
    return result;
}


max (Enumerable)

/*
 *  call-seq:
 *     enum.max                   => obj
 *     enum.max {|a,b| block }    => obj
 *
 *  Returns the object in _enum_ with the maximum value. The
 *  first form assumes all objects implement <code>Comparable</code>;
 *  the second uses the block to return <em>a <=> b</em>.
 *
 *     a = %w(albatross dog horse)
 *     a.max                                  #=> "horse"
 *     a.max {|a,b| a.length <=> b.length }   #=> "albatross"
 */

static VALUE
enum_max(obj)
    VALUE obj;
{
    VALUE result = Qundef;

    rb_iterate(rb_each, obj, rb_block_given_p() ? max_ii : max_i, (VALUE)&result);
    if (result == Qundef) return Qnil;
    return result;
}


member? (Enumerable)

/*
 *  call-seq:
 *     enum.include?(obj)     => true or false
 *     enum.member?(obj)      => true or false
 *
 *  Returns <code>true</code> if any member of <i>enum</i> equals
 *  <i>obj</i>. Equality is tested using <code>==</code>.
 *
 *     IO.constants.include? "SEEK_SET"          #=> true
 *     IO.constants.include? "SEEK_NO_FURTHER"   #=> false
 *
 */

static VALUE
enum_member(obj, val)
    VALUE obj, val;
{
    VALUE memo[2];

    memo[0] = val;
    memo[1] = Qfalse;
    rb_iterate(rb_each, obj, member_i, (VALUE)memo);
    return memo[1];
}


include? (Enumerable)

/*
 *  call-seq:
 *     enum.include?(obj)     => true or false
 *     enum.member?(obj)      => true or false
 *
 *  Returns <code>true</code> if any member of <i>enum</i> equals
 *  <i>obj</i>. Equality is tested using <code>==</code>.
 *
 *     IO.constants.include? "SEEK_SET"          #=> true
 *     IO.constants.include? "SEEK_NO_FURTHER"   #=> false
 *
 */

static VALUE
enum_member(obj, val)
    VALUE obj, val;
{
    VALUE memo[2];

    memo[0] = val;
    memo[1] = Qfalse;
    rb_iterate(rb_each, obj, member_i, (VALUE)memo);
    return memo[1];
}


each_with_index (Enumerable)

/*
 *  call-seq:
 *     enum.each_with_index {|obj, i| block }  -> enum
 *
 *  Calls <em>block</em> with two arguments, the item and its index, for
 *  each item in <i>enum</i>.
 *
 *     hash = Hash.new
 *     %w(cat dog wombat).each_with_index {|item, index|
 *       hash[item] = index
 *     }
 *     hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
 *
 */

static VALUE
enum_each_with_index(obj)
    VALUE obj;
{
    VALUE memo = 0;

    rb_need_block();
    rb_iterate(rb_each, obj, each_with_index_i, (VALUE)&memo);
    return obj;
}


zip (Enumerable)

/*
 *  call-seq:
 *     enum.zip(arg, ...)                   => array
 *     enum.zip(arg, ...) {|arr| block }    => nil
 *
 *  Converts any arguments to arrays, then merges elements of
 *  <i>enum</i> with corresponding elements from each argument. This
 *  generates a sequence of <code>enum#size</code> <em>n</em>-element
 *  arrays, where <em>n</em> is one more that the count of arguments. If
 *  the size of any argument is less than <code>enum#size</code>,
 *  <code>nil</code> values are supplied. If a block given, it is
 *  invoked for each output array, otherwise an array of arrays is
 *  returned.
 *
 *     a = [ 4, 5, 6 ]
 *     b = [ 7, 8, 9 ]
 *
 *     (1..3).zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
 *     "cat\ndog".zip([1])   #=> [["cat\n", 1], ["dog", nil]]
 *     (1..3).zip            #=> [[1], [2], [3]]
 *
 */

static VALUE
enum_zip(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    int i;
    VALUE result;
    VALUE memo[3];

    for (i=0; i<argc; i++) {
        argv[i] = rb_convert_type(argv[i], T_ARRAY, "Array", "to_a");
    }
    result = rb_block_given_p() ? Qnil : rb_ary_new();
    memo[0] = result;
    memo[1] = rb_ary_new4(argc, argv);
    memo[2] = 0;
    rb_iterate(rb_each, obj, zip_i, (VALUE)memo);

    return result;
}


to_set (Enumerable)

# File lib/set.rb, line 523
  def to_set(klass = Set, *args, &block)
    klass.new(self, *args, &block)
  end


inject (Enumerable)

# File lib/soap/property.rb, line 325
    def inject(init)
      result = init
      each do |item|
        result = yield(result, item)
      end
      result
    end


enum_with_index (Enumerable)

/*
 *  call-seq:
 *    enum_with_index
 *
 *  Returns Enumerable::Enumerator.new(self, :each_with_index).
 *
 */
static VALUE
enumerator_enum_with_index(obj)
    VALUE obj;
{
    return rb_funcall(rb_cEnumerator, id_new, 2, obj, sym_each_with_index);
}


each_slice (Enumerable)

/*
 *  call-seq:
 *    e.each_slice(n) {...}
 *
 *  Iterates the given block for each slice of <n> elements.
 *
 *  e.g.:
 *      (1..10).each_slice(3) {|a| p a}
 *      # outputs below
 *      [1, 2, 3]
 *      [4, 5, 6]
 *      [7, 8, 9]
 *      [10]
 *
 */
static VALUE
enum_each_slice(obj, n)
    VALUE obj, n;
{
    long size = NUM2LONG(n);
    NODE *memo;
    VALUE ary;

    if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");

    memo = rb_node_newnode(NODE_MEMO, rb_ary_new2(size), 0, size);

    rb_iterate(rb_each, obj, each_slice_i, (VALUE)memo);

    ary = memo->u1.value;
    if (RARRAY(ary)->len > 0) rb_yield(ary);

    return Qnil;
}


enum_slice (Enumerable)

/*
 *  call-seq:
 *    e.enum_slice(n)
 *
 *  Returns Enumerable::Enumerator.new(self, :each_slice, n).
 *
 */
static VALUE
enumerator_enum_slice(obj, n)
    VALUE obj, n;
{
    return rb_funcall(rb_cEnumerator, id_new, 3, obj, sym_each_slice, n);
}


each_cons (Enumerable)

/*
 *  call-seq:
 *    each_cons(n) {...}
 *
 *  Iterates the given block for each array of consecutive <n>
 *  elements.
 *
 *  e.g.:
 *      (1..10).each_cons(3) {|a| p a}
 *      # outputs below
 *      [1, 2, 3]
 *      [2, 3, 4]
 *      [3, 4, 5]
 *      [4, 5, 6]
 *      [5, 6, 7]
 *      [6, 7, 8]
 *      [7, 8, 9]
 *      [8, 9, 10]
 *
 */
static VALUE
enum_each_cons(obj, n)
    VALUE obj, n;
{
    long size = NUM2LONG(n);
    NODE *memo;

    if (size <= 0) rb_raise(rb_eArgError, "invalid size");
    memo = rb_node_newnode(NODE_MEMO, rb_ary_new2(size), 0, size);

    rb_iterate(rb_each, obj, each_cons_i, (VALUE)memo);

    return Qnil;
}


enum_cons (Enumerable)

/*
 *  call-seq:
 *    e.enum_cons(n)
 *
 *  Returns Enumerable::Enumerator.new(self, :each_cons, n).
 *
 */
static VALUE
enumerator_enum_cons(obj, n)
    VALUE obj, n;
{
    return rb_funcall(rb_cEnumerator, id_new, 3, obj, sym_each_cons, n);
}


html_escape (ERB::Util)

# File lib/erb.rb, line 782
    def html_escape(s)
      s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
    end


url_encode (ERB::Util)

# File lib/erb.rb, line 801
    def url_encode(s)
      s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
    end


version (ERB)

# File lib/erb.rb, line 242
  def self.version
    "erb.rb [2.0.4 #{ERB::Revision.split[1]}]"
  end


new (ERB)

# File lib/erb.rb, line 687
  def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
    @safe_level = safe_level
    compiler = ERB::Compiler.new(trim_mode)
    set_eoutvar(compiler, eoutvar)
    @src = compiler.compile(str)
    @filename = nil
  end


set_eoutvar (ERB)

# File lib/erb.rb, line 707
  def set_eoutvar(compiler, eoutvar = '_erbout')
    compiler.put_cmd = "#{eoutvar}.concat"
    compiler.insert_cmd = "#{eoutvar}.concat"

    cmd = []
    cmd.push "#{eoutvar} = ''"

    compiler.pre_cmd = cmd

    cmd = []
    cmd.push(eoutvar)

    compiler.post_cmd = cmd
  end


run (ERB)

# File lib/erb.rb, line 723
  def run(b=TOPLEVEL_BINDING)
    print self.result(b)
  end


result (ERB)

# File lib/erb.rb, line 735
  def result(b=TOPLEVEL_BINDING)
    if @safe_level
      th = Thread.start {
        $SAFE = @safe_level
        eval(@src, b, (@filename || '(erb)'), 1)
      }
      return th.value
    else
      return eval(@src, b, (@filename || '(erb)'), 1)
    end
  end


exception (Exception)

/*
 *  Document-method: exception
 *
 *  call-seq:
 *     exc.exception(string) -> an_exception or exc
 *
 *  With no argument, or if the argument is the same as the receiver,
 *  return the receiver. Otherwise, create a new
 *  exception object of the same class as the receiver, but with a
 *  message equal to <code>string.to_str</code>.
 *
 */

static VALUE
exc_exception(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE exc;

    if (argc == 0) return self;
    if (argc == 1 && self == argv[0]) return self;
    exc = rb_obj_clone(self);
    exc_initialize(argc, argv, exc);

    return exc;
}


new (Exception)

/*
 * call-seq:
 *    Exception.new(msg = nil)   =>  exception
 *
 *  Construct a new Exception object, optionally passing in
 *  a message.
 */

static VALUE
exc_initialize(argc, argv, exc)
    int argc;
    VALUE *argv;
    VALUE exc;
{
    VALUE arg;

    rb_scan_args(argc, argv, "01", &arg);
    rb_iv_set(exc, "mesg", arg);
    rb_iv_set(exc, "bt", Qnil);

    return exc;
}


to_s (Exception)

/*
 * call-seq:
 *   exception.to_s   =>  string
 *
 * Returns exception's message (or the name of the exception if
 * no message is set).
 */

static VALUE
exc_to_s(exc)
    VALUE exc;
{
    VALUE mesg = rb_attr_get(exc, rb_intern("mesg"));

    if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
    if (OBJ_TAINTED(exc)) OBJ_TAINT(mesg);
    return mesg;
}


to_str (Exception)

/*
 * call-seq:
 *   exception.message   =>  string
 *   exception.to_str    =>  string
 *
 * Returns the result of invoking <code>exception.to_s</code>.
 * Normally this returns the exception's message or name. By
 * supplying a to_str method, exceptions are agreeing to
 * be used where Strings are expected.
 */

static VALUE
exc_to_str(exc)
    VALUE exc;
{
    return rb_funcall(exc, rb_intern("to_s"), 0, 0);
}


message (Exception)

/*
 * call-seq:
 *   exception.message   =>  string
 *   exception.to_str    =>  string
 *
 * Returns the result of invoking <code>exception.to_s</code>.
 * Normally this returns the exception's message or name. By
 * supplying a to_str method, exceptions are agreeing to
 * be used where Strings are expected.
 */

static VALUE
exc_to_str(exc)
    VALUE exc;
{
    return rb_funcall(exc, rb_intern("to_s"), 0, 0);
}


inspect (Exception)

/*
 * call-seq:
 *   exception.inspect   => string
 *
 * Return this exception's class name an message
 */

static VALUE
exc_inspect(exc)
    VALUE exc;
{
    VALUE str, klass;

    klass = CLASS_OF(exc);
    exc = rb_obj_as_string(exc);
    if (RSTRING(exc)->len == 0) {
        return rb_str_dup(rb_class_name(klass));
    }

    str = rb_str_buf_new2("#<");
    klass = rb_class_name(klass);
    rb_str_buf_append(str, klass);
    rb_str_buf_cat(str, ": ", 2);
    rb_str_buf_append(str, exc);
    rb_str_buf_cat(str, ">", 1);

    return str;
}


backtrace (Exception)

/*
 *  call-seq:
 *     exception.backtrace    => array
 *
 *  Returns any backtrace associated with the exception. The backtrace
 *  is an array of strings, each containing either ``filename:lineNo: in
 *  `method''' or ``filename:lineNo.''
 *
 *     def a
 *       raise "boom"
 *     end
 *
 *     def b
 *       a()
 *     end
 *
 *     begin
 *       b()
 *     rescue => detail
 *       print detail.backtrace.join("\n")
 *     end
 *
 *  <em>produces:</em>
 *
 *     prog.rb:2:in `a'
 *     prog.rb:6:in `b'
 *     prog.rb:10
*/

static VALUE
exc_backtrace(exc)
    VALUE exc;
{
    static ID bt;

    if (!bt) bt = rb_intern("bt");
    return rb_attr_get(exc, bt);
}


set_backtrace (Exception)

/*
 *  call-seq:
 *     exc.set_backtrace(array)   =>  array
 *
 *  Sets the backtrace information associated with <i>exc</i>. The
 *  argument must be an array of <code>String</code> objects in the
 *  format described in <code>Exception#backtrace</code>.
 *
 */

static VALUE
exc_set_backtrace(exc, bt)
    VALUE exc;
    VALUE bt;
{
    return rb_iv_set(exc, "bt", rb_check_backtrace(bt));
}


yaml_new (Exception)

# File lib/yaml/rubytypes.rb, line 119
    def Exception.yaml_new( klass, tag, val )
        o = YAML.object_maker( klass, { 'mesg' => val.delete( 'message' ) } )
        val.each_pair do |k,v|
            o.instance_variable_set("@#{k}", v)
        end
        o
    end


to_yaml (Exception)

# File lib/yaml/rubytypes.rb, line 126
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            out.map( taguri, to_yaml_style ) do |map|
                map.add( 'message', message )
                                to_yaml_properties.each do |m|
                    map.add( m[1..-1], instance_variable_get( m ) )
                end
            end
        end
        end


extend_object (Exception2MessageMapper::E2MM)

# File lib/e2mmap.rb, line 58
  def E2MM.extend_object(cl)
    super
    cl.bind(self) unless cl == E2MM
  end


extend_to (Exception2MessageMapper::E2MM)

# File lib/e2mmap.rb, line 64
  def E2MM.extend_to(b)
    c = eval("self", b)
    c.extend(self)
  end


def_e2message (Exception2MessageMapper::E2MM)

# File lib/e2mmap.rb, line 136
  def E2MM.def_e2message(k, c, m)
    E2MM.instance_eval{@MessageMap[[k, c]] = m}
    c
  end


def_exception (Exception2MessageMapper::E2MM)

# File lib/e2mmap.rb, line 148
  def E2MM.def_exception(k, n, m, s = StandardError)
    n = n.id2name if n.kind_of?(Fixnum)
    e = Class.new(s)
    E2MM.instance_eval{@MessageMap[[k, e]] = m}
    k.const_set(n, e)
  end


Raise (Exception2MessageMapper::E2MM)

# File lib/e2mmap.rb, line 160
  def E2MM.Raise(klass = E2MM, err = nil, *rest)
    if form = e2mm_message(klass, err)
      $! = err.new(sprintf(form, *rest))
      $@ = caller(1) if $@.nil?
      #p $@
      #p __FILE__
      $@.shift if $@[0] =~ /^#{Regexp.quote(__FILE__)}:/
      raise
    else
      E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect
    end
  end


e2mm_message (Exception2MessageMapper::E2MM)

# File lib/e2mmap.rb, line 176
  def E2MM.e2mm_message(klass, exp)
    for c in klass.ancestors
      if mes = @MessageMap[[c,exp]]
        #p mes
        m = klass.instance_eval('"' + mes + '"')
        return m
      end
    end
    nil
  end


bind (Exception2MessageMapper)

# File lib/e2mmap.rb, line 69
  def bind(cl)
    self.module_eval %[
      def Raise(err = nil, *rest)
        Exception2MessageMapper.Raise(self.class, err, *rest)
      end
      alias Fail Raise

      def self.included(mod)
        mod.extend Exception2MessageMapper
      end
    ]
  end


Raise (Exception2MessageMapper)

# File lib/e2mmap.rb, line 86
  def Raise(err = nil, *rest)
    E2MM.Raise(self, err, *rest)
  end


fail (Exception2MessageMapper)

# File lib/e2mmap.rb, line 93
  def fail(err = nil, *rest)
    begin
      E2MM.Fail(self, err, *rest)
    rescue E2MM::ErrNotRegisteredException
      super
    end
  end


def_e2message (Exception2MessageMapper)

# File lib/e2mmap.rb, line 110
  def def_e2message(c, m)
    E2MM.def_e2message(self, c, m)
  end


def_exception (Exception2MessageMapper)

# File lib/e2mmap.rb, line 120
  def def_exception(n, m, s = StandardError)
    E2MM.def_exception(self, n, m, s)
  end


to_s (FalseClass)

/*
 * call-seq:
 *   false.to_s   =>  "false"
 *
 * 'nuf said...
 */

static VALUE
false_to_s(obj)
    VALUE obj;
{
    return rb_str_new2("false");
}


& (FalseClass)

/*
 *  call-seq:
 *     false & obj   => false
 *     nil & obj     => false
 *
 *  And---Returns <code>false</code>. <i>obj</i> is always
 *  evaluated as it is the argument to a method call---there is no
 *  short-circuit evaluation in this case.
 */

static VALUE
false_and(obj, obj2)
    VALUE obj, obj2;
{
    return Qfalse;
}


| (FalseClass)

/*
 *  call-seq:
 *     false | obj   =>   true or false
 *     nil   | obj   =>   true or false
 *
 *  Or---Returns <code>false</code> if <i>obj</i> is
 *  <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
 */

static VALUE
false_or(obj, obj2)
    VALUE obj, obj2;
{
    return RTEST(obj2)?Qtrue:Qfalse;
}


^ (FalseClass)

/*
 *  call-seq:
 *     false ^ obj    => true or false
 *     nil   ^ obj    => true or false
 *
 *  Exclusive Or---If <i>obj</i> is <code>nil</code> or
 *  <code>false</code>, returns <code>false</code>; otherwise, returns
 *  <code>true</code>.
 *
 */

static VALUE
false_xor(obj, obj2)
    VALUE obj, obj2;
{
    return RTEST(obj2)?Qtrue:Qfalse;
}


to_yaml (FalseClass)

# File lib/yaml/rubytypes.rb, line 393
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( taguri, "false", :plain )
        end
        end


new (File::Stat)

/*
 * call-seq:
 *
 *   File::Stat.new(file_name)  => stat
 *
 * Create a File::Stat object for the given file name (raising an
 * exception if the file doesn't exist).
 */

static VALUE
rb_stat_init(obj, fname)
    VALUE obj, fname;
{
    struct stat st, *nst;

    SafeStringValue(fname);

    if (stat(StringValueCStr(fname), &st) == -1) {
        rb_sys_fail(RSTRING(fname)->ptr);
    }
    if (DATA_PTR(obj)) {
        free(DATA_PTR(obj));
        DATA_PTR(obj) = NULL;
    }
    nst = ALLOC(struct stat);
    *nst = st;
    DATA_PTR(obj) = nst;

    return Qnil;
}


<=> (File::Stat)

/*
 *  call-seq:
 *     stat <=> other_stat    => -1, 0, 1
 *
 *  Compares <code>File::Stat</code> objects by comparing their
 *  respective modification times.
 *
 *     f1 = File.new("f1", "w")
 *     sleep 1
 *     f2 = File.new("f2", "w")
 *     f1.stat <=> f2.stat   #=> -1
 */

static VALUE
rb_stat_cmp(self, other)
    VALUE self, other;
{
    if (rb_obj_is_kind_of(other, rb_obj_class(self))) {
        time_t t1 = get_stat(self)->st_mtime;
        time_t t2 = get_stat(other)->st_mtime;
        if (t1 == t2)
            return INT2FIX(0);
        else if (t1 < t2)
            return INT2FIX(-1);
        else
            return INT2FIX(1);
    }
    return Qnil;
}


dev (File::Stat)

/*
 *  call-seq:
 *     stat.dev    => fixnum
 *
 *  Returns an integer representing the device on which <i>stat</i>
 *  resides.
 *
 *     File.stat("testfile").dev   #=> 774
 */

static VALUE
rb_stat_dev(self)
    VALUE self;
{
    return INT2NUM(get_stat(self)->st_dev);
}


dev_major (File::Stat)

/*
 *  call-seq:
 *     stat.dev_major   => fixnum
 *
 *  Returns the major part of <code>File_Stat#dev</code> or
 *  <code>nil</code>.
 *
 *     File.stat("/dev/fd1").dev_major   #=> 2
 *     File.stat("/dev/tty").dev_major   #=> 5
 */

static VALUE
rb_stat_dev_major(self)
    VALUE self;
{
#if defined(major)
    long dev = get_stat(self)->st_dev;
    return ULONG2NUM(major(dev));
#else
    return Qnil;
#endif
}


dev_minor (File::Stat)

/*
 *  call-seq:
 *     stat.dev_minor   => fixnum
 *
 *  Returns the minor part of <code>File_Stat#dev</code> or
 *  <code>nil</code>.
 *
 *     File.stat("/dev/fd1").dev_minor   #=> 1
 *     File.stat("/dev/tty").dev_minor   #=> 0
 */

static VALUE
rb_stat_dev_minor(self)
    VALUE self;
{
#if defined(minor)
    long dev = get_stat(self)->st_dev;
    return ULONG2NUM(minor(dev));
#else
    return Qnil;
#endif
}


ino (File::Stat)

/*
 *  call-seq:
 *     stat.ino   => fixnum
 *
 *  Returns the inode number for <i>stat</i>.
 *
 *     File.stat("testfile").ino   #=> 1083669
 *
 */

static VALUE
rb_stat_ino(self)
    VALUE self;
{
#ifdef HUGE_ST_INO
    return ULL2NUM(get_stat(self)->st_ino);
#else
    return ULONG2NUM(get_stat(self)->st_ino);
#endif
}


mode (File::Stat)

/*
 *  call-seq:
 *     stat.mode   => fixnum
 *
 *  Returns an integer representing the permission bits of
 *  <i>stat</i>. The meaning of the bits is platform dependent; on
 *  Unix systems, see <code>stat(2)</code>.
 *
 *     File.chmod(0644, "testfile")   #=> 1
 *     s = File.stat("testfile")
 *     sprintf("%o", s.mode)          #=> "100644"
 */

static VALUE
rb_stat_mode(self)
    VALUE self;
{
#ifdef __BORLANDC__
    return UINT2NUM((unsigned short)(get_stat(self)->st_mode));
#else
    return UINT2NUM(get_stat(self)->st_mode);
#endif
}


nlink (File::Stat)

/*
 *  call-seq:
 *     stat.nlink   => fixnum
 *
 *  Returns the number of hard links to <i>stat</i>.
 *
 *     File.stat("testfile").nlink             #=> 1
 *     File.link("testfile", "testfile.bak")   #=> 0
 *     File.stat("testfile").nlink             #=> 2
 *
 */

static VALUE
rb_stat_nlink(self)
    VALUE self;
{
    return UINT2NUM(get_stat(self)->st_nlink);
}


uid (File::Stat)

/*
 *  call-seq:
 *     stat.uid    => fixnum
 *
 *  Returns the numeric user id of the owner of <i>stat</i>.
 *
 *     File.stat("testfile").uid   #=> 501
 *
 */

static VALUE
rb_stat_uid(self)
    VALUE self;
{
    return UINT2NUM(get_stat(self)->st_uid);
}


gid (File::Stat)

/*
 *  call-seq:
 *     stat.gid   => fixnum
 *
 *  Returns the numeric group id of the owner of <i>stat</i>.
 *
 *     File.stat("testfile").gid   #=> 500
 *
 */

static VALUE
rb_stat_gid(self)
    VALUE self;
{
    return UINT2NUM(get_stat(self)->st_gid);
}


rdev (File::Stat)

/*
 *  call-seq:
 *     stat.rdev   =>  fixnum or nil
 *
 *  Returns an integer representing the device type on which
 *  <i>stat</i> resides. Returns <code>nil</code> if the operating
 *  system doesn't support this feature.
 *
 *     File.stat("/dev/fd1").rdev   #=> 513
 *     File.stat("/dev/tty").rdev   #=> 1280
 */

static VALUE
rb_stat_rdev(self)
    VALUE self;
{
#ifdef HAVE_ST_RDEV
    return ULONG2NUM(get_stat(self)->st_rdev);
#else
    return Qnil;
#endif
}


rdev_major (File::Stat)

/*
 *  call-seq:
 *     stat.rdev_major   => fixnum
 *
 *  Returns the major part of <code>File_Stat#rdev</code> or
 *  <code>nil</code>.
 *
 *     File.stat("/dev/fd1").rdev_major   #=> 2
 *     File.stat("/dev/tty").rdev_major   #=> 5
 */

static VALUE
rb_stat_rdev_major(self)
    VALUE self;
{
#if defined(HAVE_ST_RDEV) && defined(major)
    long rdev = get_stat(self)->st_rdev;
    return ULONG2NUM(major(rdev));
#else
    return Qnil;
#endif
}


rdev_minor (File::Stat)

/*
 *  call-seq:
 *     stat.rdev_minor   => fixnum
 *
 *  Returns the minor part of <code>File_Stat#rdev</code> or
 *  <code>nil</code>.
 *
 *     File.stat("/dev/fd1").rdev_minor   #=> 1
 *     File.stat("/dev/tty").rdev_minor   #=> 0
 */

static VALUE
rb_stat_rdev_minor(self)
    VALUE self;
{
#if defined(HAVE_ST_RDEV) && defined(minor)
    long rdev = get_stat(self)->st_rdev;
    return ULONG2NUM(minor(rdev));
#else
    return Qnil;
#endif
}


size (File::Stat)

/*
 *  call-seq:
 *     stat.size    => fixnum
 *
 *  Returns the size of <i>stat</i> in bytes.
 *
 *     File.stat("testfile").size   #=> 66
 */

static VALUE
rb_stat_size(self)
    VALUE self;
{
    return OFFT2NUM(get_stat(self)->st_size);
}


blksize (File::Stat)

/*
 *  call-seq:
 *     stat.blksize   => integer or nil
 *
 *  Returns the native file system's block size. Will return <code>nil</code>
 *  on platforms that don't support this information.
 *
 *     File.stat("testfile").blksize   #=> 4096
 *
 */

static VALUE
rb_stat_blksize(self)
    VALUE self;
{
#ifdef HAVE_ST_BLKSIZE
    return ULONG2NUM(get_stat(self)->st_blksize);
#else
    return Qnil;
#endif
}


blocks (File::Stat)

/*
 *  call-seq:
 *     stat.blocks    => integer or nil
 *
 *  Returns the number of native file system blocks allocated for this
 *  file, or <code>nil</code> if the operating system doesn't
 *  support this feature.
 *
 *     File.stat("testfile").blocks   #=> 2
 */

static VALUE
rb_stat_blocks(self)
    VALUE self;
{
#ifdef HAVE_ST_BLOCKS
    return ULONG2NUM(get_stat(self)->st_blocks);
#else
    return Qnil;
#endif
}


atime (File::Stat)

/*
 *  call-seq:
 *     stat.atime   => time
 *
 *  Returns the last access time for this file as an object of class
 *  <code>Time</code>.
 *
 *     File.stat("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969
 *
 */

static VALUE
rb_stat_atime(self)
    VALUE self;
{
    return rb_time_new(get_stat(self)->st_atime, 0);
}


mtime (File::Stat)

/*
 *  call-seq:
 *     stat.mtime -> aTime
 *
 *  Returns the modification time of <i>stat</i>.
 *
 *     File.stat("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003
 *
 */

static VALUE
rb_stat_mtime(self)
    VALUE self;
{
    return rb_time_new(get_stat(self)->st_mtime, 0);
}


ctime (File::Stat)

/*
 *  call-seq:
 *     stat.ctime -> aTime
 *
 *  Returns the change time for <i>stat</i> (that is, the time
 *  directory information about the file was changed, not the file
 *  itself).
 *
 *     File.stat("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003
 *
 */

static VALUE
rb_stat_ctime(self)
    VALUE self;
{
    return rb_time_new(get_stat(self)->st_ctime, 0);
}


inspect (File::Stat)

/*
 * call-seq:
 *   stat.inspect  =>  string
 *
 * Produce a nicely formatted description of <i>stat</i>.
 *
 *   File.stat("/etc/passwd").inspect
 *      #=> "#<File::Stat dev=0xe000005, ino=1078078, mode=0100644,
 *           nlink=1, uid=0, gid=0, rdev=0x0, size=1374, blksize=4096,
 *           blocks=8, atime=Wed Dec 10 10:16:12 CST 2003,
 *           mtime=Fri Sep 12 15:41:41 CDT 2003,
 *           ctime=Mon Oct 27 11:20:27 CST 2003>"
 */

static VALUE
rb_stat_inspect(self)
    VALUE self;
{
    VALUE str;
    int i;
    static const struct {
        const char *name;
        VALUE (*func)_((VALUE));
    } member[] = {
        {"dev",            rb_stat_dev},
        {"ino",            rb_stat_ino},
        {"mode",    rb_stat_mode},
        {"nlink",   rb_stat_nlink},
        {"uid",            rb_stat_uid},
        {"gid",            rb_stat_gid},
        {"rdev",    rb_stat_rdev},
        {"size",    rb_stat_size},
        {"blksize", rb_stat_blksize},
        {"blocks",  rb_stat_blocks},
        {"atime",   rb_stat_atime},
        {"mtime",   rb_stat_mtime},
        {"ctime",   rb_stat_ctime},
    };

    str = rb_str_buf_new2("#<");
    rb_str_buf_cat2(str, rb_obj_classname(self));
    rb_str_buf_cat2(str, " ");

    for (i = 0; i < sizeof(member)/sizeof(member[0]); i++) {
        VALUE v;

        if (i > 0) {
            rb_str_buf_cat2(str, ", ");
        }
        rb_str_buf_cat2(str, member[i].name);
        rb_str_buf_cat2(str, "=");
        v = (*member[i].func)(self);
        if (i == 2) {          /* mode */
            char buf[32];

            sprintf(buf, "0%lo", NUM2ULONG(v));
            rb_str_buf_cat2(str, buf);
        }
        else if (i == 0 || i == 6) { /* dev/rdev */
            char buf[32];

            sprintf(buf, "0x%lx", NUM2ULONG(v));
            rb_str_buf_cat2(str, buf);
        }
        else {
            rb_str_append(str, rb_inspect(v));
        }
    }
    rb_str_buf_cat2(str, ">");
    OBJ_INFECT(str, self);

    return str;
}


ftype (File::Stat)

/*
 *  call-seq:
 *     stat.ftype   => string
 *
 *  Identifies the type of <i>stat</i>. The return string is one of:
 *  ``<code>file</code>'', ``<code>directory</code>'',
 *  ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
 *  ``<code>fifo</code>'', ``<code>link</code>'',
 *  ``<code>socket</code>'', or ``<code>unknown</code>''.
 *
 *     File.stat("/dev/tty").ftype   #=> "characterSpecial"
 *
 */

static VALUE
rb_stat_ftype(obj)
    VALUE obj;
{
    return rb_file_ftype(get_stat(obj));
}


directory? (File::Stat)

/*
 *  call-seq:
 *     stat.directory?   => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is a directory,
 *  <code>false</code> otherwise.
 *
 *     File.stat("testfile").directory?   #=> false
 *     File.stat(".").directory?          #=> true
 */

static VALUE
rb_stat_d(obj)
    VALUE obj;
{
    if (S_ISDIR(get_stat(obj)->st_mode)) return Qtrue;
    return Qfalse;
}


readable? (File::Stat)

/*
 *  call-seq:
 *     stat.readable?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is readable by the
 *  effective user id of this process.
 *
 *     File.stat("testfile").readable?   #=> true
 *
 */

static VALUE
rb_stat_r(obj)
    VALUE obj;
{
    struct stat *st = get_stat(obj);

#ifdef USE_GETEUID
    if (geteuid() == 0) return Qtrue;
#endif
#ifdef S_IRUSR
    if (rb_stat_owned(obj))
        return st->st_mode & S_IRUSR ? Qtrue : Qfalse;
#endif
#ifdef S_IRGRP
    if (rb_stat_grpowned(obj))
        return st->st_mode & S_IRGRP ? Qtrue : Qfalse;
#endif
#ifdef S_IROTH
    if (!(st->st_mode & S_IROTH)) return Qfalse;
#endif
    return Qtrue;
}


readable_real? (File::Stat)

/*
 *  call-seq:
 *     stat.readable_real? -> true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is readable by the real
 *  user id of this process.
 *
 *     File.stat("testfile").readable_real?   #=> true
 *
 */

static VALUE
rb_stat_R(obj)
    VALUE obj;
{
    struct stat *st = get_stat(obj);

#ifdef USE_GETEUID
    if (getuid() == 0) return Qtrue;
#endif
#ifdef S_IRUSR
    if (rb_stat_rowned(obj))
        return st->st_mode & S_IRUSR ? Qtrue : Qfalse;
#endif
#ifdef S_IRGRP
    if (group_member(get_stat(obj)->st_gid))
        return st->st_mode & S_IRGRP ? Qtrue : Qfalse;
#endif
#ifdef S_IROTH
    if (!(st->st_mode & S_IROTH)) return Qfalse;
#endif
    return Qtrue;
}


writable? (File::Stat)

/*
 *  call-seq:
 *     stat.writable? -> true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is writable by the
 *  effective user id of this process.
 *
 *     File.stat("testfile").writable?   #=> true
 *
 */

static VALUE
rb_stat_w(obj)
    VALUE obj;
{
    struct stat *st = get_stat(obj);

#ifdef USE_GETEUID
    if (geteuid() == 0) return Qtrue;
#endif
#ifdef S_IWUSR
    if (rb_stat_owned(obj))
        return st->st_mode & S_IWUSR ? Qtrue : Qfalse;
#endif
#ifdef S_IWGRP
    if (rb_stat_grpowned(obj))
        return st->st_mode & S_IWGRP ? Qtrue : Qfalse;
#endif
#ifdef S_IWOTH
    if (!(st->st_mode & S_IWOTH)) return Qfalse;
#endif
    return Qtrue;
}


writable_real? (File::Stat)

/*
 *  call-seq:
 *     stat.writable_real? -> true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is writable by the real
 *  user id of this process.
 *
 *     File.stat("testfile").writable_real?   #=> true
 *
 */

static VALUE
rb_stat_W(obj)
    VALUE obj;
{
    struct stat *st = get_stat(obj);

#ifdef USE_GETEUID
    if (getuid() == 0) return Qtrue;
#endif
#ifdef S_IWUSR
    if (rb_stat_rowned(obj))
        return st->st_mode & S_IWUSR ? Qtrue : Qfalse;
#endif
#ifdef S_IWGRP
    if (group_member(get_stat(obj)->st_gid))
        return st->st_mode & S_IWGRP ? Qtrue : Qfalse;
#endif
#ifdef S_IWOTH
    if (!(st->st_mode & S_IWOTH)) return Qfalse;
#endif
    return Qtrue;
}


executable? (File::Stat)

/*
 *  call-seq:
 *     stat.executable?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is executable or if the
 *  operating system doesn't distinguish executable files from
 *  nonexecutable files. The tests are made using the effective owner of
 *  the process.
 *
 *     File.stat("testfile").executable?   #=> false
 *
 */

static VALUE
rb_stat_x(obj)
    VALUE obj;
{
    struct stat *st = get_stat(obj);

#ifdef USE_GETEUID
    if (geteuid() == 0) {
        return st->st_mode & S_IXUGO ? Qtrue : Qfalse;
    }
#endif
#ifdef S_IXUSR
    if (rb_stat_owned(obj))
        return st->st_mode & S_IXUSR ? Qtrue : Qfalse;
#endif
#ifdef S_IXGRP
    if (rb_stat_grpowned(obj))
        return st->st_mode & S_IXGRP ? Qtrue : Qfalse;
#endif
#ifdef S_IXOTH
    if (!(st->st_mode & S_IXOTH)) return Qfalse;
#endif
    return Qtrue;
}


executable_real? (File::Stat)

/*
 *  call-seq:
 *     stat.executable_real?    => true or false
 *
 *  Same as <code>executable?</code>, but tests using the real owner of
 *  the process.
 */

static VALUE
rb_stat_X(obj)
    VALUE obj;
{
    struct stat *st = get_stat(obj);

#ifdef USE_GETEUID
    if (getuid() == 0) {
        return st->st_mode & S_IXUGO ? Qtrue : Qfalse;
    }
#endif
#ifdef S_IXUSR
    if (rb_stat_rowned(obj))
        return st->st_mode & S_IXUSR ? Qtrue : Qfalse;
#endif
#ifdef S_IXGRP
    if (group_member(get_stat(obj)->st_gid))
        return st->st_mode & S_IXGRP ? Qtrue : Qfalse;
#endif
#ifdef S_IXOTH
    if (!(st->st_mode & S_IXOTH)) return Qfalse;
#endif
    return Qtrue;
}


file? (File::Stat)

/*
 *  call-seq:
 *     stat.file?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is a regular file (not
 *  a device file, pipe, socket, etc.).
 *
 *     File.stat("testfile").file?   #=> true
 *
 */

static VALUE
rb_stat_f(obj)
    VALUE obj;
{
    if (S_ISREG(get_stat(obj)->st_mode)) return Qtrue;
    return Qfalse;
}


zero? (File::Stat)

/*
 *  call-seq:
 *     stat.zero?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is a zero-length file;
 *  <code>false</code> otherwise.
 *
 *     File.stat("testfile").zero?   #=> false
 *
 */

static VALUE
rb_stat_z(obj)
    VALUE obj;
{
    if (get_stat(obj)->st_size == 0) return Qtrue;
    return Qfalse;
}


size? (File::Stat)

/*
 *  call-seq:
 *     state.size    => integer
 *
 *  Returns the size of <i>stat</i> in bytes.
 *
 *     File.stat("testfile").size   #=> 66
 *
 */

static VALUE
rb_stat_s(obj)
    VALUE obj;
{
    off_t size = get_stat(obj)->st_size;

    if (size == 0) return Qnil;
    return OFFT2NUM(size);
}


owned? (File::Stat)

/*
 *  call-seq:
 *     stat.owned?    => true or false
 *
 *  Returns <code>true</code> if the effective user id of the process is
 *  the same as the owner of <i>stat</i>.
 *
 *     File.stat("testfile").owned?      #=> true
 *     File.stat("/etc/passwd").owned?   #=> false
 *
 */

static VALUE
rb_stat_owned(obj)
    VALUE obj;
{
    if (get_stat(obj)->st_uid == geteuid()) return Qtrue;
    return Qfalse;
}


grpowned? (File::Stat)

/*
 *  call-seq:
 *     stat.grpowned?   => true or false
 *
 *  Returns true if the effective group id of the process is the same as
 *  the group id of <i>stat</i>. On Windows NT, returns <code>false</code>.
 *
 *     File.stat("testfile").grpowned?      #=> true
 *     File.stat("/etc/passwd").grpowned?   #=> false
 *
 */

static VALUE
rb_stat_grpowned(obj)
    VALUE obj;
{
#ifndef _WIN32
    if (group_member(get_stat(obj)->st_gid)) return Qtrue;
#endif
    return Qfalse;
}


pipe? (File::Stat)

/*
 *  call-seq:
 *     stat.pipe?    => true or false
 *
 *  Returns <code>true</code> if the operating system supports pipes and
 *  <i>stat</i> is a pipe; <code>false</code> otherwise.
 */

static VALUE
rb_stat_p(obj)
    VALUE obj;
{
#ifdef S_IFIFO
    if (S_ISFIFO(get_stat(obj)->st_mode)) return Qtrue;

#endif
    return Qfalse;
}


symlink? (File::Stat)

/*
 *  call-seq:
 *     stat.symlink?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is a symbolic link,
 *  <code>false</code> if it isn't or if the operating system doesn't
 *  support this feature. As <code>File::stat</code> automatically
 *  follows symbolic links, <code>symlink?</code> will always be
 *  <code>false</code> for an object returned by
 *  <code>File::stat</code>.
 *
 *     File.symlink("testfile", "alink")   #=> 0
 *     File.stat("alink").symlink?         #=> false
 *     File.lstat("alink").symlink?        #=> true
 *
 */

static VALUE
rb_stat_l(obj)
    VALUE obj;
{
#ifdef S_ISLNK
    if (S_ISLNK(get_stat(obj)->st_mode)) return Qtrue;
#endif
    return Qfalse;
}


socket? (File::Stat)

/*
 *  call-seq:
 *     stat.socket?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> is a socket,
 *  <code>false</code> if it isn't or if the operating system doesn't
 *  support this feature.
 *
 *     File.stat("testfile").socket?   #=> false
 *
 */

static VALUE
rb_stat_S(obj)
    VALUE obj;
{
#ifdef S_ISSOCK
    if (S_ISSOCK(get_stat(obj)->st_mode)) return Qtrue;

#endif
    return Qfalse;
}


blockdev? (File::Stat)

/*
 *  call-seq:
 *     stat.blockdev?   => true or false
 *
 *  Returns <code>true</code> if the file is a block device,
 *  <code>false</code> if it isn't or if the operating system doesn't
 *  support this feature.
 *
 *     File.stat("testfile").blockdev?    #=> false
 *     File.stat("/dev/hda1").blockdev?   #=> true
 *
 */

static VALUE
rb_stat_b(obj)
    VALUE obj;
{
#ifdef S_ISBLK
    if (S_ISBLK(get_stat(obj)->st_mode)) return Qtrue;

#endif
    return Qfalse;
}


chardev? (File::Stat)

/*
 *  call-seq:
 *     stat.chardev?    => true or false
 *
 *  Returns <code>true</code> if the file is a character device,
 *  <code>false</code> if it isn't or if the operating system doesn't
 *  support this feature.
 *
 *     File.stat("/dev/tty").chardev?   #=> true
 *
 */

static VALUE
rb_stat_c(obj)
    VALUE obj;
{
    if (S_ISCHR(get_stat(obj)->st_mode)) return Qtrue;

    return Qfalse;
}


setuid? (File::Stat)

/*
 *  call-seq:
 *     stat.setuid?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> has the set-user-id
 *  permission bit set, <code>false</code> if it doesn't or if the
 *  operating system doesn't support this feature.
 *
 *     File.stat("/bin/su").setuid?   #=> true
 */

static VALUE
rb_stat_suid(obj)
    VALUE obj;
{
#ifdef S_ISUID
    if (get_stat(obj)->st_mode & S_ISUID) return Qtrue;
#endif
    return Qfalse;
}


setgid? (File::Stat)

/*
 *  call-seq:
 *     stat.setgid?   => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> has the set-group-id
 *  permission bit set, <code>false</code> if it doesn't or if the
 *  operating system doesn't support this feature.
 *
 *     File.stat("/usr/sbin/lpc").setgid?   #=> true
 *
 */

static VALUE
rb_stat_sgid(obj)
    VALUE obj;
{
#ifdef S_ISGID
    if (get_stat(obj)->st_mode & S_ISGID) return Qtrue;
#endif
    return Qfalse;
}


sticky? (File::Stat)

/*
 *  call-seq:
 *     stat.sticky?    => true or false
 *
 *  Returns <code>true</code> if <i>stat</i> has its sticky bit set,
 *  <code>false</code> if it doesn't or if the operating system doesn't
 *  support this feature.
 *
 *     File.stat("testfile").sticky?   #=> false
 *
 */

static VALUE
rb_stat_sticky(obj)
    VALUE obj;
{
#ifdef S_ISVTX
    if (get_stat(obj)->st_mode & S_ISVTX) return Qtrue;
#endif
    return Qfalse;
}


pretty_print (File::Stat)

# File lib/pp.rb, line 362
    def pretty_print(q)
      require 'etc.so'
      q.object_group(self) {
        q.breakable
        q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
        q.text "ino="; q.pp self.ino; q.comma_breakable
        q.group {
          m = self.mode
          q.text sprintf("mode=0%o", m)
          q.breakable
          q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
            self.ftype,
            (m & 0400 == 0 ? ?- : ?r),
            (m & 0200 == 0 ? ?- : ?w),
            (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
                             (m & 04000 == 0 ? ?x : ?s)),
            (m & 0040 == 0 ? ?- : ?r),
            (m & 0020 == 0 ? ?- : ?w),
            (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
                             (m & 02000 == 0 ? ?x : ?s)),
            (m & 0004 == 0 ? ?- : ?r),
            (m & 0002 == 0 ? ?- : ?w),
            (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
                             (m & 01000 == 0 ? ?x : ?t)))
        }
        q.comma_breakable
        q.text "nlink="; q.pp self.nlink; q.comma_breakable
        q.group {
          q.text "uid="; q.pp self.uid
          begin
            pw = Etc.getpwuid(self.uid)
          rescue ArgumentError
          end
          if pw
            q.breakable; q.text "(#{pw.name})"
          end
        }
        q.comma_breakable
        q.group {
          q.text "gid="; q.pp self.gid
          begin
            gr = Etc.getgrgid(self.gid)
          rescue ArgumentError
          end
          if gr
            q.breakable; q.text "(#{gr.name})"
          end
        }
        q.comma_breakable
        q.group {
          q.text sprintf("rdev=0x%x", self.rdev)
          q.breakable
          q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
        }
        q.comma_breakable
        q.text "size="; q.pp self.size; q.comma_breakable
        q.text "blksize="; q.pp self.blksize; q.comma_breakable
        q.text "blocks="; q.pp self.blocks; q.comma_breakable
        q.group {
          t = self.atime
          q.text "atime="; q.pp t
          q.breakable; q.text "(#{t.tv_sec})"
        }
        q.comma_breakable
        q.group {
          t = self.mtime
          q.text "mtime="; q.pp t
          q.breakable; q.text "(#{t.tv_sec})"
        }
        q.comma_breakable
        q.group {
          t = self.ctime
          q.text "ctime="; q.pp t
          q.breakable; q.text "(#{t.tv_sec})"
        }
      }
    end


stat (File)

/*
 *  call-seq:
 *     File.stat(file_name)   =>  stat
 *
 *  Returns a <code>File::Stat</code> object for the named file (see
 *  <code>File::Stat</code>).
 *
 *     File.stat("testfile").mtime   #=> Tue Apr 08 12:58:04 CDT 2003
 *
 */

static VALUE
rb_file_s_stat(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    SafeStringValue(fname);
    if (rb_stat(fname, &st) < 0) {
        rb_sys_fail(StringValueCStr(fname));
    }
    return stat_new(&st);
}


lstat (File)

/*
 *  call-seq:
 *     File.lstat(file_name)   => stat
 *
 *  Same as <code>File::stat</code>, but does not follow the last symbolic
 *  link. Instead, reports on the link itself.
 *
 *     File.symlink("testfile", "link2test")   #=> 0
 *     File.stat("testfile").size              #=> 66
 *     File.lstat("link2test").size            #=> 8
 *     File.stat("link2test").size             #=> 66
 *
 */

static VALUE
rb_file_s_lstat(klass, fname)
    VALUE klass, fname;
{
#ifdef HAVE_LSTAT
    struct stat st;

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) == -1) {
        rb_sys_fail(RSTRING(fname)->ptr);
    }
    return stat_new(&st);
#else
    return rb_file_s_stat(klass, fname);
#endif
}


ftype (File)

/*
 *  call-seq:
 *     File.ftype(file_name)   => string
 *
 *  Identifies the type of the named file; the return string is one of
 *  ``<code>file</code>'', ``<code>directory</code>'',
 *  ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
 *  ``<code>fifo</code>'', ``<code>link</code>'',
 *  ``<code>socket</code>'', or ``<code>unknown</code>''.
 *
 *     File.ftype("testfile")            #=> "file"
 *     File.ftype("/dev/tty")            #=> "characterSpecial"
 *     File.ftype("/tmp/.X11-unix/X0")   #=> "socket"
 */

static VALUE
rb_file_s_ftype(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) == -1) {
        rb_sys_fail(RSTRING(fname)->ptr);
    }

    return rb_file_ftype(&st);
}


atime (File)

/*
 *  call-seq:
 *     File.atime(file_name)  =>  time
 *
 *  Returns the last access time for the named file as a Time object).
 *
 *     File.atime("testfile")   #=> Wed Apr 09 08:51:48 CDT 2003
 *
 */

static VALUE
rb_file_s_atime(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(StringValueCStr(fname));
    return rb_time_new(st.st_atime, 0);
}


mtime (File)

/*
 *  call-seq:
 *     File.mtime(file_name)  =>  time
 *
 *  Returns the modification time for the named file as a Time object.
 *
 *     File.mtime("testfile")   #=> Tue Apr 08 12:58:04 CDT 2003
 *
 */

static VALUE
rb_file_s_mtime(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(RSTRING(fname)->ptr);
    return rb_time_new(st.st_mtime, 0);
}


ctime (File)

/*
 *  call-seq:
 *     File.ctime(file_name)  => time
 *
 *  Returns the change time for the named file (the time at which
 *  directory information about the file was changed, not the file
 *  itself).
 *
 *     File.ctime("testfile")   #=> Wed Apr 09 08:53:13 CDT 2003
 *
 */

static VALUE
rb_file_s_ctime(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(RSTRING(fname)->ptr);
    return rb_time_new(st.st_ctime, 0);
}


utime (File)

/*
 * call-seq:
 *  File.utime(atime, mtime, file_name,...)   =>  integer
 *
 * Sets the access and modification times of each
 * named file to the first two arguments. Returns
 * the number of file names in the argument list.
 */

static VALUE
rb_file_s_utime(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE atime, mtime, rest;
    struct timeval tvs[2], *tvp = NULL;
    long n;

    rb_scan_args(argc, argv, "2*", &atime, &mtime, &rest);

    if (!NIL_P(atime) || !NIL_P(mtime)) {
        tvp = tvs;
        tvp[0] = rb_time_timeval(atime);
        tvp[1] = rb_time_timeval(mtime);
    }

    n = apply2files(utime_internal, rest, tvp);
    return LONG2FIX(n);
}


chmod (File)

/*
 *  call-seq:
 *     File.chmod(mode_int, file_name, ... ) -> integer
 *
 *  Changes permission bits on the named file(s) to the bit pattern
 *  represented by <i>mode_int</i>. Actual effects are operating system
 *  dependent (see the beginning of this section). On Unix systems, see
 *  <code>chmod(2)</code> for details. Returns the number of files
 *  processed.
 *
 *     File.chmod(0644, "testfile", "out")   #=> 2
 */

static VALUE
rb_file_s_chmod(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE vmode;
    VALUE rest;
    int mode;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "1*", &vmode, &rest);
    mode = NUM2INT(vmode);

    n = apply2files(chmod_internal, rest, &mode);
    return LONG2FIX(n);
}


chown (File)

/*
 *  call-seq:
 *     File.chown(owner_int, group_int, file_name,... ) -> integer
 *
 *  Changes the owner and group of the named file(s) to the given
 *  numeric owner and group id's. Only a process with superuser
 *  privileges may change the owner of a file. The current owner of a
 *  file may change the file's group to any group to which the owner
 *  belongs. A <code>nil</code> or -1 owner or group id is ignored.
 *  Returns the number of files processed.
 *
 *     File.chown(nil, 100, "testfile")
 *
 */

static VALUE
rb_file_s_chown(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE o, g, rest;
    struct chown_args arg;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "2*", &o, &g, &rest);
    if (NIL_P(o)) {
        arg.owner = -1;
    }
    else {
        arg.owner = NUM2INT(o);
    }
    if (NIL_P(g)) {
        arg.group = -1;
    }
    else {
        arg.group = NUM2INT(g);
    }

    n = apply2files(chown_internal, rest, &arg);
    return LONG2FIX(n);
}


lchmod (File)

/*
 *  call-seq:
 *     File.lchmod(mode_int, file_name, ...)  => integer
 *
 *  Equivalent to <code>File::chmod</code>, but does not follow symbolic
 *  links (so it will change the permissions associated with the link,
 *  not the file referenced by the link). Often not available.
 *
 */

static VALUE
rb_file_s_lchmod(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE vmode;
    VALUE rest;
    long mode, n;

    rb_secure(2);
    rb_scan_args(argc, argv, "1*", &vmode, &rest);
    mode = NUM2INT(vmode);

    n = apply2files(lchmod_internal, rest, (void *)(long)mode);
    return LONG2FIX(n);
}


lchown (File)

/*
 *  call-seq:
 *     file.lchown(owner_int, group_int, file_name,..) => integer
 *
 *  Equivalent to <code>File::chown</code>, but does not follow symbolic
 *  links (so it will change the owner associated with the link, not the
 *  file referenced by the link). Often not available. Returns number
 *  of files in the argument list.
 *
 */

static VALUE
rb_file_s_lchown(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE o, g, rest;
    struct chown_args arg;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "2*", &o, &g, &rest);
    if (NIL_P(o)) {
        arg.owner = -1;
    }
    else {
        arg.owner = NUM2INT(o);
    }
    if (NIL_P(g)) {
        arg.group = -1;
    }
    else {
        arg.group = NUM2INT(g);
    }

    n = apply2files(lchown_internal, rest, &arg);
    return LONG2FIX(n);
}


link (File)

/*
 *  call-seq:
 *     File.link(old_name, new_name)    => 0
 *
 *  Creates a new name for an existing file using a hard link. Will not
 *  overwrite <i>new_name</i> if it already exists (raising a subclass
 *  of <code>SystemCallError</code>). Not available on all platforms.
 *
 *     File.link("testfile", ".testfile")   #=> 0
 *     IO.readlines(".testfile")[0]         #=> "This is line one\n"
 */

static VALUE
rb_file_s_link(klass, from, to)
    VALUE klass, from, to;
{
#ifdef HAVE_LINK
    SafeStringValue(from);
    SafeStringValue(to);

    if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
        sys_fail2(from, to);
    }
    return INT2FIX(0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


symlink (File)

/*
 *  call-seq:
 *     File.symlink(old_name, new_name)   => 0
 *
 *  Creates a symbolic link called <i>new_name</i> for the existing file
 *  <i>old_name</i>. Raises a <code>NotImplemented</code> exception on
 *  platforms that do not support symbolic links.
 *
 *     File.symlink("testfile", "link2test")   #=> 0
 *
 */

static VALUE
rb_file_s_symlink(klass, from, to)
    VALUE klass, from, to;
{
#ifdef HAVE_SYMLINK
    SafeStringValue(from);
    SafeStringValue(to);

    if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
        sys_fail2(from, to);
    }
    return INT2FIX(0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


readlink (File)

/*
 *  call-seq:
 *     File.readlink(link_name) -> file_name
 *
 *  Returns the name of the file referenced by the given link.
 *  Not available on all platforms.
 *
 *     File.symlink("testfile", "link2test")   #=> 0
 *     File.readlink("link2test")              #=> "testfile"
 */

static VALUE
rb_file_s_readlink(klass, path)
    VALUE klass, path;
{
#ifdef HAVE_READLINK
    char *buf;
    int size = 100;
    int rv;
    VALUE v;

    SafeStringValue(path);
    buf = xmalloc(size);
    while ((rv = readlink(RSTRING(path)->ptr, buf, size)) == size
#ifdef _AIX
            || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
#endif
        ) {
        size *= 2;
        buf = xrealloc(buf, size);
    }
    if (rv < 0) {
        free(buf);
        rb_sys_fail(RSTRING(path)->ptr);
    }
    v = rb_tainted_str_new(buf, rv);
    free(buf);

    return v;
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


unlink (File)

/*
 *  call-seq:
 *     File.delete(file_name, ...)  => integer
 *     File.unlink(file_name, ...)  => integer
 *
 *  Deletes the named files, returning the number of names
 *  passed as arguments. Raises an exception on any error.
 *  See also <code>Dir::rmdir</code>.
 */

static VALUE
rb_file_s_unlink(klass, args)
    VALUE klass, args;
{
    long n;

    rb_secure(2);
    n = apply2files(unlink_internal, args, 0);
    return LONG2FIX(n);
}


delete (File)

/*
 *  call-seq:
 *     File.delete(file_name, ...)  => integer
 *     File.unlink(file_name, ...)  => integer
 *
 *  Deletes the named files, returning the number of names
 *  passed as arguments. Raises an exception on any error.
 *  See also <code>Dir::rmdir</code>.
 */

static VALUE
rb_file_s_unlink(klass, args)
    VALUE klass, args;
{
    long n;

    rb_secure(2);
    n = apply2files(unlink_internal, args, 0);
    return LONG2FIX(n);
}


rename (File)

/*
 *  call-seq:
 *     File.rename(old_name, new_name)   => 0
 *
 *  Renames the given file to the new name. Raises a
 *  <code>SystemCallError</code> if the file cannot be renamed.
 *
 *     File.rename("afile", "afile.bak")   #=> 0
 */

static VALUE
rb_file_s_rename(klass, from, to)
    VALUE klass, from, to;
{
    const char *src, *dst;
    SafeStringValue(from);
    SafeStringValue(to);

    src = StringValueCStr(from);
    dst = StringValueCStr(to);
#if defined __CYGWIN__
    errno = 0;
#endif
    if (rename(src, dst) < 0) {
#if defined DOSISH && !defined _WIN32
        switch (errno) {
          case EEXIST:
#if defined (__EMX__)
          case EACCES:
#endif
            if (chmod(dst, 0666) == 0 &&
                unlink(dst) == 0 &&
                rename(src, dst) == 0)
                return INT2FIX(0);
        }
#endif
        sys_fail2(from, to);
    }

    return INT2FIX(0);
}


umask (File)

/*
 *  call-seq:
 *     File.umask()          => integer
 *     File.umask(integer)   => integer
 *
 *  Returns the current umask value for this process. If the optional
 *  argument is given, set the umask to that value and return the
 *  previous value. Umask values are <em>subtracted</em> from the
 *  default permissions, so a umask of <code>0222</code> would make a
 *  file read-only for everyone.
 *
 *     File.umask(0006)   #=> 18
 *     File.umask         #=> 6
 */

static VALUE
rb_file_s_umask(argc, argv)
    int argc;
    VALUE *argv;
{
    int omask = 0;

    rb_secure(2);
    if (argc == 0) {
        omask = umask(0);
        umask(omask);
    }
    else if (argc == 1) {
        omask = umask(NUM2INT(argv[0]));
    }
    else {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    return INT2FIX(omask);
}


truncate (File)

/*
 *  call-seq:
 *     File.truncate(file_name, integer)  => 0
 *
 *  Truncates the file <i>file_name</i> to be at most <i>integer</i>
 *  bytes long. Not available on all platforms.
 *
 *     f = File.new("out", "w")
 *     f.write("1234567890")     #=> 10
 *     f.close                   #=> nil
 *     File.truncate("out", 5)   #=> 0
 *     File.size("out")          #=> 5
 *
 */

static VALUE
rb_file_s_truncate(klass, path, len)
    VALUE klass, path, len;
{
    off_t pos;

    rb_secure(2);
    pos = NUM2OFFT(len);
    SafeStringValue(path);

#ifdef HAVE_TRUNCATE
    if (truncate(StringValueCStr(path), pos) < 0)
        rb_sys_fail(RSTRING(path)->ptr);
#else
# ifdef HAVE_CHSIZE
    {
        int tmpfd;

#  ifdef _WIN32
        if ((tmpfd = open(StringValueCStr(path), O_RDWR)) < 0) {
            rb_sys_fail(RSTRING(path)->ptr);
        }
#  else
        if ((tmpfd = open(StringValueCStr(path), 0)) < 0) {
            rb_sys_fail(RSTRING(path)->ptr);
        }
#  endif
        if (chsize(tmpfd, pos) < 0) {
            close(tmpfd);
            rb_sys_fail(RSTRING(path)->ptr);
        }
        close(tmpfd);
    }
# else
    rb_notimplement();
# endif
#endif
    return INT2FIX(0);
}


expand_path (File)

/*
 *  call-seq:
 *     File.expand_path(file_name [, dir_string] ) -> abs_file_name
 *
 *  Converts a pathname to an absolute pathname. Relative paths are
 *  referenced from the current working directory of the process unless
 *  <i>dir_string</i> is given, in which case it will be used as the
 *  starting point. The given pathname may start with a
 *  ``<code>~</code>'', which expands to the process owner's home
 *  directory (the environment variable <code>HOME</code> must be set
 *  correctly). ``<code>~</code><i>user</i>'' expands to the named
 *  user's home directory.
 *
 *     File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"
 *     File.expand_path("../../bin", "/tmp/x")   #=> "/bin"
 */

VALUE
rb_file_s_expand_path(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, dname;

    if (argc == 1) {
        return rb_file_expand_path(argv[0], Qnil);
    }
    rb_scan_args(argc, argv, "11", &fname, &dname);

    return rb_file_expand_path(fname, dname);
}


basename (File)

/*
 *  call-seq:
 *     File.basename(file_name [, suffix] ) -> base_name
 *
 *  Returns the last component of the filename given in <i>file_name</i>,
 *  which must be formed using forward slashes (``<code>/</code>'')
 *  regardless of the separator used on the local file system. If
 *  <i>suffix</i> is given and present at the end of <i>file_name</i>,
 *  it is removed.
 *
 *     File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
 *     File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"
 */

static VALUE
rb_file_s_basename(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, fext, basename;
    char *name, *p;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
    char *root;
#endif
    int f;

    if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
        StringValue(fext);
    }
    StringValue(fname);
    if (RSTRING(fname)->len == 0 || !*(name = RSTRING(fname)->ptr))
        return fname;
    name = skipprefix(name);
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
    root = name;
#endif
    while (isdirsep(*name))
        name++;
    if (!*name) {
        p = name - 1;
        f = 1;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
        if (name != root) {
            /* has slashes */
        }
#ifdef DOSISH_DRIVE_LETTER
        else if (*p == ':') {
            p++;
            f = 0;
        }
#endif
#ifdef DOSISH_UNC
        else {
            p = "/";
        }
#endif
#endif
    }
    else if (!(p = strrdirsep(name))) {
        if (NIL_P(fext) || !(f = rmext(name, StringValueCStr(fext)))) {
            f = chompdirsep(name) - name;
            if (f == RSTRING(fname)->len) return fname;
        }
        p = name;
    }
    else {
        while (isdirsep(*p)) p++; /* skip last / */
        if (NIL_P(fext) || !(f = rmext(p, StringValueCStr(fext)))) {
            f = chompdirsep(p) - p;
        }
    }
    basename = rb_str_new(p, f);
    OBJ_INFECT(basename, fname);
    return basename;
}


dirname (File)

/*
 *  call-seq:
 *     File.dirname(file_name ) -> dir_name
 *
 *  Returns all components of the filename given in <i>file_name</i>
 *  except the last one. The filename must be formed using forward
 *  slashes (``<code>/</code>'') regardless of the separator used on the
 *  local file system.
 *
 *     File.dirname("/home/gumby/work/ruby.rb")   #=> "/home/gumby/work"
 */

static VALUE
rb_file_s_dirname(klass, fname)
    VALUE klass, fname;
{
    const char *name, *root, *p;
    VALUE dirname;

    name = StringValueCStr(fname);
    root = skiproot(name);
#ifdef DOSISH_UNC
    if (root > name + 1 && isdirsep(*name))
        root = skipprefix(name = root - 2);
#else
    if (root > name + 1)
        name = root - 1;
#endif
    p = strrdirsep(root);
    if (!p) {
        p = root;
    }
    if (p == name)
        return rb_str_new2(".");
#ifdef DOSISH_DRIVE_LETTER
    if (has_drive_letter(name) && isdirsep(*(name + 2))) {
        const char *top = skiproot(name + 2);
        dirname = rb_str_new(name, 3);
        rb_str_cat(dirname, top, p - top);
    }
    else
#endif
    dirname = rb_str_new(name, p - name);
#ifdef DOSISH_DRIVE_LETTER
    if (has_drive_letter(name) && root == name + 2 && p - name == 2)
        rb_str_cat(dirname, ".", 1);
#endif
    OBJ_INFECT(dirname, fname);
    return dirname;
}


extname (File)

/*
 *  call-seq:
 *     File.extname(path) -> string
 *
 *  Returns the extension (the portion of file name in <i>path</i>
 *  after the period).
 *
 *     File.extname("test.rb")         #=> ".rb"
 *     File.extname("a/b/d/test.rb")   #=> ".rb"
 *     File.extname("test")            #=> ""
 *     File.extname(".profile")        #=> ""
 *
 */

static VALUE
rb_file_s_extname(klass, fname)
    VALUE klass, fname;
{
    char *name, *p, *e;
    VALUE extname;

    name = StringValueCStr(fname);
    p = strrdirsep(name);       /* get the last path component */
    if (!p)
        p = name;
    else
        p++;

     e = strrchr(p, '.');       /* get the last dot of the last component */
     if (!e || e == p || !e[1]) /* no dot, or the only dot is first or end? */
         return rb_str_new2("");
     extname = rb_str_new(e, chompdirsep(e) - e);       /* keep the dot, too! */
     OBJ_INFECT(extname, fname);
     return extname;
}


split (File)

/*
 *  call-seq:
 *     File.split(file_name)   => array
 *
 *  Splits the given string into a directory and a file component and
 *  returns them in a two-element array. See also
 *  <code>File::dirname</code> and <code>File::basename</code>.
 *
 *     File.split("/home/gumby/.profile")   #=> ["/home/gumby", ".profile"]
 */

static VALUE
rb_file_s_split(klass, path)
    VALUE klass, path;
{
    StringValue(path);          /* get rid of converting twice */
    return rb_assoc_new(rb_file_s_dirname(Qnil, path), rb_file_s_basename(1,&path));
}


join (File)

/*
 *  call-seq:
 *     File.join(string, ...) -> path
 *
 *  Returns a new string formed by joining the strings using
 *  <code>File::SEPARATOR</code>.
 *
 *     File.join("usr", "mail", "gumby")   #=> "usr/mail/gumby"
 *
 */

static VALUE
rb_file_s_join(klass, args)
    VALUE klass, args;
{
    return rb_file_join(args, separator);
}


lstat (File)

/*
 *  call-seq:
 *     file.lstat   =>  stat
 *
 *  Same as <code>IO#stat</code>, but does not follow the last symbolic
 *  link. Instead, reports on the link itself.
 *
 *     File.symlink("testfile", "link2test")   #=> 0
 *     File.stat("testfile").size              #=> 66
 *     f = File.new("link2test")
 *     f.lstat.size                            #=> 8
 *     f.stat.size                             #=> 66
 */

static VALUE
rb_file_lstat(obj)
    VALUE obj;
{
#ifdef HAVE_LSTAT
    OpenFile *fptr;
    struct stat st;

    rb_secure(2);
    GetOpenFile(obj, fptr);
    if (!fptr->path) return Qnil;
    if (lstat(fptr->path, &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return stat_new(&st);
#else
    return rb_io_stat(obj);
#endif
}


atime (File)

/*
 *  call-seq:
 *     file.atime    => time
 *
 *  Returns the last access time (a <code>Time</code> object)
 *   for <i>file</i>, or epoch if <i>file</i> has not been accessed.
 *
 *     File.new("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969
 *
 */

static VALUE
rb_file_atime(obj)
    VALUE obj;
{
    OpenFile *fptr;
    struct stat st;

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return rb_time_new(st.st_atime, 0);
}


mtime (File)

/*
 *  call-seq:
 *     file.mtime -> time
 *
 *  Returns the modification time for <i>file</i>.
 *
 *     File.new("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003
 *
 */

static VALUE
rb_file_mtime(obj)
    VALUE obj;
{
    OpenFile *fptr;
    struct stat st;

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return rb_time_new(st.st_mtime, 0);
}


ctime (File)

/*
 *  call-seq:
 *     file.ctime -> time
 *
 *  Returns the change time for <i>file</i> (that is, the time directory
 *  information about the file was changed, not the file itself).
 *
 *     File.new("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003
 *
 */

static VALUE
rb_file_ctime(obj)
    VALUE obj;
{
    OpenFile *fptr;
    struct stat st;

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return rb_time_new(st.st_ctime, 0);
}


chmod (File)

/*
 *  call-seq:
 *     file.chmod(mode_int)   => 0
 *
 *  Changes permission bits on <i>file</i> to the bit pattern
 *  represented by <i>mode_int</i>. Actual effects are platform
 *  dependent; on Unix systems, see <code>chmod(2)</code> for details.
 *  Follows symbolic links. Also see <code>File#lchmod</code>.
 *
 *     f = File.new("out", "w");
 *     f.chmod(0644)   #=> 0
 */

static VALUE
rb_file_chmod(obj, vmode)
    VALUE obj, vmode;
{
    OpenFile *fptr;
    int mode;

    rb_secure(2);
    mode = NUM2INT(vmode);

    GetOpenFile(obj, fptr);
#ifdef HAVE_FCHMOD
    if (fchmod(fileno(fptr->f), mode) == -1)
        rb_sys_fail(fptr->path);
#else
    if (!fptr->path) return Qnil;
    if (chmod(fptr->path, mode) == -1)
        rb_sys_fail(fptr->path);
#endif

    return INT2FIX(0);
}


chown (File)

/*
 *  call-seq:
 *     file.chown(owner_int, group_int )   => 0
 *
 *  Changes the owner and group of <i>file</i> to the given numeric
 *  owner and group id's. Only a process with superuser privileges may
 *  change the owner of a file. The current owner of a file may change
 *  the file's group to any group to which the owner belongs. A
 *  <code>nil</code> or -1 owner or group id is ignored. Follows
 *  symbolic links. See also <code>File#lchown</code>.
 *
 *     File.new("testfile").chown(502, 1000)
 *
 */

static VALUE
rb_file_chown(obj, owner, group)
    VALUE obj, owner, group;
{
    OpenFile *fptr;
    int o, g;

    rb_secure(2);
    o = NIL_P(owner) ? -1 : NUM2INT(owner);
    g = NIL_P(group) ? -1 : NUM2INT(group);
    GetOpenFile(obj, fptr);
#if defined(DJGPP) || defined(__CYGWIN32__) || defined(_WIN32) || defined(__EMX__)
    if (!fptr->path) return Qnil;
    if (chown(fptr->path, o, g) == -1)
        rb_sys_fail(fptr->path);
#else
    if (fchown(fileno(fptr->f), o, g) == -1)
        rb_sys_fail(fptr->path);
#endif

    return INT2FIX(0);
}


truncate (File)

/*
 *  call-seq:
 *     file.truncate(integer)    => 0
 *
 *  Truncates <i>file</i> to at most <i>integer</i> bytes. The file
 *  must be opened for writing. Not available on all platforms.
 *
 *     f = File.new("out", "w")
 *     f.syswrite("1234567890")   #=> 10
 *     f.truncate(5)              #=> 0
 *     f.close()                  #=> nil
 *     File.size("out")           #=> 5
 */

static VALUE
rb_file_truncate(obj, len)
    VALUE obj, len;
{
    OpenFile *fptr;
    FILE *f;
    off_t pos;

    rb_secure(2);
    pos = NUM2OFFT(len);
    GetOpenFile(obj, fptr);
    if (!(fptr->mode & FMODE_WRITABLE)) {
        rb_raise(rb_eIOError, "not opened for writing");
    }
    f = GetWriteFile(fptr);
    fflush(f);
    fseeko(f, (off_t)0, SEEK_CUR);
#ifdef HAVE_TRUNCATE
    if (ftruncate(fileno(f), pos) < 0)
        rb_sys_fail(fptr->path);
#else
# ifdef HAVE_CHSIZE
    if (chsize(fileno(f), pos) < 0)
        rb_sys_fail(fptr->path);
# else
    rb_notimplement();
# endif
#endif
    return INT2FIX(0);
}


flock (File)

/*
 *  call-seq:
 *     file.flock (locking_constant ) =>  0 or false
 *
 *  Locks or unlocks a file according to <i>locking_constant</i> (a
 *  logical <em>or</em> of the values in the table below).
 *  Returns <code>false</code> if <code>File::LOCK_NB</code> is
 *  specified and the operation would otherwise have blocked. Not
 *  available on all platforms.
 *
 *  Locking constants (in class File):
 *
 *     LOCK_EX   | Exclusive lock. Only one process may hold an
 *               | exclusive lock for a given file at a time.
 *     ----------+------------------------------------------------
 *     LOCK_NB   | Don't block when locking. May be combined
 *               | with other lock options using logical or.
 *     ----------+------------------------------------------------
 *     LOCK_SH   | Shared lock. Multiple processes may each hold a
 *               | shared lock for a given file at the same time.
 *     ----------+------------------------------------------------
 *     LOCK_UN   | Unlock.
 *
 *  Example:
 *
 *     File.new("testfile").flock(File::LOCK_UN)   #=> 0
 *
 */

static VALUE
rb_file_flock(obj, operation)
    VALUE obj;
    VALUE operation;
{
#ifndef __CHECKER__
    OpenFile *fptr;
    int op;

    rb_secure(2);
    op = NUM2INT(operation);
    GetOpenFile(obj, fptr);

    if (fptr->mode & FMODE_WRITABLE) {
        fflush(GetWriteFile(fptr));
    }
  retry:
    if (flock(fileno(fptr->f), op) < 0) {
        switch (errno) {
          case EAGAIN:
          case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
          case EWOULDBLOCK:
#endif
              return Qfalse;
          case EINTR:
#if defined(ERESTART)
          case ERESTART:
#endif
            goto retry;
        }
        rb_sys_fail(fptr->path);
    }
#endif
    return INT2FIX(0);
}


path (File)

/*
 *  call-seq:
 *     file.path -> filename
 *
 *  Returns the pathname used to create <i>file</i> as a string. Does
 *  not normalize the name.
 *
 *     File.new("testfile").path               #=> "testfile"
 *     File.new("/tmp/../tmp/xxx", "w").path   #=> "/tmp/../tmp/xxx"
 *
 */

static VALUE
rb_file_path(obj)
    VALUE obj;
{
    OpenFile *fptr;

    fptr = RFILE(rb_io_taint_check(obj))->fptr;
    rb_io_check_initialized(fptr);
    if (!fptr->path) return Qnil;
    return rb_tainted_str_new2(fptr->path);
}


directory? (File)

/*
 * call-seq:
 *   File.directory?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a directory,
 * <code>false</code> otherwise.
 *
 *    File.directory?(".")
 */

static VALUE
test_d(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISDIR
#   define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
#endif

    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISDIR(st.st_mode)) return Qtrue;
    return Qfalse;
}


exist? (File)

/*
 * call-seq:
 *    File.exist?(file_name)    =>  true or false
 *    File.exists?(file_name)   =>  true or false    (obsolete)
 *
 * Return <code>true</code> if the named file exists.
 */

static VALUE
test_e(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    return Qtrue;
}


exists? (File)

/*
 * call-seq:
 *    File.exist?(file_name)    =>  true or false
 *    File.exists?(file_name)   =>  true or false    (obsolete)
 *
 * Return <code>true</code> if the named file exists.
 */

static VALUE
test_e(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    return Qtrue;
}


readable? (File)

/*
 * call-seq:
 *    File.readable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is readable by the effective
 * user id of this process.
 */

static VALUE
test_r(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), R_OK) < 0) return Qfalse;
    return Qtrue;
}


readable_real? (File)

/*
 * call-seq:
 *    File.readable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is readable by the real
 * user id of this process.
 */

static VALUE
test_R(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), R_OK) < 0) return Qfalse;
    return Qtrue;
}


writable? (File)

/*
 * call-seq:
 *    File.writable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is writable by the effective
 * user id of this process.
 */

static VALUE
test_w(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), W_OK) < 0) return Qfalse;
    return Qtrue;
}


writable_real? (File)

/*
 * call-seq:
 *    File.writable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is writable by the real
 * user id of this process.
 */

static VALUE
test_W(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), W_OK) < 0) return Qfalse;
    return Qtrue;
}


executable? (File)

/*
 * call-seq:
 *    File.executable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is executable by the effective
 * user id of this process.
 */

static VALUE
test_x(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), X_OK) < 0) return Qfalse;
    return Qtrue;
}


executable_real? (File)

/*
 * call-seq:
 *    File.executable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is executable by the real
 * user id of this process.
 */

static VALUE
test_X(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), X_OK) < 0) return Qfalse;
    return Qtrue;
}


file? (File)

/*
 * call-seq:
 *    File.file?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and is a
 * regular file.
 */

static VALUE
test_f(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISREG(st.st_mode)) return Qtrue;
    return Qfalse;
}


zero? (File)

/*
 * call-seq:
 *    File.zero?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and has
 * a zero size.
 */

static VALUE
test_z(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (st.st_size == 0) return Qtrue;
    return Qfalse;
}


size? (File)

/*
 * call-seq:
 *    File.size?(file_name)   => Integer or nil
 *
 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
 * file otherwise.
 */

static VALUE
test_s(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qnil;
    if (st.st_size == 0) return Qnil;
    return OFFT2NUM(st.st_size);
}


size (File)

/*
 * call-seq:
 *    File.size(file_name)   => integer
 *
 * Returns the size of <code>file_name</code>.
 */

static VALUE
rb_file_s_size(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(StringValueCStr(fname));
    return OFFT2NUM(st.st_size);
}


owned? (File)

/*
 * call-seq:
 *    File.owned?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and the
 * effective used id of the calling process is the owner of
 * the file.
 */

static VALUE
test_owned(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (st.st_uid == geteuid()) return Qtrue;
    return Qfalse;
}


grpowned? (File)

/*
 * call-seq:
 *    File.grpowned?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and the
 * effective group id of the calling process is the owner of
 * the file. Returns <code>false</code> on Windows.
 */

static VALUE
test_grpowned(obj, fname)
    VALUE obj, fname;
{
#ifndef _WIN32
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (group_member(st.st_gid)) return Qtrue;
#endif
    return Qfalse;
}


pipe? (File)

/*
 * call-seq:
 *   File.pipe?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a pipe.
 */

static VALUE
test_p(obj, fname)
    VALUE obj, fname;
{
#ifdef S_IFIFO
#  ifndef S_ISFIFO
#    define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO)
#  endif

    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISFIFO(st.st_mode)) return Qtrue;

#endif
    return Qfalse;
}


symlink? (File)

/*
 * call-seq:
 *   File.symlink?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a symbolic link.
 */

static VALUE
test_l(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISLNK
#  ifdef _S_ISLNK
#    define S_ISLNK(m) _S_ISLNK(m)
#  elif defined __BORLANDC__
#    ifdef _S_IFLNK
#      define S_ISLNK(m) (((unsigned short)(m) & S_IFMT) == _S_IFLNK)
#    else
#      ifdef S_IFLNK
#        define S_ISLNK(m) (((unsigned short)(m) & S_IFMT) == S_IFLNK)
#      endif
#    endif
#  else
#    ifdef _S_IFLNK
#      define S_ISLNK(m) ((m & S_IFMT) == _S_IFLNK)
#    else
#      ifdef S_IFLNK
#        define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
#      endif
#    endif
#  endif
#endif

#ifdef S_ISLNK
    struct stat st;

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) < 0) return Qfalse;
    if (S_ISLNK(st.st_mode)) return Qtrue;
#endif

    return Qfalse;
}


socket? (File)

/*
 * call-seq:
 *   File.socket?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a socket.
 */

static VALUE
test_S(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISSOCK
#  ifdef _S_ISSOCK
#    define S_ISSOCK(m) _S_ISSOCK(m)
#  elif defined __BORLANDC__
#    ifdef _S_IFSOCK
#      define S_ISSOCK(m) (((unsigned short)(m) & S_IFMT) == _S_IFSOCK)
#    else
#      ifdef S_IFSOCK
#        define S_ISSOCK(m) (((unsigned short)(m) & S_IFMT) == S_IFSOCK)
#      endif
#    endif
#  else
#    ifdef _S_IFSOCK
#      define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
#    else
#      ifdef S_IFSOCK
#        define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
#      endif
#    endif
#  endif
#endif

#ifdef S_ISSOCK
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISSOCK(st.st_mode)) return Qtrue;

#endif
    return Qfalse;
}


blockdev? (File)

/*
 * call-seq:
 *   File.blockdev?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a block device.
 */

static VALUE
test_b(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISBLK
#   ifdef S_IFBLK
#       define S_ISBLK(m) ((m & S_IFMT) == S_IFBLK)
#   else
#       define S_ISBLK(m) (0)  /* anytime false */
#   endif
#endif

#ifdef S_ISBLK
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISBLK(st.st_mode)) return Qtrue;

#endif
    return Qfalse;
}


chardev? (File)

/*
 * call-seq:
 *   File.chardev?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a character device.
 */
static VALUE
test_c(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISCHR
#   define S_ISCHR(m) ((m & S_IFMT) == S_IFCHR)
#endif

    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISCHR(st.st_mode)) return Qtrue;

    return Qfalse;
}


setuid? (File)

/*
 * call-seq:
 *   File.setuid?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the setuid bit set.
 */

static VALUE
test_suid(obj, fname)
    VALUE obj, fname;
{
#ifdef S_ISUID
    return check3rdbyte(fname, S_ISUID);
#else
    return Qfalse;
#endif
}


setgid? (File)

/*
 * call-seq:
 *   File.setgid?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the setgid bit set.
 */

static VALUE
test_sgid(obj, fname)
    VALUE obj, fname;
{
#ifdef S_ISGID
    return check3rdbyte(fname, S_ISGID);
#else
    return Qfalse;
#endif
}


sticky? (File)

/*
 * call-seq:
 *   File.sticky?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the sticky bit set.
 */

static VALUE
test_sticky(obj, fname)
    VALUE obj, fname;
{
#ifdef S_ISVTX
    return check3rdbyte(fname, S_ISVTX);
#else
    return Qnil;
#endif
}


identical? (File)

/*
 * call-seq:
 *   File.identical?(file_1, file_2)   =>  true or false
 *
 * Returns <code>true</code> if the named files are identical.
 *
 *     open("a", "w") {}
 *     p File.identical?("a", "a")      #=> true
 *     p File.identical?("a", "./a")    #=> true
 *     File.link("a", "b")
 *     p File.identical?("a", "b")      #=> true
 *     File.symlink("a", "c")
 *     p File.identical?("a", "c")      #=> true
 *     open("d", "w") {}
 *     p File.identical?("a", "d")      #=> false
 */

static VALUE
test_identical(obj, fname1, fname2)
    VALUE obj, fname1, fname2;
{
#ifndef DOSISH
    struct stat st1, st2;

    if (rb_stat(fname1, &st1) < 0) return Qfalse;
    if (rb_stat(fname2, &st2) < 0) return Qfalse;
    if (st1.st_dev != st2.st_dev) return Qfalse;
    if (st1.st_ino != st2.st_ino) return Qfalse;
#else
#ifdef _WIN32
    BY_HANDLE_FILE_INFORMATION st1, st2;
    HANDLE f1 = 0, f2 = 0;
#endif

    rb_secure(2);
#ifdef _WIN32
    f1 = w32_io_info(&fname1, &st1);
    if (f1 == INVALID_HANDLE_VALUE) return Qfalse;
    f2 = w32_io_info(&fname2, &st2);
    if (f1) CloseHandle(f1);
    if (f2 == INVALID_HANDLE_VALUE) return Qfalse;
    if (f2) CloseHandle(f2);

    if (st1.dwVolumeSerialNumber == st2.dwVolumeSerialNumber &&
        st1.nFileIndexHigh == st2.nFileIndexHigh &&
        st1.nFileIndexLow == st2.nFileIndexLow)
        return Qtrue;
    if (!f1 || !f2) return Qfalse;
    if (rb_w32_iswin95()) return Qfalse;
#else
    SafeStringValue(fname1);
    fname1 = rb_str_new4(fname1);
    SafeStringValue(fname2);
    if (access(RSTRING(fname1)->ptr, 0)) return Qfalse;
    if (access(RSTRING(fname2)->ptr, 0)) return Qfalse;
#endif
    fname1 = rb_file_expand_path(fname1, Qnil);
    fname2 = rb_file_expand_path(fname2, Qnil);
    if (RSTRING(fname1)->len != RSTRING(fname2)->len) return Qfalse;
    if (rb_memcicmp(RSTRING(fname1)->ptr, RSTRING(fname2)->ptr, RSTRING(fname1)->len))
        return Qfalse;
#endif
    return Qtrue;
}


new (File)

/*
 *  call-seq:
 *     File.new(filename, mode="r")            => file
 *     File.new(filename [, mode [, perm]])    => file
 *

 *  Opens the file named by _filename_ according to
 *  _mode_ (default is ``r'') and returns a new
 *  <code>File</code> object. See the description of class +IO+ for
 *  a description of _mode_. The file mode may optionally be
 *  specified as a +Fixnum+ by _or_-ing together the
 *  flags (O_RDONLY etc, again described under +IO+). Optional
 *  permission bits may be given in _perm_. These mode and permission
 *  bits are platform dependent; on Unix systems, see
 *  <code>open(2)</code> for details.
 *
 *     f = File.new("testfile", "r")
 *     f = File.new("newfile",  "w+")
 *     f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
 */

static VALUE
rb_file_initialize(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    if (RFILE(io)->fptr) {
        rb_raise(rb_eRuntimeError, "reinitializing File");
    }
    if (0 < argc && argc < 3) {
        VALUE fd = rb_check_convert_type(argv[0], T_FIXNUM, "Fixnum", "to_int");

        if (!NIL_P(fd)) {
            argv[0] = fd;
            return rb_io_initialize(argc, argv, io);
        }
    }
    rb_open_file(argc, argv, io);

    return io;
}


fnmatch (File)

/*
 *  call-seq:
 *     File.fnmatch( pattern, path, [flags] ) => (true or false)
 *     File.fnmatch?( pattern, path, [flags] ) => (true or false)
 *
 *  Returns true if <i>path</i> matches against <i>pattern</i> The
 *  pattern is not a regular expression; instead it follows rules
 *  similar to shell filename globbing. It may contain the following
 *  metacharacters:
 *
 *  <code>*</code>::        Matches any file. Can be restricted by
 *                          other values in the glob. <code>*</code>
 *                          will match all files; <code>c*</code> will
 *                          match all files beginning with
 *                          <code>c</code>; <code>*c</code> will match
 *                          all files ending with <code>c</code>; and
 *                          <code>*c*</code> will match all files that
 *                          have <code>c</code> in them (including at
 *                          the beginning or end). Equivalent to
 *                          <code>/ .* /x</code> in regexp.
 *  <code>**</code>::       Matches directories recursively or files
 *                          expansively.
 *  <code>?</code>::        Matches any one character. Equivalent to
 *                          <code>/.{1}/</code> in regexp.
 *  <code>[set]</code>::    Matches any one character in +set+.
 *                          Behaves exactly like character sets in
 *                          Regexp, including set negation
 *                          (<code>[^a-z]</code>).
 *  <code>\</code>::        Escapes the next metacharacter.
 *
 *  <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
 *  parameters. The same glob pattern and flags are used by
 *  <code>Dir::glob</code>.
 *
 *     File.fnmatch('cat',       'cat')        #=> true  : match entire string
 *     File.fnmatch('cat',       'category')   #=> false : only match partial string
 *     File.fnmatch('c{at,ub}s', 'cats')       #=> false : { } isn't supported
 *
 *     File.fnmatch('c?t',     'cat')          #=> true  : '?' match only 1 character
 *     File.fnmatch('c??t',    'cat')          #=> false : ditto
 *     File.fnmatch('c*',      'cats')         #=> true  : '*' match 0 or more characters
 *     File.fnmatch('c*t',     'c/a/b/t')      #=> true  : ditto
 *     File.fnmatch('ca[a-z]', 'cat')          #=> true  : inclusive bracket expression
 *     File.fnmatch('ca[^t]',  'cat')          #=> false : exclusive bracket expression ('^' or '!')
 *
 *     File.fnmatch('cat', 'CAT')                     #=> false : case sensitive
 *     File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true  : case insensitive
 *
 *     File.fnmatch('?',   '/', File::FNM_PATHNAME)  #=> false : wildcard doesn't match '/' on FNM_PATHNAME
 *     File.fnmatch('*',   '/', File::FNM_PATHNAME)  #=> false : ditto
 *     File.fnmatch('[/]', '/', File::FNM_PATHNAME)  #=> false : ditto
 *
 *     File.fnmatch('\?',   '?')                       #=> true  : escaped wildcard becomes ordinary
 *     File.fnmatch('\a',   'a')                       #=> true  : escaped ordinary remains ordinary
 *     File.fnmatch('\a',   '\a', File::FNM_NOESCAPE)  #=> true  : FNM_NOESACPE makes '\' ordinary
 *     File.fnmatch('[\?]', '?')                       #=> true  : can escape inside bracket expression
 *
 *     File.fnmatch('*',   '.profile')                      #=> false : wildcard doesn't match leading
 *     File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)  #=> true    period by default.
 *     File.fnmatch('.*',  '.profile')                      #=> true
 *
 *     rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
 *     File.fnmatch(rbfiles, 'main.rb')                    #=> false
 *     File.fnmatch(rbfiles, './main.rb')                  #=> false
 *     File.fnmatch(rbfiles, 'lib/song.rb')                #=> true
 *     File.fnmatch('**.rb', 'main.rb')                    #=> true
 *     File.fnmatch('**.rb', './main.rb')                  #=> false
 *     File.fnmatch('**.rb', 'lib/song.rb')                #=> true
 *     File.fnmatch('*',           'dave/.profile')                      #=> true
 *
 *     pattern = '*' '/' '*'
 *     File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME)  #=> false
 *     File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
 *
 *     pattern = '**' '/' 'foo'
 *     File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME)     #=> true
 *     File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME)    #=> true
 *     File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME)  #=> true
 *     File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME)    #=> false
 *     File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
 */
static VALUE
file_s_fnmatch(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE pattern, path;
    VALUE rflags;
    int flags;

    if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
        flags = NUM2INT(rflags);
    else
        flags = 0;

    StringValue(pattern);
    StringValue(path);

    if (fnmatch(RSTRING(pattern)->ptr, RSTRING(path)->ptr, flags) == 0)
        return Qtrue;

    return Qfalse;
}


fnmatch? (File)

/*
 *  call-seq:
 *     File.fnmatch( pattern, path, [flags] ) => (true or false)
 *     File.fnmatch?( pattern, path, [flags] ) => (true or false)
 *
 *  Returns true if <i>path</i> matches against <i>pattern</i> The
 *  pattern is not a regular expression; instead it follows rules
 *  similar to shell filename globbing. It may contain the following
 *  metacharacters:
 *
 *  <code>*</code>::        Matches any file. Can be restricted by
 *                          other values in the glob. <code>*</code>
 *                          will match all files; <code>c*</code> will
 *                          match all files beginning with
 *                          <code>c</code>; <code>*c</code> will match
 *                          all files ending with <code>c</code>; and
 *                          <code>*c*</code> will match all files that
 *                          have <code>c</code> in them (including at
 *                          the beginning or end). Equivalent to
 *                          <code>/ .* /x</code> in regexp.
 *  <code>**</code>::       Matches directories recursively or files
 *                          expansively.
 *  <code>?</code>::        Matches any one character. Equivalent to
 *                          <code>/.{1}/</code> in regexp.
 *  <code>[set]</code>::    Matches any one character in +set+.
 *                          Behaves exactly like character sets in
 *                          Regexp, including set negation
 *                          (<code>[^a-z]</code>).
 *  <code>\</code>::        Escapes the next metacharacter.
 *
 *  <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
 *  parameters. The same glob pattern and flags are used by
 *  <code>Dir::glob</code>.
 *
 *     File.fnmatch('cat',       'cat')        #=> true  : match entire string
 *     File.fnmatch('cat',       'category')   #=> false : only match partial string
 *     File.fnmatch('c{at,ub}s', 'cats')       #=> false : { } isn't supported
 *
 *     File.fnmatch('c?t',     'cat')          #=> true  : '?' match only 1 character
 *     File.fnmatch('c??t',    'cat')          #=> false : ditto
 *     File.fnmatch('c*',      'cats')         #=> true  : '*' match 0 or more characters
 *     File.fnmatch('c*t',     'c/a/b/t')      #=> true  : ditto
 *     File.fnmatch('ca[a-z]', 'cat')          #=> true  : inclusive bracket expression
 *     File.fnmatch('ca[^t]',  'cat')          #=> false : exclusive bracket expression ('^' or '!')
 *
 *     File.fnmatch('cat', 'CAT')                     #=> false : case sensitive
 *     File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true  : case insensitive
 *
 *     File.fnmatch('?',   '/', File::FNM_PATHNAME)  #=> false : wildcard doesn't match '/' on FNM_PATHNAME
 *     File.fnmatch('*',   '/', File::FNM_PATHNAME)  #=> false : ditto
 *     File.fnmatch('[/]', '/', File::FNM_PATHNAME)  #=> false : ditto
 *
 *     File.fnmatch('\?',   '?')                       #=> true  : escaped wildcard becomes ordinary
 *     File.fnmatch('\a',   'a')                       #=> true  : escaped ordinary remains ordinary
 *     File.fnmatch('\a',   '\a', File::FNM_NOESCAPE)  #=> true  : FNM_NOESACPE makes '\' ordinary
 *     File.fnmatch('[\?]', '?')                       #=> true  : can escape inside bracket expression
 *
 *     File.fnmatch('*',   '.profile')                      #=> false : wildcard doesn't match leading
 *     File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)  #=> true    period by default.
 *     File.fnmatch('.*',  '.profile')                      #=> true
 *
 *     rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
 *     File.fnmatch(rbfiles, 'main.rb')                    #=> false
 *     File.fnmatch(rbfiles, './main.rb')                  #=> false
 *     File.fnmatch(rbfiles, 'lib/song.rb')                #=> true
 *     File.fnmatch('**.rb', 'main.rb')                    #=> true
 *     File.fnmatch('**.rb', './main.rb')                  #=> false
 *     File.fnmatch('**.rb', 'lib/song.rb')                #=> true
 *     File.fnmatch('*',           'dave/.profile')                      #=> true
 *
 *     pattern = '*' '/' '*'
 *     File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME)  #=> false
 *     File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
 *
 *     pattern = '**' '/' 'foo'
 *     File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME)     #=> true
 *     File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME)    #=> true
 *     File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME)  #=> true
 *     File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME)    #=> false
 *     File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
 */
static VALUE
file_s_fnmatch(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE pattern, path;
    VALUE rflags;
    int flags;

    if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
        flags = NUM2INT(rflags);
    else
        flags = 0;

    StringValue(pattern);
    StringValue(path);

    if (fnmatch(RSTRING(pattern)->ptr, RSTRING(path)->ptr, flags) == 0)
        return Qtrue;

    return Qfalse;
}


catname (File)

# File lib/ftools.rb, line 44
  def catname(from, to)
    if directory? to
      join to.sub(%r([/\\]$), ''), basename(from)
    else
      to
    end
  end


syscopy (File)

# File lib/ftools.rb, line 56
  def syscopy(from, to)
    to = catname(from, to)

    fmode = stat(from).mode
    tpath = to
    not_exist = !exist?(tpath)

    from = open(from, "rb")
    to = open(to, "wb")

    begin
      while true
        to.syswrite from.sysread(BUFSIZE)
      end
    rescue EOFError
      ret = true
    rescue
      ret = false
    ensure
      to.close
      from.close
    end
    chmod(fmode, tpath) if not_exist
    ret
  end


copy (File)

# File lib/ftools.rb, line 87
  def copy(from, to, verbose = false)
    $stderr.print from, " -> ", catname(from, to), "\n" if verbose
    syscopy from, to
  end


move (File)

# File lib/ftools.rb, line 99
  def move(from, to, verbose = false)
    to = catname(from, to)
    $stderr.print from, " -> ", to, "\n" if verbose

    if RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/ and file? to
      unlink to
    end
    fstat = stat(from)
    begin
      rename from, to
    rescue
      begin
        symlink readlink(from), to and unlink from
      rescue
        from_stat = stat(from)
        syscopy from, to and unlink from
        utime(from_stat.atime, from_stat.mtime, to)
        begin
          chown(fstat.uid, fstat.gid, to)
        rescue
        end
      end
    end
  end


compare (File)

# File lib/ftools.rb, line 130
  def compare(from, to, verbose = false)
    $stderr.print from, " <=> ", to, "\n" if verbose

    return false if stat(from).size != stat(to).size

    from = open(from, "rb")
    to = open(to, "rb")

    ret = false
    fr = tr = ''

    begin
      while fr == tr
        fr = from.read(BUFSIZE)
        if fr
          tr = to.read(fr.size)
        else
          ret = to.read(BUFSIZE)
          ret = !ret || ret.length == 0
          break
        end
      end
    rescue
      ret = false
    ensure
      to.close
      from.close
    end
    ret
  end


safe_unlink (File)

# File lib/ftools.rb, line 168
  def safe_unlink(*files)
    verbose = if files[-1].is_a? String then false else files.pop end
    files.each do |file|
      begin
        unlink file
        $stderr.print "removing ", file, "\n" if verbose
      rescue Errno::EACCES # for Windows
        continue if symlink? file
        begin
          mode = stat(file).mode
          o_chmod mode | 0200, file
          unlink file
          $stderr.print "removing ", file, "\n" if verbose
        rescue
          o_chmod mode, file rescue nil
        end
      rescue
      end
    end
  end


makedirs (File)

# File lib/ftools.rb, line 205
  def makedirs(*dirs)
    verbose = if dirs[-1].is_a? String then false else dirs.pop end
    mode = 0755
    for dir in dirs
      parent = dirname(dir)
      next if parent == dir or directory? dir
      makedirs parent unless directory? parent
      $stderr.print "mkdir ", dir, "\n" if verbose
      if basename(dir) != ""
        begin
          Dir.mkdir dir, mode
        rescue SystemCallError
          raise unless directory? dir
        end
      end
    end
  end


chmod (File)

# File lib/ftools.rb, line 237
  def chmod(mode, *files)
    verbose = if files[-1].is_a? String then false else files.pop end
    $stderr.printf "chmod %04o %s\n", mode, files.join(" ") if verbose
    o_chmod mode, *files
  end


install (File)

# File lib/ftools.rb, line 250
  def install(from, to, mode = nil, verbose = false)
    to = catname(from, to)
    unless exist? to and cmp from, to
      safe_unlink to if exist? to
      cp from, to, verbose
      chmod mode, to, verbose if mode
    end
  end


directory? (FileTest)

/*
 * call-seq:
 *   File.directory?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a directory,
 * <code>false</code> otherwise.
 *
 *    File.directory?(".")
 */

static VALUE
test_d(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISDIR
#   define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
#endif

    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISDIR(st.st_mode)) return Qtrue;
    return Qfalse;
}


exist? (FileTest)

/*
 * call-seq:
 *    File.exist?(file_name)    =>  true or false
 *    File.exists?(file_name)   =>  true or false    (obsolete)
 *
 * Return <code>true</code> if the named file exists.
 */

static VALUE
test_e(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    return Qtrue;
}


exists? (FileTest)

/*
 * call-seq:
 *    File.exist?(file_name)    =>  true or false
 *    File.exists?(file_name)   =>  true or false    (obsolete)
 *
 * Return <code>true</code> if the named file exists.
 */

static VALUE
test_e(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    return Qtrue;
}


readable? (FileTest)

/*
 * call-seq:
 *    File.readable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is readable by the effective
 * user id of this process.
 */

static VALUE
test_r(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), R_OK) < 0) return Qfalse;
    return Qtrue;
}


readable_real? (FileTest)

/*
 * call-seq:
 *    File.readable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is readable by the real
 * user id of this process.
 */

static VALUE
test_R(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), R_OK) < 0) return Qfalse;
    return Qtrue;
}


writable? (FileTest)

/*
 * call-seq:
 *    File.writable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is writable by the effective
 * user id of this process.
 */

static VALUE
test_w(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), W_OK) < 0) return Qfalse;
    return Qtrue;
}


writable_real? (FileTest)

/*
 * call-seq:
 *    File.writable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is writable by the real
 * user id of this process.
 */

static VALUE
test_W(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), W_OK) < 0) return Qfalse;
    return Qtrue;
}


executable? (FileTest)

/*
 * call-seq:
 *    File.executable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is executable by the effective
 * user id of this process.
 */

static VALUE
test_x(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), X_OK) < 0) return Qfalse;
    return Qtrue;
}


executable_real? (FileTest)

/*
 * call-seq:
 *    File.executable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is executable by the real
 * user id of this process.
 */

static VALUE
test_X(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), X_OK) < 0) return Qfalse;
    return Qtrue;
}


file? (FileTest)

/*
 * call-seq:
 *    File.file?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and is a
 * regular file.
 */

static VALUE
test_f(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISREG(st.st_mode)) return Qtrue;
    return Qfalse;
}


zero? (FileTest)

/*
 * call-seq:
 *    File.zero?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and has
 * a zero size.
 */

static VALUE
test_z(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (st.st_size == 0) return Qtrue;
    return Qfalse;
}


size? (FileTest)

/*
 * call-seq:
 *    File.size?(file_name)   => Integer or nil
 *
 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
 * file otherwise.
 */

static VALUE
test_s(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qnil;
    if (st.st_size == 0) return Qnil;
    return OFFT2NUM(st.st_size);
}


size (FileTest)

/*
 * call-seq:
 *    File.size(file_name)   => integer
 *
 * Returns the size of <code>file_name</code>.
 */

static VALUE
rb_file_s_size(klass, fname)
    VALUE klass, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(StringValueCStr(fname));
    return OFFT2NUM(st.st_size);
}


owned? (FileTest)

/*
 * call-seq:
 *    File.owned?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and the
 * effective used id of the calling process is the owner of
 * the file.
 */

static VALUE
test_owned(obj, fname)
    VALUE obj, fname;
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (st.st_uid == geteuid()) return Qtrue;
    return Qfalse;
}


grpowned? (FileTest)

/*
 * call-seq:
 *    File.grpowned?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and the
 * effective group id of the calling process is the owner of
 * the file. Returns <code>false</code> on Windows.
 */

static VALUE
test_grpowned(obj, fname)
    VALUE obj, fname;
{
#ifndef _WIN32
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (group_member(st.st_gid)) return Qtrue;
#endif
    return Qfalse;
}


pipe? (FileTest)

/*
 * call-seq:
 *   File.pipe?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a pipe.
 */

static VALUE
test_p(obj, fname)
    VALUE obj, fname;
{
#ifdef S_IFIFO
#  ifndef S_ISFIFO
#    define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO)
#  endif

    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISFIFO(st.st_mode)) return Qtrue;

#endif
    return Qfalse;
}


symlink? (FileTest)

/*
 * call-seq:
 *   File.symlink?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a symbolic link.
 */

static VALUE
test_l(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISLNK
#  ifdef _S_ISLNK
#    define S_ISLNK(m) _S_ISLNK(m)
#  elif defined __BORLANDC__
#    ifdef _S_IFLNK
#      define S_ISLNK(m) (((unsigned short)(m) & S_IFMT) == _S_IFLNK)
#    else
#      ifdef S_IFLNK
#        define S_ISLNK(m) (((unsigned short)(m) & S_IFMT) == S_IFLNK)
#      endif
#    endif
#  else
#    ifdef _S_IFLNK
#      define S_ISLNK(m) ((m & S_IFMT) == _S_IFLNK)
#    else
#      ifdef S_IFLNK
#        define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
#      endif
#    endif
#  endif
#endif

#ifdef S_ISLNK
    struct stat st;

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) < 0) return Qfalse;
    if (S_ISLNK(st.st_mode)) return Qtrue;
#endif

    return Qfalse;
}


socket? (FileTest)

/*
 * call-seq:
 *   File.socket?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a socket.
 */

static VALUE
test_S(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISSOCK
#  ifdef _S_ISSOCK
#    define S_ISSOCK(m) _S_ISSOCK(m)
#  elif defined __BORLANDC__
#    ifdef _S_IFSOCK
#      define S_ISSOCK(m) (((unsigned short)(m) & S_IFMT) == _S_IFSOCK)
#    else
#      ifdef S_IFSOCK
#        define S_ISSOCK(m) (((unsigned short)(m) & S_IFMT) == S_IFSOCK)
#      endif
#    endif
#  else
#    ifdef _S_IFSOCK
#      define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
#    else
#      ifdef S_IFSOCK
#        define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
#      endif
#    endif
#  endif
#endif

#ifdef S_ISSOCK
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISSOCK(st.st_mode)) return Qtrue;

#endif
    return Qfalse;
}


blockdev? (FileTest)

/*
 * call-seq:
 *   File.blockdev?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a block device.
 */

static VALUE
test_b(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISBLK
#   ifdef S_IFBLK
#       define S_ISBLK(m) ((m & S_IFMT) == S_IFBLK)
#   else
#       define S_ISBLK(m) (0)  /* anytime false */
#   endif
#endif

#ifdef S_ISBLK
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISBLK(st.st_mode)) return Qtrue;

#endif
    return Qfalse;
}


chardev? (FileTest)

/*
 * call-seq:
 *   File.chardev?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a character device.
 */
static VALUE
test_c(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISCHR
#   define S_ISCHR(m) ((m & S_IFMT) == S_IFCHR)
#endif

    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    if (S_ISCHR(st.st_mode)) return Qtrue;

    return Qfalse;
}


setuid? (FileTest)

/*
 * call-seq:
 *   File.setuid?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the setuid bit set.
 */

static VALUE
test_suid(obj, fname)
    VALUE obj, fname;
{
#ifdef S_ISUID
    return check3rdbyte(fname, S_ISUID);
#else
    return Qfalse;
#endif
}


setgid? (FileTest)

/*
 * call-seq:
 *   File.setgid?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the setgid bit set.
 */

static VALUE
test_sgid(obj, fname)
    VALUE obj, fname;
{
#ifdef S_ISGID
    return check3rdbyte(fname, S_ISGID);
#else
    return Qfalse;
#endif
}


sticky? (FileTest)

/*
 * call-seq:
 *   File.sticky?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the sticky bit set.
 */

static VALUE
test_sticky(obj, fname)
    VALUE obj, fname;
{
#ifdef S_ISVTX
    return check3rdbyte(fname, S_ISVTX);
#else
    return Qnil;
#endif
}


identical? (FileTest)

/*
 * call-seq:
 *   File.identical?(file_1, file_2)   =>  true or false
 *
 * Returns <code>true</code> if the named files are identical.
 *
 *     open("a", "w") {}
 *     p File.identical?("a", "a")      #=> true
 *     p File.identical?("a", "./a")    #=> true
 *     File.link("a", "b")
 *     p File.identical?("a", "b")      #=> true
 *     File.symlink("a", "c")
 *     p File.identical?("a", "c")      #=> true
 *     open("d", "w") {}
 *     p File.identical?("a", "d")      #=> false
 */

static VALUE
test_identical(obj, fname1, fname2)
    VALUE obj, fname1, fname2;
{
#ifndef DOSISH
    struct stat st1, st2;

    if (rb_stat(fname1, &st1) < 0) return Qfalse;
    if (rb_stat(fname2, &st2) < 0) return Qfalse;
    if (st1.st_dev != st2.st_dev) return Qfalse;
    if (st1.st_ino != st2.st_ino) return Qfalse;
#else
#ifdef _WIN32
    BY_HANDLE_FILE_INFORMATION st1, st2;
    HANDLE f1 = 0, f2 = 0;
#endif

    rb_secure(2);
#ifdef _WIN32
    f1 = w32_io_info(&fname1, &st1);
    if (f1 == INVALID_HANDLE_VALUE) return Qfalse;
    f2 = w32_io_info(&fname2, &st2);
    if (f1) CloseHandle(f1);
    if (f2 == INVALID_HANDLE_VALUE) return Qfalse;
    if (f2) CloseHandle(f2);

    if (st1.dwVolumeSerialNumber == st2.dwVolumeSerialNumber &&
        st1.nFileIndexHigh == st2.nFileIndexHigh &&
        st1.nFileIndexLow == st2.nFileIndexLow)
        return Qtrue;
    if (!f1 || !f2) return Qfalse;
    if (rb_w32_iswin95()) return Qfalse;
#else
    SafeStringValue(fname1);
    fname1 = rb_str_new4(fname1);
    SafeStringValue(fname2);
    if (access(RSTRING(fname1)->ptr, 0)) return Qfalse;
    if (access(RSTRING(fname2)->ptr, 0)) return Qfalse;
#endif
    fname1 = rb_file_expand_path(fname1, Qnil);
    fname2 = rb_file_expand_path(fname2, Qnil);
    if (RSTRING(fname1)->len != RSTRING(fname2)->len) return Qfalse;
    if (rb_memcicmp(RSTRING(fname1)->ptr, RSTRING(fname2)->ptr, RSTRING(fname1)->len))
        return Qfalse;
#endif
    return Qtrue;
}


pwd (FileUtils)

# File lib/fileutils.rb, line 100
  def pwd
    Dir.pwd
  end


cd (FileUtils)

# File lib/fileutils.rb, line 118
  def cd(dir, options = {}, &block) # :yield: dir
    fu_check_options options, OPT_TABLE['cd']
    fu_output_message "cd #{dir}" if options[:verbose]
    Dir.chdir(dir, &block)
    fu_output_message 'cd -' if options[:verbose] and block
  end


uptodate? (FileUtils)

# File lib/fileutils.rb, line 141
  def uptodate?(new, old_list, options = nil)
    raise ArgumentError, 'uptodate? does not accept any option' if options

    return false unless File.exist?(new)
    new_time = File.mtime(new)
    old_list.each do |old|
      if File.exist?(old)
        return false unless new_time > File.mtime(old)
      end
    end
    true
  end


mkdir (FileUtils)

# File lib/fileutils.rb, line 165
  def mkdir(list, options = {})
    fu_check_options options, OPT_TABLE['mkdir']
    list = fu_list(list)
    fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
    return if options[:noop]

    list.each do |dir|
      fu_mkdir dir, options[:mode]
    end
  end


mkdir_p (FileUtils)

# File lib/fileutils.rb, line 195
  def mkdir_p(list, options = {})
    fu_check_options options, OPT_TABLE['mkdir_p']
    list = fu_list(list)
    fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
    return *list if options[:noop]

    list.map {|path| path.sub(%r</\z>, '') }.each do |path|
      # optimize for the most common case
      begin
        fu_mkdir path, options[:mode]
        next
      rescue SystemCallError
        next if File.directory?(path)
      end

      stack = []
      until path == stack.last   # dirname("/")=="/", dirname("C:/")=="C:/"
        stack.push path
        path = File.dirname(path)
      end
      stack.reverse_each do |path|
        begin
          fu_mkdir path, options[:mode]
        rescue SystemCallError => err
          raise unless File.directory?(path)
        end
      end
    end

    return *list
  end


rmdir (FileUtils)

# File lib/fileutils.rb, line 258
  def rmdir(list, options = {})
    fu_check_options options, OPT_TABLE['rmdir']
    list = fu_list(list)
    fu_output_message "rmdir #{list.join ' '}" if options[:verbose]
    return if options[:noop]
    list.each do |dir|
      Dir.rmdir dir.sub(%r</\z>, '')
    end
  end


ln (FileUtils)

# File lib/fileutils.rb, line 293
  def ln(src, dest, options = {})
    fu_check_options options, OPT_TABLE['ln']
    fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
    return if options[:noop]
    fu_each_src_dest0(src, dest) do |s,d|
      remove_file d, true if options[:force]
      File.link s, d
    end
  end


ln_s (FileUtils)

# File lib/fileutils.rb, line 332
  def ln_s(src, dest, options = {})
    fu_check_options options, OPT_TABLE['ln_s']
    fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
    return if options[:noop]
    fu_each_src_dest0(src, dest) do |s,d|
      remove_file d, true if options[:force]
      File.symlink s, d
    end
  end


ln_sf (FileUtils)

# File lib/fileutils.rb, line 355
  def ln_sf(src, dest, options = {})
    fu_check_options options, OPT_TABLE['ln_sf']
    options = options.dup
    options[:force] = true
    ln_s src, dest, options
  end


cp (FileUtils)

# File lib/fileutils.rb, line 378
  def cp(src, dest, options = {})
    fu_check_options options, OPT_TABLE['cp']
    fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
    return if options[:noop]
    fu_each_src_dest(src, dest) do |s, d|
      copy_file s, d, options[:preserve]
    end
  end


cp_r (FileUtils)

# File lib/fileutils.rb, line 417
  def cp_r(src, dest, options = {})
    fu_check_options options, OPT_TABLE['cp_r']
    fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
    return if options[:noop]
    options[:dereference_root] = true unless options.key?(:dereference_root)
    fu_each_src_dest(src, dest) do |s, d|
      copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
    end
  end


copy_entry (FileUtils)

# File lib/fileutils.rb, line 447
  def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
    Entry_.new(src, nil, dereference_root).traverse do |ent|
      destent = Entry_.new(dest, ent.rel, false)
      File.unlink destent.path if remove_destination && File.file?(destent.path)
      ent.copy destent.path
      ent.copy_metadata destent.path if preserve
    end
  end


copy_file (FileUtils)

# File lib/fileutils.rb, line 461
  def copy_file(src, dest, preserve = false, dereference = true)
    ent = Entry_.new(src, nil, dereference)
    ent.copy_file dest
    ent.copy_metadata dest if preserve
  end


copy_stream (FileUtils)

# File lib/fileutils.rb, line 473
  def copy_stream(src, dest)
    fu_copy_stream0 src, dest, fu_stream_blksize(src, dest)
  end


mv (FileUtils)

# File lib/fileutils.rb, line 490
  def mv(src, dest, options = {})
    fu_check_options options, OPT_TABLE['mv']
    fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
    return if options[:noop]
    fu_each_src_dest(src, dest) do |s, d|
      destent = Entry_.new(d, nil, true)
      begin
        if destent.exist?
          if destent.directory?
            raise Errno::EEXIST, dest
          else
            destent.remove_file if rename_cannot_overwrite_file?
          end
        end
        begin
          File.rename s, d
        rescue Errno::EXDEV
          copy_entry s, d, true
          if options[:secure]
            remove_entry_secure s, options[:force]
          else
            remove_entry s, options[:force]
          end
        end
      rescue SystemCallError
        raise unless options[:force]
      end
    end
  end


rm (FileUtils)

# File lib/fileutils.rb, line 542
  def rm(list, options = {})
    fu_check_options options, OPT_TABLE['rm']
    list = fu_list(list)
    fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
    return if options[:noop]

    list.each do |path|
      remove_file path, options[:force]
    end
  end


rm_f (FileUtils)

# File lib/fileutils.rb, line 567
  def rm_f(list, options = {})
    fu_check_options options, OPT_TABLE['rm_f']
    options = options.dup
    options[:force] = true
    rm list, options
  end


rm_r (FileUtils)

# File lib/fileutils.rb, line 602
  def rm_r(list, options = {})
    fu_check_options options, OPT_TABLE['rm_r']
    # options[:secure] = true unless options.key?(:secure)
    list = fu_list(list)
    fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose]
    return if options[:noop]
    list.each do |path|
      if options[:secure]
        remove_entry_secure path, options[:force]
      else
        remove_entry path, options[:force]
      end
    end
  end


rm_rf (FileUtils)

# File lib/fileutils.rb, line 630
  def rm_rf(list, options = {})
    fu_check_options options, OPT_TABLE['rm_rf']
    options = options.dup
    options[:force] = true
    rm_r list, options
  end


remove_entry_secure (FileUtils)

# File lib/fileutils.rb, line 676
  def remove_entry_secure(path, force = false)
    unless fu_have_symlink?
      remove_entry path, force
      return
    end
    fullpath = File.expand_path(path)
    st = File.lstat(fullpath)
    unless st.directory?
      File.unlink fullpath
      return
    end
    # is a directory.
    parent_st = File.stat(File.dirname(fullpath))
    unless fu_world_writable?(parent_st)
      remove_entry path, force
      return
    end
    unless parent_st.sticky?
      raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
    end
    # freeze tree root
    euid = Process.euid
    File.open(fullpath + '/.') {|f|
      unless fu_stat_identical_entry?(st, f.stat)
        # symlink (TOC-to-TOU attack?)
        File.unlink fullpath
        return
      end
      f.chown euid, -1
      f.chmod 0700
    }
    # ---- tree root is frozen ----
    root = Entry_.new(path)
    root.preorder_traverse do |ent|
      if ent.directory?
        ent.chown euid, -1
        ent.chmod 0700
      end
    end
    root.postorder_traverse do |ent|
      begin
        ent.remove
      rescue
        raise unless force
      end
    end
  rescue
    raise unless force
  end


fu_world_writable? (FileUtils)

# File lib/fileutils.rb, line 727
  def fu_world_writable?(st)
    (st.mode & 0002) != 0
  end


fu_have_symlink? (FileUtils)

# File lib/fileutils.rb, line 732
  def fu_have_symlink?   #:nodoc
    File.symlink nil, nil
  rescue NotImplementedError
    return false
  rescue
    return true
  end


remove_entry (FileUtils)

# File lib/fileutils.rb, line 753
  def remove_entry(path, force = false)
    Entry_.new(path).postorder_traverse do |ent|
      begin
        ent.remove
      rescue
        raise unless force
      end
    end
  rescue
    raise unless force
  end


remove_file (FileUtils)

# File lib/fileutils.rb, line 770
  def remove_file(path, force = false)
    Entry_.new(path).remove_file
  rescue
    raise unless force
  end


remove_dir (FileUtils)

# File lib/fileutils.rb, line 781
  def remove_dir(path, force = false)
    remove_entry path, force   # FIXME?? check if it is a directory
  end


compare_file (FileUtils)

# File lib/fileutils.rb, line 792
  def compare_file(a, b)
    return false unless File.size(a) == File.size(b)
    File.open(a, 'rb') {|fa|
      File.open(b, 'rb') {|fb|
        return compare_stream(fa, fb)
      }
    }
  end


compare_stream (FileUtils)

# File lib/fileutils.rb, line 810
  def compare_stream(a, b)
    bsize = fu_stream_blksize(a, b)
    sa = sb = nil
    while sa == sb
      sa = a.read(bsize)
      sb = b.read(bsize)
      unless sa and sb
        if sa.nil? and sb.nil?
          return true
        end
      end
    end
    false
  end


install (FileUtils)

# File lib/fileutils.rb, line 836
  def install(src, dest, options = {})
    fu_check_options options, OPT_TABLE['install']
    fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
    return if options[:noop]
    fu_each_src_dest(src, dest) do |s, d|
      unless File.exist?(d) and compare_file(s, d)
        remove_file d, true
        st = File.stat(s) if options[:preserve]
        copy_file s, d
        File.utime st.atime, st.mtime, d if options[:preserve]
        File.chmod options[:mode], d if options[:mode]
      end
    end
  end


chmod (FileUtils)

# File lib/fileutils.rb, line 864
  def chmod(mode, list, options = {})
    fu_check_options options, OPT_TABLE['chmod']
    list = fu_list(list)
    fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]
    return if options[:noop]
    list.each do |path|
      Entry_.new(path).chmod mode
    end
  end


chmod_R (FileUtils)

# File lib/fileutils.rb, line 885
  def chmod_R(mode, list, options = {})
    fu_check_options options, OPT_TABLE['chmod_R']
    list = fu_list(list)
    fu_output_message sprintf('chmod -R%s %o %s',
                              (options[:force] ? 'f' : ''),
                              mode, list.join(' ')) if options[:verbose]
    return if options[:noop]
    list.each do |root|
      Entry_.new(root).traverse do |ent|
        begin
          ent.chmod mode
        rescue
          raise unless options[:force]
        end
      end
    end
  end


chown (FileUtils)

# File lib/fileutils.rb, line 918
  def chown(user, group, list, options = {})
    fu_check_options options, OPT_TABLE['chown']
    list = fu_list(list)
    fu_output_message sprintf('chown %s%s',
                              [user,group].compact.join(':') + ' ',
                              list.join(' ')) if options[:verbose]
    return if options[:noop]
    uid = fu_get_uid(user)
    gid = fu_get_gid(group)
    list.each do |path|
      Entry_.new(path).chown uid, gid
    end
  end


chown_R (FileUtils)

# File lib/fileutils.rb, line 947
  def chown_R(user, group, list, options = {})
    fu_check_options options, OPT_TABLE['chown_R']
    list = fu_list(list)
    fu_output_message sprintf('chown -R%s %s%s',
                              (options[:force] ? 'f' : ''),
                              [user,group].compact.join(':') + ' ',
                              list.join(' ')) if options[:verbose]
    return if options[:noop]
    uid = fu_get_uid(user)
    gid = fu_get_gid(group)
    return unless uid or gid
    list.each do |root|
      Entry_.new(root).traverse do |ent|
        begin
          ent.chown uid, gid
        rescue
          raise unless options[:force]
        end
      end
    end
  end


touch (FileUtils)

# File lib/fileutils.rb, line 1017
  def touch(list, options = {})
    fu_check_options options, OPT_TABLE['touch']
    list = fu_list(list)
    created = nocreate = options[:nocreate]
    t = options[:mtime]
    if options[:verbose]
      fu_output_message "touch #{nocreate ? ' -c' : ''}#{t ? t.strftime(' -t %Y%m%d%H%M.%S') : ''}#{list.join ' '}"
    end
    return if options[:noop]
    list.each do |path|
      created = nocreate
      begin
        File.utime(t, t, path)
      rescue Errno::ENOENT
        raise if created
        File.open(path, 'a') {
          ;
        }
        created = true
        retry if t
      end
    end
  end


add_dependency (Finalizer)

# File lib/finalize.rb, line 58
    def add_dependency(obj, dependant, method = :finalize, *opt)
      ObjectSpace.call_finalizer(obj)
      method = method.intern unless method.kind_of?(Integer)
      assoc = [dependant, method].concat(opt)
      if dep = @dependency[obj.object_id]
        dep.push assoc
      else
        @dependency[obj.object_id] = [assoc]
      end
    end


delete_dependency (Finalizer)

# File lib/finalize.rb, line 71
    def delete_dependency(id, dependant, method = :finalize)
      id = id.object_id unless id.kind_of?(Integer)
      method = method.intern unless method.kind_of?(Integer)
      for assoc in @dependency[id]
        assoc.delete_if do
          |d, m, *o|
          d == dependant && m == method
        end
        @dependency.delete(id) if assoc.empty?
      end
    end


delete_all_dependency (Finalizer)

# File lib/finalize.rb, line 85
    def delete_all_dependency(id, dependant)
      id = id.object_id unless id.kind_of?(Integer)
      method = method.intern unless method.kind_of?(Integer)
      for assoc in @dependency[id]
        assoc.delete_if do
          |d, m, *o|
          d == dependant
        end
        @dependency.delete(id) if assoc.empty?
      end
    end


delete_by_dependant (Finalizer)

# File lib/finalize.rb, line 98
    def delete_by_dependant(dependant, method = :finalize)
      method = method.intern unless method.kind_of?(Integer)
      for id in @dependency.keys
        delete(id, dependant, method)
      end
    end


delete_all_by_dependant (Finalizer)

# File lib/finalize.rb, line 106
    def delete_all_by_dependant(dependant)
      for id in @dependency.keys
        delete_all_dependency(id, dependant)
      end
    end


finalize_dependency (Finalizer)

# File lib/finalize.rb, line 113
    def finalize_dependency(id, dependant, method = :finalize)
      id = id.object_id unless id.kind_of?(Integer)
      method = method.intern unless method.kind_of?(Integer)
      for assocs in @dependency[id]
        assocs.delete_if do
          |d, m, *o|
          d.send(m, id, *o) if ret = d == dependant && m == method
          ret
        end
        @dependency.delete(id) if assoc.empty?
      end
    end


finalize_all_dependency (Finalizer)

# File lib/finalize.rb, line 128
    def finalize_all_dependency(id, dependant)
      id = id.object_id unless id.kind_of?(Integer)
      method = method.intern unless method.kind_of?(Integer)
      for assoc in @dependency[id]
        assoc.delete_if do
          |d, m, *o|
          d.send(m, id, *o) if ret = d == dependant
        end
        @dependency.delete(id) if assoc.empty?
      end
    end


finalize_by_dependant (Finalizer)

# File lib/finalize.rb, line 141
    def finalize_by_dependant(dependant, method = :finalize)
      method = method.intern unless method.kind_of?(Integer)
      for id in @dependency.keys
        finalize(id, dependant, method)
      end
    end


finalize_all_by_dependant (Finalizer)

# File lib/finalize.rb, line 149
    def finalize_all_by_dependant(dependant)
      for id in @dependency.keys
        finalize_all_dependency(id, dependant)
      end
    end


finalize_all (Finalizer)

# File lib/finalize.rb, line 156
    def finalize_all
      for id, assocs in @dependency
        for dependant, method, *opt in assocs
          dependant.send(method, id, *opt)
        end
        assocs.clear
      end
    end


safe (Finalizer)

# File lib/finalize.rb, line 166
    def safe
      old_status = Thread.critical
      Thread.critical = true
      ObjectSpace.remove_finalizer(@proc)
      begin
        yield
      ensure
        ObjectSpace.add_finalizer(@proc)
        Thread.critical = old_status
      end
    end


find (Find)

# File lib/find.rb, line 35
  def find(*paths) # :yield: path
    paths.collect!{|d| d.dup}
    while file = paths.shift
      catch(:prune) do
        yield file.dup.taint
        next unless File.exist? file
        begin
          if File.lstat(file).directory? then
            d = Dir.open(file)
            begin
              for f in d
                next if f == "." or f == ".."
                if File::ALT_SEPARATOR and file =~ /^(?:[\/\\]|[A-Za-z]:[\/\\]?)$/ then
                  f = file + f
                elsif file == "/" then
                  f = "/" + f
                else
                  f = File.join(file, f)
                end
                paths.unshift f.untaint
              end
            ensure
              d.close
            end
          end
        rescue Errno::ENOENT, Errno::EACCES
        end
      end
    end
  end


prune (Find)

# File lib/find.rb, line 74
  def prune
    throw :prune
  end


induced_from (Fixnum)

/*
 * call-seq:
 *   Fixnum.induced_from(obj)    =>  fixnum
 *
 * Convert <code>obj</code> to a Fixnum. Works with numeric parameters.
 * Also works with Symbols, but this is deprecated.
 */

static VALUE
rb_fix_induced_from(klass, x)
    VALUE klass, x;
{
    return rb_num2fix(x);
}


to_s (Fixnum)

/*
 *  call-seq:
 *     fix.to_s( base=10 ) -> aString
 *
 *  Returns a string containing the representation of <i>fix</i> radix
 *  <i>base</i> (between 2 and 36).
 *
 *     12345.to_s       #=> "12345"
 *     12345.to_s(2)    #=> "11000000111001"
 *     12345.to_s(8)    #=> "30071"
 *     12345.to_s(10)   #=> "12345"
 *     12345.to_s(16)   #=> "3039"
 *     12345.to_s(36)   #=> "9ix"
 *
 */
static VALUE
fix_to_s(argc, argv, x)
    int argc;
    VALUE *argv;
    VALUE x;
{
    VALUE b;
    int base;

    rb_scan_args(argc, argv, "01", &b);
    if (argc == 0) base = 10;
    else base = NUM2INT(b);

    return rb_fix2str(x, base);
}


id2name (Fixnum)

/*
 *  call-seq:
 *     fix.id2name -> string or nil
 *
 *  Returns the name of the object whose symbol id is <i>fix</i>. If
 *  there is no symbol in the symbol table with this value, returns
 *  <code>nil</code>. <code>id2name</code> has nothing to do with the
 *  <code>Object.id</code> method. See also <code>Fixnum#to_sym</code>,
 *  <code>String#intern</code>, and class <code>Symbol</code>.
 *
 *     symbol = :@inst_var    #=> :@inst_var
 *     id     = symbol.to_i   #=> 9818
 *     id.id2name             #=> "@inst_var"
 */

static VALUE
fix_id2name(fix)
    VALUE fix;
{
    char *name = rb_id2name(FIX2UINT(fix));
    if (name) return rb_str_new2(name);
    return Qnil;
}


to_sym (Fixnum)

/*
 *  call-seq:
 *     fix.to_sym -> aSymbol
 *
 *  Returns the symbol whose integer value is <i>fix</i>. See also
 *  <code>Fixnum#id2name</code>.
 *
 *     fred = :fred.to_i
 *     fred.id2name   #=> "fred"
 *     fred.to_sym    #=> :fred
 */

static VALUE
fix_to_sym(fix)
    VALUE fix;
{
    ID id = FIX2UINT(fix);

    if (rb_id2name(id)) {
        return ID2SYM(id);
    }
    return Qnil;
}


-@ (Fixnum)

/*
 * call-seq:
 *   -fix   =>  integer
 *
 * Negates <code>fix</code> (which might return a Bignum).
 */

static VALUE
fix_uminus(num)
    VALUE num;
{
    return LONG2NUM(-FIX2LONG(num));
}


+ (Fixnum)

/*
 * call-seq:
 *   fix + numeric   =>  numeric_result
 *
 * Performs addition: the class of the resulting object depends on
 * the class of <code>numeric</code> and on the magnitude of the
 * result.
 */

static VALUE
fix_plus(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long a, b, c;
        VALUE r;

        a = FIX2LONG(x);
        b = FIX2LONG(y);
        c = a + b;
        r = LONG2NUM(c);

        return r;
    }
    if (TYPE(y) == T_FLOAT) {
        return rb_float_new((double)FIX2LONG(x) + RFLOAT(y)->value);
    }
    return rb_num_coerce_bin(x, y);
}


- (Fixnum)

/*
 * call-seq:
 *   fix - numeric   =>  numeric_result
 *
 * Performs subtraction: the class of the resulting object depends on
 * the class of <code>numeric</code> and on the magnitude of the
 * result.
 */

static VALUE
fix_minus(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long a, b, c;
        VALUE r;

        a = FIX2LONG(x);
        b = FIX2LONG(y);
        c = a - b;
        r = LONG2NUM(c);

        return r;
    }
    if (TYPE(y) == T_FLOAT) {
        return rb_float_new((double)FIX2LONG(x) - RFLOAT(y)->value);
    }
    return rb_num_coerce_bin(x, y);
}


* (Fixnum)

/*
 * call-seq:
 *   fix * numeric   =>  numeric_result
 *
 * Performs multiplication: the class of the resulting object depends on
 * the class of <code>numeric</code> and on the magnitude of the
 * result.
 */

static VALUE
fix_mul(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
#ifdef __HP_cc
        /* avoids an optimization bug of HP aC++/ANSI C B3910B A.06.05 [Jul 25 2005] */
        volatile
#endif
        long a, b, c;
        VALUE r;

        a = FIX2LONG(x);
        if (a == 0) return x;

        b = FIX2LONG(y);
        c = a * b;
        r = LONG2FIX(c);

        if (FIX2LONG(r) != c || c/a != b) {
            r = rb_big_mul(rb_int2big(a), rb_int2big(b));
        }
        return r;
    }
    if (TYPE(y) == T_FLOAT) {
        return rb_float_new((double)FIX2LONG(x) * RFLOAT(y)->value);
    }
    return rb_num_coerce_bin(x, y);
}


/ (Fixnum)

/*
 * call-seq:
 *   fix / numeric      =>  numeric_result
 *   fix.div(numeric)   =>  numeric_result
 *
 * Performs division: the class of the resulting object depends on
 * the class of <code>numeric</code> and on the magnitude of the
 * result.
 */

static VALUE
fix_div(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long div;

        fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, 0);
        return LONG2NUM(div);
    }
    return rb_num_coerce_bin(x, y);
}


div (Fixnum)

/*
 * call-seq:
 *   fix / numeric      =>  numeric_result
 *   fix.div(numeric)   =>  numeric_result
 *
 * Performs division: the class of the resulting object depends on
 * the class of <code>numeric</code> and on the magnitude of the
 * result.
 */

static VALUE
fix_div(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long div;

        fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, 0);
        return LONG2NUM(div);
    }
    return rb_num_coerce_bin(x, y);
}


% (Fixnum)

/*
 *  call-seq:
 *    fix % other         => Numeric
 *    fix.modulo(other)   => Numeric
 *
 *  Returns <code>fix</code> modulo <code>other</code>.
 *  See <code>Numeric.divmod</code> for more information.
 */

static VALUE
fix_mod(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long mod;

        fixdivmod(FIX2LONG(x), FIX2LONG(y), 0, &mod);
        return LONG2NUM(mod);
    }
    return rb_num_coerce_bin(x, y);
}


modulo (Fixnum)

/*
 *  call-seq:
 *    fix % other         => Numeric
 *    fix.modulo(other)   => Numeric
 *
 *  Returns <code>fix</code> modulo <code>other</code>.
 *  See <code>Numeric.divmod</code> for more information.
 */

static VALUE
fix_mod(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long mod;

        fixdivmod(FIX2LONG(x), FIX2LONG(y), 0, &mod);
        return LONG2NUM(mod);
    }
    return rb_num_coerce_bin(x, y);
}


divmod (Fixnum)

/*
 *  call-seq:
 *     fix.divmod(numeric)    => array
 *
 *  See <code>Numeric#divmod</code>.
 */
static VALUE
fix_divmod(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long div, mod;

        fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, &mod);

        return rb_assoc_new(LONG2NUM(div), LONG2NUM(mod));
    }
    return rb_num_coerce_bin(x, y);
}


quo (Fixnum)

/*
 *  call-seq:
 *     fix.quo(numeric)    => float
 *
 *  Returns the floating point result of dividing <i>fix</i> by
 *  <i>numeric</i>.
 *
 *     654321.quo(13731)      #=> 47.6528293642124
 *     654321.quo(13731.24)   #=> 47.6519964693647
 *
 */

static VALUE
fix_quo(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        return rb_float_new((double)FIX2LONG(x) / (double)FIX2LONG(y));
    }
    return rb_num_coerce_bin(x, y);
}


** (Fixnum)

/*
 *  call-seq:
 *    fix ** other         => Numeric
 *
 *  Raises <code>fix</code> to the <code>other</code> power, which may
 *  be negative or fractional.
 *
 *    2 ** 3      #=> 8
 *    2 ** -1     #=> 0.5
 *    2 ** 0.5    #=> 1.4142135623731
 */

static VALUE
fix_pow(x, y)
    VALUE x, y;
{
    long a = FIX2LONG(x);

    if (FIXNUM_P(y)) {
        long b;

        b = FIX2LONG(y);
        if (b == 0) return INT2FIX(1);
        if (b == 1) return x;
        a = FIX2LONG(x);
        if (a == 0) return INT2FIX(0);
        if (a == 1) return INT2FIX(1);
        if (a == -1) {
            if (b % 2 == 0)
                return INT2FIX(1);
            else
                return INT2FIX(-1);
        }
        if (b > 0) {
            return rb_big_pow(rb_int2big(a), y);
        }
        return rb_float_new(pow((double)a, (double)b));
    }
    switch (TYPE(y)) {
      case T_BIGNUM:
        if (a == 0) return INT2FIX(0);
        if (a == 1) return INT2FIX(1);
        if (a == -1) {
            if (int_even_p(y)) return INT2FIX(1);
            else return INT2FIX(-1);
        }
        x = rb_int2big(FIX2LONG(x));
        return rb_big_pow(x, y);
      case T_FLOAT:
        if (a == 0) return rb_float_new(0.0);
        if (a == 1) return rb_float_new(1.0);
        return rb_float_new(pow((double)a, RFLOAT(y)->value));
      default:
        return rb_num_coerce_bin(x, y);
    }
}


abs (Fixnum)

/*
 *  call-seq:
 *     fix.abs -> aFixnum
 *
 *  Returns the absolute value of <i>fix</i>.
 *
 *     -12345.abs   #=> 12345
 *     12345.abs    #=> 12345
 *
 */

static VALUE
fix_abs(fix)
    VALUE fix;
{
    long i = FIX2LONG(fix);

    if (i < 0) i = -i;

    return LONG2NUM(i);
}


== (Fixnum)

/*
 * call-seq:
 *   fix == other
 *
 * Return <code>true</code> if <code>fix</code> equals <code>other</code>
 * numerically.
 *
 *   1 == 2      #=> false
 *   1 == 1.0    #=> true
 */

static VALUE
fix_equal(x, y)
    VALUE x, y;
{
    if (x == y) return Qtrue;
    if (FIXNUM_P(y)) return Qfalse;
    return num_equal(x, y);
}


<=> (Fixnum)

/*
 *  call-seq:
 *     fix <=> numeric    => -1, 0, +1
 *
 *  Comparison---Returns -1, 0, or +1 depending on whether <i>fix</i> is
 *  less than, equal to, or greater than <i>numeric</i>. This is the
 *  basis for the tests in <code>Comparable</code>.
 */

static VALUE
fix_cmp(x, y)
    VALUE x, y;
{
    if (x == y) return INT2FIX(0);
    if (FIXNUM_P(y)) {
        long a = FIX2LONG(x), b = FIX2LONG(y);

        if (a > b) return INT2FIX(1);
        return INT2FIX(-1);
    }
    else {
        return rb_num_coerce_cmp(x, y);
    }
}


> (Fixnum)

/*
 * call-seq:
 *   fix > other     => true or false
 *
 * Returns <code>true</code> if the value of <code>fix</code> is
 * greater than that of <code>other</code>.
 */

static VALUE
fix_gt(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long a = FIX2LONG(x), b = FIX2LONG(y);

        if (a > b) return Qtrue;
        return Qfalse;
    }
    else {
        return rb_num_coerce_relop(x, y);
    }
}


>= (Fixnum)

/*
 * call-seq:
 *   fix >= other     => true or false
 *
 * Returns <code>true</code> if the value of <code>fix</code> is
 * greater than or equal to that of <code>other</code>.
 */

static VALUE
fix_ge(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long a = FIX2LONG(x), b = FIX2LONG(y);

        if (a >= b) return Qtrue;
        return Qfalse;
    }
    else {
        return rb_num_coerce_relop(x, y);
    }
}


< (Fixnum)

/*
 * call-seq:
 *   fix < other     => true or false
 *
 * Returns <code>true</code> if the value of <code>fix</code> is
 * less than that of <code>other</code>.
 */

static VALUE
fix_lt(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long a = FIX2LONG(x), b = FIX2LONG(y);

        if (a < b) return Qtrue;
        return Qfalse;
    }
    else {
        return rb_num_coerce_relop(x, y);
    }
}


<= (Fixnum)

/*
 * call-seq:
 *   fix <= other     => true or false
 *
 * Returns <code>true</code> if the value of <code>fix</code> is
 * less thanor equal to that of <code>other</code>.
 */

static VALUE
fix_le(x, y)
    VALUE x, y;
{
    if (FIXNUM_P(y)) {
        long a = FIX2LONG(x), b = FIX2LONG(y);

        if (a <= b) return Qtrue;
        return Qfalse;
    }
    else {
        return rb_num_coerce_relop(x, y);
    }
}


~ (Fixnum)

/*
 * call-seq:
 *   ~fix     => integer
 *
 * One's complement: returns a number where each bit is flipped.
 */

static VALUE
fix_rev(num)
    VALUE num;
{
    long val = FIX2LONG(num);

    val = ~val;
    return LONG2NUM(val);
}


& (Fixnum)

/*
 * call-seq:
 *   fix & other     => integer
 *
 * Bitwise AND.
 */

static VALUE
fix_and(x, y)
    VALUE x, y;
{
    long val;

    if (TYPE(y) == T_BIGNUM) {
        return rb_big_and(y, x);
    }
    val = FIX2LONG(x) & NUM2LONG(y);
    return LONG2NUM(val);
}


| (Fixnum)

/*
 * call-seq:
 *   fix | other     => integer
 *
 * Bitwise OR.
 */

static VALUE
fix_or(x, y)
    VALUE x, y;
{
    long val;

    if (TYPE(y) == T_BIGNUM) {
        return rb_big_or(y, x);
    }
    val = FIX2LONG(x) | NUM2LONG(y);
    return LONG2NUM(val);
}


^ (Fixnum)

/*
 * call-seq:
 *   fix ^ other     => integer
 *
 * Bitwise EXCLUSIVE OR.
 */

static VALUE
fix_xor(x, y)
    VALUE x, y;
{
    long val;

    if (TYPE(y) == T_BIGNUM) {
        return rb_big_xor(y, x);
    }
    val = FIX2LONG(x) ^ NUM2LONG(y);
    return LONG2NUM(val);
}


[] (Fixnum)

/*
 *  call-seq:
 *     fix[n]     => 0, 1
 *
 *  Bit Reference---Returns the <em>n</em>th bit in the binary
 *  representation of <i>fix</i>, where <i>fix</i>[0] is the least
 *  significant bit.
 *
 *     a = 0b11001100101010
 *     30.downto(0) do |n| print a[n] end
 *
 *  <em>produces:</em>
 *
 *     0000000000000000011001100101010
 */

static VALUE
fix_aref(fix, idx)
    VALUE fix, idx;
{
    long val = FIX2LONG(fix);
    long i;

    if (TYPE(idx) == T_BIGNUM) {
        idx = rb_big_norm(idx);
        if (!FIXNUM_P(idx)) {
            if (!RBIGNUM(idx)->sign || val >= 0)
                return INT2FIX(0);
            return INT2FIX(1);
        }
    }
    i = NUM2LONG(idx);

    if (i < 0) return INT2FIX(0);
    if (sizeof(VALUE)*CHAR_BIT-1 < i) {
        if (val < 0) return INT2FIX(1);
        return INT2FIX(0);
    }
    if (val & (1L<<i))
        return INT2FIX(1);
    return INT2FIX(0);
}


<< (Fixnum)

/*
 * call-seq:
 *   fix << count     => integer
 *
 * Shifts _fix_ left _count_ positions (right if _count_ is negative).
 */

static VALUE
rb_fix_lshift(x, y)
    VALUE x, y;
{
    long val, width;

    val = NUM2LONG(x);
    if (!FIXNUM_P(y))
        return rb_big_lshift(rb_int2big(val), y);
    width = FIX2LONG(y);
    if (width < 0)
        return fix_rshift(val, (unsigned long)-width);
    return fix_lshift(val, width);
}


>> (Fixnum)

/*
 * call-seq:
 *   fix >> count     => integer
 *
 * Shifts _fix_ right _count_ positions (left if _count_ is negative).
 */

static VALUE
rb_fix_rshift(x, y)
    VALUE x, y;
{
    long i, val;

    val = FIX2LONG(x);
    if (!FIXNUM_P(y))
        return rb_big_rshift(rb_int2big(val), y);
    i = FIX2LONG(y);
    if (i == 0) return x;
    if (i < 0)
        return fix_lshift(val, (unsigned long)-i);
    return fix_rshift(val, i);
}


to_f (Fixnum)

/*
 *  call-seq:
 *     fix.to_f -> float
 *
 *  Converts <i>fix</i> to a <code>Float</code>.
 *
 */

static VALUE
fix_to_f(num)
    VALUE num;
{
    double val;

    val = (double)FIX2LONG(num);

    return rb_float_new(val);
}


size (Fixnum)

/*
 *  call-seq:
 *     fix.size -> fixnum
 *
 *  Returns the number of <em>bytes</em> in the machine representation
 *  of a <code>Fixnum</code>.
 *
 *     1.size            #=> 4
 *     -1.size           #=> 4
 *     2147483647.size   #=> 4
 */

static VALUE
fix_size(fix)
    VALUE fix;
{
    return INT2FIX(sizeof(long));
}


zero? (Fixnum)

/*
 *  call-seq:
 *     fix.zero?    => true or false
 *
 *  Returns <code>true</code> if <i>fix</i> is zero.
 *
 */

static VALUE
fix_zero_p(num)
    VALUE num;
{
    if (FIX2LONG(num) == 0) {
        return Qtrue;
    }
    return Qfalse;
}


quo (Fixnum)

# File lib/rational.rb, line 486
  def quo(other)
    Rational.new!(self,1) / other
  end


rpower (Fixnum)

# File lib/rational.rb, line 492
  def rpower (other)
    if other >= 0
      self.power!(other)
    else
      Rational.new!(self,1)**other
    end
  end


dclone (Fixnum)

# File lib/rexml/xpath_parser.rb, line 16
  def dclone ; self ; end


induced_from (Float)

/*
 * call-seq:
 *   Float.induced_from(obj)    =>  float
 *
 * Convert <code>obj</code> to a float.
 */

static VALUE
rb_flo_induced_from(klass, x)
    VALUE klass, x;
{
    switch (TYPE(x)) {
    case T_FIXNUM:
    case T_BIGNUM:
       return rb_funcall(x, rb_intern("to_f"), 0);
    case T_FLOAT:
       return x;
    default:
       rb_raise(rb_eTypeError, "failed to convert %s into Float",
                rb_obj_classname(x));
    }
}


to_s (Float)

/*
 *  call-seq:
 *     flt.to_s    => string
 *
 *  Returns a string containing a representation of self. As well as a
 *  fixed or exponential form of the number, the call may return
 *  ``<code>NaN</code>'', ``<code>Infinity</code>'', and
 *  ``<code>-Infinity</code>''.
 */

static VALUE
flo_to_s(flt)
    VALUE flt;
{
    char buf[32];
    double value = RFLOAT(flt)->value;
    char *p, *e;

    if (isinf(value))
        return rb_str_new2(value < 0 ? "-Infinity" : "Infinity");
    else if(isnan(value))
        return rb_str_new2("NaN");

    sprintf(buf, "%#.15g", value); /* ensure to print decimal point */
    if (!(e = strchr(buf, 'e'))) {
        e = buf + strlen(buf);
    }
    if (!ISDIGIT(e[-1])) { /* reformat if ended with decimal point (ex 111111111111111.) */
        sprintf(buf, "%#.14e", value);
        if (!(e = strchr(buf, 'e'))) {
            e = buf + strlen(buf);
        }
    }
    p = e;
    while (p[-1]=='0' && ISDIGIT(p[-2]))
        p--;
    memmove(p, e, strlen(e)+1);
    return rb_str_new2(buf);
}


coerce (Float)

/*
 * MISSING: documentation
 */

static VALUE
flo_coerce(x, y)
    VALUE x, y;
{
    return rb_assoc_new(rb_Float(y), x);
}


-@ (Float)

/*
 * call-seq:
 *    -float   => float
 *
 * Returns float, negated.
 */

static VALUE
flo_uminus(flt)
    VALUE flt;
{
    return rb_float_new(-RFLOAT(flt)->value);
}


+ (Float)

/*
 * call-seq:
 *   float + other   => float
 *
 * Returns a new float which is the sum of <code>float</code>
 * and <code>other</code>.
 */

static VALUE
flo_plus(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        return rb_float_new(RFLOAT(x)->value + (double)FIX2LONG(y));
      case T_BIGNUM:
        return rb_float_new(RFLOAT(x)->value + rb_big2dbl(y));
      case T_FLOAT:
        return rb_float_new(RFLOAT(x)->value + RFLOAT(y)->value);
      default:
        return rb_num_coerce_bin(x, y);
    }
}


- (Float)

/*
 * call-seq:
 *   float + other   => float
 *
 * Returns a new float which is the difference of <code>float</code>
 * and <code>other</code>.
 */

static VALUE
flo_minus(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        return rb_float_new(RFLOAT(x)->value - (double)FIX2LONG(y));
      case T_BIGNUM:
        return rb_float_new(RFLOAT(x)->value - rb_big2dbl(y));
      case T_FLOAT:
        return rb_float_new(RFLOAT(x)->value - RFLOAT(y)->value);
      default:
        return rb_num_coerce_bin(x, y);
    }
}


* (Float)

/*
 * call-seq:
 *   float * other   => float
 *
 * Returns a new float which is the product of <code>float</code>
 * and <code>other</code>.
 */

static VALUE
flo_mul(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        return rb_float_new(RFLOAT(x)->value * (double)FIX2LONG(y));
      case T_BIGNUM:
        return rb_float_new(RFLOAT(x)->value * rb_big2dbl(y));
      case T_FLOAT:
        return rb_float_new(RFLOAT(x)->value * RFLOAT(y)->value);
      default:
        return rb_num_coerce_bin(x, y);
    }
}


/ (Float)

/*
 * call-seq:
 *   float / other   => float
 *
 * Returns a new float which is the result of dividing
 * <code>float</code> by <code>other</code>.
 */

static VALUE
flo_div(x, y)
    VALUE x, y;
{
    long f_y;
    double d;

    switch (TYPE(y)) {
      case T_FIXNUM:
        f_y = FIX2LONG(y);
        return rb_float_new(RFLOAT(x)->value / (double)f_y);
      case T_BIGNUM:
        d = rb_big2dbl(y);
        return rb_float_new(RFLOAT(x)->value / d);
      case T_FLOAT:
        return rb_float_new(RFLOAT(x)->value / RFLOAT(y)->value);
      default:
        return rb_num_coerce_bin(x, y);
    }
}


% (Float)

/*
 *  call-seq:
 *     flt % other         => float
 *     flt.modulo(other)   => float
 *
 *  Return the modulo after division of <code>flt</code> by <code>other</code>.
 *
 *     6543.21.modulo(137)      #=> 104.21
 *     6543.21.modulo(137.24)   #=> 92.9299999999996
 */

static VALUE
flo_mod(x, y)
    VALUE x, y;
{
    double fy, mod;

    switch (TYPE(y)) {
      case T_FIXNUM:
        fy = (double)FIX2LONG(y);
        break;
      case T_BIGNUM:
        fy = rb_big2dbl(y);
        break;
      case T_FLOAT:
        fy = RFLOAT(y)->value;
        break;
      default:
        return rb_num_coerce_bin(x, y);
    }
    flodivmod(RFLOAT(x)->value, fy, 0, &mod);
    return rb_float_new(mod);
}


modulo (Float)

/*
 *  call-seq:
 *     flt % other         => float
 *     flt.modulo(other)   => float
 *
 *  Return the modulo after division of <code>flt</code> by <code>other</code>.
 *
 *     6543.21.modulo(137)      #=> 104.21
 *     6543.21.modulo(137.24)   #=> 92.9299999999996
 */

static VALUE
flo_mod(x, y)
    VALUE x, y;
{
    double fy, mod;

    switch (TYPE(y)) {
      case T_FIXNUM:
        fy = (double)FIX2LONG(y);
        break;
      case T_BIGNUM:
        fy = rb_big2dbl(y);
        break;
      case T_FLOAT:
        fy = RFLOAT(y)->value;
        break;
      default:
        return rb_num_coerce_bin(x, y);
    }
    flodivmod(RFLOAT(x)->value, fy, 0, &mod);
    return rb_float_new(mod);
}


divmod (Float)

/*
 *  call-seq:
 *     flt.divmod(numeric)    => array
 *
 *  See <code>Numeric#divmod</code>.
 */

static VALUE
flo_divmod(x, y)
    VALUE x, y;
{
    double fy, div, mod, val;
    volatile VALUE a, b;

    switch (TYPE(y)) {
      case T_FIXNUM:
        fy = (double)FIX2LONG(y);
        break;
      case T_BIGNUM:
        fy = rb_big2dbl(y);
        break;
      case T_FLOAT:
        fy = RFLOAT(y)->value;
        break;
      default:
        return rb_num_coerce_bin(x, y);
    }
    flodivmod(RFLOAT(x)->value, fy, &div, &mod);
    if (FIXABLE(div)) {
        val = div;
        a = LONG2FIX(val);
    }
    else {
        a = rb_dbl2big(div);
    }
    b = rb_float_new(mod);
    return rb_assoc_new(a, b);
}


** (Float)

/*
 * call-seq:
 *
 *  flt ** other   => float
 *
 * Raises <code>float</code> the <code>other</code> power.
 */

static VALUE
flo_pow(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_FIXNUM:
        return rb_float_new(pow(RFLOAT(x)->value, (double)FIX2LONG(y)));
      case T_BIGNUM:
        return rb_float_new(pow(RFLOAT(x)->value, rb_big2dbl(y)));
      case T_FLOAT:
        return rb_float_new(pow(RFLOAT(x)->value, RFLOAT(y)->value));
      default:
        return rb_num_coerce_bin(x, y);
    }
}


== (Float)

/*
 *  call-seq:
 *     flt == obj   => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> has the same value
 *  as <i>flt</i>. Contrast this with <code>Float#eql?</code>, which
 *  requires <i>obj</i> to be a <code>Float</code>.
 *
 *     1.0 == 1   #=> true
 *
 */

static VALUE
flo_eq(x, y)
    VALUE x, y;
{
    volatile double a, b;

    switch (TYPE(y)) {
      case T_FIXNUM:
        b = FIX2LONG(y);
        break;
      case T_BIGNUM:
        b = rb_big2dbl(y);
        break;
      case T_FLOAT:
        b = RFLOAT(y)->value;
        if (isnan(b)) return Qfalse;
        break;
      default:
        return num_equal(x, y);
    }
    a = RFLOAT(x)->value;
    if (isnan(a)) return Qfalse;
    return (a == b)?Qtrue:Qfalse;
}


<=> (Float)

/*
 *  call-seq:
 *     flt <=> numeric   => -1, 0, +1
 *
 *  Returns -1, 0, or +1 depending on whether <i>flt</i> is less than,
 *  equal to, or greater than <i>numeric</i>. This is the basis for the
 *  tests in <code>Comparable</code>.
 */

static VALUE
flo_cmp(x, y)
    VALUE x, y;
{
    double a, b;

    a = RFLOAT(x)->value;
    switch (TYPE(y)) {
      case T_FIXNUM:
        b = (double)FIX2LONG(y);
        break;

      case T_BIGNUM:
        b = rb_big2dbl(y);
        break;

      case T_FLOAT:
        b = RFLOAT(y)->value;
        break;

      default:
        return rb_num_coerce_cmp(x, y);
    }
    return rb_dbl_cmp(a, b);
}


> (Float)

/*
 * call-seq:
 *   flt > other    =>  true or false
 *
 * <code>true</code> if <code>flt</code> is greater than <code>other</code>.
 */

static VALUE
flo_gt(x, y)
    VALUE x, y;
{
    double a, b;

    a = RFLOAT(x)->value;
    switch (TYPE(y)) {
      case T_FIXNUM:
        b = (double)FIX2LONG(y);
        break;

      case T_BIGNUM:
        b = rb_big2dbl(y);
        break;

      case T_FLOAT:
        b = RFLOAT(y)->value;
        if (isnan(b)) return Qfalse;
        break;

      default:
        return rb_num_coerce_relop(x, y);
    }
    if (isnan(a)) return Qfalse;
    return (a > b)?Qtrue:Qfalse;
}


>= (Float)

/*
 * call-seq:
 *   flt >= other    =>  true or false
 *
 * <code>true</code> if <code>flt</code> is greater than
 * or equal to <code>other</code>.
 */

static VALUE
flo_ge(x, y)
    VALUE x, y;
{
    double a, b;

    a = RFLOAT(x)->value;
    switch (TYPE(y)) {
      case T_FIXNUM:
        b = (double)FIX2LONG(y);
        break;

      case T_BIGNUM:
        b = rb_big2dbl(y);
        break;

      case T_FLOAT:
        b = RFLOAT(y)->value;
        if (isnan(b)) return Qfalse;
        break;

      default:
        return rb_num_coerce_relop(x, y);
    }
    if (isnan(a)) return Qfalse;
    return (a >= b)?Qtrue:Qfalse;
}


< (Float)

/*
 * call-seq:
 *   flt < other    =>  true or false
 *
 * <code>true</code> if <code>flt</code> is less than <code>other</code>.
 */

static VALUE
flo_lt(x, y)
    VALUE x, y;
{
    double a, b;

    a = RFLOAT(x)->value;
    switch (TYPE(y)) {
      case T_FIXNUM:
        b = (double)FIX2LONG(y);
        break;

      case T_BIGNUM:
        b = rb_big2dbl(y);
        break;

      case T_FLOAT:
        b = RFLOAT(y)->value;
        if (isnan(b)) return Qfalse;
        break;

      default:
        return rb_num_coerce_relop(x, y);
    }
    if (isnan(a)) return Qfalse;
    return (a < b)?Qtrue:Qfalse;
}


<= (Float)

/*
 * call-seq:
 *   flt <= other    =>  true or false
 *
 * <code>true</code> if <code>flt</code> is less than
 * or equal to <code>other</code>.
 */

static VALUE
flo_le(x, y)
    VALUE x, y;
{
    double a, b;

    a = RFLOAT(x)->value;
    switch (TYPE(y)) {
      case T_FIXNUM:
        b = (double)FIX2LONG(y);
        break;

      case T_BIGNUM:
        b = rb_big2dbl(y);
        break;

      case T_FLOAT:
        b = RFLOAT(y)->value;
        if (isnan(b)) return Qfalse;
        break;

      default:
        return rb_num_coerce_relop(x, y);
    }
    if (isnan(a)) return Qfalse;
    return (a <= b)?Qtrue:Qfalse;
}


eql? (Float)

/*
 *  call-seq:
 *     flt.eql?(obj)   => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> is a
 *  <code>Float</code> with the same value as <i>flt</i>. Contrast this
 *  with <code>Float#==</code>, which performs type conversions.
 *
 *     1.0.eql?(1)   #=> false
 */

static VALUE
flo_eql(x, y)
    VALUE x, y;
{
    if (TYPE(y) == T_FLOAT) {
        double a = RFLOAT(x)->value;
        double b = RFLOAT(y)->value;

        if (isnan(a) || isnan(b)) return Qfalse;
        if (a == b) return Qtrue;
    }
    return Qfalse;
}


hash (Float)

/*
 * call-seq:
 *   flt.hash   => integer
 *
 * Returns a hash code for this float.
 */

static VALUE
flo_hash(num)
    VALUE num;
{
    double d;
    char *c;
    int i, hash;

    d = RFLOAT(num)->value;
    if (d == 0) d = fabs(d);
    c = (char*)&d;
    for (hash=0, i=0; i<sizeof(double);i++) {
        hash = (hash * 971) ^ (unsigned char)c[i];
    }
    if (hash < 0) hash = -hash;
    return INT2FIX(hash);
}


to_f (Float)

/*
 * call-seq:
 *   flt.to_f   => flt
 *
 * As <code>flt</code> is already a float, returns <i>self</i>.
 */

static VALUE
flo_to_f(num)
    VALUE num;
{
    return num;
}


abs (Float)

/*
 *  call-seq:
 *     flt.abs    => float
 *
 *  Returns the absolute value of <i>flt</i>.
 *
 *     (-34.56).abs   #=> 34.56
 *     -34.56.abs     #=> 34.56
 *
 */

static VALUE
flo_abs(flt)
    VALUE flt;
{
    double val = fabs(RFLOAT(flt)->value);
    return rb_float_new(val);
}


zero? (Float)

/*
 *  call-seq:
 *     flt.zero? -> true or false
 *
 *  Returns <code>true</code> if <i>flt</i> is 0.0.
 *
 */

static VALUE
flo_zero_p(num)
    VALUE num;
{
    if (RFLOAT(num)->value == 0.0) {
        return Qtrue;
    }
    return Qfalse;
}


to_i (Float)

/*
 *  call-seq:
 *     flt.to_i       => integer
 *     flt.to_int     => integer
 *     flt.truncate   => integer
 *
 *  Returns <i>flt</i> truncated to an <code>Integer</code>.
 */

static VALUE
flo_truncate(num)
    VALUE num;
{
    double f = RFLOAT(num)->value;
    long val;

    if (f > 0.0) f = floor(f);
    if (f < 0.0) f = ceil(f);

    if (!FIXABLE(f)) {
        return rb_dbl2big(f);
    }
    val = f;
    return LONG2FIX(val);
}


to_int (Float)

/*
 *  call-seq:
 *     flt.to_i       => integer
 *     flt.to_int     => integer
 *     flt.truncate   => integer
 *
 *  Returns <i>flt</i> truncated to an <code>Integer</code>.
 */

static VALUE
flo_truncate(num)
    VALUE num;
{
    double f = RFLOAT(num)->value;
    long val;

    if (f > 0.0) f = floor(f);
    if (f < 0.0) f = ceil(f);

    if (!FIXABLE(f)) {
        return rb_dbl2big(f);
    }
    val = f;
    return LONG2FIX(val);
}


floor (Float)

/*
 *  call-seq:
 *     flt.floor   => integer
 *
 *  Returns the largest integer less than or equal to <i>flt</i>.
 *
 *     1.2.floor      #=> 1
 *     2.0.floor      #=> 2
 *     (-1.2).floor   #=> -2
 *     (-2.0).floor   #=> -2
 */

static VALUE
flo_floor(num)
    VALUE num;
{
    double f = floor(RFLOAT(num)->value);
    long val;

    if (!FIXABLE(f)) {
        return rb_dbl2big(f);
    }
    val = f;
    return LONG2FIX(val);
}


ceil (Float)

/*
 *  call-seq:
 *     flt.ceil    => integer
 *
 *  Returns the smallest <code>Integer</code> greater than or equal to
 *  <i>flt</i>.
 *
 *     1.2.ceil      #=> 2
 *     2.0.ceil      #=> 2
 *     (-1.2).ceil   #=> -1
 *     (-2.0).ceil   #=> -2
 */

static VALUE
flo_ceil(num)
    VALUE num;
{
    double f = ceil(RFLOAT(num)->value);
    long val;

    if (!FIXABLE(f)) {
        return rb_dbl2big(f);
    }
    val = f;
    return LONG2FIX(val);
}


round (Float)

/*
 *  call-seq:
 *     flt.round   => integer
 *
 *  Rounds <i>flt</i> to the nearest integer. Equivalent to:
 *
 *     def round
 *       return (self+0.5).floor if self > 0.0
 *       return (self-0.5).ceil  if self < 0.0
 *       return 0
 *     end
 *
 *     1.5.round      #=> 2
 *     (-1.5).round   #=> -2
 *
 */

static VALUE
flo_round(num)
    VALUE num;
{
    double f = RFLOAT(num)->value;
    long val;

    if (f > 0.0) f = floor(f+0.5);
    if (f < 0.0) f = ceil(f-0.5);

    if (!FIXABLE(f)) {
        return rb_dbl2big(f);
    }
    val = f;
    return LONG2FIX(val);
}


truncate (Float)

/*
 *  call-seq:
 *     flt.to_i       => integer
 *     flt.to_int     => integer
 *     flt.truncate   => integer
 *
 *  Returns <i>flt</i> truncated to an <code>Integer</code>.
 */

static VALUE
flo_truncate(num)
    VALUE num;
{
    double f = RFLOAT(num)->value;
    long val;

    if (f > 0.0) f = floor(f);
    if (f < 0.0) f = ceil(f);

    if (!FIXABLE(f)) {
        return rb_dbl2big(f);
    }
    val = f;
    return LONG2FIX(val);
}


nan? (Float)

/*
 *  call-seq:
 *     flt.nan? -> true or false
 *
 *  Returns <code>true</code> if <i>flt</i> is an invalid IEEE floating
 *  point number.
 *
 *     a = -1.0      #=> -1.0
 *     a.nan?        #=> false
 *     a = 0.0/0.0   #=> NaN
 *     a.nan?        #=> true
 */

static VALUE
flo_is_nan_p(num)
     VALUE num;
{
    double value = RFLOAT(num)->value;

    return isnan(value) ? Qtrue : Qfalse;
}


infinite? (Float)

/*
 *  call-seq:
 *     flt.infinite? -> nil, -1, +1
 *
 *  Returns <code>nil</code>, -1, or +1 depending on whether <i>flt</i>
 *  is finite, -infinity, or +infinity.
 *
 *     (0.0).infinite?        #=> nil
 *     (-1.0/0.0).infinite?   #=> -1
 *     (+1.0/0.0).infinite?   #=> 1
 */

static VALUE
flo_is_infinite_p(num)
     VALUE num;
{
    double value = RFLOAT(num)->value;

    if (isinf(value)) {
        return INT2FIX( value < 0 ? -1 : 1 );
    }

    return Qnil;
}


finite? (Float)

/*
 *  call-seq:
 *     flt.finite? -> true or false
 *
 *  Returns <code>true</code> if <i>flt</i> is a valid IEEE floating
 *  point number (it is not infinite, and <code>nan?</code> is
 *  <code>false</code>).
 *
 */

static VALUE
flo_is_finite_p(num)
     VALUE num;
{
    double value = RFLOAT(num)->value;

#if HAVE_FINITE
    if (!finite(value))
        return Qfalse;
#else
    if (isinf(value) || isnan(value))
        return Qfalse;
#endif

    return Qtrue;
}


dclone (Float)

# File lib/rexml/xpath_parser.rb, line 19
  def dclone ; self ; end


to_yaml (Float)

# File lib/yaml/rubytypes.rb, line 367
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            str = self.to_s
            if str == "Infinity"
                str = ".Inf"
            elsif str == "-Infinity"
                str = "-.Inf"
            elsif str == "NaN"
                str = ".NaN"
            end
            out.scalar( "tag:yaml.org,2002:float", str, :plain )
        end
        end


new (Foo)

# File lib/drb/extserv.rb, line 42
    def initialize(str)
      @str = str
    end


hello (Foo)

# File lib/drb/extserv.rb, line 46
    def hello(it)
      "#{it}: #{self}"
    end


to_s (Foo)

# File lib/drb/extserv.rb, line 50
    def to_s
      @str
    end


def_instance_delegators (Forwardable)

# File lib/forwardable.rb, line 130
  def def_instance_delegators(accessor, *methods)
    for method in methods
      def_instance_delegator(accessor, method)
    end
  end


def_instance_delegator (Forwardable)

# File lib/forwardable.rb, line 143
  def def_instance_delegator(accessor, method, ali = method)
    accessor = accessor.id2name if accessor.kind_of?(Integer)
    method = method.id2name if method.kind_of?(Integer)
    ali = ali.id2name if ali.kind_of?(Integer)

    module_eval("def \#{ali}(*args, &block)\nbegin\n\#{accessor}.__send__(:\#{method}, *args, &block)\nrescue Exception\n$@.delete_if{|s| /^\\\\(__FORWARDABLE__\\\\):/ =~ s} unless Forwardable::debug\nKernel::raise\nend\nend\n", "(__FORWARDABLE__)", 1)
  end


start (GC)

/*
 *  call-seq:
 *     GC.start                     => nil
 *     gc.garbage_collect           => nil
 *     ObjectSpace.garbage_collect  => nil
 *
 *  Initiates garbage collection, unless manually disabled.
 *
 */

VALUE
rb_gc_start()
{
    rb_gc();
    return Qnil;
}


enable (GC)

/*
 *  call-seq:
 *     GC.enable    => true or false
 *
 *  Enables garbage collection, returning <code>true</code> if garbage
 *  collection was previously disabled.
 *
 *     GC.disable   #=> false
 *     GC.enable    #=> true
 *     GC.enable    #=> false
 *
 */

VALUE
rb_gc_enable()
{
    int old = dont_gc;

    dont_gc = Qfalse;
    return old;
}


disable (GC)

/*
 *  call-seq:
 *     GC.disable    => true or false
 *
 *  Disables garbage collection, returning <code>true</code> if garbage
 *  collection was already disabled.
 *
 *     GC.disable   #=> false
 *     GC.disable   #=> true
 *
 */

VALUE
rb_gc_disable()
{
    int old = dont_gc;

    dont_gc = Qtrue;
    return old;
}


garbage_collect (GC)

/*
 *  call-seq:
 *     GC.start                     => nil
 *     gc.garbage_collect           => nil
 *     ObjectSpace.garbage_collect  => nil
 *
 *  Initiates garbage collection, unless manually disabled.
 *
 */

VALUE
rb_gc_start()
{
    rb_gc();
    return Qnil;
}


new (Generator)

# File lib/generator.rb, line 69
  def initialize(enum = nil, &block)
    if enum
      @block = proc { |g|
        enum.each { |x| g.yield x }
      }
    else
      @block = block
    end

    @index = 0
    @queue = []
    @cont_next = @cont_yield = @cont_endp = nil

    if @cont_next = callcc { |c| c }
      @block.call(self)

      @cont_endp.call(nil) if @cont_endp
    end

    self
  end


yield (Generator)

# File lib/generator.rb, line 92
  def yield(value)
    if @cont_yield = callcc { |c| c }
      @queue << value
      @cont_next.call(nil)
    end

    self
  end


end? (Generator)

# File lib/generator.rb, line 102
  def end?()
    if @cont_endp = callcc { |c| c }
      @cont_yield.nil? && @queue.empty?
    else
      @queue.empty?
    end
  end


next? (Generator)

# File lib/generator.rb, line 111
  def next?()
    !end?
  end


index (Generator)

# File lib/generator.rb, line 116
  def index()
    @index
  end


pos (Generator)

# File lib/generator.rb, line 121
  def pos()
    @index
  end


next (Generator)

# File lib/generator.rb, line 126
  def next()
    if end?
      raise EOFError, "no more elements available"
    end

    if @cont_next = callcc { |c| c }
      @cont_yield.call(nil) if @cont_yield
    end

    @index += 1

    @queue.shift
  end


current (Generator)

# File lib/generator.rb, line 141
  def current()
    if @queue.empty?
      raise EOFError, "no more elements available"
    end

    @queue.first
  end


rewind (Generator)

# File lib/generator.rb, line 150
  def rewind()
    initialize(nil, &@block) if @index.nonzero?

    self
  end


each (Generator)

# File lib/generator.rb, line 157
  def each
    rewind

    until end?
      yield self.next
    end

    self
  end


reset (Generators::AllReferences)

# File lib/rdoc/generators/html_generator.rb, line 65
    def AllReferences::reset
      @@refs = {}
    end


add (Generators::AllReferences)

# File lib/rdoc/generators/html_generator.rb, line 69
    def AllReferences.add(name, html_class)
      @@refs[name] = html_class
    end


[] (Generators::AllReferences)

# File lib/rdoc/generators/html_generator.rb, line 73
    def AllReferences.[](name)
      @@refs[name]
    end


keys (Generators::AllReferences)

# File lib/rdoc/generators/html_generator.rb, line 77
    def AllReferences.keys
      @@refs.keys
    end


for (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 10
    def CHMGenerator.for(options)
      CHMGenerator.new(options)
    end


new (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 15
    def initialize(*args)
      super
      @op_name = @options.op_name || "rdoc"
      check_for_html_help_workshop
    end


check_for_html_help_workshop (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 21
    def check_for_html_help_workshop
      stat = File.stat(HHC_PATH)
    rescue
      $stderr <<
        "\n.chm output generation requires that Microsoft's Html Help\n" <<
        "Workshop is installed. RDoc looks for it in:\n\n    " <<
        HHC_PATH <<
        "\n\nYou can download a copy for free from:\n\n" <<
        "    http://msdn.microsoft.com/library/default.asp?" <<
        "url=/library/en-us/htmlhelp/html/hwMicrosoftHTMLHelpDownloads.asp\n\n"

      exit 99
    end


generate (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 37
    def generate(info)
      super
      @project_name = @op_name + ".hhp"
      create_help_project
    end


create_help_project (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 45
    def create_help_project
      create_project_file
      create_contents_and_index
      compile_project
    end


create_project_file (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 54
    def create_project_file
      template = TemplatePage.new(RDoc::Page::HPP_FILE)
      values = { "title" => @options.title, "opname" => @op_name }
      files = []
      @files.each do |f|
        files << { "html_file_name" => f.path }
      end

      values['all_html_files'] = files

      File.open(@project_name, "w") do |f|
        template.write_html_on(f, values)
      end
    end


create_contents_and_index (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 74
    def create_contents_and_index
      contents = []
      index    = []

      (@files+@classes).sort.each do |entry|
        content_entry = { "c_name" => entry.name, "ref" => entry.path }
        index << { "name" => entry.name, "aref" => entry.path }

        internals = []

        methods = entry.build_method_summary_list(entry.path)

        content_entry["methods"] = methods unless methods.empty?
        contents << content_entry
        index.concat methods
      end

      values = { "contents" => contents }
      template = TemplatePage.new(RDoc::Page::CONTENTS)
      File.open("contents.hhc", "w") do |f|
        template.write_html_on(f, values)
      end

      values = { "index" => index }
      template = TemplatePage.new(RDoc::Page::CHM_INDEX)
      File.open("index.hhk", "w") do |f|
        template.write_html_on(f, values)
      end
    end


compile_project (Generators::CHMGenerator)

# File lib/rdoc/generators/chm_generator.rb, line 105
    def compile_project
      system(HHC_PATH, @project_name)
    end


new (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 294
    def initialize(context, options)
      @context = context
      @options = options
    end


href (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 300
    def href(link, cls, name)
      %{<a href="#{link}" class="#{cls}">#{name}</a>} #"
    end


as_href (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 308
    def as_href(from_path)
      if @options.all_one_file
        "#" + path
      else
        HTMLGenerator.gen_url(from_path, path)
      end
    end


collect_methods (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 321
    def collect_methods
      list = @context.method_list
      unless @options.show_all
        list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation }
      end
      @methods = list.collect {|m| HtmlMethod.new(m, self, @options) }
    end


build_method_summary_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 330
    def build_method_summary_list(path_prefix="")
      collect_methods unless @methods
      meths = @methods.sort
      res = []
      meths.each do |meth|
        res << {
          "name" => CGI.escapeHTML(meth.name),
          "aref" => "#{path_prefix}\##{meth.aref}"
        }
      end
      res
    end


build_alias_summary_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 346
    def build_alias_summary_list(section)
      values = []
      @context.aliases.each do |al|
        next unless al.section == section
        res = {
          'old_name' => al.old_name,
          'new_name' => al.new_name,
        }
        if al.comment && !al.comment.empty?
          res['desc'] = markup(al.comment, true)
        end
        values << res
      end
      values
    end


build_constants_summary_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 363
    def build_constants_summary_list(section)
      values = []
      @context.constants.each do |co|
        next unless co.section == section
        res = {
          'name'  => co.name,
          'value' => CGI.escapeHTML(co.value)
        }
        res['desc'] = markup(co.comment, true) if co.comment && !co.comment.empty?
        values << res
      end
      values
    end


build_requires_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 377
    def build_requires_list(context)
      potentially_referenced_list(context.requires) {|fn| [fn + ".rb"] }
    end


build_include_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 381
    def build_include_list(context)
      potentially_referenced_list(context.includes)
    end


potentially_referenced_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 394
    def potentially_referenced_list(array)
      res = []
      array.each do |i|
        ref = AllReferences[i.name]
#         if !ref
#           container = @context.parent
#           while !ref && container
#             name = container.name + "::" + i.name
#             ref = AllReferences[name]
#             container = container.parent
#           end
#         end

        ref = @context.find_symbol(i.name)
        ref = ref.viewer if ref

        if !ref && block_given?
          possibles = yield(i.name)
          while !ref and !possibles.empty?
            ref = AllReferences[possibles.shift]
          end
        end
        h_name = CGI.escapeHTML(i.name)
        if ref and ref.document_self
          path = url(ref.path)
          res << { "name" => h_name, "aref" => path }
        else
          res << { "name" => h_name }
        end
      end
      res
    end


build_method_detail_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 432
    def build_method_detail_list(section)
      outer = []

      methods = @methods.sort
      for singleton in [true, false]
        for vis in [ :public, :protected, :private ]
          res = []
          methods.each do |m|
            if m.section == section and
                m.document_self and
                m.visibility == vis and
                m.singleton == singleton
              row = {}
              if m.call_seq
                row["callseq"] = m.call_seq.gsub(/->/, '&rarr;')
              else
                row["name"]        = CGI.escapeHTML(m.name)
                row["params"]      = m.params
              end
              desc = m.description.strip
              row["m_desc"]      = desc unless desc.empty?
              row["aref"]        = m.aref
              row["visibility"]  = m.visibility.to_s

              alias_names = []
              m.aliases.each do |other|
                if other.viewer   # won't be if the alias is private
                  alias_names << {
                    'name' => other.name,
                    'aref'  => other.viewer.as_href(path)
                  }
                end
              end
              unless alias_names.empty?
                row["aka"] = alias_names
              end

              if @options.inline_source
                code = m.source_code
                row["sourcecode"] = code if code
              else
                code = m.src_url
                if code
                  row["codeurl"] = code
                  row["imgurl"]  = m.img_url
                end
              end
              res << row
            end
          end
          if res.size > 0
            outer << {
              "type"    => vis.to_s.capitalize,
              "category"    => singleton ? "Class" : "Instance",
              "methods" => res
            }
          end
        end
      end
      outer
    end


build_class_list (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 497
    def build_class_list(level, from, section, infile=nil)
      res = ""
      prefix = "&nbsp;&nbsp;::" * level;

      from.modules.sort.each do |mod|
        next unless mod.section == section
        next if infile && !mod.defined_in?(infile)
        if mod.document_self
          res <<
            prefix <<
            "Module " <<
            href(url(mod.viewer.path), "link", mod.full_name) <<
            "<br />\n" <<
            build_class_list(level + 1, mod, section, infile)
        end
      end

      from.classes.sort.each do |cls|
        next unless cls.section == section
        next if infile && !cls.defined_in?(infile)
        if cls.document_self
          res      <<
            prefix <<
            "Class " <<
            href(url(cls.viewer.path), "link", cls.full_name) <<
            "<br />\n" <<
            build_class_list(level + 1, cls, section, infile)
        end
      end

      res
    end


url (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 530
    def url(target)
      HTMLGenerator.gen_url(path, target)
    end


aref_to (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 534
    def aref_to(target)
      if @options.all_one_file
        "#" + target
      else
        url(target)
      end
    end


document_self (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 542
    def document_self
      @context.document_self
    end


diagram_reference (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 546
    def diagram_reference(diagram)
      res = diagram.gsub(/((?:src|href)=")(.*?)"/) {
        $1 + url($2) + '"'
      }
      res
    end


find_symbol (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 555
    def find_symbol(symbol, method=nil)
      res = @context.find_symbol(symbol, method)
      if res
        res = res.viewer
      end
      res
    end


add_table_of_sections (Generators::ContextUser)

# File lib/rdoc/generators/html_generator.rb, line 565
    def add_table_of_sections
      toc = []
      @context.sections.each do |section|
        if section.title
          toc << {
            'secname' => section.title,
            'href'    => section.sequence
          }
        end
      end

      @values['toc'] = toc unless toc.empty?
    end


new (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 590
    def initialize(context, html_file, prefix, options)
      super(context, options)

      @html_file = html_file
      @is_module = context.is_module?
      @values    = {}

      context.viewer = self

      if options.all_one_file
        @path = context.full_name
      else
        @path = http_url(context.full_name, prefix)
      end

      collect_methods

      AllReferences.add(name, self)
    end


http_url (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 612
    def http_url(full_name, prefix)
      path = full_name.dup
      if path['<<']
        path.gsub!(/<<\s*(\w*)/) { "from-#$1" }
      end
      File.join(prefix, path.split("::")) + ".html"
    end


name (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 621
    def name
      @context.full_name
    end


parent_name (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 625
    def parent_name
      @context.parent.full_name
    end


index_name (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 629
    def index_name
      name
    end


write_on (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 633
    def write_on(f)
      value_hash
      template = TemplatePage.new(RDoc::Page::BODY,
                                      RDoc::Page::CLASS_PAGE,
                                      RDoc::Page::METHOD_LIST)
      template.write_html_on(f, @values)
    end


value_hash (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 641
    def value_hash
      class_attribute_values
      add_table_of_sections

      @values["charset"] = @options.charset
      @values["style_url"] = style_url(path, @options.css)

      d = markup(@context.comment)
      @values["description"] = d unless d.empty?

      ml = build_method_summary_list
      @values["methods"] = ml unless ml.empty?

      il = build_include_list(@context)
      @values["includes"] = il unless il.empty?

      @values["sections"] = @context.sections.map do |section|

        secdata = {
          "sectitle" => section.title,
          "secsequence" => section.sequence,
          "seccomment" => markup(section.comment)
        }

        al = build_alias_summary_list(section)
        secdata["aliases"] = al unless al.empty?

        co = build_constants_summary_list(section)
        secdata["constants"] = co unless co.empty?

        al = build_attribute_list(section)
        secdata["attributes"] = al unless al.empty?

        cl = build_class_list(0, @context, section)
        secdata["classlist"] = cl unless cl.empty?

        mdl = build_method_detail_list(section)
        secdata["method_list"] = mdl unless mdl.empty?

        secdata
      end

      @values
    end


build_attribute_list (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 686
    def build_attribute_list(section)
      atts = @context.attributes.sort
      res = []
      atts.each do |att|
        next unless att.section == section
        if att.visibility == :public || att.visibility == :protected || @options.show_all
          entry = {
            "name"   => CGI.escapeHTML(att.name),
            "rw"     => att.rw,
            "a_desc" => markup(att.comment, true)
          }
          unless att.visibility == :public || att.visibility == :protected
            entry["rw"] << "-"
          end
          res << entry
        end
      end
      res
    end


class_attribute_values (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 706
    def class_attribute_values
      h_name = CGI.escapeHTML(name)

      @values["classmod"]  = @is_module ? "Module" : "Class"
      @values["title"]     = "#{@values['classmod']}: #{h_name}"

      c = @context
      c = c.parent while c and !c.diagram
      if c && c.diagram
        @values["diagram"] = diagram_reference(c.diagram)
      end

      @values["full_name"] = h_name

      parent_class = @context.superclass

      if parent_class
        @values["parent"] = CGI.escapeHTML(parent_class)

        if parent_name
          lookup = parent_name + "::" + parent_class
        else
          lookup = parent_class
        end

        parent_url = AllReferences[lookup] || AllReferences[parent_class]

        if parent_url and parent_url.document_self
          @values["par_url"] = aref_to(parent_url.path)
        end
      end

      files = []
      @context.in_files.each do |f|
        res = {}
        full_path = CGI.escapeHTML(f.file_absolute_name)

        res["full_path"]     = full_path
        res["full_path_url"] = aref_to(f.viewer.path) if f.document_self

        if @options.webcvs
          res["cvsurl"] = cvs_url( @options.webcvs, full_path )
        end

        files << res
      end

      @values['infiles'] = files
    end


<=> (Generators::HtmlClass)

# File lib/rdoc/generators/html_generator.rb, line 756
    def <=>(other)
      self.name <=> other.name
    end


new (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 774
    def initialize(context, options, file_dir)
      super(context, options)

      @values = {}

      if options.all_one_file
        @path = filename_to_label
      else
        @path = http_url(file_dir)
      end

      @name = @context.file_relative_name

      collect_methods
      AllReferences.add(name, self)
      context.viewer = self
    end


http_url (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 792
    def http_url(file_dir)
      File.join(file_dir, @context.file_relative_name.tr('.', '_')) +
        ".html"
    end


filename_to_label (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 797
    def filename_to_label
      @context.file_relative_name.gsub(/%|\/|\?|\#/) {|s| '%' + ("%x" % s[0]) }
    end


index_name (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 801
    def index_name
      name
    end


parent_name (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 805
    def parent_name
      nil
    end


value_hash (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 809
    def value_hash
      file_attribute_values
      add_table_of_sections

      @values["charset"]   = @options.charset
      @values["href"]      = path
      @values["style_url"] = style_url(path, @options.css)

      if @context.comment
        d = markup(@context.comment)
        @values["description"] = d if d.size > 0
      end

      ml = build_method_summary_list
      @values["methods"] = ml unless ml.empty?

      il = build_include_list(@context)
      @values["includes"] = il unless il.empty?

      rl = build_requires_list(@context)
      @values["requires"] = rl unless rl.empty?

      if @options.promiscuous
        file_context = nil
      else
        file_context = @context
      end

      @values["sections"] = @context.sections.map do |section|

        secdata = {
          "sectitle" => section.title,
          "secsequence" => section.sequence,
          "seccomment" => markup(section.comment)
        }

        cl = build_class_list(0, @context, section, file_context)
        @values["classlist"] = cl unless cl.empty?

        mdl = build_method_detail_list(section)
        secdata["method_list"] = mdl unless mdl.empty?

        al = build_alias_summary_list(section)
        secdata["aliases"] = al unless al.empty?

        co = build_constants_summary_list(section)
        @values["constants"] = co unless co.empty?

        secdata
      end

      @values
    end


write_on (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 864
    def write_on(f)
      value_hash
      template = TemplatePage.new(RDoc::Page::BODY,
                                  RDoc::Page::FILE_PAGE,
                                  RDoc::Page::METHOD_LIST)
      template.write_html_on(f, @values)
    end


file_attribute_values (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 872
    def file_attribute_values
      full_path = @context.file_absolute_name
      short_name = File.basename(full_path)

      @values["title"] = CGI.escapeHTML("File: #{short_name}")

      if @context.diagram
        @values["diagram"] = diagram_reference(@context.diagram)
      end

      @values["short_name"]   = CGI.escapeHTML(short_name)
      @values["full_path"]    = CGI.escapeHTML(full_path)
      @values["dtm_modified"] = @context.file_stat.mtime.to_s

      if @options.webcvs
        @values["cvsurl"] = cvs_url( @options.webcvs, @values["full_path"] )
      end
    end


<=> (Generators::HtmlFile)

# File lib/rdoc/generators/html_generator.rb, line 891
    def <=>(other)
      self.name <=> other.name
    end


gen_url (Generators::HTMLGenerator)

# File lib/rdoc/generators/html_generator.rb, line 1138
    def HTMLGenerator.gen_url(path, target)
      from          = File.dirname(path)
      to, to_file   = File.split(target)

      from = from.split("/")
      to   = to.split("/")

      while from.size > 0 and to.size > 0 and from[0] == to[0]
        from.shift
        to.shift
      end

      from.fill("..")
      from.concat(to)
      from << to_file
      File.join(*from)
    end


for (Generators::HTMLGenerator)

# File lib/rdoc/generators/html_generator.rb, line 1160
    def HTMLGenerator.for(options)
      AllReferences::reset
      HtmlMethod::reset

      if options.all_one_file
        HTMLGeneratorInOne.new(options)
      else
        HTMLGenerator.new(options)
      end
    end


new (Generators::HTMLGenerator)

# File lib/rdoc/generators/html_generator.rb, line 1178
    def initialize(options) #:not-new:
      @options    = options
      load_html_template
    end


generate (Generators::HTMLGenerator)

# File lib/rdoc/generators/html_generator.rb, line 1189
    def generate(toplevels)
      @toplevels  = toplevels
      @files      = []
      @classes    = []

      write_style_sheet
      gen_sub_directories()
      build_indices
      generate_html
    end


new (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1400
    def initialize(*args)
      super
    end


generate (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1409
    def generate(info)
      @toplevels  = info
      @files      = []
      @classes    = []
      @hyperlinks = {}

      build_indices
      generate_xml
    end


build_indices (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1429
    def build_indices

      @toplevels.each do |toplevel|
        @files << HtmlFile.new(toplevel, @options, FILE_DIR)
      end

      RDoc::TopLevel.all_classes_and_modules.each do |cls|
        build_class_list(cls, @files[0], CLASS_DIR)
      end
    end


build_class_list (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1440
    def build_class_list(from, html_file, class_dir)
      @classes << HtmlClass.new(from, html_file, class_dir, @options)
      from.each_classmodule do |mod|
        build_class_list(mod, html_file, class_dir)
      end
    end


generate_xml (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1451
    def generate_xml
      values = {
        'charset' => @options.charset,
        'files'   => gen_into(@files),
        'classes' => gen_into(@classes),
        'title'        => CGI.escapeHTML(@options.title),
      }

      # this method is defined in the template file
      write_extra_pages if defined? write_extra_pages

      template = TemplatePage.new(RDoc::Page::ONE_PAGE)

      if @options.op_name
        opfile = File.open(@options.op_name, "w")
      else
        opfile = $stdout
      end
      template.write_html_on(opfile, values)
    end


gen_into (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1472
    def gen_into(list)
      res = []
      list.each do |item|
        res << item.value_hash
      end
      res
    end


gen_file_index (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1480
    def gen_file_index
      gen_an_index(@files, 'Files')
    end


gen_class_index (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1484
    def gen_class_index
      gen_an_index(@classes, 'Classes')
    end


gen_method_index (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1488
    def gen_method_index
      gen_an_index(HtmlMethod.all_methods, 'Methods')
    end


gen_an_index (Generators::HTMLGeneratorInOne)

# File lib/rdoc/generators/html_generator.rb, line 1493
    def gen_an_index(collection, title)
      res = []
      collection.sort.each do |f|
        if f.document_self
          res << { "href" => f.path, "name" => f.index_name }
        end
      end

      return {
        "entries" => res,
        'list_title' => title,
        'index_url'  => main_url,
      }
    end


reset (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 910
    def HtmlMethod::reset
      @@all_methods = []
    end


new (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 914
    def initialize(context, html_class, options)
      @context    = context
      @html_class = html_class
      @options    = options
      @@seq       = @@seq.succ
      @seq        = @@seq
      @@all_methods << self

      context.viewer = self

      if (ts = @context.token_stream)
        @source_code = markup_code(ts)
        unless @options.inline_source
          @src_url = create_source_code_file(@source_code)
          @img_url = HTMLGenerator.gen_url(path, 'source.png')
        end
      end

      AllReferences.add(name, self)
    end


as_href (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 939
    def as_href(from_path)
      if @options.all_one_file
        "#" + path
      else
        HTMLGenerator.gen_url(from_path, path)
      end
    end


name (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 947
    def name
      @context.name
    end


section (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 951
    def section
      @context.section
    end


index_name (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 955
    def index_name
      "#{@context.name} (#{@html_class.name})"
    end


parent_name (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 959
    def parent_name
      if @context.parent.parent
        @context.parent.parent.full_name
      else
        nil
      end
    end


aref (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 967
    def aref
      @seq
    end


path (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 971
    def path
      if @options.all_one_file
        aref
      else
        @html_class.path + "#" + aref
      end
    end


description (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 979
    def description
      markup(@context.comment)
    end


visibility (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 983
    def visibility
      @context.visibility
    end


singleton (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 987
    def singleton
      @context.singleton
    end


call_seq (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 991
    def call_seq
      cs = @context.call_seq
      if cs
        cs.gsub(/\n/, "<br />\n")
      else
        nil
      end
    end


params (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1000
    def params
      # params coming from a call-seq in 'C' will start with the
      # method name
      p = @context.params
      if p !~ /^\w/
        p = @context.params.gsub(/\s*\#.*/, '')
        p = p.tr("\n", " ").squeeze(" ")
        p = "(" + p + ")" unless p[0] == ?(

        if (block = @context.block_params)
         # If this method has explicit block parameters, remove any
         # explicit &block

         p.sub!(/,?\s*&\w+/, '')

          block.gsub!(/\s*\#.*/, '')
          block = block.tr("\n", " ").squeeze(" ")
          if block[0] == ?(
            block.sub!(/^\(/, '').sub!(/\)/, '')
          end
          p << " {|#{block.strip}| ...}"
        end
      end
      CGI.escapeHTML(p)
    end


create_source_code_file (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1026
    def create_source_code_file(code_body)
      meth_path = @html_class.path.sub(/\.html$/, '.src')
      File.makedirs(meth_path)
      file_path = File.join(meth_path, @seq) + ".html"

      template = TemplatePage.new(RDoc::Page::SRC_PAGE)
      File.open(file_path, "w") do |f|
        values = {
          'title'     => CGI.escapeHTML(index_name),
          'code'      => code_body,
          'style_url' => style_url(file_path, @options.css),
          'charset'   => @options.charset
        }
        template.write_html_on(f, values)
      end
      HTMLGenerator.gen_url(path, file_path)
    end


all_methods (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1044
    def HtmlMethod.all_methods
      @@all_methods
    end


<=> (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1048
    def <=>(other)
      @context <=> other.context
    end


markup_code (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1057
    def markup_code(tokens)
      src = ""
      tokens.each do |t|
        next unless t
        #    p t.class
#        style = STYLE_MAP[t.class]
        style = case t
                when RubyToken::TkCONSTANT then "ruby-constant"
                when RubyToken::TkKW       then "ruby-keyword kw"
                when RubyToken::TkIVAR     then "ruby-ivar"
                when RubyToken::TkOp       then "ruby-operator"
                when RubyToken::TkId       then "ruby-identifier"
                when RubyToken::TkNode     then "ruby-node"
                when RubyToken::TkCOMMENT  then "ruby-comment cmt"
                when RubyToken::TkREGEXP   then "ruby-regexp re"
                when RubyToken::TkSTRING   then "ruby-value str"
                when RubyToken::TkVal      then "ruby-value"
                else
                    nil
                end

        text = CGI.escapeHTML(t.text)

        if style
          src << "<span class=\"#{style}\">#{text}</span>"
        else
          src << text
        end
      end

      add_line_numbers(src) if Options.instance.include_line_numbers
      src
    end


add_line_numbers (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1095
    def add_line_numbers(src)
      if src =~ /\A.*, line (\d+)/
        first = $1.to_i - 1
        last  = first + src.count("\n")
        size = last.to_s.length
        real_fmt = "%#{size}d: "
        fmt = " " * (size+2)
        src.gsub!(/^/) do
          res = sprintf(fmt, first)
          first += 1
          fmt = real_fmt
          res
        end
      end
    end


document_self (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1111
    def document_self
      @context.document_self
    end


aliases (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1115
    def aliases
      @context.aliases
    end


find_symbol (Generators::HtmlMethod)

# File lib/rdoc/generators/html_generator.rb, line 1119
    def find_symbol(symbol, method=nil)
      res = @context.parent.find_symbol(symbol, method)
      if res
        res = res.viewer
      end
      res
    end


new (Generators::HyperlinkHtml)

# File lib/rdoc/generators/html_generator.rb, line 92
    def initialize(from_path, context)
      super()
      @from_path = from_path

      @parent_name = context.parent_name
      @parent_name += "::" if @parent_name
      @context = context
    end


handle_special_CROSSREF (Generators::HyperlinkHtml)

# File lib/rdoc/generators/html_generator.rb, line 108
    def handle_special_CROSSREF(special)
      name = special.text
      if name[0,1] == '#'
        lookup = name[1..-1]
        name = lookup unless Options.instance.show_hash
      else
        lookup = name
      end

      # Find class, module, or method in class or module.
      if /([A-Z]\w*)[.\#](\w+[!?=]?)/ =~ lookup
        container = $1
        method = $2
        ref = @context.find_symbol(container, method)
      elsif /([A-Za-z]\w*)[.\#](\w+(\([\.\w+\*\/\+\-\=\<\>]+\))?)/ =~ lookup
        container = $1
        method = $2
        ref = @context.find_symbol(container, method)
      else
        ref = @context.find_symbol(lookup)
      end

      if ref and ref.document_self
        "<a href=\"#{ref.as_href(@from_path)}\">#{name}</a>"
      else
        name
      end
    end


gen_url (Generators::HyperlinkHtml)

# File lib/rdoc/generators/html_generator.rb, line 140
    def gen_url(url, text)
      if url =~ /([A-Za-z]+):(.*)/
        type = $1
        path = $2
      else
        type = "http"
        path = url
        url  = "http://#{url}"
      end

      if type == "link"
        if path[0,1] == '#'     # is this meaningful?
          url = path
        else
          url = HTMLGenerator.gen_url(@from_path, path)
        end
      end

      if (type == "http" || type == "link") &&
          url =~ /\.(gif|png|jpg|jpeg|bmp)$/

        "<img src=\"#{url}\" />"
      else
        "<a href=\"#{url}\">#{text.sub(%r{^#{type}:/*}, '')}</a>"
      end
    end


handle_special_HYPERLINK (Generators::HyperlinkHtml)

# File lib/rdoc/generators/html_generator.rb, line 174
    def handle_special_HYPERLINK(special)
      url = special.text
      gen_url(url, url)
    end


handle_special_TIDYLINK (Generators::HyperlinkHtml)

# File lib/rdoc/generators/html_generator.rb, line 183
    def handle_special_TIDYLINK(special)
      text = special.text
#      unless text =~ /(\S+)\[(.*?)\]/
      unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/
        return text
      end
      label = $1
      url   = $2
      gen_url(url, label)
    end


markup (Generators::MarkUp)

# File lib/rdoc/generators/html_generator.rb, line 209
    def markup(str, remove_para=false)
      return '' unless str
      unless defined? @markup
        @markup = SM::SimpleMarkup.new

        # class names, variable names, or instance variables
        @markup.add_special(/(
                               \w+(::\w+)*[.\#]\w+(\([\.\w+\*\/\+\-\=\<\>]+\))?  # A::B.meth(**) (for operator in Fortran95)
                             | \#\w+(\([.\w\*\/\+\-\=\<\>]+\))?  #  meth(**) (for operator in Fortran95)
                             | \b([A-Z]\w*(::\w+)*[.\#]\w+)  #    A::B.meth
                             | \b([A-Z]\w+(::\w+)*)       #    A::B..
                             | \#\w+[!?=]?                #    #meth_name
                             | \b\w+([_\/\.]+\w+)*[!?=]?  #    meth_name
                             )/x,
                            :CROSSREF)

        # external hyperlinks
        @markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK)

        # and links of the form  <text>[<url>]
        @markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\.\S+?\])/, :TIDYLINK)
#        @markup.add_special(/\b(\S+?\[\S+?\.\S+?\])/, :TIDYLINK)

      end
      unless defined? @html_formatter
        @html_formatter = HyperlinkHtml.new(self.path, self)
      end

      # Convert leading comment markers to spaces, but only
      # if all non-blank lines have them

      if str =~ /^(?>\s*)[^\#]/
        content = str
      else
        content = str.gsub(/^\s*(#+)/)  { $1.tr('#',' ') }
      end

      res = @markup.convert(content, @html_formatter)
      if remove_para
        res.sub!(/^<p>/, '')
        res.sub!(/<\/p>$/, '')
      end
      res
    end


style_url (Generators::MarkUp)

# File lib/rdoc/generators/html_generator.rb, line 258
    def style_url(path, css_name=nil)
#      $stderr.puts "style_url( #{path.inspect}, #{css_name.inspect} )"
      css_name ||= CSS_NAME
      if %r{^(https?:/)?/} =~ css_name
        return css_name
      else
        return HTMLGenerator.gen_url(path, css_name)
      end
    end


cvs_url (Generators::MarkUp)

# File lib/rdoc/generators/html_generator.rb, line 272
    def cvs_url(url, full_path)
      if /%s/ =~ url
        return sprintf( url, full_path )
      else
        return url + full_path
      end
    end


for (Generators::RIGenerator)

# File lib/rdoc/generators/ri_generator.rb, line 59
    def RIGenerator.for(options)
      new(options)
    end


new (Generators::RIGenerator)

# File lib/rdoc/generators/ri_generator.rb, line 70
    def initialize(options) #:not-new:
      @options   = options
      @ri_writer = RI::RiWriter.new(".")
      @markup    = SM::SimpleMarkup.new
      @to_flow   = SM::ToFlow.new
    end


generate (Generators::RIGenerator)

# File lib/rdoc/generators/ri_generator.rb, line 83
    def generate(toplevels)
      RDoc::TopLevel.all_classes_and_modules.each do |cls|
        process_class(cls)
      end
    end


process_class (Generators::RIGenerator)

# File lib/rdoc/generators/ri_generator.rb, line 89
    def process_class(from_class)
      generate_class_info(from_class)

      # now recure into this classes constituent classess
      from_class.each_classmodule do |mod|
        process_class(mod)
      end
    end


generate_class_info (Generators::RIGenerator)

# File lib/rdoc/generators/ri_generator.rb, line 98
    def generate_class_info(cls)
      if cls === RDoc::NormalModule
        cls_desc = RI::ModuleDescription.new
      else
        cls_desc = RI::ClassDescription.new
        cls_desc.superclass  = cls.superclass
      end
      cls_desc.name        = cls.name
      cls_desc.full_name   = cls.full_name
      cls_desc.comment     = markup(cls.comment)

      cls_desc.attributes =cls.attributes.sort.map do |a|
        RI::Attribute.new(a.name, a.rw, markup(a.comment))
      end

      cls_desc.constants = cls.constants.map do |c|
        RI::Constant.new(c.name, c.value, markup(c.comment))
      end

      cls_desc.includes = cls.includes.map do |i|
        RI::IncludedModule.new(i.name)
      end

      class_methods, instance_methods = method_list(cls)

      cls_desc.class_methods = class_methods.map do |m|
        RI::MethodSummary.new(m.name)
      end
      cls_desc.instance_methods = instance_methods.map do |m|
        RI::MethodSummary.new(m.name)
      end

      update_or_replace(cls_desc)

      class_methods.each do |m|
        generate_method_info(cls_desc, m)
      end

      instance_methods.each do |m|
        generate_method_info(cls_desc, m)
      end
    end


generate_method_info (Generators::RIGenerator)

# File lib/rdoc/generators/ri_generator.rb, line 142
    def generate_method_info(cls_desc, method)
      meth_desc = RI::MethodDescription.new
      meth_desc.name = method.name
      meth_desc.full_name = cls_desc.full_name
      if method.singleton
        meth_desc.full_name += "::"
      else
        meth_desc.full_name += "#"
      end
      meth_desc.full_name << method.name

      meth_desc.comment = markup(method.comment)
      meth_desc.params = params_of(method)
      meth_desc.visibility = method.visibility.to_s
      meth_desc.is_singleton = method.singleton
      meth_desc.block_params = method.block_params

      meth_desc.aliases = method.aliases.map do |a|
        RI::AliasName.new(a.name)
      end

      @ri_writer.add_method(cls_desc, meth_desc)
    end


for (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 16
    def XMLGenerator.for(options)
      XMLGenerator.new(options)
    end


new (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 21
    def initialize(*args)
      super
    end


generate (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 30
    def generate(info)
      @info       = info
      @files      = []
      @classes    = []
      @hyperlinks = {}

      build_indices
      generate_xml
    end


build_indices (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 50
    def build_indices

      @info.each do |toplevel|
        @files << HtmlFile.new(toplevel, @options, FILE_DIR)
      end

      RDoc::TopLevel.all_classes_and_modules.each do |cls|
        build_class_list(cls, @files[0], CLASS_DIR)
      end
    end


build_class_list (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 61
    def build_class_list(from, html_file, class_dir)
      @classes << HtmlClass.new(from, html_file, class_dir, @options)
      from.each_classmodule do |mod|
        build_class_list(mod, html_file, class_dir)
      end
    end


generate_xml (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 72
    def generate_xml
      values = {
        'charset' => @options.charset,
        'files'   => gen_into(@files),
        'classes' => gen_into(@classes)
      }

      # this method is defined in the template file
      write_extra_pages if defined? write_extra_pages

      template = TemplatePage.new(RDoc::Page::ONE_PAGE)

      if @options.op_name
        opfile = File.open(@options.op_name, "w")
      else
        opfile = $stdout
      end
      template.write_html_on(opfile, values)
    end


gen_into (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 92
    def gen_into(list)
      res = []
      list.each do |item|
        res << item.value_hash
      end
      res
    end


gen_file_index (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 100
    def gen_file_index
      gen_an_index(@files, 'Files')
    end


gen_class_index (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 104
    def gen_class_index
      gen_an_index(@classes, 'Classes')
    end


gen_method_index (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 108
    def gen_method_index
      gen_an_index(HtmlMethod.all_methods, 'Methods')
    end


gen_an_index (Generators::XMLGenerator)

# File lib/rdoc/generators/xml_generator.rb, line 113
    def gen_an_index(collection, title)
      res = []
      collection.sort.each do |f|
        if f.document_self
          res << { "href" => f.path, "name" => f.index_name }
        end
      end

      return {
        "entries" => res,
        'list_title' => title,
        'index_url'  => main_url,
      }
    end


new (GetoptLong)

# File lib/getoptlong.rb, line 135
  def initialize(*arguments)
    #
    # Current ordering.
    #
    if ENV.include?('POSIXLY_CORRECT')
      @ordering = REQUIRE_ORDER
    else
      @ordering = PERMUTE
    end

    #
    # Hash table of option names.
    # Keys of the table are option names, and their values are canonical
    # names of the options.
    #
    @canonical_names = Hash.new

    #
    # Hash table of argument flags.
    # Keys of the table are option names, and their values are argument
    # flags of the options.
    #
    @argument_flags = Hash.new

    #
    # Whether error messages are output to $deferr.
    #
    @quiet = FALSE

    #
    # Status code.
    #
    @status = STATUS_YET

    #
    # Error code.
    #
    @error = nil

    #
    # Error message.
    #
    @error_message = nil

    #
    # Rest of catenated short options.
    #
    @rest_singles = ''

    #
    # List of non-option-arguments.
    # Append them to ARGV when option processing is terminated.
    #
    @non_option_arguments = Array.new

    if 0 < arguments.length
      set_options(*arguments)
    end
  end


ordering= (GetoptLong)

# File lib/getoptlong.rb, line 244
  def ordering=(ordering)
    #
    # The method is failed if option processing has already started.
    #
    if @status != STATUS_YET
      set_error(ArgumentError, "argument error")
      raise RuntimeError,
        "invoke ordering=, but option processing has already started"
    end

    #
    # Check ordering.
    #
    if !ORDERINGS.include?(ordering)
      raise ArgumentError, "invalid ordering `#{ordering}'"
    end
    if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
      @ordering = REQUIRE_ORDER
    else
      @ordering = ordering
    end
  end


set_options (GetoptLong)

# File lib/getoptlong.rb, line 277
  def set_options(*arguments)
    #
    # The method is failed if option processing has already started.
    #
    if @status != STATUS_YET
      raise RuntimeError,
        "invoke set_options, but option processing has already started"
    end

    #
    # Clear tables of option names and argument flags.
    #
    @canonical_names.clear
    @argument_flags.clear

    arguments.each do |arg|
      #
      # Each argument must be an Array.
      #
      if !arg.is_a?(Array)
        raise ArgumentError, "the option list contains non-Array argument"
      end

      #
      # Find an argument flag and it set to `argument_flag'.
      #
      argument_flag = nil
      arg.each do |i|
        if ARGUMENT_FLAGS.include?(i)
          if argument_flag != nil
            raise ArgumentError, "too many argument-flags"
          end
          argument_flag = i
        end
      end
      raise ArgumentError, "no argument-flag" if argument_flag == nil

      canonical_name = nil
      arg.each do |i|
        #
        # Check an option name.
        #
        next if i == argument_flag
        begin
          if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
            raise ArgumentError, "an invalid option `#{i}'"
          end
          if (@canonical_names.include?(i))
            raise ArgumentError, "option redefined `#{i}'"
          end
        rescue
          @canonical_names.clear
          @argument_flags.clear
          raise
        end

        #
        # Register the option (`i') to the `@canonical_names' and
        # `@canonical_names' Hashes.
        #
        if canonical_name == nil
          canonical_name = i
        end
        @canonical_names[i] = canonical_name
        @argument_flags[i] = argument_flag
      end
      raise ArgumentError, "no option name" if canonical_name == nil
    end
    return self
  end


terminate (GetoptLong)

# File lib/getoptlong.rb, line 366
  def terminate
    return nil if @status == STATUS_TERMINATED
    raise RuntimeError, "an error has occured" if @error != nil

    @status = STATUS_TERMINATED
    @non_option_arguments.reverse_each do |argument|
      ARGV.unshift(argument)
    end

    @canonical_names = nil
    @argument_flags = nil
    @rest_singles = nil
    @non_option_arguments = nil

    return self
  end


terminated? (GetoptLong)

# File lib/getoptlong.rb, line 386
  def terminated?
    return @status == STATUS_TERMINATED
  end


set_error (GetoptLong)

# File lib/getoptlong.rb, line 393
  def set_error(type, message)
    $deferr.print("#{$0}: #{message}\n") if !@quiet

    @error = type
    @error_message = message
    @canonical_names = nil
    @argument_flags = nil
    @rest_singles = nil
    @non_option_arguments = nil

    raise type, message
  end


error_message (GetoptLong)

# File lib/getoptlong.rb, line 420
  def error_message
    return @error_message
  end


get (GetoptLong)

# File lib/getoptlong.rb, line 435
  def get
    option_name, option_argument = nil, ''

    #
    # Check status.
    #
    return nil if @error != nil
    case @status
    when STATUS_YET
      @status = STATUS_STARTED
    when STATUS_TERMINATED
      return nil
    end

    #
    # Get next option argument.
    #
    if 0 < @rest_singles.length
      argument = '-' + @rest_singles
    elsif (ARGV.length == 0)
      terminate
      return nil
    elsif @ordering == PERMUTE
      while 0 < ARGV.length && ARGV[0] !~ /^-./
        @non_option_arguments.push(ARGV.shift)
      end
      if ARGV.length == 0
        terminate
        return nil
      end
      argument = ARGV.shift
    elsif @ordering == REQUIRE_ORDER
      if (ARGV[0] !~ /^-./)
        terminate
        return nil
      end
      argument = ARGV.shift
    else
      argument = ARGV.shift
    end

    #
    # Check the special argument `--'.
    # `--' indicates the end of the option list.
    #
    if argument == '--' && @rest_singles.length == 0
      terminate
      return nil
    end

    #
    # Check for long and short options.
    #
    if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
      #
      # This is a long style option, which start with `--'.
      #
      pattern = $1
      if @canonical_names.include?(pattern)
        option_name = pattern
      else
        #
        # The option `option_name' is not registered in `@canonical_names'.
        # It may be an abbreviated.
        #
        match_count = 0
        @canonical_names.each_key do |key|
          if key.index(pattern) == 0
            option_name = key
            match_count += 1
          end
        end
        if 2 <= match_count
          set_error(AmbigousOption, "option `#{argument}' is ambiguous")
        elsif match_count == 0
          set_error(InvalidOption, "unrecognized option `#{argument}'")
        end
      end

      #
      # Check an argument to the option.
      #
      if @argument_flags[option_name] == REQUIRED_ARGUMENT
        if argument =~ /=(.*)$/
          option_argument = $1
        elsif 0 < ARGV.length
          option_argument = ARGV.shift
        else
          set_error(MissingArgument,
                    "option `#{argument}' requires an argument")
        end
      elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
        if argument =~ /=(.*)$/
          option_argument = $1
        elsif 0 < ARGV.length && ARGV[0] !~ /^-./
          option_argument = ARGV.shift
        else
          option_argument = ''
        end
      elsif argument =~ /=(.*)$/
        set_error(NeedlessArgument,
                  "option `#{option_name}' doesn't allow an argument")
      end

    elsif argument =~ /^(-(.))(.*)/
      #
      # This is a short style option, which start with `-' (not `--').
      # Short options may be catenated (e.g. `-l -g' is equivalent to
      # `-lg').
      #
      option_name, ch, @rest_singles = $1, $2, $3

      if @canonical_names.include?(option_name)
        #
        # The option `option_name' is found in `@canonical_names'.
        # Check its argument.
        #
        if @argument_flags[option_name] == REQUIRED_ARGUMENT
          if 0 < @rest_singles.length
            option_argument = @rest_singles
            @rest_singles = ''
          elsif 0 < ARGV.length
            option_argument = ARGV.shift
          else
            # 1003.2 specifies the format of this message.
            set_error(MissingArgument, "option requires an argument -- #{ch}")
          end
        elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
          if 0 < @rest_singles.length
            option_argument = @rest_singles
            @rest_singles = ''
          elsif 0 < ARGV.length && ARGV[0] !~ /^-./
            option_argument = ARGV.shift
          else
            option_argument = ''
          end
        end
      else
        #
        # This is an invalid option.
        # 1003.2 specifies the format of this message.
        #
        if ENV.include?('POSIXLY_CORRECT')
          set_error(InvalidOption, "illegal option -- #{ch}")
        else
          set_error(InvalidOption, "invalid option -- #{ch}")
        end
      end
    else
      #
      # This is a non-option argument.
      # Only RETURN_IN_ORDER falled into here.
      #
      return '', argument
    end

    return @canonical_names[option_name], option_argument
  end


each (GetoptLong)

# File lib/getoptlong.rb, line 609
  def each
    loop do
      option_name, option_argument = get_option
      break if option_name == nil
      yield option_name, option_argument
    end
  end


serve (GServer)

# File lib/gserver.rb, line 90
  def serve(io)
  end


stop (GServer)

# File lib/gserver.rb, line 96
  def GServer.stop(port, host = DEFAULT_HOST)
    @@servicesMutex.synchronize {
      @@services[host][port].stop
    }
  end


in_service? (GServer)

# File lib/gserver.rb, line 102
  def GServer.in_service?(port, host = DEFAULT_HOST)
    @@services.has_key?(host) and
      @@services[host].has_key?(port)
  end


stop (GServer)

# File lib/gserver.rb, line 107
  def stop
    @connectionsMutex.synchronize  {
      if @tcpServerThread
        @tcpServerThread.raise "stop"
      end
    }
  end


stopped? (GServer)

# File lib/gserver.rb, line 115
  def stopped?
    @tcpServerThread == nil
  end


shutdown (GServer)

# File lib/gserver.rb, line 119
  def shutdown
    @shutdown = true
  end


connections (GServer)

# File lib/gserver.rb, line 123
  def connections
    @connections.size
  end


join (GServer)

# File lib/gserver.rb, line 127
  def join
    @tcpServerThread.join if @tcpServerThread
  end


connecting (GServer)

# File lib/gserver.rb, line 134
  def connecting(client)
    addr = client.peeraddr
    log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " +
        "#{addr[2]}<#{addr[3]}> connect")
    true
  end


disconnecting (GServer)

# File lib/gserver.rb, line 141
  def disconnecting(clientPort)
    log("#{self.class.to_s} #{@host}:#{@port} " +
      "client:#{clientPort} disconnect")
  end


starting (GServer)

# File lib/gserver.rb, line 148
  def starting()
    log("#{self.class.to_s} #{@host}:#{@port} start")
  end


stopping (GServer)

# File lib/gserver.rb, line 152
  def stopping()
    log("#{self.class.to_s} #{@host}:#{@port} stop")
  end


error (GServer)

# File lib/gserver.rb, line 158
  def error(detail)
    log(detail.backtrace.join("\n"))
  end


log (GServer)

# File lib/gserver.rb, line 162
  def log(msg)
    if @stdlog
      @stdlog.puts("[#{Time.new.ctime}] %s" % msg)
      @stdlog.flush
    end
  end


new (GServer)

# File lib/gserver.rb, line 171
  def initialize(port, host = DEFAULT_HOST, maxConnections = 4,
    stdlog = $stderr, audit = false, debug = false)
    @tcpServerThread = nil
    @port = port
    @host = host
    @maxConnections = maxConnections
    @connections = []
    @connectionsMutex = Mutex.new
    @connectionsCV = ConditionVariable.new
    @stdlog = stdlog
    @audit = audit
    @debug = debug
  end


start (GServer)

# File lib/gserver.rb, line 185
  def start(maxConnections = -1)
    raise "running" if !stopped?
    @shutdown = false
    @maxConnections = maxConnections if maxConnections > 0
    @@servicesMutex.synchronize  {
      if GServer.in_service?(@port,@host)
        raise "Port already in use: #{host}:#{@port}!"
      end
      @tcpServer = TCPServer.new(@host,@port)
      @port = @tcpServer.addr[1]
      @@services[@host] = {} unless @@services.has_key?(@host)
      @@services[@host][@port] = self;
    }
    @tcpServerThread = Thread.new {
      begin
        starting if @audit
        while !@shutdown
          @connectionsMutex.synchronize  {
             while @connections.size >= @maxConnections
               @connectionsCV.wait(@connectionsMutex)
             end
          }
          client = @tcpServer.accept
          @connections << Thread.new(client)  { |myClient|
            begin
              myPort = myClient.peeraddr[1]
              serve(myClient) if !@audit or connecting(myClient)
            rescue => detail
              error(detail) if @debug
            ensure
              begin
                myClient.close
              rescue
              end
              @connectionsMutex.synchronize {
                @connections.delete(Thread.current)
                @connectionsCV.signal
              }
              disconnecting(myPort) if @audit
            end
          }
        end
      rescue => detail
        error(detail) if @debug
      ensure
        begin
          @tcpServer.close
        rescue
        end
        if @shutdown
          @connectionsMutex.synchronize  {
             while @connections.size > 0
               @connectionsCV.wait(@connectionsMutex)
             end
          }
        else
          @connections.each { |c| c.raise "stop" }
        end
        @tcpServerThread = nil
        @@servicesMutex.synchronize  {
          @@services[@host].delete(@port)
        }
        stopping if @audit
      end
    }
    self
  end


[] (Hash)

/*
 *  call-seq:
 *     Hash[ [key =>|, value]* ]   => hash
 *
 *  Creates a new hash populated with the given objects. Equivalent to
 *  the literal <code>{ <i>key</i>, <i>value</i>, ... }</code>. Keys and
 *  values occur in pairs, so there must be an even number of arguments.
 *
 *     Hash["a", 100, "b", 200]       #=> {"a"=>100, "b"=>200}
 *     Hash["a" => 100, "b" => 200]   #=> {"a"=>100, "b"=>200}
 *     { "a" => 100, "b" => 200 }     #=> {"a"=>100, "b"=>200}
 */

static VALUE
rb_hash_s_create(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE hash;
    int i;

    if (argc == 1 && TYPE(argv[0]) == T_HASH) {
        hash = hash_alloc0(klass);
        RHASH(hash)->tbl = st_copy(RHASH(argv[0])->tbl);

        return hash;
    }

    if (argc % 2 != 0) {
        rb_raise(rb_eArgError, "odd number of arguments for Hash");
    }

    hash = hash_alloc(klass);
    for (i=0; i<argc; i+=2) {
        rb_hash_aset(hash, argv[i], argv[i + 1]);
    }

    return hash;
}


new (Hash)

/*
 *  call-seq:
 *     Hash.new                          => hash
 *     Hash.new(obj)                     => aHash
 *     Hash.new {|hash, key| block }     => aHash
 *
 *  Returns a new, empty hash. If this hash is subsequently accessed by
 *  a key that doesn't correspond to a hash entry, the value returned
 *  depends on the style of <code>new</code> used to create the hash. In
 *  the first form, the access returns <code>nil</code>. If
 *  <i>obj</i> is specified, this single object will be used for
 *  all <em>default values</em>. If a block is specified, it will be
 *  called with the hash object and the key, and should return the
 *  default value. It is the block's responsibility to store the value
 *  in the hash if required.
 *
 *     h = Hash.new("Go Fish")
 *     h["a"] = 100
 *     h["b"] = 200
 *     h["a"]           #=> 100
 *     h["c"]           #=> "Go Fish"
 *     # The following alters the single default object
 *     h["c"].upcase!   #=> "GO FISH"
 *     h["d"]           #=> "GO FISH"
 *     h.keys           #=> ["a", "b"]
 *
 *     # While this creates a new default object each time
 *     h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
 *     h["c"]           #=> "Go Fish: c"
 *     h["c"].upcase!   #=> "GO FISH: C"
 *     h["d"]           #=> "Go Fish: d"
 *     h.keys           #=> ["c", "d"]
 *
 */

static VALUE
rb_hash_initialize(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE ifnone;

    rb_hash_modify(hash);
    if (rb_block_given_p()) {
        if (argc > 0) {
            rb_raise(rb_eArgError, "wrong number of arguments");
        }
        RHASH(hash)->ifnone = rb_block_proc();
        FL_SET(hash, HASH_PROC_DEFAULT);
    }
    else {
        rb_scan_args(argc, argv, "01", &ifnone);
        RHASH(hash)->ifnone = ifnone;
    }

    return hash;
}


initialize_copy (Hash)

/*
 *  call-seq:
 *     hsh.replace(other_hash) -> hsh
 *
 *  Replaces the contents of <i>hsh</i> with the contents of
 *  <i>other_hash</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.replace({ "c" => 300, "d" => 400 })   #=> {"c"=>300, "d"=>400}
 *
 */

static VALUE
rb_hash_replace(hash, hash2)
    VALUE hash, hash2;
{
    hash2 = to_hash(hash2);
    if (hash == hash2) return hash;
    rb_hash_clear(hash);
    rb_hash_foreach(hash2, replace_i, hash);
    RHASH(hash)->ifnone = RHASH(hash2)->ifnone;
    if (FL_TEST(hash2, HASH_PROC_DEFAULT)) {
        FL_SET(hash, HASH_PROC_DEFAULT);
    }
    else {
        FL_UNSET(hash, HASH_PROC_DEFAULT);
    }

    return hash;
}


rehash (Hash)

/*
 *  call-seq:
 *     hsh.rehash -> hsh
 *
 *  Rebuilds the hash based on the current hash values for each key. If
 *  values of key objects have changed since they were inserted, this
 *  method will reindex <i>hsh</i>. If <code>Hash#rehash</code> is
 *  called while an iterator is traversing the hash, an
 *  <code>IndexError</code> will be raised in the iterator.
 *
 *     a = [ "a", "b" ]
 *     c = [ "c", "d" ]
 *     h = { a => 100, c => 300 }
 *     h[a]       #=> 100
 *     a[0] = "z"
 *     h[a]       #=> nil
 *     h.rehash   #=> {["z", "b"]=>100, ["c", "d"]=>300}
 *     h[a]       #=> 100
 */

static VALUE
rb_hash_rehash(hash)
    VALUE hash;
{
    st_table *tbl;

    rb_hash_modify(hash);
    tbl = st_init_table_with_size(&objhash, RHASH(hash)->tbl->num_entries);
    rb_hash_foreach(hash, rb_hash_rehash_i, (st_data_t)tbl);
    st_free_table(RHASH(hash)->tbl);
    RHASH(hash)->tbl = tbl;

    return hash;
}


to_hash (Hash)

/*
 * call-seq:
 *    hsh.to_hash   => hsh
 *
 * Returns <i>self</i>.
 */

static VALUE
rb_hash_to_hash(hash)
    VALUE hash;
{
    return hash;
}


to_a (Hash)

/*
 *  call-seq:
 *     hsh.to_a -> array
 *
 *  Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
 *  value</i> <code>]</code> arrays.
 *
 *     h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
 *     h.to_a   #=> [["a", 100], ["c", 300], ["d", 400]]
 */

static VALUE
rb_hash_to_a(hash)
    VALUE hash;
{
    VALUE ary;

    ary = rb_ary_new();
    rb_hash_foreach(hash, to_a_i, ary);
    if (OBJ_TAINTED(hash)) OBJ_TAINT(ary);

    return ary;
}


to_s (Hash)

/*
 *  call-seq:
 *     hsh.to_s   => string
 *
 *  Converts <i>hsh</i> to a string by converting the hash to an array
 *  of <code>[</code> <i>key, value</i> <code>]</code> pairs and then
 *  converting that array to a string using <code>Array#join</code> with
 *  the default separator.
 *
 *     h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
 *     h.to_s   #=> "a100c300d400"
 */

static VALUE
rb_hash_to_s(hash)
    VALUE hash;
{
    if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
    return rb_protect_inspect(to_s_hash, hash, 0);
}


inspect (Hash)

/*
 * call-seq:
 *   hsh.inspect  => string
 *
 * Return the contents of this hash as a string.
 */

static VALUE
rb_hash_inspect(hash)
    VALUE hash;
{
    if (RHASH(hash)->tbl == 0 || RHASH(hash)->tbl->num_entries == 0)
        return rb_str_new2("{}");
    if (rb_inspecting_p(hash)) return rb_str_new2("{...}");
    return rb_protect_inspect(inspect_hash, hash, 0);
}


== (Hash)

/*
 *  call-seq:
 *     hsh == other_hash    => true or false
 *
 *  Equality---Two hashes are equal if they each contain the same number
 *  of keys and if each key-value pair is equal to (according to
 *  <code>Object#==</code>) the corresponding elements in the other
 *  hash.
 *
 *     h1 = { "a" => 1, "c" => 2 }
 *     h2 = { 7 => 35, "c" => 2, "a" => 1 }
 *     h3 = { "a" => 1, "c" => 2, 7 => 35 }
 *     h4 = { "a" => 1, "d" => 2, "f" => 35 }
 *     h1 == h2   #=> false
 *     h2 == h3   #=> true
 *     h3 == h4   #=> false
 *
 */

static VALUE
rb_hash_equal(hash1, hash2)
    VALUE hash1, hash2;
{
    return hash_equal(hash1, hash2, Qfalse);
}


[] (Hash)

/*
 *  call-seq:
 *     hsh[key]    =>  value
 *
 *  Element Reference---Retrieves the <i>value</i> object corresponding
 *  to the <i>key</i> object. If not found, returns the a default value (see
 *  <code>Hash::new</code> for details).
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h["a"]   #=> 100
 *     h["c"]   #=> nil
 *
 */

VALUE
rb_hash_aref(hash, key)
    VALUE hash, key;
{
    VALUE val;

    if (!st_lookup(RHASH(hash)->tbl, key, &val)) {
        return rb_funcall(hash, id_default, 1, key);
    }
    return val;
}


fetch (Hash)

/*
 *  call-seq:
 *     hsh.fetch(key [, default] )       => obj
 *     hsh.fetch(key) {| key | block }   => obj
 *
 *  Returns a value from the hash for the given key. If the key can't be
 *  found, there are several options: With no other arguments, it will
 *  raise an <code>IndexError</code> exception; if <i>default</i> is
 *  given, then that will be returned; if the optional code block is
 *  specified, then that will be run and its result returned.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.fetch("a")                            #=> 100
 *     h.fetch("z", "go fish")                 #=> "go fish"
 *     h.fetch("z") { |el| "go fish, #{el}"}   #=> "go fish, z"
 *
 *  The following example shows that an exception is raised if the key
 *  is not found and a default value is not supplied.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.fetch("z")
 *
 *  <em>produces:</em>
 *
 *     prog.rb:2:in `fetch': key not found (IndexError)
 *      from prog.rb:2
 *
 */

static VALUE
rb_hash_fetch(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE key, if_none;
    VALUE val;
    long block_given;

    rb_scan_args(argc, argv, "11", &key, &if_none);

    block_given = rb_block_given_p();
    if (block_given && argc == 2) {
        rb_warn("block supersedes default value argument");
    }
    if (!st_lookup(RHASH(hash)->tbl, key, &val)) {
        if (block_given) return rb_yield(key);
        if (argc == 1) {
            rb_raise(rb_eIndexError, "key not found");
        }
        return if_none;
    }
    return val;
}


[]= (Hash)

/*
 *  call-seq:
 *     hsh[key] = value        => value
 *     hsh.store(key, value)   => value
 *
 *  Element Assignment---Associates the value given by
 *  <i>value</i> with the key given by <i>key</i>.
 *  <i>key</i> should not have its value changed while it is in
 *  use as a key (a <code>String</code> passed as a key will be
 *  duplicated and frozen).
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h["a"] = 9
 *     h["c"] = 4
 *     h   #=> {"a"=>9, "b"=>200, "c"=>4}
 *
 */

VALUE
rb_hash_aset(hash, key, val)
    VALUE hash, key, val;
{
    rb_hash_modify(hash);
    if (TYPE(key) != T_STRING || st_lookup(RHASH(hash)->tbl, key, 0)) {
        st_insert(RHASH(hash)->tbl, key, val);
    }
    else {
        st_add_direct(RHASH(hash)->tbl, rb_str_new4(key), val);
    }
    return val;
}


store (Hash)

/*
 *  call-seq:
 *     hsh[key] = value        => value
 *     hsh.store(key, value)   => value
 *
 *  Element Assignment---Associates the value given by
 *  <i>value</i> with the key given by <i>key</i>.
 *  <i>key</i> should not have its value changed while it is in
 *  use as a key (a <code>String</code> passed as a key will be
 *  duplicated and frozen).
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h["a"] = 9
 *     h["c"] = 4
 *     h   #=> {"a"=>9, "b"=>200, "c"=>4}
 *
 */

VALUE
rb_hash_aset(hash, key, val)
    VALUE hash, key, val;
{
    rb_hash_modify(hash);
    if (TYPE(key) != T_STRING || st_lookup(RHASH(hash)->tbl, key, 0)) {
        st_insert(RHASH(hash)->tbl, key, val);
    }
    else {
        st_add_direct(RHASH(hash)->tbl, rb_str_new4(key), val);
    }
    return val;
}


default (Hash)

/*
 *  call-seq:
 *     hsh.default(key=nil)   => obj
 *
 *  Returns the default value, the value that would be returned by
 *  <i>hsh</i>[<i>key</i>] if <i>key</i> did not exist in <i>hsh</i>.
 *  See also <code>Hash::new</code> and <code>Hash#default=</code>.
 *
 *     h = Hash.new                            #=> {}
 *     h.default                               #=> nil
 *     h.default(2)                            #=> nil
 *
 *     h = Hash.new("cat")                     #=> {}
 *     h.default                               #=> "cat"
 *     h.default(2)                            #=> "cat"
 *
 *     h = Hash.new {|h,k| h[k] = k.to_i*10}   #=> {}
 *     h.default                               #=> 0
 *     h.default(2)                            #=> 20
 */

static VALUE
rb_hash_default(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE key;

    rb_scan_args(argc, argv, "01", &key);
    if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
        if (argc == 0) return Qnil;
        return rb_funcall(RHASH(hash)->ifnone, id_call, 2, hash, key);
    }
    return RHASH(hash)->ifnone;
}


default= (Hash)

/*
 *  call-seq:
 *     hsh.default = obj     => hsh
 *
 *  Sets the default value, the value returned for a key that does not
 *  exist in the hash. It is not possible to set the a default to a
 *  <code>Proc</code> that will be executed on each key lookup.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.default = "Go fish"
 *     h["a"]     #=> 100
 *     h["z"]     #=> "Go fish"
 *     # This doesn't do what you might hope...
 *     h.default = proc do |hash, key|
 *       hash[key] = key + key
 *     end
 *     h[2]       #=> #<Proc:0x401b3948@-:6>
 *     h["cat"]   #=> #<Proc:0x401b3948@-:6>
 */

static VALUE
rb_hash_set_default(hash, ifnone)
    VALUE hash, ifnone;
{
    rb_hash_modify(hash);
    RHASH(hash)->ifnone = ifnone;
    FL_UNSET(hash, HASH_PROC_DEFAULT);
    return ifnone;
}


default_proc (Hash)

/*
 *  call-seq:
 *     hsh.default_proc -> anObject
 *
 *  If <code>Hash::new</code> was invoked with a block, return that
 *  block, otherwise return <code>nil</code>.
 *
 *     h = Hash.new {|h,k| h[k] = k*k }   #=> {}
 *     p = h.default_proc                 #=> #<Proc:0x401b3d08@-:1>
 *     a = []                             #=> []
 *     p.call(a, 2)
 *     a                                  #=> [nil, nil, 4]
 */

static VALUE
rb_hash_default_proc(hash)
    VALUE hash;
{
    if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
        return RHASH(hash)->ifnone;
    }
    return Qnil;
}


index (Hash)

/*
 *  call-seq:
 *     hsh.index(value)    => key
 *
 *  Returns the key for a given value. If not found, returns <code>nil</code>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.index(200)   #=> "b"
 *     h.index(999)   #=> nil
 *
 */

static VALUE
rb_hash_index(hash, value)
    VALUE hash, value;
{
    VALUE args[2];

    args[0] = value;
    args[1] = Qnil;

    rb_hash_foreach(hash, index_i, (st_data_t)args);

    return args[1];
}


indexes (Hash)

/*
 *  call-seq:
 *     hsh.indexes(key, ...)    => array
 *     hsh.indices(key, ...)    => array
 *
 *  Deprecated in favor of <code>Hash#select</code>.
 *
 */

static VALUE
rb_hash_indexes(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE indexes;
    int i;

    rb_warn("Hash#%s is deprecated; use Hash#values_at",
            rb_id2name(rb_frame_last_func()));
    indexes = rb_ary_new2(argc);
    for (i=0; i<argc; i++) {
        RARRAY(indexes)->ptr[i] = rb_hash_aref(hash, argv[i]);
        RARRAY(indexes)->len++;
    }
    return indexes;
}


indices (Hash)

/*
 *  call-seq:
 *     hsh.indexes(key, ...)    => array
 *     hsh.indices(key, ...)    => array
 *
 *  Deprecated in favor of <code>Hash#select</code>.
 *
 */

static VALUE
rb_hash_indexes(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE indexes;
    int i;

    rb_warn("Hash#%s is deprecated; use Hash#values_at",
            rb_id2name(rb_frame_last_func()));
    indexes = rb_ary_new2(argc);
    for (i=0; i<argc; i++) {
        RARRAY(indexes)->ptr[i] = rb_hash_aref(hash, argv[i]);
        RARRAY(indexes)->len++;
    }
    return indexes;
}


size (Hash)

/*
 *  call-seq:
 *     hsh.length    =>  fixnum
 *     hsh.size      =>  fixnum
 *
 *  Returns the number of key-value pairs in the hash.
 *
 *     h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
 *     h.length        #=> 4
 *     h.delete("a")   #=> 200
 *     h.length        #=> 3
 */

static VALUE
rb_hash_size(hash)
    VALUE hash;
{
    return INT2FIX(RHASH(hash)->tbl->num_entries);
}


length (Hash)

/*
 *  call-seq:
 *     hsh.length    =>  fixnum
 *     hsh.size      =>  fixnum
 *
 *  Returns the number of key-value pairs in the hash.
 *
 *     h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
 *     h.length        #=> 4
 *     h.delete("a")   #=> 200
 *     h.length        #=> 3
 */

static VALUE
rb_hash_size(hash)
    VALUE hash;
{
    return INT2FIX(RHASH(hash)->tbl->num_entries);
}


empty? (Hash)

/*
 *  call-seq:
 *     hsh.empty?    => true or false
 *
 *  Returns <code>true</code> if <i>hsh</i> contains no key-value pairs.
 *
 *     {}.empty?   #=> true
 *
 */

static VALUE
rb_hash_empty_p(hash)
    VALUE hash;
{
    if (RHASH(hash)->tbl->num_entries == 0)
        return Qtrue;
    return Qfalse;
}


each (Hash)

/*
 *  call-seq:
 *     hsh.each {| key, value | block } -> hsh
 *
 *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
 *  and value to the block as a two-element array. Because of the assignment
 *  semantics of block parameters, these elements will be split out if the
 *  block has two formal parameters. Also see <code>Hash.each_pair</code>, which
 *  will be marginally more efficient for blocks with two parameters.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.each {|key, value| puts "#{key} is #{value}" }
 *
 *  <em>produces:</em>
 *
 *     a is 100
 *     b is 200
 *
 */

static VALUE
rb_hash_each(hash)
    VALUE hash;
{
    rb_hash_foreach(hash, each_i, 0);
    return hash;
}


each_value (Hash)

/*
 *  call-seq:
 *     hsh.each_value {| value | block } -> hsh
 *
 *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the
 *  value as a parameter.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.each_value {|value| puts value }
 *
 *  <em>produces:</em>
 *
 *     100
 *     200
 */

static VALUE
rb_hash_each_value(hash)
    VALUE hash;
{
    rb_hash_foreach(hash, each_value_i, 0);
    return hash;
}


each_key (Hash)

/*
 *  call-seq:
 *     hsh.each_key {| key | block } -> hsh
 *
 *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
 *  as a parameter.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.each_key {|key| puts key }
 *
 *  <em>produces:</em>
 *
 *     a
 *     b
 */
static VALUE
rb_hash_each_key(hash)
    VALUE hash;
{
    rb_hash_foreach(hash, each_key_i, 0);
    return hash;
}


each_pair (Hash)

/*
 *  call-seq:
 *     hsh.each_pair {| key_value_array | block } -> hsh
 *
 *  Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
 *  and value as parameters.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.each_pair {|key, value| puts "#{key} is #{value}" }
 *
 *  <em>produces:</em>
 *
 *     a is 100
 *     b is 200
 *
 */

static VALUE
rb_hash_each_pair(hash)
    VALUE hash;
{
    rb_hash_foreach(hash, each_pair_i, 0);
    return hash;
}


sort (Hash)

/*
 *  call-seq:
 *     hsh.sort                    => array
 *     hsh.sort {| a, b | block }  => array
 *
 *  Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
 *  value</i> <code>]</code> arrays and sorts it, using
 *  <code>Array#sort</code>.
 *
 *     h = { "a" => 20, "b" => 30, "c" => 10  }
 *     h.sort                       #=> [["a", 20], ["b", 30], ["c", 10]]
 *     h.sort {|a,b| a[1]<=>b[1]}   #=> [["c", 10], ["a", 20], ["b", 30]]
 *
 */

static VALUE
rb_hash_sort(hash)
    VALUE hash;
{
    VALUE entries = rb_hash_to_a(hash);
    rb_ary_sort_bang(entries);
    return entries;
}


keys (Hash)

/*
 *  call-seq:
 *     hsh.keys    => array
 *
 *  Returns a new array populated with the keys from this hash. See also
 *  <code>Hash#values</code>.
 *
 *     h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
 *     h.keys   #=> ["a", "b", "c", "d"]
 *
 */

static VALUE
rb_hash_keys(hash)
    VALUE hash;
{
    VALUE ary;

    ary = rb_ary_new();
    rb_hash_foreach(hash, keys_i, ary);

    return ary;
}


values (Hash)

/*
 *  call-seq:
 *     hsh.values    => array
 *
 *  Returns a new array populated with the values from <i>hsh</i>. See
 *  also <code>Hash#keys</code>.
 *
 *     h = { "a" => 100, "b" => 200, "c" => 300 }
 *     h.values   #=> [100, 200, 300]
 *
 */

static VALUE
rb_hash_values(hash)
    VALUE hash;
{
    VALUE ary;

    ary = rb_ary_new();
    rb_hash_foreach(hash, values_i, ary);

    return ary;
}


values_at (Hash)

/*
 * call-seq:
 *   hsh.values_at(key, ...)   => array
 *
 * Return an array containing the values associated with the given keys.
 * Also see <code>Hash.select</code>.
 *
 *   h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
 *   h.values_at("cow", "cat")  #=> ["bovine", "feline"]
*/

VALUE
rb_hash_values_at(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE result = rb_ary_new();
    long i;

    for (i=0; i<argc; i++) {
        rb_ary_push(result, rb_hash_aref(hash, argv[i]));
    }
    return result;
}


shift (Hash)

/*
 *  call-seq:
 *     hsh.shift -> anArray or obj
 *
 *  Removes a key-value pair from <i>hsh</i> and returns it as the
 *  two-item array <code>[</code> <i>key, value</i> <code>]</code>, or
 *  the hash's default value if the hash is empty.
 *
 *     h = { 1 => "a", 2 => "b", 3 => "c" }
 *     h.shift   #=> [1, "a"]
 *     h         #=> {2=>"b", 3=>"c"}
 */

static VALUE
rb_hash_shift(hash)
    VALUE hash;
{
    struct shift_var var;

    rb_hash_modify(hash);
    var.key = Qundef;
    if (RHASH(hash)->iter_lev > 0) {
        rb_hash_foreach(hash, shift_i_safe, (st_data_t)&var);
        if (var.key != Qundef) {
            st_data_t key = var.key;
            if (st_delete_safe(RHASH(hash)->tbl, &key, 0, Qundef)) {
                FL_SET(hash, HASH_DELETED);
            }
        }
    }
    else {
        rb_hash_foreach(hash, shift_i, (st_data_t)&var);
    }

    if (var.key != Qundef) {
        return rb_assoc_new(var.key, var.val);
    }
    else if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
        return rb_funcall(RHASH(hash)->ifnone, id_call, 2, hash, Qnil);
    }
    else {
        return RHASH(hash)->ifnone;
    }
}


delete (Hash)

/*
 *  call-seq:
 *     hsh.delete(key)                   => value
 *     hsh.delete(key) {| key | block }  => value
 *
 *  Deletes and returns a key-value pair from <i>hsh</i> whose key is
 *  equal to <i>key</i>. If the key is not found, returns the
 *  <em>default value</em>. If the optional code block is given and the
 *  key is not found, pass in the key and return the result of
 *  <i>block</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.delete("a")                              #=> 100
 *     h.delete("z")                              #=> nil
 *     h.delete("z") { |el| "#{el} not found" }   #=> "z not found"
 *
 */

VALUE
rb_hash_delete(hash, key)
    VALUE hash, key;
{
    VALUE val;

    rb_hash_modify(hash);
    val = rb_hash_delete_key(hash, key);
    if (val != Qundef) return val;
    if (rb_block_given_p()) {
        return rb_yield(key);
    }
    return Qnil;
}


delete_if (Hash)

/*
 *  call-seq:
 *     hsh.delete_if {| key, value | block }  -> hsh
 *
 *  Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
 *  evaluates to <code>true</code>.
 *
 *     h = { "a" => 100, "b" => 200, "c" => 300 }
 *     h.delete_if {|key, value| key >= "b" }   #=> {"a"=>100}
 *
 */

VALUE
rb_hash_delete_if(hash)
    VALUE hash;
{
    rb_hash_modify(hash);
    rb_hash_foreach(hash, delete_if_i, hash);
    return hash;
}


select (Hash)

/*
 *  call-seq:
 *     hsh.select {|key, value| block}   => array
 *
 *  Returns a new array consisting of <code>[key,value]</code>
 *  pairs for which the block returns true.
 *  Also see <code>Hash.values_at</code>.
 *
 *     h = { "a" => 100, "b" => 200, "c" => 300 }
 *     h.select {|k,v| k > "a"}  #=> [["b", 200], ["c", 300]]
 *     h.select {|k,v| v < 200}  #=> [["a", 100]]
 */

VALUE
rb_hash_select(argc, argv, hash)
    int argc;
    VALUE *argv;
    VALUE hash;
{
    VALUE result;

    if (argc > 0) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
    }
    result = rb_ary_new();
    rb_hash_foreach(hash, select_i, result);
    return result;
}


reject (Hash)

/*
 *  call-seq:
 *     hsh.reject {| key, value | block }  -> a_hash
 *
 *  Same as <code>Hash#delete_if</code>, but works on (and returns) a
 *  copy of the <i>hsh</i>. Equivalent to
 *  <code><i>hsh</i>.dup.delete_if</code>.
 *
 */

static VALUE
rb_hash_reject(hash)
    VALUE hash;
{
    return rb_hash_delete_if(rb_obj_dup(hash));
}


reject! (Hash)

/*
 *  call-seq:
 *     hsh.reject! {| key, value | block }  -> hsh or nil
 *
 *  Equivalent to <code>Hash#delete_if</code>, but returns
 *  <code>nil</code> if no changes were made.
 */

VALUE
rb_hash_reject_bang(hash)
    VALUE hash;
{
    int n = RHASH(hash)->tbl->num_entries;
    rb_hash_delete_if(hash);
    if (n == RHASH(hash)->tbl->num_entries) return Qnil;
    return hash;
}


clear (Hash)

/*
 *  call-seq:
 *     hsh.clear -> hsh
 *
 *  Removes all key-value pairs from <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }   #=> {"a"=>100, "b"=>200}
 *     h.clear                          #=> {}
 *
 */

static VALUE
rb_hash_clear(hash)
    VALUE hash;
{
    rb_hash_modify(hash);
    if (RHASH(hash)->tbl->num_entries > 0) {
        rb_hash_foreach(hash, clear_i, 0);
    }

    return hash;
}


invert (Hash)

/*
 *  call-seq:
 *     hsh.invert -> aHash
 *
 *  Returns a new hash created by using <i>hsh</i>'s values as keys, and
 *  the keys as values.
 *
 *     h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
 *     h.invert   #=> {0=>"a", 100=>"n", 200=>"d", 300=>"y"}
 *
 */

static VALUE
rb_hash_invert(hash)
    VALUE hash;
{
    VALUE h = rb_hash_new();

    rb_hash_foreach(hash, rb_hash_invert_i, h);
    return h;
}


update (Hash)

/*
 *  call-seq:
 *     hsh.merge!(other_hash)                                 => hsh
 *     hsh.update(other_hash)                                 => hsh
 *     hsh.merge!(other_hash){|key, oldval, newval| block}    => hsh
 *     hsh.update(other_hash){|key, oldval, newval| block}    => hsh
 *
 *  Adds the contents of <i>other_hash</i> to <i>hsh</i>, overwriting
 *  entries with duplicate keys with those from <i>other_hash</i>.
 *
 *     h1 = { "a" => 100, "b" => 200 }
 *     h2 = { "b" => 254, "c" => 300 }
 *     h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
 */

static VALUE
rb_hash_update(hash1, hash2)
    VALUE hash1, hash2;
{
    hash2 = to_hash(hash2);
    if (rb_block_given_p()) {
        rb_hash_foreach(hash2, rb_hash_update_block_i, hash1);
    }
    else {
        rb_hash_foreach(hash2, rb_hash_update_i, hash1);
    }
    return hash1;
}


replace (Hash)

/*
 *  call-seq:
 *     hsh.replace(other_hash) -> hsh
 *
 *  Replaces the contents of <i>hsh</i> with the contents of
 *  <i>other_hash</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.replace({ "c" => 300, "d" => 400 })   #=> {"c"=>300, "d"=>400}
 *
 */

static VALUE
rb_hash_replace(hash, hash2)
    VALUE hash, hash2;
{
    hash2 = to_hash(hash2);
    if (hash == hash2) return hash;
    rb_hash_clear(hash);
    rb_hash_foreach(hash2, replace_i, hash);
    RHASH(hash)->ifnone = RHASH(hash2)->ifnone;
    if (FL_TEST(hash2, HASH_PROC_DEFAULT)) {
        FL_SET(hash, HASH_PROC_DEFAULT);
    }
    else {
        FL_UNSET(hash, HASH_PROC_DEFAULT);
    }

    return hash;
}


merge! (Hash)

/*
 *  call-seq:
 *     hsh.merge!(other_hash)                                 => hsh
 *     hsh.update(other_hash)                                 => hsh
 *     hsh.merge!(other_hash){|key, oldval, newval| block}    => hsh
 *     hsh.update(other_hash){|key, oldval, newval| block}    => hsh
 *
 *  Adds the contents of <i>other_hash</i> to <i>hsh</i>, overwriting
 *  entries with duplicate keys with those from <i>other_hash</i>.
 *
 *     h1 = { "a" => 100, "b" => 200 }
 *     h2 = { "b" => 254, "c" => 300 }
 *     h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
 */

static VALUE
rb_hash_update(hash1, hash2)
    VALUE hash1, hash2;
{
    hash2 = to_hash(hash2);
    if (rb_block_given_p()) {
        rb_hash_foreach(hash2, rb_hash_update_block_i, hash1);
    }
    else {
        rb_hash_foreach(hash2, rb_hash_update_i, hash1);
    }
    return hash1;
}


merge (Hash)

/*
 *  call-seq:
 *     hsh.merge(other_hash)                              -> a_hash
 *     hsh.merge(other_hash){|key, oldval, newval| block} -> a_hash
 *
 *  Returns a new hash containing the contents of <i>other_hash</i> and
 *  the contents of <i>hsh</i>, overwriting entries in <i>hsh</i> with
 *  duplicate keys with those from <i>other_hash</i>.
 *
 *     h1 = { "a" => 100, "b" => 200 }
 *     h2 = { "b" => 254, "c" => 300 }
 *     h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
 *     h1             #=> {"a"=>100, "b"=>200}
 *
 */

static VALUE
rb_hash_merge(hash1, hash2)
    VALUE hash1, hash2;
{
    return rb_hash_update(rb_obj_dup(hash1), hash2);
}


include? (Hash)

/*
 *  call-seq:
 *     hsh.has_key?(key)    => true or false
 *     hsh.include?(key)    => true or false
 *     hsh.key?(key)        => true or false
 *     hsh.member?(key)     => true or false
 *
 *  Returns <code>true</code> if the given key is present in <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.has_key?("a")   #=> true
 *     h.has_key?("z")   #=> false
 *
 */

static VALUE
rb_hash_has_key(hash, key)
    VALUE hash;
    VALUE key;
{
    if (st_lookup(RHASH(hash)->tbl, key, 0)) {
        return Qtrue;
    }
    return Qfalse;
}


member? (Hash)

/*
 *  call-seq:
 *     hsh.has_key?(key)    => true or false
 *     hsh.include?(key)    => true or false
 *     hsh.key?(key)        => true or false
 *     hsh.member?(key)     => true or false
 *
 *  Returns <code>true</code> if the given key is present in <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.has_key?("a")   #=> true
 *     h.has_key?("z")   #=> false
 *
 */

static VALUE
rb_hash_has_key(hash, key)
    VALUE hash;
    VALUE key;
{
    if (st_lookup(RHASH(hash)->tbl, key, 0)) {
        return Qtrue;
    }
    return Qfalse;
}


has_key? (Hash)

/*
 *  call-seq:
 *     hsh.has_key?(key)    => true or false
 *     hsh.include?(key)    => true or false
 *     hsh.key?(key)        => true or false
 *     hsh.member?(key)     => true or false
 *
 *  Returns <code>true</code> if the given key is present in <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.has_key?("a")   #=> true
 *     h.has_key?("z")   #=> false
 *
 */

static VALUE
rb_hash_has_key(hash, key)
    VALUE hash;
    VALUE key;
{
    if (st_lookup(RHASH(hash)->tbl, key, 0)) {
        return Qtrue;
    }
    return Qfalse;
}


has_value? (Hash)

/*
 *  call-seq:
 *     hsh.has_value?(value)    => true or false
 *     hsh.value?(value)        => true or false
 *
 *  Returns <code>true</code> if the given value is present for some key
 *  in <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.has_value?(100)   #=> true
 *     h.has_value?(999)   #=> false
 */

static VALUE
rb_hash_has_value(hash, val)
    VALUE hash;
    VALUE val;
{
    VALUE data[2];

    data[0] = Qfalse;
    data[1] = val;
    rb_hash_foreach(hash, rb_hash_search_value, (st_data_t)data);
    return data[0];
}


key? (Hash)

/*
 *  call-seq:
 *     hsh.has_key?(key)    => true or false
 *     hsh.include?(key)    => true or false
 *     hsh.key?(key)        => true or false
 *     hsh.member?(key)     => true or false
 *
 *  Returns <code>true</code> if the given key is present in <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.has_key?("a")   #=> true
 *     h.has_key?("z")   #=> false
 *
 */

static VALUE
rb_hash_has_key(hash, key)
    VALUE hash;
    VALUE key;
{
    if (st_lookup(RHASH(hash)->tbl, key, 0)) {
        return Qtrue;
    }
    return Qfalse;
}


value? (Hash)

/*
 *  call-seq:
 *     hsh.has_value?(value)    => true or false
 *     hsh.value?(value)        => true or false
 *
 *  Returns <code>true</code> if the given value is present for some key
 *  in <i>hsh</i>.
 *
 *     h = { "a" => 100, "b" => 200 }
 *     h.has_value?(100)   #=> true
 *     h.has_value?(999)   #=> false
 */

static VALUE
rb_hash_has_value(hash, val)
    VALUE hash;
    VALUE val;
{
    VALUE data[2];

    data[0] = Qfalse;
    data[1] = val;
    rb_hash_foreach(hash, rb_hash_search_value, (st_data_t)data);
    return data[0];
}


pretty_print (Hash)

# File lib/pp.rb, line 315
  def pretty_print(q)
    q.pp_hash self
  end


pretty_print_cycle (Hash)

# File lib/pp.rb, line 319
  def pretty_print_cycle(q)
    q.text(empty? ? '{}' : '{...}')
  end


yaml_initialize (Hash)

# File lib/yaml/rubytypes.rb, line 28
    def yaml_initialize( tag, val )
        if Array === val
            update Hash.[]( *val )              # Convert the map to a sequence
        elsif Hash === val
            update val
        else
            raise YAML::TypeError, "Invalid map explicitly tagged #{ tag }: " + val.inspect
        end
    end


to_yaml (Hash)

# File lib/yaml/rubytypes.rb, line 37
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            out.map( taguri, to_yaml_style ) do |map|
                each do |k, v|
                    map.add( k, v )
                end
            end
        end
        end


success (Iconv::Failure)

/*
 * Document-method: success
 * call-seq: success
 *
 * Returns string(s) translated successfully until the exception occurred.
 * * In the case of failure occurred within Iconv.iconv, returned
 *   value is an array of strings translated successfully preceding
 *   failure and the last element is string on the way.
 */
static VALUE
iconv_failure_success
    (self)
    VALUE self;
{
    return rb_attr_get(self, rb_success);
}


failed (Iconv::Failure)

/*
 * Document-method: failed
 * call-seq: failed
 *
 * Returns substring of the original string passed to Iconv that starts at the
 * character caused the exception.
 */
static VALUE
iconv_failure_failed
    (self)
    VALUE self;
{
    return rb_attr_get(self, rb_failed);
}


inspect (Iconv::Failure)

/*
 * Document-method: inspect
 * call-seq: inspect
 *
 * Returns inspected string like as: #<_class_: _success_, _failed_>
 */
static VALUE
iconv_failure_inspect
    (self)
    VALUE self;
{
    char *cname = rb_class2name(CLASS_OF(self));
    VALUE success = rb_attr_get(self, rb_success);
    VALUE failed = rb_attr_get(self, rb_failed);
    VALUE str = rb_str_buf_cat2(rb_str_new2("#<"), cname);
    str = rb_str_buf_cat(str, ": ", 2);
    str = rb_str_buf_append(str, rb_inspect(success));
    str = rb_str_buf_cat(str, ", ", 2);
    str = rb_str_buf_append(str, rb_inspect(failed));
    return rb_str_buf_cat(str, ">", 1);
}


open (Iconv)

/*
 * Document-method: open
 * call-seq: Iconv.open(to, from) { |iconv| ... }
 *
 * Equivalent to Iconv.new except that when it is called with a block, it
 * yields with the new instance and closes it, and returns the result which
 * returned from the block.
 */
static VALUE
iconv_s_open
    (self, to, from)
    VALUE self;
    VALUE to;
    VALUE from;
{
    VALUE cd = ICONV2VALUE(iconv_create(to, from));

    self = Data_Wrap_Struct(self, NULL, ICONV_FREE, (void *)cd);
    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, self, (VALUE(*)())iconv_finish, self);
    }
    else {
        return self;
    }
}


iconv (Iconv)

/*
 * Document-method: iconv
 * call-seq: Iconv.iconv(to, from, *strs)
 *
 * Shorthand for
 *   Iconv.open(to, from) { |cd|
 *     (strs + [nil]).collect { |s| cd.iconv(s) }
 *   }
 *
 * === Parameters
 *
 * <tt>to, from</tt>:: see Iconv.new
 * <tt>strs</tt>:: strings to be converted
 *
 * === Exceptions
 *
 * Exceptions thrown by Iconv.new, Iconv.open and Iconv#iconv.
 */
static VALUE
iconv_s_iconv
    (argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct iconv_env_t arg;

    if (argc < 2)               /* needs `to' and `from' arguments at least */
        rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", argc, 2);

    arg.argc = argc -= 2;
    arg.argv = argv + 2;
    arg.append = rb_ary_push;
    arg.ret = rb_ary_new2(argc);
    arg.cd = iconv_create(argv[0], argv[1]);
    return rb_ensure(iconv_s_convert, (VALUE)&arg, iconv_free, ICONV2VALUE(arg.cd));
}


conv (Iconv)

/*
 * Document-method: Iconv::conv
 * call-seq: Iconv.conv(to, from, str)
 *
 * Shorthand for
 *   Iconv.iconv(to, from, str).join
 * See Iconv.iconv.
 */
static VALUE
iconv_s_conv
    (self, to, from, str)
    VALUE self, to, from, str;
{
    struct iconv_env_t arg;

    arg.argc = 1;
    arg.argv = &str;
    arg.append = rb_str_append;
    arg.ret = rb_str_new(0, 0);
    arg.cd = iconv_create(to, from);
    return rb_ensure(iconv_s_convert, (VALUE)&arg, iconv_free, ICONV2VALUE(arg.cd));
}


new (Iconv)

/*
 * Document-method: new
 * call-seq: Iconv.new(to, from)
 *
 * Creates new code converter from a coding-system designated with +from+
 * to another one designated with +to+.
 *
 * === Parameters
 *
 * +to+::   encoding name for destination
 * +from+:: encoding name for source
 *
 * === Exceptions
 *
 * TypeError::       if +to+ or +from+ aren't String
 * InvalidEncoding:: if designated converter couldn't find out
 * SystemCallError:: if <tt>iconv_open(3)</tt> fails
 */
static VALUE
iconv_initialize
    (self, to, from)
    VALUE self;
    VALUE to;
    VALUE from;
{
    iconv_free(check_iconv(self));
    DATA_PTR(self) = NULL;
    DATA_PTR(self) = (void *)ICONV2VALUE(iconv_create(to, from));
    return self;
}


iconv (Iconv)

/*
 * Document-method: iconv
 * call-seq: iconv(str, start=0, length=-1)
 *
 * Converts string and returns the result.
 * * If +str+ is a String, converts <tt>str[start, length]</tt> and returns the converted string.
 * * If +str+ is +nil+, places converter itself into initial shift state and
 *   just returns a string containing the byte sequence to change the output
 *   buffer to its initial shift state.
 * * Otherwise, raises an exception.
 *
 * === Parameters
 *
 * str::    string to be converted, or nil
 * start::  starting offset
 * length:: conversion length; nil or -1 means whole the string from start
 *
 * === Exceptions
 *
 * * IconvIllegalSequence
 * * IconvInvalidCharacter
 * * IconvOutOfRange
 *
 * === Examples
 *
 * See the Iconv documentation.
 */
static VALUE
iconv_iconv
    (argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE str, n1, n2;
    VALUE cd = check_iconv(self);

    n1 = n2 = Qnil;
    rb_scan_args(argc, argv, "12", &str, &n1, &n2);

    return iconv_convert(VALUE2ICONV(cd), str,
                         NIL_P(n1) ? 0 : NUM2INT(n1),
                         NIL_P(n2) ? -1 : NUM2INT(n2),
                         NULL);
}


integer? (Integer)

/*
 *  call-seq:
 *     int.integer? -> true
 *
 *  Always returns <code>true</code>.
 */

static VALUE
int_int_p(num)
    VALUE num;
{
    return Qtrue;
}


upto (Integer)

/*
 *  call-seq:
 *     int.upto(limit) {|i| block }     => int
 *
 *  Iterates <em>block</em>, passing in integer values from <i>int</i>
 *  up to and including <i>limit</i>.
 *
 *     5.upto(10) { |i| print i, " " }
 *
 *  <em>produces:</em>
 *
 *     5 6 7 8 9 10
 */

static VALUE
int_upto(from, to)
    VALUE from, to;
{
    if (FIXNUM_P(from) && FIXNUM_P(to)) {
        long i, end;

        end = FIX2LONG(to);
        for (i = FIX2LONG(from); i <= end; i++) {
            rb_yield(LONG2FIX(i));
        }
    }
    else {
        VALUE i = from, c;

        while (!(c = rb_funcall(i, '>', 1, to))) {
            rb_yield(i);
            i = rb_funcall(i, '+', 1, INT2FIX(1));
        }
        if (NIL_P(c)) rb_cmperr(i, to);
    }
    return from;
}


downto (Integer)

/*
 *  call-seq:
 *     int.downto(limit) {|i| block }     => int
 *
 *  Iterates <em>block</em>, passing decreasing values from <i>int</i>
 *  down to and including <i>limit</i>.
 *
 *     5.downto(1) { |n| print n, ".. " }
 *     print "  Liftoff!\n"
 *
 *  <em>produces:</em>
 *
 *     5.. 4.. 3.. 2.. 1..   Liftoff!
 */

static VALUE
int_downto(from, to)
    VALUE from, to;
{
    if (FIXNUM_P(from) && FIXNUM_P(to)) {
        long i, end;

        end = FIX2LONG(to);
        for (i=FIX2LONG(from); i >= end; i--) {
            rb_yield(LONG2FIX(i));
        }
    }
    else {
        VALUE i = from, c;

        while (!(c = rb_funcall(i, '<', 1, to))) {
            rb_yield(i);
            i = rb_funcall(i, '-', 1, INT2FIX(1));
        }
        if (NIL_P(c)) rb_cmperr(i, to);
    }
    return from;
}


times (Integer)

/*
 *  call-seq:
 *     int.times {|i| block }     => int
 *
 *  Iterates block <i>int</i> times, passing in values from zero to
 *  <i>int</i> - 1.
 *
 *     5.times do |i|
 *       print i, " "
 *     end
 *
 *  <em>produces:</em>
 *
 *     0 1 2 3 4
 */

static VALUE
int_dotimes(num)
    VALUE num;
{
    if (FIXNUM_P(num)) {
        long i, end;

        end = FIX2LONG(num);
        for (i=0; i<end; i++) {
            rb_yield(LONG2FIX(i));
        }
    }
    else {
        VALUE i = INT2FIX(0);

        for (;;) {
            if (!RTEST(rb_funcall(i, '<', 1, num))) break;
            rb_yield(i);
            i = rb_funcall(i, '+', 1, INT2FIX(1));
        }
    }
    return num;
}


succ (Integer)

/*
 *  call-seq:
 *     int.next    => integer
 *     int.succ    => integer
 *
 *  Returns the <code>Integer</code> equal to <i>int</i> + 1.
 *
 *     1.next      #=> 2
 *     (-1).next   #=> 0
 */

static VALUE
int_succ(num)
    VALUE num;
{
    if (FIXNUM_P(num)) {
        long i = FIX2LONG(num) + 1;
        return LONG2NUM(i);
    }
    return rb_funcall(num, '+', 1, INT2FIX(1));
}


next (Integer)

/*
 *  call-seq:
 *     int.next    => integer
 *     int.succ    => integer
 *
 *  Returns the <code>Integer</code> equal to <i>int</i> + 1.
 *
 *     1.next      #=> 2
 *     (-1).next   #=> 0
 */

static VALUE
int_succ(num)
    VALUE num;
{
    if (FIXNUM_P(num)) {
        long i = FIX2LONG(num) + 1;
        return LONG2NUM(i);
    }
    return rb_funcall(num, '+', 1, INT2FIX(1));
}


chr (Integer)

/*
 *  call-seq:
 *     int.chr    => string
 *
 *  Returns a string containing the ASCII character represented by the
 *  receiver's value.
 *
 *     65.chr    #=> "A"
 *     ?a.chr    #=> "a"
 *     230.chr   #=> "\346"
 */

static VALUE
int_chr(num)
    VALUE num;
{
    char c;
    long i = NUM2LONG(num);

    if (i < 0 || 0xff < i)
        rb_raise(rb_eRangeError, "%ld out of char range", i);
    c = i;
    return rb_str_new(&c, 1);
}


to_i (Integer)

/*
 *  call-seq:
 *     int.to_i      => int
 *     int.to_int    => int
 *     int.floor     => int
 *     int.ceil      => int
 *     int.round     => int
 *     int.truncate  => int
 *
 *  As <i>int</i> is already an <code>Integer</code>, all these
 *  methods simply return the receiver.
 */

static VALUE
int_to_i(num)
    VALUE num;
{
    return num;
}


to_int (Integer)

/*
 *  call-seq:
 *     int.to_i      => int
 *     int.to_int    => int
 *     int.floor     => int
 *     int.ceil      => int
 *     int.round     => int
 *     int.truncate  => int
 *
 *  As <i>int</i> is already an <code>Integer</code>, all these
 *  methods simply return the receiver.
 */

static VALUE
int_to_i(num)
    VALUE num;
{
    return num;
}


floor (Integer)

/*
 *  call-seq:
 *     int.to_i      => int
 *     int.to_int    => int
 *     int.floor     => int
 *     int.ceil      => int
 *     int.round     => int
 *     int.truncate  => int
 *
 *  As <i>int</i> is already an <code>Integer</code>, all these
 *  methods simply return the receiver.
 */

static VALUE
int_to_i(num)
    VALUE num;
{
    return num;
}


ceil (Integer)

/*
 *  call-seq:
 *     int.to_i      => int
 *     int.to_int    => int
 *     int.floor     => int
 *     int.ceil      => int
 *     int.round     => int
 *     int.truncate  => int
 *
 *  As <i>int</i> is already an <code>Integer</code>, all these
 *  methods simply return the receiver.
 */

static VALUE
int_to_i(num)
    VALUE num;
{
    return num;
}


round (Integer)

/*
 *  call-seq:
 *     int.to_i      => int
 *     int.to_int    => int
 *     int.floor     => int
 *     int.ceil      => int
 *     int.round     => int
 *     int.truncate  => int
 *
 *  As <i>int</i> is already an <code>Integer</code>, all these
 *  methods simply return the receiver.
 */

static VALUE
int_to_i(num)
    VALUE num;
{
    return num;
}


truncate (Integer)

/*
 *  call-seq:
 *     int.to_i      => int
 *     int.to_int    => int
 *     int.floor     => int
 *     int.ceil      => int
 *     int.round     => int
 *     int.truncate  => int
 *
 *  As <i>int</i> is already an <code>Integer</code>, all these
 *  methods simply return the receiver.
 */

static VALUE
int_to_i(num)
    VALUE num;
{
    return num;
}


induced_from (Integer)

/*
 * call-seq:
 *   Integer.induced_from(obj)    =>  fixnum, bignum
 *
 * Convert <code>obj</code> to an Integer.
 */

static VALUE
rb_int_induced_from(klass, x)
    VALUE klass, x;
{
    switch (TYPE(x)) {
    case T_FIXNUM:
    case T_BIGNUM:
       return x;
    case T_FLOAT:
       return rb_funcall(x, id_to_i, 0);
    default:
       rb_raise(rb_eTypeError, "failed to convert %s into Integer",
                rb_obj_classname(x));
    }
}


gcd2 (Integer)

# File lib/mathn.rb, line 19
  def gcd2(int)
    a = self.abs
    b = int.abs
    a, b = b, a if a < b

    pd_a = a.prime_division
    pd_b = b.prime_division

    gcd = 1
    for pair in pd_a
      as = pd_b.assoc(pair[0])
      if as
        gcd *= as[0] ** [as[1], pair[1]].min
      end
    end
    return gcd
  end


from_prime_division (Integer)

# File lib/mathn.rb, line 37
  def Integer.from_prime_division(pd)
    value = 1
    for prime, index in pd
      value *= prime**index
    end
    value
  end


prime_division (Integer)

# File lib/mathn.rb, line 45
  def prime_division
    raise ZeroDivisionError if self == 0
    ps = Prime.new
    value = self
    pv = []
    for prime in ps
      count = 0
      while (value1, mod = value.divmod(prime)
             mod) == 0
        value = value1
        count += 1
      end
      if count != 0
        pv.push [prime, count]
      end
      break if prime * prime  >= value
    end
    if value > 1
      pv.push [value, 1]
    end
    return pv
  end


numerator (Integer)

# File lib/rational.rb, line 410
  def numerator
    self
  end


denominator (Integer)

# File lib/rational.rb, line 417
  def denominator
    1
  end


to_r (Integer)

# File lib/rational.rb, line 424
  def to_r
    Rational(self, 1)
  end


gcd (Integer)

# File lib/rational.rb, line 438
  def gcd(other)
    min = self.abs
    max = other.abs
    while min > 0
      tmp = min
      min = max % min
      max = tmp
    end
    max
  end


lcm (Integer)

# File lib/rational.rb, line 457
  def lcm(other)
    if self.zero? or other.zero?
      0
    else
      (self.div(self.gcd(other)) * other).abs
    end
  end


gcdlcm (Integer)

# File lib/rational.rb, line 473
  def gcdlcm(other)
    gcd = self.gcd(other)
    if self.zero? or other.zero?
      [gcd, 0]
    else
      [gcd, (self.div(gcd) * other).abs]
    end
  end


to_yaml (Integer)

# File lib/yaml/rubytypes.rb, line 358
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( "tag:yaml.org,2002:int", self.to_s, :plain )
        end
        end


stat (IO)

/*
 *  call-seq:
 *     ios.stat    => stat
 *
 *  Returns status information for <em>ios</em> as an object of type
 *  <code>File::Stat</code>.
 *
 *     f = File.new("testfile")
 *     s = f.stat
 *     "%o" % s.mode   #=> "100644"
 *     s.blksize       #=> 4096
 *     s.atime         #=> Wed Apr 09 08:53:54 CDT 2003
 *
 */

static VALUE
rb_io_stat(obj)
    VALUE obj;
{
    OpenFile *fptr;
    struct stat st;

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return stat_new(&st);
}


new (IO)

/*
 *  call-seq:
 *     IO.new(fd, mode_string)   => io
 *
 *  Returns a new <code>IO</code> object (a stream) for the given
 *  integer file descriptor and mode string. See also
 *  <code>IO#fileno</code> and <code>IO::for_fd</code>.
 *
 *     a = IO.new(2,"w")      # '2' is standard error
 *     $stderr.puts "Hello"
 *     a.puts "World"
 *
 *  <em>produces:</em>
 *
 *     Hello
 *     World
 */

static VALUE
rb_io_s_new(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    if (rb_block_given_p()) {
        char *cname = rb_class2name(klass);

        rb_warn("%s::new() does not take block; use %s::open() instead",
                cname, cname);
    }
    return rb_class_new_instance(argc, argv, klass);
}


open (IO)

/*
 *  call-seq:
 *     IO.open(fd, mode_string="r" )               => io
 *     IO.open(fd, mode_string="r" ) {|io| block } => obj
 *
 *  With no associated block, <code>open</code> is a synonym for
 *  <code>IO::new</code>. If the optional code block is given, it will
 *  be passed <i>io</i> as an argument, and the IO object will
 *  automatically be closed when the block terminates. In this instance,
 *  <code>IO::open</code> returns the value of the block.
 *
 */

static VALUE
rb_io_s_open(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE io = rb_class_new_instance(argc, argv, klass);

    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, io, io_close, io);
    }

    return io;
}


sysopen (IO)

/*
 *  call-seq:
 *     IO.sysopen(path, [mode, [perm]])  => fixnum
 *
 *  Opens the given path, returning the underlying file descriptor as a
 *  <code>Fixnum</code>.
 *
 *     IO.sysopen("testfile")   #=> 3
 *
 */

static VALUE
rb_io_s_sysopen(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, vmode, perm;
    int flags, fmode, fd;
    char *path;

    rb_scan_args(argc, argv, "12", &fname, &vmode, &perm);
    SafeStringValue(fname);

    if (NIL_P(vmode)) flags = O_RDONLY;
    else if (FIXNUM_P(vmode)) flags = FIX2INT(vmode);
    else {
        SafeStringValue(vmode);
        flags = rb_io_mode_modenum(RSTRING(vmode)->ptr);
    }
    if (NIL_P(perm)) fmode = 0666;
    else             fmode = NUM2INT(perm);

    path = ALLOCA_N(char, strlen(RSTRING(fname)->ptr)+1);
    strcpy(path, RSTRING(fname)->ptr);
    fd = rb_sysopen(path, flags, fmode);
    return INT2NUM(fd);
}


for_fd (IO)

/*
 *  call-seq:
 *     IO.for_fd(fd, mode)    => io
 *
 *  Synonym for <code>IO::new</code>.
 *
 */

static VALUE
rb_io_s_for_fd(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE io = rb_obj_alloc(klass);
    rb_io_initialize(argc, argv, io);
    return io;
}


popen (IO)

/*
 *  call-seq:
 *     IO.popen(cmd_string, mode="r" )               => io
 *     IO.popen(cmd_string, mode="r" ) {|io| block } => obj
 *
 *  Runs the specified command string as a subprocess; the subprocess's
 *  standard input and output will be connected to the returned
 *  <code>IO</code> object. If <i>cmd_string</i> starts with a
 *  ``<code>-</code>'', then a new instance of Ruby is started as the
 *  subprocess. The default mode for the new file object is ``r'', but
 *  <i>mode</i> may be set to any of the modes listed in the description
 *  for class IO.
 *
 *  If a block is given, Ruby will run the command as a child connected
 *  to Ruby with a pipe. Ruby's end of the pipe will be passed as a
 *  parameter to the block.
 *  At the end of block, Ruby close the pipe and sets <code>$?</code>.
 *  In this case <code>IO::popen</code> returns
 *  the value of the block.
 *
 *  If a block is given with a <i>cmd_string</i> of ``<code>-</code>'',
 *  the block will be run in two separate processes: once in the parent,
 *  and once in a child. The parent process will be passed the pipe
 *  object as a parameter to the block, the child version of the block
 *  will be passed <code>nil</code>, and the child's standard in and
 *  standard out will be connected to the parent through the pipe. Not
 *  available on all platforms.
 *
 *     f = IO.popen("uname")
 *     p f.readlines
 *     puts "Parent is #{Process.pid}"
 *     IO.popen ("date") { |f| puts f.gets }
 *     IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}
 *     p $?
 *
 *  <em>produces:</em>
 *
 *     ["Linux\n"]
 *     Parent is 26166
 *     Wed Apr  9 08:53:52 CDT 2003
 *     26169 is here, f is
 *     26166 is here, f is #<IO:0x401b3d44>
 *     #<Process::Status: pid=26166,exited(0)>
 */

static VALUE
rb_io_s_popen(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    char *mode;
    VALUE pname, pmode, port;

    if (rb_scan_args(argc, argv, "11", &pname, &pmode) == 1) {
        mode = "r";
    }
    else if (FIXNUM_P(pmode)) {
        mode = rb_io_modenum_mode(FIX2INT(pmode));
    }
    else {
        mode = rb_io_flags_mode(rb_io_mode_flags(StringValuePtr(pmode)));
    }
    SafeStringValue(pname);
    port = pipe_open(pname, 0, mode);
    if (NIL_P(port)) {
        /* child */
        if (rb_block_given_p()) {
            rb_yield(Qnil);
            fflush(stdout);
            fflush(stderr);
            _exit(0);
        }
        return Qnil;
    }
    RBASIC(port)->klass = klass;
    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, port, io_close, port);
    }
    return port;
}


foreach (IO)

/*
 *  call-seq:
 *     IO.foreach(name, sep_string=$/) {|line| block }   => nil
 *
 *  Executes the block for every line in the named I/O port, where lines
 *  are separated by <em>sep_string</em>.
 *
 *     IO.foreach("testfile") {|x| print "GOT ", x }
 *
 *  <em>produces:</em>
 *
 *     GOT This is line one
 *     GOT This is line two
 *     GOT This is line three
 *     GOT And so on...
 */

static VALUE
rb_io_s_foreach(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname;
    struct foreach_arg arg;

    rb_scan_args(argc, argv, "11", &fname, &arg.sep);
    SafeStringValue(fname);

    if (argc == 1) {
        arg.sep = rb_default_rs;
    }
    else if (!NIL_P(arg.sep)) {
        StringValue(arg.sep);
    }
    arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
    if (NIL_P(arg.io)) return Qnil;

    return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, arg.io);
}


readlines (IO)

/*
 *  call-seq:
 *     IO.readlines(name, sep_string=$/)   => array
 *
 *  Reads the entire file specified by <i>name</i> as individual
 *  lines, and returns those lines in an array. Lines are separated by
 *  <i>sep_string</i>.
 *
 *     a = IO.readlines("testfile")
 *     a[0]   #=> "This is line one\n"
 *
 */

static VALUE
rb_io_s_readlines(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE fname;
    struct foreach_arg arg;

    rb_scan_args(argc, argv, "11", &fname, &arg.sep);
    SafeStringValue(fname);

    arg.argc = argc - 1;
    arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
    if (NIL_P(arg.io)) return Qnil;
    return rb_ensure(io_s_readlines, (VALUE)&arg, rb_io_close, arg.io);
}


read (IO)

/*
 *  call-seq:
 *     IO.read(name, [length [, offset]] )   => string
 *
 *  Opens the file, optionally seeks to the given offset, then returns
 *  <i>length</i> bytes (defaulting to the rest of the file).
 *  <code>read</code> ensures the file is closed before returning.
 *
 *     IO.read("testfile")           #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
 *     IO.read("testfile", 20)       #=> "This is line one\nThi"
 *     IO.read("testfile", 20, 10)   #=> "ne one\nThis is line "
 */

static VALUE
rb_io_s_read(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE fname, offset;
    struct foreach_arg arg;

    rb_scan_args(argc, argv, "12", &fname, &arg.sep, &offset);
    SafeStringValue(fname);

    arg.argc = argc ? 1 : 0;
    arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
    if (NIL_P(arg.io)) return Qnil;
    if (!NIL_P(offset)) {
        rb_io_seek(arg.io, offset, SEEK_SET);
    }
    return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
}


select (IO)

/*
 *  call-seq:
 *     IO.select(read_array
 *               [, write_array
 *               [, error_array
 *               [, timeout]]] ) =>  array  or  nil
 *
 *  See <code>Kernel#select</code>.
 */

static VALUE
rb_f_select(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE read, write, except, timeout, res, list;
    fd_set rset, wset, eset, pset;
    fd_set *rp, *wp, *ep;
    struct timeval *tp, timerec;
    OpenFile *fptr;
    long i;
    int max = 0, n;
    int interrupt_flag = 0;
    int pending = 0;

    rb_scan_args(argc, argv, "13", &read, &write, &except, &timeout);
    if (NIL_P(timeout)) {
        tp = 0;
    }
    else {
        timerec = rb_time_interval(timeout);
        tp = &timerec;
    }

    FD_ZERO(&pset);
    if (!NIL_P(read)) {
        Check_Type(read, T_ARRAY);
        rp = &rset;
        FD_ZERO(rp);
        for (i=0; i<RARRAY(read)->len; i++) {
            GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
            FD_SET(fileno(fptr->f), rp);
            if (READ_DATA_PENDING(fptr->f)) { /* check for buffered data */
                pending++;
                FD_SET(fileno(fptr->f), &pset);
            }
            if (max < fileno(fptr->f)) max = fileno(fptr->f);
        }
        if (pending) {         /* no blocking if there's buffered data */
            timerec.tv_sec = timerec.tv_usec = 0;
            tp = &timerec;
        }
    }
    else
        rp = 0;

    if (!NIL_P(write)) {
        Check_Type(write, T_ARRAY);
        wp = &wset;
        FD_ZERO(wp);
        for (i=0; i<RARRAY(write)->len; i++) {
            GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
            FD_SET(fileno(fptr->f), wp);
            if (max < fileno(fptr->f)) max = fileno(fptr->f);
            if (fptr->f2) {
                FD_SET(fileno(fptr->f2), wp);
                if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
            }
        }
    }
    else
        wp = 0;

    if (!NIL_P(except)) {
        Check_Type(except, T_ARRAY);
        ep = &eset;
        FD_ZERO(ep);
        for (i=0; i<RARRAY(except)->len; i++) {
            GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
            FD_SET(fileno(fptr->f), ep);
            if (max < fileno(fptr->f)) max = fileno(fptr->f);
            if (fptr->f2) {
                FD_SET(fileno(fptr->f2), ep);
                if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
            }
        }
    }
    else {
        ep = 0;
    }

    max++;

    n = rb_thread_select(max, rp, wp, ep, tp);
    if (n < 0) {
        rb_sys_fail(0);
    }
    if (!pending && n == 0) return Qnil; /* returns nil on timeout */

    res = rb_ary_new2(3);
    rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
    rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
    rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));

    if (interrupt_flag == 0) {
        if (rp) {
            list = RARRAY(res)->ptr[0];
            for (i=0; i< RARRAY(read)->len; i++) {
                GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
                if (FD_ISSET(fileno(fptr->f), rp)
                    || FD_ISSET(fileno(fptr->f), &pset)) {
                    rb_ary_push(list, rb_ary_entry(read, i));
                }
            }
        }

        if (wp) {
            list = RARRAY(res)->ptr[1];
            for (i=0; i< RARRAY(write)->len; i++) {
                GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
                if (FD_ISSET(fileno(fptr->f), wp)) {
                    rb_ary_push(list, rb_ary_entry(write, i));
                }
                else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), wp)) {
                    rb_ary_push(list, rb_ary_entry(write, i));
                }
            }
        }

        if (ep) {
            list = RARRAY(res)->ptr[2];
            for (i=0; i< RARRAY(except)->len; i++) {
                GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
                if (FD_ISSET(fileno(fptr->f), ep)) {
                    rb_ary_push(list, rb_ary_entry(except, i));
                }
                else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), ep)) {
                    rb_ary_push(list, rb_ary_entry(except, i));
                }
            }
        }
    }

    return res;                 /* returns an empty array on interrupt */
}


pipe (IO)

/*
 *  call-seq:
 *     IO.pipe -> array
 *
 *  Creates a pair of pipe endpoints (connected to each other) and
 *  returns them as a two-element array of <code>IO</code> objects:
 *  <code>[</code> <i>read_file</i>, <i>write_file</i> <code>]</code>. Not
 *  available on all platforms.
 *
 *  In the example below, the two processes close the ends of the pipe
 *  that they are not using. This is not just a cosmetic nicety. The
 *  read end of a pipe will not generate an end of file condition if
 *  there are any writers with the pipe still open. In the case of the
 *  parent process, the <code>rd.read</code> will never return if it
 *  does not first issue a <code>wr.close</code>.
 *
 *     rd, wr = IO.pipe
 *
 *     if fork
 *       wr.close
 *       puts "Parent got: <#{rd.read}>"
 *       rd.close
 *       Process.wait
 *     else
 *       rd.close
 *       puts "Sending message to parent"
 *       wr.write "Hi Dad"
 *       wr.close
 *     end
 *
 *  <em>produces:</em>
 *
 *     Sending message to parent
 *     Parent got: <Hi Dad>
 */

static VALUE
rb_io_s_pipe(klass)
    VALUE klass;
{
#ifndef __human68k__
    int pipes[2], state;
    VALUE r, w, args[3];

#ifdef _WIN32
    if (_pipe(pipes, 1024, O_BINARY) == -1)
#else
    if (pipe(pipes) == -1)
#endif
        rb_sys_fail(0);

    args[0] = klass;
    args[1] = INT2NUM(pipes[0]);
    args[2] = INT2FIX(O_RDONLY);
    r = rb_protect(io_new_instance, (VALUE)args, &state);
    if (state) {
        close(pipes[0]);
        close(pipes[1]);
        rb_jump_tag(state);
    }
    args[1] = INT2NUM(pipes[1]);
    args[2] = INT2FIX(O_WRONLY);
    w = rb_protect(io_new_instance, (VALUE)args, &state);
    if (state) {
        close(pipes[1]);
        if (!NIL_P(r)) rb_io_close(r);
        rb_jump_tag(state);
    }
    rb_io_synchronized(RFILE(w)->fptr);

    return rb_assoc_new(r, w);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


new (IO)

/*
 *  call-seq:
 *     IO.new(fd, mode)   => io
 *
 *  Returns a new <code>IO</code> object (a stream) for the given
 *  integer file descriptor and mode string. See also
 *  <code>IO#fileno</code> and <code>IO::for_fd</code>.
 *
 *     a = IO.new(2,"w")      # '2' is standard error
 *     $stderr.puts "Hello"
 *     a.puts "World"
 *
 *  <em>produces:</em>
 *
 *     Hello
 *     World
 */

static VALUE
rb_io_initialize(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE fnum, mode;
    OpenFile *fp;
    int fd, flags;

    rb_secure(4);
    rb_scan_args(argc, argv, "11", &fnum, &mode);
    fd = NUM2INT(fnum);
    if (argc == 2) {
        if (FIXNUM_P(mode)) {
            flags = FIX2LONG(mode);
        }
        else {
            SafeStringValue(mode);
            flags = rb_io_mode_modenum(RSTRING(mode)->ptr);
        }
    }
    else {
#if defined(HAVE_FCNTL) && defined(F_GETFL)
        flags = fcntl(fd, F_GETFL);
        if (flags == -1) rb_sys_fail(0);
#else
        flags = O_RDONLY;
#endif
    }
    MakeOpenFile(io, fp);
    fp->mode = rb_io_modenum_flags(flags);
    fp->f = rb_fdopen(fd, rb_io_modenum_mode(flags));

    return io;
}


reopen (IO)

/*
 *  call-seq:
 *     ios.reopen(other_IO)         => ios
 *     ios.reopen(path, mode_str)   => ios
 *
 *  Reassociates <em>ios</em> with the I/O stream given in
 *  <i>other_IO</i> or to a new stream opened on <i>path</i>. This may
 *  dynamically change the actual class of this stream.
 *
 *     f1 = File.new("testfile")
 *     f2 = File.new("testfile")
 *     f2.readlines[0]   #=> "This is line one\n"
 *     f2.reopen(f1)     #=> #<File:testfile>
 *     f2.readlines[0]   #=> "This is line one\n"
 */

static VALUE
rb_io_reopen(argc, argv, file)
    int argc;
    VALUE *argv;
    VALUE file;
{
    VALUE fname, nmode;
    char *mode;
    OpenFile *fptr;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "11", &fname, &nmode) == 1) {
        VALUE tmp = rb_io_check_io(fname);
        if (!NIL_P(tmp)) {
            return io_reopen(file, tmp);
        }
    }

    SafeStringValue(fname);
    rb_io_taint_check(file);
    fptr = RFILE(file)->fptr;
    if (!fptr) {
        fptr = RFILE(file)->fptr = ALLOC(OpenFile);
        MEMZERO(fptr, OpenFile, 1);
    }

    if (!NIL_P(nmode)) {
        fptr->mode = rb_io_mode_flags(StringValuePtr(nmode));
    }

    if (fptr->path) {
        free(fptr->path);
        fptr->path = 0;
    }

    fptr->path = strdup(RSTRING(fname)->ptr);
    mode = rb_io_flags_mode(fptr->mode);
    if (!fptr->f) {
        fptr->f = rb_fopen(fptr->path, mode);
        if (fptr->f2) {
            fclose(fptr->f2);
            fptr->f2 = 0;
        }
        return file;
    }

    if (freopen(RSTRING(fname)->ptr, mode, fptr->f) == 0) {
        rb_sys_fail(fptr->path);
    }
#ifdef USE_SETVBUF
    if (setvbuf(fptr->f, NULL, _IOFBF, 0) != 0)
        rb_warn("setvbuf() can't be honoured for %s", RSTRING(fname)->ptr);
#endif

    if (fptr->f2) {
        if (freopen(RSTRING(fname)->ptr, "w", fptr->f2) == 0) {
            rb_sys_fail(fptr->path);
        }
    }

    return file;
}


print (IO)

/*
 *  call-seq:
 *     ios.print()             => nil
 *     ios.print(obj, ...)     => nil
 *
 *  Writes the given object(s) to <em>ios</em>. The stream must be
 *  opened for writing. If the output record separator (<code>$\\</code>)
 *  is not <code>nil</code>, it will be appended to the output. If no
 *  arguments are given, prints <code>$_</code>. Objects that aren't
 *  strings will be converted by calling their <code>to_s</code> method.
 *  With no argument, prints the contents of the variable <code>$_</code>.
 *  Returns <code>nil</code>.
 *
 *     $stdout.print("This is ", 100, " percent.\n")
 *
 *  <em>produces:</em>
 *
 *     This is 100 percent.
 */

VALUE
rb_io_print(argc, argv, out)
    int argc;
    VALUE *argv;
    VALUE out;
{
    int i;
    VALUE line;

    /* if no argument given, print `$_' */
    if (argc == 0) {
        argc = 1;
        line = rb_lastline_get();
        argv = &line;
    }
    for (i=0; i<argc; i++) {
        if (!NIL_P(rb_output_fs) && i>0) {
            rb_io_write(out, rb_output_fs);
        }
        switch (TYPE(argv[i])) {
          case T_NIL:
            rb_io_write(out, rb_str_new2("nil"));
            break;
          default:
            rb_io_write(out, argv[i]);
            break;
        }
    }
    if (!NIL_P(rb_output_rs)) {
        rb_io_write(out, rb_output_rs);
    }

    return Qnil;
}


putc (IO)

/*
 *  call-seq:
 *     ios.putc(obj)    => obj
 *
 *  If <i>obj</i> is <code>Numeric</code>, write the character whose
 *  code is <i>obj</i>, otherwise write the first character of the
 *  string representation of  <i>obj</i> to <em>ios</em>.
 *
 *     $stdout.putc "A"
 *     $stdout.putc 65
 *
 *  <em>produces:</em>
 *
 *     AA
 */

static VALUE
rb_io_putc(io, ch)
    VALUE io, ch;
{
    char c = NUM2CHR(ch);

    rb_io_write(io, rb_str_new(&c, 1));
    return ch;
}


puts (IO)

/*
 *  call-seq:
 *     ios.puts(obj, ...)    => nil
 *
 *  Writes the given objects to <em>ios</em> as with
 *  <code>IO#print</code>. Writes a record separator (typically a
 *  newline) after any that do not already end with a newline sequence.
 *  If called with an array argument, writes each element on a new line.
 *  If called without arguments, outputs a single record separator.
 *
 *     $stdout.puts("this", "is", "a", "test")
 *
 *  <em>produces:</em>
 *
 *     this
 *     is
 *     a
 *     test
 */

VALUE
rb_io_puts(argc, argv, out)
    int argc;
    VALUE *argv;
    VALUE out;
{
    int i;
    VALUE line;

    /* if no argument given, print newline. */
    if (argc == 0) {
        rb_io_write(out, rb_default_rs);
        return Qnil;
    }
    for (i=0; i<argc; i++) {
        if (NIL_P(argv[i])) {
            line = rb_str_new2("nil");
        }
        else {
            line = rb_check_array_type(argv[i]);
            if (!NIL_P(line)) {
                rb_protect_inspect(io_puts_ary, line, out);
                continue;
            }
            line = rb_obj_as_string(argv[i]);
        }
        rb_io_write(out, line);
        if (RSTRING(line)->len == 0 ||
            RSTRING(line)->ptr[RSTRING(line)->len-1] != '\n') {
            rb_io_write(out, rb_default_rs);
        }
    }

    return Qnil;
}


printf (IO)

/*
 *  call-seq:
 *     ios.printf(format_string [, obj, ...] )   => nil
 *
 *  Formats and writes to <em>ios</em>, converting parameters under
 *  control of the format string. See <code>Kernel#sprintf</code>
 *  for details.
 */

VALUE
rb_io_printf(argc, argv, out)
    int argc;
    VALUE argv[];
    VALUE out;
{
    rb_io_write(out, rb_f_sprintf(argc, argv));
    return Qnil;
}


each (IO)

/*
 *  call-seq:
 *     ios.each(sep_string=$/)      {|line| block }  => ios
 *     ios.each_line(sep_string=$/) {|line| block }  => ios
 *
 *  Executes the block for every line in <em>ios</em>, where lines are
 *  separated by <i>sep_string</i>. <em>ios</em> must be opened for
 *  reading or an <code>IOError</code> will be raised.
 *
 *     f = File.new("testfile")
 *     f.each {|line| puts "#{f.lineno}: #{line}" }
 *
 *  <em>produces:</em>
 *
 *     1: This is line one
 *     2: This is line two
 *     3: This is line three
 *     4: And so on...
 */

static VALUE
rb_io_each_line(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE str;
    VALUE rs;

    if (argc == 0) {
        rs = rb_rs;
    }
    else {
        rb_scan_args(argc, argv, "1", &rs);
        if (!NIL_P(rs)) StringValue(rs);
    }
    while (!NIL_P(str = rb_io_getline(rs, io))) {
        rb_yield(str);
    }
    return io;
}


each_line (IO)

/*
 *  call-seq:
 *     ios.each(sep_string=$/)      {|line| block }  => ios
 *     ios.each_line(sep_string=$/) {|line| block }  => ios
 *
 *  Executes the block for every line in <em>ios</em>, where lines are
 *  separated by <i>sep_string</i>. <em>ios</em> must be opened for
 *  reading or an <code>IOError</code> will be raised.
 *
 *     f = File.new("testfile")
 *     f.each {|line| puts "#{f.lineno}: #{line}" }
 *
 *  <em>produces:</em>
 *
 *     1: This is line one
 *     2: This is line two
 *     3: This is line three
 *     4: And so on...
 */

static VALUE
rb_io_each_line(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE str;
    VALUE rs;

    if (argc == 0) {
        rs = rb_rs;
    }
    else {
        rb_scan_args(argc, argv, "1", &rs);
        if (!NIL_P(rs)) StringValue(rs);
    }
    while (!NIL_P(str = rb_io_getline(rs, io))) {
        rb_yield(str);
    }
    return io;
}


each_byte (IO)

/*
 *  call-seq:
 *     ios.each_byte {|byte| block }  => nil
 *
 *  Calls the given block once for each byte (0..255) in <em>ios</em>,
 *  passing the byte as an argument. The stream must be opened for
 *  reading or an <code>IOError</code> will be raised.
 *
 *     f = File.new("testfile")
 *     checksum = 0
 *     f.each_byte {|x| checksum ^= x }   #=> #<File:testfile>
 *     checksum                           #=> 12
 */

static VALUE
rb_io_each_byte(io)
    VALUE io;
{
    OpenFile *fptr;
    FILE *f;
    int c;

    GetOpenFile(io, fptr);

    for (;;) {
        rb_io_check_readable(fptr);
        f = fptr->f;
        READ_CHECK(f);
        clearerr(f);
        TRAP_BEG;
        c = getc(f);
        TRAP_END;
        if (c == EOF) {
            if (ferror(f)) {
                clearerr(f);
                if (!rb_io_wait_readable(fileno(f)))
                    rb_sys_fail(fptr->path);
                continue;
            }
            break;
        }
        rb_yield(INT2FIX(c & 0xff));
    }
    if (ferror(f)) rb_sys_fail(fptr->path);
    return io;
}


syswrite (IO)

/*
 *  call-seq:
 *     ios.syswrite(string)   => integer
 *
 *  Writes the given string to <em>ios</em> using a low-level write.
 *  Returns the number of bytes written. Do not mix with other methods
 *  that write to <em>ios</em> or you may get unpredictable results.
 *  Raises <code>SystemCallError</code> on error.
 *
 *     f = File.new("out", "w")
 *     f.syswrite("ABCDEF")   #=> 6
 */

static VALUE
rb_io_syswrite(io, str)
    VALUE io, str;
{
    OpenFile *fptr;
    FILE *f;
    long n;

    rb_secure(4);
    if (TYPE(str) != T_STRING)
        str = rb_obj_as_string(str);

    GetOpenFile(io, fptr);
    rb_io_check_writable(fptr);
    f = GetWriteFile(fptr);

    if (fptr->mode & FMODE_WBUF) {
        rb_warn("syswrite for buffered IO");
    }
    if (!rb_thread_fd_writable(fileno(f))) {
        rb_io_check_closed(fptr);
    }
    TRAP_BEG;
    n = write(fileno(f), RSTRING(str)->ptr, RSTRING(str)->len);
    TRAP_END;

    if (n == -1) rb_sys_fail(fptr->path);

    return LONG2FIX(n);
}


sysread (IO)

/*
 *  call-seq:
 *     ios.sysread(integer )    => string
 *
 *  Reads <i>integer</i> bytes from <em>ios</em> using a low-level
 *  read and returns them as a string. Do not mix with other methods
 *  that read from <em>ios</em> or you may get unpredictable results.
 *  Raises <code>SystemCallError</code> on error and
 *  <code>EOFError</code> at end of file.
 *
 *     f = File.new("testfile")
 *     f.sysread(16)   #=> "This is line one"
 */

static VALUE
rb_io_sysread(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE len, str;
    OpenFile *fptr;
    long n, ilen;

    rb_scan_args(argc, argv, "11", &len, &str);
    ilen = NUM2LONG(len);

    if (NIL_P(str)) {
        str = rb_str_new(0, ilen);
    }
    else {
        StringValue(str);
        rb_str_modify(str);
        rb_str_resize(str, ilen);
    }
    if (ilen == 0) return str;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);

    if (READ_DATA_BUFFERED(fptr->f)) {
        rb_raise(rb_eIOError, "sysread for buffered IO");
    }
    rb_str_locktmp(str);

    n = fileno(fptr->f);
    rb_thread_wait_fd(fileno(fptr->f));
    rb_io_check_closed(fptr);
    if (RSTRING(str)->len != ilen) {
        rb_raise(rb_eRuntimeError, "buffer string modified");
    }
    TRAP_BEG;
    n = read(fileno(fptr->f), RSTRING(str)->ptr, ilen);
    TRAP_END;

    rb_str_unlocktmp(str);
    if (n == -1) {
        rb_sys_fail(fptr->path);
    }
    rb_str_resize(str, n);
    if (n == 0 && ilen > 0) {
        rb_eof_error();
    }
    RSTRING(str)->len = n;
    RSTRING(str)->ptr[n] = '\0';
    OBJ_TAINT(str);

    return str;
}


fileno (IO)

/*
 *  call-seq:
 *     ios.fileno    => fixnum
 *     ios.to_i      => fixnum
 *
 *  Returns an integer representing the numeric file descriptor for
 *  <em>ios</em>.
 *
 *     $stdin.fileno    #=> 0
 *     $stdout.fileno   #=> 1
 */

static VALUE
rb_io_fileno(io)
    VALUE io;
{
    OpenFile *fptr;
    int fd;

    GetOpenFile(io, fptr);
    fd = fileno(fptr->f);
    return INT2FIX(fd);
}


to_io (IO)

/*
 *  call-seq:
 *     ios.to_io -> ios
 *
 *  Returns <em>ios</em>.
 */

static VALUE
rb_io_to_io(io)
    VALUE io;
{
    return io;
}


fsync (IO)

/*
 *  call-seq:
 *     ios.fsync   => 0 or nil
 *
 *  Immediately writes all buffered data in <em>ios</em> to disk.
 *  Returns <code>nil</code> if the underlying operating system does not
 *  support <em>fsync(2)</em>. Note that <code>fsync</code> differs from
 *  using <code>IO#sync=</code>. The latter ensures that data is flushed
 *  from Ruby's buffers, but doesn't not guarantee that the underlying
 *  operating system actually writes it to disk.
 */

static VALUE
rb_io_fsync(io)
    VALUE io;
{
#ifdef HAVE_FSYNC
    OpenFile *fptr;
    FILE *f;

    GetOpenFile(io, fptr);
    f = GetWriteFile(fptr);

    io_fflush(f, fptr);
    if (fsync(fileno(f)) < 0)
        rb_sys_fail(fptr->path);
    return INT2FIX(0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


sync (IO)

/*
 *  call-seq:
 *     ios.sync    => true or false
 *
 *  Returns the current ``sync mode'' of <em>ios</em>. When sync mode is
 *  true, all output is immediately flushed to the underlying operating
 *  system and is not buffered by Ruby internally. See also
 *  <code>IO#fsync</code>.
 *
 *     f = File.new("testfile")
 *     f.sync   #=> false
 */

static VALUE
rb_io_sync(io)
    VALUE io;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    return (fptr->mode & FMODE_SYNC) ? Qtrue : Qfalse;
}


sync= (IO)

/*
 *  call-seq:
 *     ios.sync = boolean   => boolean
 *
 *  Sets the ``sync mode'' to <code>true</code> or <code>false</code>.
 *  When sync mode is true, all output is immediately flushed to the
 *  underlying operating system and is not buffered internally. Returns
 *  the new state. See also <code>IO#fsync</code>.
 *
 *     f = File.new("testfile")
 *     f.sync = true
 *
 *  <em>(produces no output)</em>
 */

static VALUE
rb_io_set_sync(io, mode)
    VALUE io, mode;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    if (RTEST(mode)) {
        fptr->mode |= FMODE_SYNC;
    }
    else {
        fptr->mode &= ~FMODE_SYNC;
    }
    return mode;
}


lineno (IO)

/*
 *  call-seq:
 *     ios.lineno    => integer
 *
 *  Returns the current line number in <em>ios</em>. The stream must be
 *  opened for reading. <code>lineno</code> counts the number of times
 *  <code>gets</code> is called, rather than the number of newlines
 *  encountered. The two values will differ if <code>gets</code> is
 *  called with a separator other than newline. See also the
 *  <code>$.</code> variable.
 *
 *     f = File.new("testfile")
 *     f.lineno   #=> 0
 *     f.gets     #=> "This is line one\n"
 *     f.lineno   #=> 1
 *     f.gets     #=> "This is line two\n"
 *     f.lineno   #=> 2
 */

static VALUE
rb_io_lineno(io)
    VALUE io;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    return INT2NUM(fptr->lineno);
}


lineno= (IO)

/*
 *  call-seq:
 *     ios.lineno = integer    => integer
 *
 *  Manually sets the current line number to the given value.
 *  <code>$.</code> is updated only on the next read.
 *
 *     f = File.new("testfile")
 *     f.gets                     #=> "This is line one\n"
 *     $.                         #=> 1
 *     f.lineno = 1000
 *     f.lineno                   #=> 1000
 *     $. # lineno of last read   #=> 1
 *     f.gets                     #=> "This is line two\n"
 *     $. # lineno of last read   #=> 1001
 */

static VALUE
rb_io_set_lineno(io, lineno)
    VALUE io, lineno;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    fptr->lineno = NUM2INT(lineno);
    return lineno;
}


readlines (IO)

/*
 *  call-seq:
 *     ios.readlines(sep_string=$/)  =>   array
 *
 *  Reads all of the lines in <em>ios</em>, and returns them in
 *  <i>anArray</i>. Lines are separated by the optional
 *  <i>sep_string</i>. If <i>sep_string</i> is <code>nil</code>, the
 *  rest of the stream is returned as a single record.
 *  The stream must be opened for reading or an
 *  <code>IOError</code> will be raised.
 *
 *     f = File.new("testfile")
 *     f.readlines[0]   #=> "This is line one\n"
 */

static VALUE
rb_io_readlines(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE line, ary;
    VALUE rs;

    if (argc == 0) {
        rs = rb_rs;
    }
    else {
        rb_scan_args(argc, argv, "1", &rs);
        if (!NIL_P(rs)) StringValue(rs);
    }
    ary = rb_ary_new();
    while (!NIL_P(line = rb_io_getline(rs, io))) {
        rb_ary_push(ary, line);
    }
    return ary;
}


read_nonblock (IO)

/*
 *  call-seq:
 *     ios.read_nonblock(maxlen)              => string
 *     ios.read_nonblock(maxlen, outbuf)      => outbuf
 *
 *  Reads at most <i>maxlen</i> bytes from <em>ios</em> using
 *  read(2) system call after O_NONBLOCK is set for
 *  the underlying file descriptor.
 *
 *  If the optional <i>outbuf</i> argument is present,
 *  it must reference a String, which will receive the data.
 *
 *  read_nonblock just calls read(2).
 *  It causes all errors read(2) causes: EAGAIN, EINTR, etc.
 *  The caller should care such errors.
 *
 *  read_nonblock causes EOFError on EOF.
 *
 *  If the read buffer is not empty,
 *  read_nonblock reads from the buffer like readpartial.
 *  In this case, read(2) is not called.
 *
 */

static VALUE
io_read_nonblock(int argc, VALUE *argv, VALUE io)
{
    VALUE ret;

    ret = io_getpartial(argc, argv, io, 1);
    if (NIL_P(ret))
        rb_eof_error();
    else
        return ret;
}


write_nonblock (IO)

/*
 *  call-seq:
 *     ios.write_nonblock(string)   => integer
 *
 *  Writes the given string to <em>ios</em> using
 *  write(2) system call after O_NONBLOCK is set for
 *  the underlying file descriptor.
 *
 *  write_nonblock just calls write(2).
 *  It causes all errors write(2) causes: EAGAIN, EINTR, etc.
 *  The result may also be smaller than string.length (partial write).
 *  The caller should care such errors and partial write.
 *
 */

static VALUE
rb_io_write_nonblock(VALUE io, VALUE str)
{
    OpenFile *fptr;
    FILE *f;
    long n;

    rb_secure(4);
    if (TYPE(str) != T_STRING)
        str = rb_obj_as_string(str);

    GetOpenFile(io, fptr);
    rb_io_check_writable(fptr);

    f = GetWriteFile(fptr);

    rb_io_set_nonblock(fptr);
    n = write(fileno(f), RSTRING(str)->ptr, RSTRING(str)->len);

    if (n == -1) rb_sys_fail(fptr->path);

    return LONG2FIX(n);
}


readpartial (IO)

/*
 *  call-seq:
 *     ios.readpartial(maxlen)              => string
 *     ios.readpartial(maxlen, outbuf)      => outbuf
 *
 *  Reads at most <i>maxlen</i> bytes from the I/O stream.
 *  It blocks only if <em>ios</em> has no data immediately available.
 *  It doesn't block if some data available.
 *  If the optional <i>outbuf</i> argument is present,
 *  it must reference a String, which will receive the data.
 *  It raises <code>EOFError</code> on end of file.
 *
 *  readpartial is designed for streams such as pipe, socket, tty, etc.
 *  It blocks only when no data immediately available.
 *  This means that it blocks only when following all conditions hold.
 *  * the buffer in the IO object is empty.
 *  * the content of the stream is empty.
 *  * the stream is not reached to EOF.
 *
 *  When readpartial blocks, it waits data or EOF on the stream.
 *  If some data is reached, readpartial returns with the data.
 *  If EOF is reached, readpartial raises EOFError.
 *
 *  When readpartial doesn't blocks, it returns or raises immediately.
 *  If the buffer is not empty, it returns the data in the buffer.
 *  Otherwise if the stream has some content,
 *  it returns the data in the stream.
 *  Otherwise if the stream is reached to EOF, it raises EOFError.
 *
 *     r, w = IO.pipe           #               buffer          pipe content
 *     w << "abc"               #               ""              "abc".
 *     r.readpartial(4096)      #=> "abc"       ""              ""
 *     r.readpartial(4096)      # blocks because buffer and pipe is empty.
 *
 *     r, w = IO.pipe           #               buffer          pipe content
 *     w << "abc"               #               ""              "abc"
 *     w.close                  #               ""              "abc" EOF
 *     r.readpartial(4096)      #=> "abc"       ""              EOF
 *     r.readpartial(4096)      # raises EOFError
 *
 *     r, w = IO.pipe           #               buffer          pipe content
 *     w << "abc\ndef\n"        #               ""              "abc\ndef\n"
 *     r.gets                   #=> "abc\n"     "def\n"         ""
 *     w << "ghi\n"             #               "def\n"         "ghi\n"
 *     r.readpartial(4096)      #=> "def\n"     ""              "ghi\n"
 *     r.readpartial(4096)      #=> "ghi\n"     ""              ""
 *
 *  Note that readpartial behaves similar to sysread.
 *  The differences are:
 *  * If the buffer is not empty, read from the buffer instead of "sysread for buffered IO (IOError)".
 *  * It doesn't cause Errno::EAGAIN and Errno::EINTR.  When readpartial meets EAGAIN and EINTR by read system call, readpartial retry the system call.
 *
 *  The later means that readpartial is nonblocking-flag insensitive.
 *  It blocks on the situation IO#sysread causes Errno::EAGAIN as if the fd is blocking mode.
 *
 */

static VALUE
io_readpartial(int argc, VALUE *argv, VALUE io)
{
    VALUE ret;

    ret = io_getpartial(argc, argv, io, 0);
    if (NIL_P(ret))
        rb_eof_error();
    else
        return ret;
}


read (IO)

/*
 *  call-seq:
 *     ios.read([length [, buffer]])    => string, buffer, or nil
 *
 *  Reads at most <i>length</i> bytes from the I/O stream, or to the
 *  end of file if <i>length</i> is omitted or is <code>nil</code>.
 *  <i>length</i> must be a non-negative integer or nil.
 *  If the optional <i>buffer</i> argument is present, it must reference
 *  a String, which will receive the data.
 *
 *  At end of file, it returns <code>nil</code> or <code>""</code>
 *  depend on <i>length</i>.
 *  <code><i>ios</i>.read()</code> and
 *  <code><i>ios</i>.read(nil)</code> returns <code>""</code>.
 *  <code><i>ios</i>.read(<i>positive-integer</i>)</code> returns nil.
 *
 *     f = File.new("testfile")
 *     f.read(16)   #=> "This is line one"
 */

static VALUE
io_read(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    OpenFile *fptr;
    long n, len;
    VALUE length, str;

    rb_scan_args(argc, argv, "02", &length, &str);

    if (NIL_P(length)) {
        if (!NIL_P(str)) StringValue(str);
        GetOpenFile(io, fptr);
        rb_io_check_readable(fptr);
        return read_all(fptr, remain_size(fptr), str);
    }
    len = NUM2LONG(length);
    if (len < 0) {
        rb_raise(rb_eArgError, "negative length %ld given", len);
    }

    if (NIL_P(str)) {
        str = rb_tainted_str_new(0, len);
    }
    else {
        StringValue(str);
        rb_str_modify(str);
        rb_str_resize(str,len);
    }

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    if (feof(fptr->f)) return Qnil;
    if (len == 0) return str;

    rb_str_locktmp(str);
    READ_CHECK(fptr->f);
    if (RSTRING(str)->len != len) {
        rb_raise(rb_eRuntimeError, "buffer string modified");
    }
    n = io_fread(RSTRING(str)->ptr, len, fptr);
    rb_str_unlocktmp(str);
    if (n == 0) {
        if (!fptr->f) return Qnil;
        if (feof(fptr->f)) {
            rb_str_resize(str, 0);
            return Qnil;
        }
        if (len > 0) rb_sys_fail(fptr->path);
    }
    rb_str_resize(str, n);
    RSTRING(str)->len = n;
    RSTRING(str)->ptr[n] = '\0';
    OBJ_TAINT(str);

    return str;
}


write (IO)

/*
 *  call-seq:
 *     ios.write(string)    => integer
 *
 *  Writes the given string to <em>ios</em>. The stream must be opened
 *  for writing. If the argument is not a string, it will be converted
 *  to a string using <code>to_s</code>. Returns the number of bytes
 *  written.
 *
 *     count = $stdout.write( "This is a test\n" )
 *     puts "That was #{count} bytes of data"
 *
 *  <em>produces:</em>
 *
 *     This is a test
 *     That was 15 bytes of data
 */

static VALUE
io_write(io, str)
    VALUE io, str;
{
    OpenFile *fptr;
    long n;

    rb_secure(4);
    if (TYPE(str) != T_STRING)
        str = rb_obj_as_string(str);

    if (TYPE(io) != T_FILE) {
        /* port is not IO, call write method for it. */
        return rb_funcall(io, id_write, 1, str);
    }
    if (RSTRING(str)->len == 0) return INT2FIX(0);

    GetOpenFile(io, fptr);
    rb_io_check_writable(fptr);

    n = io_fwrite(str, fptr);
    if (n == -1L) rb_sys_fail(fptr->path);
    if (!(fptr->mode & FMODE_SYNC)) {
        fptr->mode |= FMODE_WBUF;
    }

    return LONG2FIX(n);
}


gets (IO)

/*
 *  call-seq:
 *     ios.gets(sep_string=$/)   => string or nil
 *
 *  Reads the next ``line'' from the I/O stream; lines are separated by
 *  <i>sep_string</i>. A separator of <code>nil</code> reads the entire
 *  contents, and a zero-length separator reads the input a paragraph at
 *  a time (two successive newlines in the input separate paragraphs).
 *  The stream must be opened for reading or an <code>IOError</code>
 *  will be raised. The line read in will be returned and also assigned
 *  to <code>$_</code>. Returns <code>nil</code> if called at end of
 *  file.
 *
 *     File.new("testfile").gets   #=> "This is line one\n"
 *     $_                          #=> "This is line one\n"
 */

static VALUE
rb_io_gets_m(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE rs, str;

    if (argc == 0) {
        rs = rb_rs;
    }
    else {
        rb_scan_args(argc, argv, "1", &rs);
        if (!NIL_P(rs)) StringValue(rs);
    }
    str = rb_io_getline(rs, io);
    rb_lastline_set(str);

    return str;
}


readline (IO)

/*
 *  call-seq:
 *     ios.readline(sep_string=$/)   => string
 *
 *  Reads a line as with <code>IO#gets</code>, but raises an
 *  <code>EOFError</code> on end of file.
 */

static VALUE
rb_io_readline(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE line = rb_io_gets_m(argc, argv, io);

    if (NIL_P(line)) {
        rb_eof_error();
    }
    return line;
}


getc (IO)

/*
 *  call-seq:
 *     ios.getc   => fixnum or nil
 *
 *  Gets the next 8-bit byte (0..255) from <em>ios</em>. Returns
 *  <code>nil</code> if called at end of file.
 *
 *     f = File.new("testfile")
 *     f.getc   #=> 84
 *     f.getc   #=> 104
 */

VALUE
rb_io_getc(io)
    VALUE io;
{
    OpenFile *fptr;
    FILE *f;
    int c;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    f = fptr->f;

  retry:
    READ_CHECK(f);
    clearerr(f);
    TRAP_BEG;
    c = getc(f);
    TRAP_END;

    if (c == EOF) {
        if (ferror(f)) {
            clearerr(f);
            if (!rb_io_wait_readable(fileno(f)))
                rb_sys_fail(fptr->path);
            goto retry;
        }
        return Qnil;
    }
    return INT2FIX(c & 0xff);
}


readchar (IO)

/*
 *  call-seq:
 *     ios.readchar   => fixnum
 *
 *  Reads a character as with <code>IO#getc</code>, but raises an
 *  <code>EOFError</code> on end of file.
 */

static VALUE
rb_io_readchar(io)
    VALUE io;
{
    VALUE c = rb_io_getc(io);

    if (NIL_P(c)) {
        rb_eof_error();
    }
    return c;
}


ungetc (IO)

/*
 *  call-seq:
 *     ios.ungetc(integer)   => nil
 *
 *  Pushes back one character (passed as a parameter) onto <em>ios</em>,
 *  such that a subsequent buffered read will return it. Only one character
 *  may be pushed back before a subsequent read operation (that is,
 *  you will be able to read only the last of several characters that have been pushed
 *  back). Has no effect with unbuffered reads (such as <code>IO#sysread</code>).
 *
 *     f = File.new("testfile")   #=> #<File:testfile>
 *     c = f.getc                 #=> 84
 *     f.ungetc(c)                #=> nil
 *     f.getc                     #=> 84
 */

VALUE
rb_io_ungetc(io, c)
    VALUE io, c;
{
    OpenFile *fptr;
    int cc = NUM2INT(c);

    GetOpenFile(io, fptr);
    if (!(fptr->mode & FMODE_RBUF))
        rb_raise(rb_eIOError, "unread stream");
    rb_io_check_readable(fptr);

    if (ungetc(cc, fptr->f) == EOF && cc != EOF) {
        rb_raise(rb_eIOError, "ungetc failed");
    }
    return Qnil;
}


<< (IO)

/*
 *  call-seq:
 *     ios << obj     => ios
 *
 *  String Output---Writes <i>obj</i> to <em>ios</em>.
 *  <i>obj</i> will be converted to a string using
 *  <code>to_s</code>.
 *
 *     $stdout << "Hello " << "world!\n"
 *
 *  <em>produces:</em>
 *
 *     Hello world!
 */

VALUE
rb_io_addstr(io, str)
    VALUE io, str;
{
    rb_io_write(io, str);
    return io;
}


flush (IO)

/*
 *  call-seq:
 *     ios.flush    => ios
 *
 *  Flushes any buffered data within <em>ios</em> to the underlying
 *  operating system (note that this is Ruby internal buffering only;
 *  the OS may buffer the data as well).
 *
 *     $stdout.print "no newline"
 *     $stdout.flush
 *
 *  <em>produces:</em>
 *
 *     no newline
 */

static VALUE
rb_io_flush(io)
    VALUE io;
{
    OpenFile *fptr;
    FILE *f;

    GetOpenFile(io, fptr);
    rb_io_check_writable(fptr);
    f = GetWriteFile(fptr);

    io_fflush(f, fptr);

    return io;
}


tell (IO)

/*
 *  call-seq:
 *     ios.pos     => integer
 *     ios.tell    => integer
 *
 *  Returns the current offset (in bytes) of <em>ios</em>.
 *
 *     f = File.new("testfile")
 *     f.pos    #=> 0
 *     f.gets   #=> "This is line one\n"
 *     f.pos    #=> 17
 */

static VALUE
rb_io_tell(io)
     VALUE io;
{
    OpenFile *fptr;
    off_t pos;

    GetOpenFile(io, fptr);
    pos = io_tell(fptr);
    if (pos < 0) rb_sys_fail(fptr->path);
    return OFFT2NUM(pos);
}


seek (IO)

/*
 *  call-seq:
 *     ios.seek(amount, whence=SEEK_SET) -> 0
 *
 *  Seeks to a given offset <i>anInteger</i> in the stream according to
 *  the value of <i>whence</i>:
 *
 *    IO::SEEK_CUR  | Seeks to _amount_ plus current position
 *    --------------+----------------------------------------------------
 *    IO::SEEK_END  | Seeks to _amount_ plus end of stream (you probably
 *                  | want a negative value for _amount_)
 *    --------------+----------------------------------------------------
 *    IO::SEEK_SET  | Seeks to the absolute location given by _amount_
 *
 *  Example:
 *
 *     f = File.new("testfile")
 *     f.seek(-13, IO::SEEK_END)   #=> 0
 *     f.readline                  #=> "And so on...\n"
 */

static VALUE
rb_io_seek_m(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE offset, ptrname;
    int whence = SEEK_SET;

    if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
        whence = NUM2INT(ptrname);
    }

    return rb_io_seek(io, offset, whence);
}


rewind (IO)

/*
 *  call-seq:
 *     ios.rewind    => 0
 *
 *  Positions <em>ios</em> to the beginning of input, resetting
 *  <code>lineno</code> to zero.
 *
 *     f = File.new("testfile")
 *     f.readline   #=> "This is line one\n"
 *     f.rewind     #=> 0
 *     f.lineno     #=> 0
 *     f.readline   #=> "This is line one\n"
 */

static VALUE
rb_io_rewind(io)
    VALUE io;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    if (io_seek(fptr, 0L, 0) != 0) rb_sys_fail(fptr->path);
    clearerr(fptr->f);
    if (io == current_file) {
        gets_lineno -= fptr->lineno;
    }
    fptr->lineno = 0;

    return INT2FIX(0);
}


pos (IO)

/*
 *  call-seq:
 *     ios.pos     => integer
 *     ios.tell    => integer
 *
 *  Returns the current offset (in bytes) of <em>ios</em>.
 *
 *     f = File.new("testfile")
 *     f.pos    #=> 0
 *     f.gets   #=> "This is line one\n"
 *     f.pos    #=> 17
 */

static VALUE
rb_io_tell(io)
     VALUE io;
{
    OpenFile *fptr;
    off_t pos;

    GetOpenFile(io, fptr);
    pos = io_tell(fptr);
    if (pos < 0) rb_sys_fail(fptr->path);
    return OFFT2NUM(pos);
}


pos= (IO)

/*
 *  call-seq:
 *     ios.pos = integer    => integer
 *
 *  Seeks to the given position (in bytes) in <em>ios</em>.
 *
 *     f = File.new("testfile")
 *     f.pos = 17
 *     f.gets   #=> "This is line two\n"
 */

static VALUE
rb_io_set_pos(io, offset)
     VALUE io, offset;
{
    OpenFile *fptr;
    off_t pos;

    pos = NUM2OFFT(offset);
    GetOpenFile(io, fptr);
    pos = io_seek(fptr, pos, SEEK_SET);
    if (pos != 0) rb_sys_fail(fptr->path);
    clearerr(fptr->f);

    return OFFT2NUM(pos);
}


eof (IO)

/*
 *  call-seq:
 *     ios.eof     => true or false
 *     ios.eof?    => true or false
 *
 *  Returns true if <em>ios</em> is at end of file that means
 *  there are no more data to read.
 *  The stream must be opened for reading or an <code>IOError</code> will be
 *  raised.
 *
 *     f = File.new("testfile")
 *     dummy = f.readlines
 *     f.eof   #=> true
 *
 *  If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
 *  blocks until the other end sends some data or closes it.
 *
 *     r, w = IO.pipe
 *     Thread.new { sleep 1; w.close }
 *     r.eof?  #=> true after 1 second blocking
 *
 *     r, w = IO.pipe
 *     Thread.new { sleep 1; w.puts "a" }
 *     r.eof?  #=> false after 1 second blocking
 *
 *     r, w = IO.pipe
 *     r.eof?  # blocks forever
 *
 *  Note that <code>IO#eof?</code> reads data to a input buffer.
 *  So <code>IO#sysread</code> doesn't work with <code>IO#eof?</code>.
 */

VALUE
rb_io_eof(io)
    VALUE io;
{
    OpenFile *fptr;
    int ch;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);

    if (feof(fptr->f)) return Qtrue;
    if (READ_DATA_PENDING(fptr->f)) return Qfalse;
    READ_CHECK(fptr->f);
    clearerr(fptr->f);
    TRAP_BEG;
    ch = getc(fptr->f);
    TRAP_END;

    if (ch != EOF) {
        ungetc(ch, fptr->f);
        return Qfalse;
    }
    rb_io_check_closed(fptr);
    clearerr(fptr->f);
    return Qtrue;
}


eof? (IO)

/*
 *  call-seq:
 *     ios.eof     => true or false
 *     ios.eof?    => true or false
 *
 *  Returns true if <em>ios</em> is at end of file that means
 *  there are no more data to read.
 *  The stream must be opened for reading or an <code>IOError</code> will be
 *  raised.
 *
 *     f = File.new("testfile")
 *     dummy = f.readlines
 *     f.eof   #=> true
 *
 *  If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
 *  blocks until the other end sends some data or closes it.
 *
 *     r, w = IO.pipe
 *     Thread.new { sleep 1; w.close }
 *     r.eof?  #=> true after 1 second blocking
 *
 *     r, w = IO.pipe
 *     Thread.new { sleep 1; w.puts "a" }
 *     r.eof?  #=> false after 1 second blocking
 *
 *     r, w = IO.pipe
 *     r.eof?  # blocks forever
 *
 *  Note that <code>IO#eof?</code> reads data to a input buffer.
 *  So <code>IO#sysread</code> doesn't work with <code>IO#eof?</code>.
 */

VALUE
rb_io_eof(io)
    VALUE io;
{
    OpenFile *fptr;
    int ch;

    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);

    if (feof(fptr->f)) return Qtrue;
    if (READ_DATA_PENDING(fptr->f)) return Qfalse;
    READ_CHECK(fptr->f);
    clearerr(fptr->f);
    TRAP_BEG;
    ch = getc(fptr->f);
    TRAP_END;

    if (ch != EOF) {
        ungetc(ch, fptr->f);
        return Qfalse;
    }
    rb_io_check_closed(fptr);
    clearerr(fptr->f);
    return Qtrue;
}


close (IO)

/*
 *  call-seq:
 *     ios.close   => nil
 *
 *  Closes <em>ios</em> and flushes any pending writes to the operating
 *  system. The stream is unavailable for any further data operations;
 *  an <code>IOError</code> is raised if such an attempt is made. I/O
 *  streams are automatically closed when they are claimed by the
 *  garbage collector.
 *
 *  If <em>ios</em> is opened by <code>IO.popen</code>,
 *  <code>close</code> sets <code>$?</code>.
 */

static VALUE
rb_io_close_m(io)
    VALUE io;
{
    if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
        rb_raise(rb_eSecurityError, "Insecure: can't close");
    }
    rb_io_check_closed(RFILE(io)->fptr);
    rb_io_close(io);
    return Qnil;
}


closed? (IO)

/*
 *  call-seq:
 *     ios.closed?    => true or false
 *
 *  Returns <code>true</code> if <em>ios</em> is completely closed (for
 *  duplex streams, both reader and writer), <code>false</code>
 *  otherwise.
 *
 *     f = File.new("testfile")
 *     f.close         #=> nil
 *     f.closed?       #=> true
 *     f = IO.popen("/bin/sh","r+")
 *     f.close_write   #=> nil
 *     f.closed?       #=> false
 *     f.close_read    #=> nil
 *     f.closed?       #=> true
 */

static VALUE
rb_io_closed(io)
    VALUE io;
{
    OpenFile *fptr;

    fptr = RFILE(io)->fptr;
    rb_io_check_initialized(fptr);
    return (fptr->f || fptr->f2)?Qfalse:Qtrue;
}


close_read (IO)

/*
 *  call-seq:
 *     ios.close_read    => nil
 *
 *  Closes the read end of a duplex I/O stream (i.e., one that contains
 *  both a read and a write stream, such as a pipe). Will raise an
 *  <code>IOError</code> if the stream is not duplexed.
 *
 *     f = IO.popen("/bin/sh","r+")
 *     f.close_read
 *     f.readlines
 *
 *  <em>produces:</em>
 *
 *     prog.rb:3:in `readlines': not opened for reading (IOError)
 *      from prog.rb:3
 */

static VALUE
rb_io_close_read(io)
    VALUE io;
{
    OpenFile *fptr;
    int n;

    if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
        rb_raise(rb_eSecurityError, "Insecure: can't close");
    }
    GetOpenFile(io, fptr);
    if (fptr->f2 == 0 && (fptr->mode & FMODE_WRITABLE)) {
        rb_raise(rb_eIOError, "closing non-duplex IO for reading");
    }
    if (fptr->f2 == 0) {
        return rb_io_close(io);
    }
    n = fclose(fptr->f);
    fptr->mode &= ~FMODE_READABLE;
    fptr->f = fptr->f2;
    fptr->f2 = 0;
    if (n != 0) rb_sys_fail(fptr->path);

    return Qnil;
}


close_write (IO)

/*
 *  call-seq:
 *     ios.close_write   => nil
 *
 *  Closes the write end of a duplex I/O stream (i.e., one that contains
 *  both a read and a write stream, such as a pipe). Will raise an
 *  <code>IOError</code> if the stream is not duplexed.
 *
 *     f = IO.popen("/bin/sh","r+")
 *     f.close_write
 *     f.print "nowhere"
 *
 *  <em>produces:</em>
 *
 *     prog.rb:3:in `write': not opened for writing (IOError)
 *      from prog.rb:3:in `print'
 *      from prog.rb:3
 */

static VALUE
rb_io_close_write(io)
    VALUE io;
{
    OpenFile *fptr;
    int n;

    if (rb_safe_level() >= 4 && !OBJ_TAINTED(io)) {
        rb_raise(rb_eSecurityError, "Insecure: can't close");
    }
    GetOpenFile(io, fptr);
    if (fptr->f2 == 0 && (fptr->mode & FMODE_READABLE)) {
        rb_raise(rb_eIOError, "closing non-duplex IO for writing");
    }
    if (fptr->f2 == 0) {
        return rb_io_close(io);
    }
    n = fclose(fptr->f2);
    fptr->f2 = 0;
    fptr->mode &= ~FMODE_WRITABLE;
    if (n != 0) rb_sys_fail(fptr->path);

    return Qnil;
}


isatty (IO)

/*
 *  call-seq:
 *     ios.isatty   => true or false
 *     ios.tty?     => true or false
 *
 *  Returns <code>true</code> if <em>ios</em> is associated with a
 *  terminal device (tty), <code>false</code> otherwise.
 *
 *     File.new("testfile").isatty   #=> false
 *     File.new("/dev/tty").isatty   #=> true
 */

static VALUE
rb_io_isatty(io)
    VALUE io;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    if (isatty(fileno(fptr->f)) == 0)
        return Qfalse;
    return Qtrue;
}


tty? (IO)

/*
 *  call-seq:
 *     ios.isatty   => true or false
 *     ios.tty?     => true or false
 *
 *  Returns <code>true</code> if <em>ios</em> is associated with a
 *  terminal device (tty), <code>false</code> otherwise.
 *
 *     File.new("testfile").isatty   #=> false
 *     File.new("/dev/tty").isatty   #=> true
 */

static VALUE
rb_io_isatty(io)
    VALUE io;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    if (isatty(fileno(fptr->f)) == 0)
        return Qfalse;
    return Qtrue;
}


binmode (IO)

/*
 *  call-seq:
 *     ios.binmode    => ios
 *
 *  Puts <em>ios</em> into binary mode. This is useful only in
 *  MS-DOS/Windows environments. Once a stream is in binary mode, it
 *  cannot be reset to nonbinary mode.
 */

VALUE
rb_io_binmode(io)
    VALUE io;
{
#if defined(_WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__) || defined(__EMX__)
    OpenFile *fptr;

    GetOpenFile(io, fptr);
#ifdef __human68k__
    if (fptr->f)
        fmode(fptr->f, _IOBIN);
    if (fptr->f2)
        fmode(fptr->f2, _IOBIN);
#else
    if (fptr->f && setmode(fileno(fptr->f), O_BINARY) == -1)
        rb_sys_fail(fptr->path);
    if (fptr->f2 && setmode(fileno(fptr->f2), O_BINARY) == -1)
        rb_sys_fail(fptr->path);
#endif

    fptr->mode |= FMODE_BINMODE;
#endif
    return io;
}


sysseek (IO)

/*
 *  call-seq:
 *     ios.sysseek(offset, whence=SEEK_SET)   => integer
 *
 *  Seeks to a given <i>offset</i> in the stream according to the value
 *  of <i>whence</i> (see <code>IO#seek</code> for values of
 *  <i>whence</i>). Returns the new offset into the file.
 *
 *     f = File.new("testfile")
 *     f.sysseek(-13, IO::SEEK_END)   #=> 53
 *     f.sysread(10)                  #=> "And so on."
 */

static VALUE
rb_io_sysseek(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE offset, ptrname;
    int whence = SEEK_SET;
    OpenFile *fptr;
    off_t pos;

    if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
        whence = NUM2INT(ptrname);
    }
    pos = NUM2OFFT(offset);
    GetOpenFile(io, fptr);
    if ((fptr->mode & FMODE_READABLE) && READ_DATA_BUFFERED(fptr->f)) {
        rb_raise(rb_eIOError, "sysseek for buffered IO");
    }
    if ((fptr->mode & FMODE_WRITABLE) && (fptr->mode & FMODE_WBUF)) {
        rb_warn("sysseek for buffered IO");
    }
    pos = lseek(fileno(fptr->f), pos, whence);
    if (pos == -1) rb_sys_fail(fptr->path);
    clearerr(fptr->f);

    return OFFT2NUM(pos);
}


ioctl (IO)

/*
 *  call-seq:
 *     ios.ioctl(integer_cmd, arg)    => integer
 *
 *  Provides a mechanism for issuing low-level commands to control or
 *  query I/O devices. Arguments and results are platform dependent. If
 *  <i>arg</i> is a number, its value is passed directly. If it is a
 *  string, it is interpreted as a binary sequence of bytes. On Unix
 *  platforms, see <code>ioctl(2)</code> for details. Not implemented on
 *  all platforms.
 */

static VALUE
rb_io_ioctl(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
    VALUE req, arg;

    rb_scan_args(argc, argv, "11", &req, &arg);
    return rb_io_ctl(io, req, arg, 1);
}


fcntl (IO)

/*
 *  call-seq:
 *     ios.fcntl(integer_cmd, arg)    => integer
 *
 *  Provides a mechanism for issuing low-level commands to control or
 *  query file-oriented I/O streams. Arguments and results are platform
 *  dependent. If <i>arg</i> is a number, its value is passed
 *  directly. If it is a string, it is interpreted as a binary sequence
 *  of bytes (<code>Array#pack</code> might be a useful way to build this
 *  string). On Unix platforms, see <code>fcntl(2)</code> for details.
 *  Not implemented on all platforms.
 */

static VALUE
rb_io_fcntl(argc, argv, io)
    int argc;
    VALUE *argv;
    VALUE io;
{
#ifdef HAVE_FCNTL
    VALUE req, arg;

    rb_scan_args(argc, argv, "11", &req, &arg);
    return rb_io_ctl(io, req, arg, 0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


pid (IO)

/*
 *  call-seq:
 *     ios.pid    => fixnum
 *
 *  Returns the process ID of a child process associated with
 *  <em>ios</em>. This will be set by <code>IO::popen</code>.
 *
 *     pipe = IO.popen("-")
 *     if pipe
 *       $stderr.puts "In parent, child pid is #{pipe.pid}"
 *     else
 *       $stderr.puts "In child, pid is #{$$}"
 *     end
 *
 *  <em>produces:</em>
 *
 *     In child, pid is 26209
 *     In parent, child pid is 26209
 */

static VALUE
rb_io_pid(io)
    VALUE io;
{
    OpenFile *fptr;

    GetOpenFile(io, fptr);
    if (!fptr->pid)
        return Qnil;
    return INT2FIX(fptr->pid);
}


inspect (IO)

/*
 * call-seq:
 *   ios.inspect   => string
 *
 * Return a string describing this IO object.
 */

static VALUE
rb_io_inspect(obj)
    VALUE obj;
{
    OpenFile *fptr;
    char *buf, *cname, *st = "";
    long len;

    fptr = RFILE(rb_io_taint_check(obj))->fptr;
    if (!fptr || !fptr->path) return rb_any_to_s(obj);
    cname = rb_obj_classname(obj);
    len = strlen(cname) + strlen(fptr->path) + 5;
    if (!(fptr->f || fptr->f2)) {
        st = " (closed)";
        len += 9;
    }
    buf = ALLOCA_N(char, len);
    snprintf(buf, len, "#<%s:%s%s>", cname, fptr->path, st);
    return rb_str_new2(buf);
}


readbytes (IO)

# File lib/readbytes.rb, line 20
  def readbytes(n)
    str = read(n)
    if str == nil
      raise EOFError, "End of file reached"
    end
    if str.size < n
      raise TruncatedDataError.new("data truncated", str)
    end
    str
  end


scanf (IO)

# File lib/scanf.rb, line 590
  def scanf(str,&b)
    return block_scanf(str,&b) if b
    return [] unless str.size > 0

    start_position = pos rescue 0
    matched_so_far = 0
    source_buffer = ""
    result_buffer = []
    final_result = []

    fstr = Scanf::FormatString.new(str)

    loop do
      if eof || (tty? &&! fstr.match(source_buffer))
        final_result.concat(result_buffer)
        break
      end

      source_buffer << gets

      current_match = fstr.match(source_buffer)

      spec = fstr.last_spec_tried

      if spec.matched
        if spec.mid_match?
          result_buffer.replace(current_match)
          next
        end

      elsif (fstr.matched_count == fstr.spec_count - 1)
        if /\A\s*\z/.match(fstr.string_left)
          break if spec.count_space?
          result_buffer.replace(current_match)
          next
        end
      end

      final_result.concat(current_match)

      matched_so_far += source_buffer.size
      source_buffer.replace(fstr.string_left)
      matched_so_far -= source_buffer.size
      break if fstr.last_spec
      fstr.prune
    end
    seek(start_position + matched_so_far, IO::SEEK_SET) rescue Errno::ESPIPE
    soak_up_spaces if fstr.last_spec && fstr.space

    return final_result
  end


new_ntoh (IPAddr)

# File lib/ipaddr.rb, line 90
  def IPAddr::new_ntoh(addr)
    return IPAddr.new(IPAddr::ntop(addr))
  end


ntop (IPAddr)

# File lib/ipaddr.rb, line 96
  def IPAddr::ntop(addr)
    case addr.size
    when 4
      s = addr.unpack('C4').join('.')
    when 16
      s = IN6FORMAT % addr.unpack('n8')
    else
      raise ArgumentError, "unsupported address family"
    end
    return s
  end


& (IPAddr)

# File lib/ipaddr.rb, line 109
  def &(other)
    return self.clone.set(@addr & other.to_i)
  end


| (IPAddr)

# File lib/ipaddr.rb, line 114
  def |(other)
    return self.clone.set(@addr | other.to_i)
  end


>> (IPAddr)

# File lib/ipaddr.rb, line 119
  def >>(num)
    return self.clone.set(@addr >> num)
  end


<< (IPAddr)

# File lib/ipaddr.rb, line 124
  def <<(num)
    return self.clone.set(addr_mask(@addr << num))
  end


~ (IPAddr)

# File lib/ipaddr.rb, line 129
  def ~
    return self.clone.set(addr_mask(~@addr))
  end


== (IPAddr)

# File lib/ipaddr.rb, line 134
  def ==(other)
    if other.kind_of?(IPAddr) && @family != other.family
      return false
    end
    return (@addr == other.to_i)
  end


mask (IPAddr)

# File lib/ipaddr.rb, line 143
  def mask(prefixlen)
    return self.clone.mask!(prefixlen)
  end


include? (IPAddr)

# File lib/ipaddr.rb, line 155
  def include?(other)
    if ipv4_mapped?
      if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
        return false
      end
      mask_addr = (@mask_addr & IN4MASK)
      addr = (@addr & IN4MASK)
      family = Socket::AF_INET
    else
      mask_addr = @mask_addr
      addr = @addr
      family = @family
    end
    if other.kind_of?(IPAddr)
      if other.ipv4_mapped?
        other_addr = (other.to_i & IN4MASK)
        other_family = Socket::AF_INET
      else
        other_addr = other.to_i
        other_family = other.family
      end
    else # Not IPAddr - assume integer in same family as us
      other_addr   = other.to_i
      other_family = family
    end

    if family != other_family
      return false
    end
    return ((addr & mask_addr) == (other_addr & mask_addr))
  end


to_i (IPAddr)

# File lib/ipaddr.rb, line 189
  def to_i
    return @addr
  end


to_s (IPAddr)

# File lib/ipaddr.rb, line 194
  def to_s
    str = to_string
    return str if ipv4?

    str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
    loop do
      break if str.sub!(/\A0:0:0:0:0:0:0:0\Z/, '::')
      break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0\b/, ':')
      break if str.sub!(/\b0:0\b/, ':')
      break
    end
    str.sub!(/:{3,}/, '::')

    if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\Z/i =~ str
      str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
    end

    str
  end


to_string (IPAddr)

# File lib/ipaddr.rb, line 220
  def to_string
    return _to_string(@addr)
  end


hton (IPAddr)

# File lib/ipaddr.rb, line 225
  def hton
    case @family
    when Socket::AF_INET
      return [@addr].pack('N')
    when Socket::AF_INET6
      return (0..7).map { |i|
        (@addr >> (112 - 16 * i)) & 0xffff
      }.pack('n8')
    else
      raise "unsupported address family"
    end
  end


ipv4? (IPAddr)

# File lib/ipaddr.rb, line 239
  def ipv4?
    return @family == Socket::AF_INET
  end


ipv6? (IPAddr)

# File lib/ipaddr.rb, line 244
  def ipv6?
    return @family == Socket::AF_INET6
  end


ipv4_mapped? (IPAddr)

# File lib/ipaddr.rb, line 249
  def ipv4_mapped?
    return ipv6? && (@addr >> 32) == 0xffff
  end


ipv4_compat? (IPAddr)

# File lib/ipaddr.rb, line 254
  def ipv4_compat?
    if !ipv6? || (@addr >> 32) != 0
      return false
    end
    a = (@addr & IN4MASK)
    return a != 0 && a != 1
  end


ipv4_mapped (IPAddr)

# File lib/ipaddr.rb, line 264
  def ipv4_mapped
    if !ipv4?
      raise ArgumentError, "not an IPv4 address"
    end
    return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
  end


ipv4_compat (IPAddr)

# File lib/ipaddr.rb, line 273
  def ipv4_compat
    if !ipv4?
      raise ArgumentError, "not an IPv4 address"
    end
    return self.clone.set(@addr, Socket::AF_INET6)
  end


native (IPAddr)

# File lib/ipaddr.rb, line 283
  def native
    if !ipv4_mapped? && !ipv4_compat?
      return self
    end
    return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
  end


reverse (IPAddr)

# File lib/ipaddr.rb, line 292
  def reverse
    case @family
    when Socket::AF_INET
      return _reverse + ".in-addr.arpa"
    when Socket::AF_INET6
      return ip6_arpa
    else
      raise "unsupported address family"
    end
  end


ip6_arpa (IPAddr)

# File lib/ipaddr.rb, line 304
  def ip6_arpa
    if !ipv6?
      raise ArgumentError, "not an IPv6 address"
    end
    return _reverse + ".ip6.arpa"
  end


ip6_int (IPAddr)

# File lib/ipaddr.rb, line 312
  def ip6_int
    if !ipv6?
      raise ArgumentError, "not an IPv6 address"
    end
    return _reverse + ".ip6.int"
  end


inspect (IPAddr)

# File lib/ipaddr.rb, line 321
  def inspect
    case @family
    when Socket::AF_INET
      af = "IPv4"
    when Socket::AF_INET6
      af = "IPv6"
    else
      raise "unsupported address family"
    end
    return sprintf("#<%s: %s:%s/%s>", self.class.name,
                   af, _to_string(@addr), _to_string(@mask_addr))
  end


set (IPAddr)

# File lib/ipaddr.rb, line 336
  def set(addr, *family)
    case family[0] ? family[0] : @family
    when Socket::AF_INET
      if addr < 0 || addr > IN4MASK
        raise ArgumentError, "invalid address"
      end
    when Socket::AF_INET6
      if addr < 0 || addr > IN6MASK
        raise ArgumentError, "invalid address"
      end
    else
      raise ArgumentError, "unsupported address family"
    end
    @addr = addr
    if family[0]
      @family = family[0]
    end
    return self
  end


mask! (IPAddr)

# File lib/ipaddr.rb, line 356
  def mask!(mask)
    if mask.kind_of?(String)
      if mask =~ /^\d+$/
        prefixlen = mask.to_i
      else
        m = IPAddr.new(mask)
        if m.family != @family
          raise ArgumentError, "address family is not same"
        end
        @mask_addr = m.to_i
        @addr &= @mask_addr
        return self
      end
    else
      prefixlen = mask
    end
    case @family
    when Socket::AF_INET
      if prefixlen < 0 || prefixlen > 32
        raise ArgumentError, "invalid length"
      end
      masklen = 32 - prefixlen
      @mask_addr = ((IN4MASK >> masklen) << masklen)
    when Socket::AF_INET6
      if prefixlen < 0 || prefixlen > 128
        raise ArgumentError, "invalid length"
      end
      masklen = 128 - prefixlen
      @mask_addr = ((IN6MASK >> masklen) << masklen)
    else
      raise "unsupported address family"
    end
    @addr = ((@addr >> masklen) << masklen)
    return self
  end


new (IPAddr)

# File lib/ipaddr.rb, line 402
  def initialize(addr = '::', family = Socket::AF_UNSPEC)
    if !addr.kind_of?(String)
      if family != Socket::AF_INET6 && family != Socket::AF_INET
        raise ArgumentError, "unsupported address family"
      end
      set(addr, family)
      @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
      return
    end
    prefix, prefixlen = addr.split('/')
    if prefix =~ /^\[(.*)\]$/i
      prefix = $1
      family = Socket::AF_INET6
    end
    # It seems AI_NUMERICHOST doesn't do the job.
    #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
    #                  Socket::AI_NUMERICHOST)
    begin
      IPSocket.getaddress(prefix)               # test if address is vaild
    rescue
      raise ArgumentError, "invalid address"
    end
    @addr = @family = nil
    if family == Socket::AF_UNSPEC || family == Socket::AF_INET
      @addr = in_addr(prefix)
      if @addr
        @family = Socket::AF_INET
      end
    end
    if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
      @addr = in6_addr(prefix)
      @family = Socket::AF_INET6
    end
    if family != Socket::AF_UNSPEC && @family != family
      raise ArgumentError, "address family unmatch"
    end
    if prefixlen
      mask!(prefixlen)
    else
      @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
    end
  end


irb_level (IRB::Context)

# File lib/irb/ext/workspaces.rb, line 16
    def irb_level
      workspace_stack.size
    end


workspaces (IRB::Context)

# File lib/irb/ext/workspaces.rb, line 20
    def workspaces
      if defined? @workspaces
        @workspaces
      else
        @workspaces = []
      end
    end


push_workspace (IRB::Context)

# File lib/irb/ext/workspaces.rb, line 28
    def push_workspace(*_main)
      if _main.empty?
        if workspaces.empty?
          print "No other workspace\n"
          return nil
        end
        ws = workspaces.pop
        workspaces.push @workspace
        @workspace = ws
        return workspaces
      end

      workspaces.push @workspace
      @workspace = WorkSpace.new(@workspace.binding, _main[0])
      if !(class<<main;ancestors;end).include?(ExtendCommandBundle)
        main.extend ExtendCommandBundle
      end
    end


pop_workspace (IRB::Context)

# File lib/irb/ext/workspaces.rb, line 47
    def pop_workspace
      if workspaces.empty?
        print "workspace stack empty\n"
        return
      end
      @workspace = workspaces.pop
    end


use_loader (IRB::Context)

# File lib/irb/ext/use-loader.rb, line 35
    def use_loader
      IRB.conf[:USE_LOADER]
    end


use_loader= (IRB::Context)

# File lib/irb/ext/use-loader.rb, line 41
    def use_loader=(opt)

      if IRB.conf[:USE_LOADER] != opt
        IRB.conf[:USE_LOADER] = opt
        if opt
          if !$".include?("irb/cmd/load")
          end
          (class<<@workspace.main;self;end).instance_eval {
            alias_method :load, :irb_load
            alias_method :require, :irb_require
          }
        else
          (class<<@workspace.main;self;end).instance_eval {
            alias_method :load, :__original__load__IRB_use_loader__
            alias_method :require, :__original__require__IRB_use_loader__
          }
        end
      end
      print "Switch to load/require#{unless use_loader; ' non';end} trace mode.\n" if verbose?
      opt
    end


set_last_value (IRB::Context)

# File lib/irb/ext/history.rb, line 21
    def set_last_value(value)
      _set_last_value(value)

#      @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
      if @eval_history #and !@eval_history_values.equal?(llv)
        @eval_history_values.push @line_no, @last_value
        @workspace.evaluate self, "__ = IRB.CurrentContext.instance_eval{@eval_history_values}"
      end

      @last_value
    end


eval_history= (IRB::Context)

# File lib/irb/ext/history.rb, line 34
    def eval_history=(no)
      if no
        if defined?(@eval_history) && @eval_history
          @eval_history_values.size(no)
        else
          @eval_history_values = History.new(no)
          IRB.conf[:__TMP__EHV__] = @eval_history_values
          @workspace.evaluate(self, "__ = IRB.conf[:__TMP__EHV__]")
          IRB.conf.delete(:__TMP_EHV__)
        end
      else
        @eval_history_values = nil
      end
      @eval_history = no
    end


home_workspace (IRB::Context)

# File lib/irb/ext/change-ws.rb, line 16
    def home_workspace
      if defined? @home_workspace
        @home_workspace
      else
        @home_workspace = @workspace
      end
    end


change_workspace (IRB::Context)

# File lib/irb/ext/change-ws.rb, line 24
    def change_workspace(*_main)
      if _main.empty?
        @workspace = home_workspace
        return main
      end

      @workspace = WorkSpace.new(_main[0])

      if !(class<<main;ancestors;end).include?(ExtendCommandBundle)
        main.extend ExtendCommandBundle
      end
    end


use_tracer= (IRB::Context)

# File lib/irb/ext/tracer.rb, line 30
    def use_tracer=(opt)
      if opt
        Tracer.set_get_line_procs(@irb_path) {
          |line_no, *rests|
          @io.line(line_no)
        }
      elsif !opt && @use_tracer
        Tracer.off
      end
      @use_tracer=opt
    end


math_mode= (IRB::Context)

# File lib/irb/ext/math-mode.rb, line 19
    def math_mode=(opt)
      if @math_mode == true && opt == false
        IRB.fail CantReturnToNormalMode
        return
      end

      @math_mode = opt
      if math_mode
        main.extend Math
        print "start math mode\n" if verbose?
      end
    end


inspect? (IRB::Context)

# File lib/irb/ext/math-mode.rb, line 32
    def inspect?
      @inspect_mode.nil? && !@math_mode or @inspect_mode
    end


init_save_history (IRB::Context)

# File lib/irb/ext/save-history.rb, line 22
    def init_save_history
      unless (class<<@io;self;end).include?(HistorySavingAbility)
        @io.extend(HistorySavingAbility)
      end
    end


save_history (IRB::Context)

# File lib/irb/ext/save-history.rb, line 28
    def save_history
      IRB.conf[:SAVE_HISTORY]
    end


save_history= (IRB::Context)

# File lib/irb/ext/save-history.rb, line 32
    def save_history=(val)
      IRB.conf[:SAVE_HISTORY] = val
      if val
        main_context = IRB.conf[:MAIN_CONTEXT]
        main_context = self unless main_context
        main_context.init_save_history
      end
    end


history_file (IRB::Context)

# File lib/irb/ext/save-history.rb, line 41
    def history_file
      IRB.conf[:HISTORY_FILE]
    end


history_file= (IRB::Context)

# File lib/irb/ext/save-history.rb, line 45
    def history_file=(hist)
      IRB.conf[:HISTORY_FILE] = hist
    end


new (IRB::Context)

# File lib/irb/context.rb, line 22
    def initialize(irb, workspace = nil, input_method = nil, output_method = nil)
      @irb = irb
      if workspace
        @workspace = workspace
      else
        @workspace = WorkSpace.new
      end
      @thread = Thread.current if defined? Thread
#      @irb_level = 0

      # copy of default configuration
      @ap_name = IRB.conf[:AP_NAME]
      @rc = IRB.conf[:RC]
      @load_modules = IRB.conf[:LOAD_MODULES]

      @use_readline = IRB.conf[:USE_READLINE]
      @inspect_mode = IRB.conf[:INSPECT_MODE]

      self.math_mode = IRB.conf[:MATH_MODE] if IRB.conf[:MATH_MODE]
      self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRACER]
      self.use_loader = IRB.conf[:USE_LOADER] if IRB.conf[:USE_LOADER]
      self.eval_history = IRB.conf[:EVAL_HISTORY] if IRB.conf[:EVAL_HISTORY]

      @ignore_sigint = IRB.conf[:IGNORE_SIGINT]
      @ignore_eof = IRB.conf[:IGNORE_EOF]

      @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT]

      self.prompt_mode = IRB.conf[:PROMPT_MODE]

      if IRB.conf[:SINGLE_IRB] or !defined?(JobManager)
        @irb_name = IRB.conf[:IRB_NAME]
      else
        @irb_name = "irb#"+IRB.JobManager.n_jobs.to_s
      end
      @irb_path = "(" + @irb_name + ")"

      case input_method
      when nil
        case use_readline?
        when nil
          if (defined?(ReadlineInputMethod) && STDIN.tty? &&
              IRB.conf[:PROMPT_MODE] != :INF_RUBY)
            @io = ReadlineInputMethod.new
          else
            @io = StdioInputMethod.new
          end
        when false
          @io = StdioInputMethod.new
        when true
          if defined?(ReadlineInputMethod)
            @io = ReadlineInputMethod.new
          else
            @io = StdioInputMethod.new
          end
        end

      when String
        @io = FileInputMethod.new(input_method)
        @irb_name = File.basename(input_method)
        @irb_path = input_method
      else
        @io = input_method
      end
      self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY]

      if output_method
        @output_method = output_method
      else
        @output_method = StdioOutputMethod.new
      end

      @verbose = IRB.conf[:VERBOSE]
      @echo = IRB.conf[:ECHO]
      if @echo.nil?
        @echo = true
      end
      @debug_level = IRB.conf[:DEBUG_LEVEL]
    end


main (IRB::Context)

# File lib/irb/context.rb, line 102
    def main
      @workspace.main
    end


verbose? (IRB::Context)

# File lib/irb/context.rb, line 143
    def verbose?
      if @verbose.nil?
        if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod)
          false
        elsif !STDIN.tty? or @io.kind_of?(FileInputMethod)
          true
        else
          false
        end
      end
    end


prompting? (IRB::Context)

# File lib/irb/context.rb, line 155
    def prompting?
      verbose? || (STDIN.tty? && @io.kind_of?(StdioInputMethod) ||
                (defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod)))
    end


set_last_value (IRB::Context)

# File lib/irb/context.rb, line 162
    def set_last_value(value)
      @last_value = value
      @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
    end


prompt_mode= (IRB::Context)

# File lib/irb/context.rb, line 169
    def prompt_mode=(mode)
      @prompt_mode = mode
      pconf = IRB.conf[:PROMPT][mode]
      @prompt_i = pconf[:PROMPT_I]
      @prompt_s = pconf[:PROMPT_S]
      @prompt_c = pconf[:PROMPT_C]
      @prompt_n = pconf[:PROMPT_N]
      @return_format = pconf[:RETURN]
      if ai = pconf.include?(:AUTO_INDENT)
        @auto_indent_mode = ai
      else
        @auto_indent_mode = IRB.conf[:AUTO_INDENT]
      end
    end


inspect? (IRB::Context)

# File lib/irb/context.rb, line 184
    def inspect?
      @inspect_mode.nil? or @inspect_mode
    end


file_input? (IRB::Context)

# File lib/irb/context.rb, line 188
    def file_input?
      @io.class == FileInputMethod
    end


inspect_mode= (IRB::Context)

# File lib/irb/context.rb, line 192
    def inspect_mode=(opt)
      if opt
        @inspect_mode = opt
      else
        @inspect_mode = !@inspect_mode
      end
      print "Switch to#{unless @inspect_mode; ' non';end} inspect mode.\n" if verbose?
      @inspect_mode
    end


use_readline= (IRB::Context)

# File lib/irb/context.rb, line 202
    def use_readline=(opt)
      @use_readline = opt
      print "use readline module\n" if @use_readline
    end


debug_level= (IRB::Context)

# File lib/irb/context.rb, line 207
    def debug_level=(value)
      @debug_level = value
      RubyLex.debug_level = value
      SLex.debug_level = value
    end


debug? (IRB::Context)

# File lib/irb/context.rb, line 213
    def debug?
      @debug_level > 0
    end


evaluate (IRB::Context)

# File lib/irb/context.rb, line 217
    def evaluate(line, line_no)
      @line_no = line_no
      set_last_value(@workspace.evaluate(self, line, irb_path, line_no))
#      @workspace.evaluate("_ = IRB.conf[:MAIN_CONTEXT]._")
#      @_ = @workspace.evaluate(line, irb_path, line_no)
    end


exit (IRB::Context)

# File lib/irb/context.rb, line 225
    def exit(ret = 0)
      IRB.irb_exit(@irb, ret)
    end


inspect (IRB::Context)

# File lib/irb/context.rb, line 234
    def inspect
      array = []
      for ivar in instance_variables.sort{|e1, e2| e1 <=> e2}
        name = ivar.sub(/^@(.*)$/){$1}
        val = instance_eval(ivar)
        case ivar
        when *NOPRINTING_IVARS
          array.push format("conf.%s=%s", name, "...")
        when *NO_INSPECTING_IVARS
          array.push format("conf.%s=%s", name, val.to_s)
        when *IDNAME_IVARS
          array.push format("conf.%s=:%s", name, val.id2name)
        else
          array.push format("conf.%s=%s", name, val.inspect)
        end
      end
      array.join("\n")
    end


install_extend_commands (IRB::ContextExtender)

# File lib/irb/extend-command.rb, line 199
    def self.install_extend_commands
      for args in @EXTEND_COMMANDS
        def_extend_command(*args)
      end
    end


def_extend_command (IRB::ContextExtender)

# File lib/irb/extend-command.rb, line 205
    def self.def_extend_command(cmd_name, load_file, *aliases)
      Context.module_eval %[
        def #{cmd_name}(*opts, &b)
          Context.module_eval {remove_method(:#{cmd_name})}
          require "#{load_file}"
          send :#{cmd_name}, *opts, &b
        end
        for ali in aliases
          alias_method ali, cmd_name
        end
      ]
    end


execute (IRB::ExtendCommand::ChangeWorkspace)

# File lib/irb/cmd/chws.rb, line 26
      def execute(*obj)
        irb_context.change_workspace(*obj)
        irb_context.main
      end


execute (IRB::ExtendCommand::CurrentWorkingWorkspace)

# File lib/irb/cmd/chws.rb, line 20
      def execute(*obj)
        irb_context.main
      end


execute (IRB::ExtendCommand::Foreground)

# File lib/irb/cmd/subirb.rb, line 32
      def execute(key)
        IRB.JobManager.switch(key)
      end


execute (IRB::ExtendCommand::Fork)

# File lib/irb/cmd/fork.rb, line 19
      def execute(&block)
        pid = send ExtendCommand.irb_original_method_name("fork")
        unless pid
          class<<self
            alias_method :exit, ExtendCommand.irb_original_method_name('exit')
          end
          if iterator?
            begin
              yield
            ensure
              exit
            end
          end
        end
        pid
      end


execute (IRB::ExtendCommand::Help)

# File lib/irb/cmd/help.rb, line 21
        def self.execute(context, *names)
          names.each do |name|
            begin
              @ri.get_info_for(name.to_s)
            rescue RiError
              puts $!.message
            end
          end
          nil
        end


execute (IRB::ExtendCommand::IrbCommand)

# File lib/irb/cmd/subirb.rb, line 20
      def execute(*obj)
        IRB.irb(nil, *obj)
      end


execute (IRB::ExtendCommand::Jobs)

# File lib/irb/cmd/subirb.rb, line 26
      def execute
        IRB.JobManager
      end


execute (IRB::ExtendCommand::Kill)

# File lib/irb/cmd/subirb.rb, line 38
      def execute(*keys)
        IRB.JobManager.kill(*keys)
      end


execute (IRB::ExtendCommand::Load)

# File lib/irb/cmd/load.rb, line 21
      def execute(file_name, priv = nil)
#       return ruby_load(file_name) unless IRB.conf[:USE_LOADER]
        return irb_load(file_name, priv)
      end


execute (IRB::ExtendCommand::Nop)

# File lib/irb/cmd/nop.rb, line 18
      def self.execute(conf, *opts)
        command = new(conf)
        command.execute(*opts)
      end


new (IRB::ExtendCommand::Nop)

# File lib/irb/cmd/nop.rb, line 23
      def initialize(conf)
        @irb_context = conf
      end


irb (IRB::ExtendCommand::Nop)

# File lib/irb/cmd/nop.rb, line 29
      def irb
        @irb_context.irb
      end


execute (IRB::ExtendCommand::Nop)

# File lib/irb/cmd/nop.rb, line 33
      def execute(*opts)
        #nop
      end


execute (IRB::ExtendCommand::PopWorkspace)

# File lib/irb/cmd/pushws.rb, line 32
      def execute(*obj)
        irb_context.pop_workspace(*obj)
        super
      end


execute (IRB::ExtendCommand::PushWorkspace)

# File lib/irb/cmd/pushws.rb, line 25
      def execute(*obj)
        irb_context.push_workspace(*obj)
        super
      end


execute (IRB::ExtendCommand::Require)

# File lib/irb/cmd/load.rb, line 30
      def execute(file_name)
#       return ruby_require(file_name) unless IRB.conf[:USE_LOADER]

        rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?")
        return false if $".find{|f| f =~ rex}

        case file_name
        when /\.rb$/
          begin
            if irb_load(file_name)
              $".push file_name
              return true
            end
          rescue LoadError
          end
        when /\.(so|o|sl)$/
          return ruby_require(file_name)
        end

        begin
          irb_load(f = file_name + ".rb")
          $".push f
          return true
        rescue LoadError
          return ruby_require(file_name)
        end
      end


execute (IRB::ExtendCommand::Source)

# File lib/irb/cmd/load.rb, line 61
      def execute(file_name)
        source_file(file_name)
      end


execute (IRB::ExtendCommand::Workspaces)

# File lib/irb/cmd/pushws.rb, line 19
      def execute(*obj)
        irb_context.workspaces.collect{|ws| ws.main}
      end


irb_load (IRB::ExtendCommandBundle)

# File lib/irb/ext/use-loader.rb, line 23
    def irb_load(*opts, &b)
      ExtendCommand::Load.execute(irb_context, *opts, &b)
    end


irb_require (IRB::ExtendCommandBundle)

# File lib/irb/ext/use-loader.rb, line 26
    def irb_require(*opts, &b)
      ExtendCommand::Require.execute(irb_context, *opts, &b)
    end


irb_exit (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 23
    def irb_exit(ret = 0)
      irb_context.exit(ret)
    end


irb_context (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 27
    def irb_context
      IRB.CurrentContext
    end


install_extend_commands (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 109
    def self.install_extend_commands
      for args in @EXTEND_COMMANDS
        def_extend_command(*args)
      end
    end


def_extend_command (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 116
    def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)
      case cmd_class
      when Symbol
        cmd_class = cmd_class.id2name
      when String
      when Class
        cmd_class = cmd_class.name
      end

      if load_file
        eval %[
          def #{cmd_name}(*opts, &b)
            require "#{load_file}"
            eval %[
              def #{cmd_name}(*opts, &b)
                ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
              end
            ]
            send :#{cmd_name}, *opts, &b
          end
        ]
      else
        eval %[
          def #{cmd_name}(*opts, &b)
            ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
          end
        ]
      end

      for ali, flag in aliases
        @ALIASES.push [ali, cmd_name, flag]
      end
    end


install_alias_method (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 151
    def install_alias_method(to, from, override = NO_OVERRIDE)
      to = to.id2name unless to.kind_of?(String)
      from = from.id2name unless from.kind_of?(String)

      if override == OVERRIDE_ALL or
          (override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or
          (override == NO_OVERRIDE) &&  !respond_to?(to, true)
        target = self
        (class<<self;self;end).instance_eval{
          if target.respond_to?(to, true) &&
              !target.respond_to?(EXCB.irb_original_method_name(to), true)
            alias_method(EXCB.irb_original_method_name(to), to)
          end
          alias_method to, from
        }
      else
        print "irb: warn: can't alias #{to} from #{from}.\n"
      end
    end


irb_original_method_name (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 171
    def self.irb_original_method_name(method_name)
      "irb_" + method_name + "_org"
    end


extend_object (IRB::ExtendCommandBundle)

# File lib/irb/extend-command.rb, line 175
    def self.extend_object(obj)
      unless (class<<obj;ancestors;end).include?(EXCB)
        super
        for ali, com, flg in @ALIASES
          obj.install_alias_method(ali, com, flg)
        end
      end
    end


new (IRB::FileInputMethod)

# File lib/irb/input-method.rb, line 66
    def initialize(file)
      super
      @io = open(file)
    end


eof? (IRB::FileInputMethod)

# File lib/irb/input-method.rb, line 72
    def eof?
      @io.eof?
    end


gets (IRB::FileInputMethod)

# File lib/irb/input-method.rb, line 76
    def gets
      print @prompt
      l = @io.gets
#      print @prompt, l
      l
    end


new (IRB::Frame)

# File lib/irb/frame.rb, line 24
    def initialize
      @frames = [TOPLEVEL_BINDING] * INIT_STACK_TIMES
    end


trace_func (IRB::Frame)

# File lib/irb/frame.rb, line 28
    def trace_func(event, file, line, id, binding)
      case event
      when 'call', 'class'
        @frames.push binding
      when 'return', 'end'
        @frames.pop
      end
    end


top (IRB::Frame)

# File lib/irb/frame.rb, line 37
    def top(n = 0)
      bind = @frames[-(n + CALL_STACK_OFFSET)]
      Fail FrameUnderflow unless bind
      bind
    end


bottom (IRB::Frame)

# File lib/irb/frame.rb, line 43
    def bottom(n = 0)
      bind = @frames[n]
      Fail FrameOverflow unless bind
      bind
    end


bottom (IRB::Frame)

# File lib/irb/frame.rb, line 50
    def Frame.bottom(n = 0)
      @backtrace.bottom(n)
    end


top (IRB::Frame)

# File lib/irb/frame.rb, line 54
    def Frame.top(n = 0)
      @backtrace.top(n)
    end


sender (IRB::Frame)

# File lib/irb/frame.rb, line 58
    def Frame.sender
      eval "self", @backtrace.top
    end


new (IRB::History)

# File lib/irb/ext/history.rb, line 54
    def initialize(size = 16)
      @size = size
      @contents = []
    end


size (IRB::History)

# File lib/irb/ext/history.rb, line 59
    def size(size)
      if size != 0 && size < @size
        @contents = @contents[@size - size .. @size]
      end
      @size = size
    end


[] (IRB::History)

# File lib/irb/ext/history.rb, line 66
    def [](idx)
      begin
        if idx >= 0
          @contents.find{|no, val| no == idx}[1]
        else
          @contents[idx][1]
        end
      rescue NameError
        nil
      end
    end


push (IRB::History)

# File lib/irb/ext/history.rb, line 78
    def push(no, val)
      @contents.push [no, val]
      @contents.shift if @size != 0 && @contents.size > @size
    end


inspect (IRB::History)

# File lib/irb/ext/history.rb, line 85
    def inspect
      if @contents.empty?
        return real_inspect
      end

      unless (last = @contents.pop)[1].equal?(self)
        @contents.push last
        last = nil
      end
      str = @contents.collect{|no, val|
        if val.equal?(self)
          "#{no} ...self-history..."
        else
          "#{no} #{val.inspect}"
        end
      }.join("\n")
      if str == ""
        str = "Empty."
      end
      @contents.push last if last
      str
    end


create_finalizer (IRB::HistorySavingAbility)

# File lib/irb/ext/save-history.rb, line 53
    def HistorySavingAbility.create_finalizer
      proc do
        if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0
          if hf = IRB.conf[:HISTORY_FILE]
            file = File.expand_path(hf)
          end
          file = IRB.rc_file("_history") unless file
          open(file, 'w' ) do |f|
            hist = HISTORY.to_a
            f.puts(hist[-num..-1] || hist)
          end
        end
      end
    end


extended (IRB::HistorySavingAbility)

# File lib/irb/ext/save-history.rb, line 68
    def HistorySavingAbility.extended(obj)
      ObjectSpace.define_finalizer(obj, HistorySavingAbility.create_finalizer)
      obj.load_history
      obj
    end


load_history (IRB::HistorySavingAbility)

# File lib/irb/ext/save-history.rb, line 74
    def load_history
      hist = IRB.conf[:HISTORY_FILE]
      hist = IRB.rc_file("_history") unless hist
      if File.exist?(hist)
        open(hist) do |f|
          f.each {|l| HISTORY << l.chomp}
        end
      end
    end


select_message (IRB::InputCompletor)

# File lib/irb/completion.rb, line 187
    def self.select_message(receiver, message, candidates)
      candidates.grep(/^#{message}/).collect do |e|
        case e
        when /^[a-zA-Z_]/
          receiver + "." + e
        when /^[0-9]/
        when *Operators
          #receiver + " " + e
        end
      end
    end


new (IRB::InputMethod)

# File lib/irb/input-method.rb, line 23
    def initialize(file = STDIN_FILE_NAME)
      @file_name = file
    end


gets (IRB::InputMethod)

# File lib/irb/input-method.rb, line 30
    def gets
      IRB.fail NotImplementedError, "gets"
    end


readable_atfer_eof? (IRB::InputMethod)

# File lib/irb/input-method.rb, line 35
    def readable_atfer_eof?
      false
    end


signal_handle (IRB::Irb)

# File lib/irb/ext/multi-irb.rb, line 214
    def signal_handle
      unless @context.ignore_sigint?
        print "\nabort!!\n" if @context.verbose?
        exit
      end

      case @signal_status
      when :IN_INPUT
        print "^C\n"
        IRB.JobManager.thread(self).raise RubyLex::TerminateLineInput
      when :IN_EVAL
        IRB.irb_abort(self)
      when :IN_LOAD
        IRB.irb_abort(self, LoadAbort)
      when :IN_IRB
        # ignore
      else
        # ignore other cases as well
      end
    end


new (IRB::Irb)

# File lib/irb.rb, line 91
    def initialize(workspace = nil, input_method = nil, output_method = nil)
      @context = Context.new(self, workspace, input_method, output_method)
      @context.main.extend ExtendCommandBundle
      @signal_status = :IN_IRB

      @scanner = RubyLex.new
      @scanner.exception_on_syntax_error = false
    end


eval_input (IRB::Irb)

# File lib/irb.rb, line 102
    def eval_input
      @scanner.set_prompt do
        |ltype, indent, continue, line_no|
        if ltype
          f = @context.prompt_s
        elsif continue
          f = @context.prompt_c
        elsif indent > 0
          f = @context.prompt_n
        else @context.prompt_i
          f = @context.prompt_i
        end
        f = "" unless f
        if @context.prompting?
          @context.io.prompt = p = prompt(f, ltype, indent, line_no)
        else
          @context.io.prompt = p = ""
        end
        if @context.auto_indent_mode
          unless ltype
            ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size +
              indent * 2 - p.size
            ind += 2 if continue
            @context.io.prompt = p + " " * ind if ind > 0
          end
        end
      end

      @scanner.set_input(@context.io) do
        signal_status(:IN_INPUT) do
          if l = @context.io.gets
            print l if @context.verbose?
          else
            if @context.ignore_eof? and @context.io.readable_atfer_eof?
              l = "\n"
              if @context.verbose?
                printf "Use \"exit\" to leave %s\n", @context.ap_name
              end
            end
          end
          l
        end
      end

      @scanner.each_top_level_statement do |line, line_no|
        signal_status(:IN_EVAL) do
          begin
            line.untaint
            @context.evaluate(line, line_no)
            output_value if @context.echo?
          rescue StandardError, ScriptError, Abort
            $! = RuntimeError.new("unknown exception raised") unless $!
            print $!.class, ": ", $!, "\n"
            if  $@[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && $!.class.to_s !~ /^IRB/
              irb_bug = true
            else
              irb_bug = false
            end

            messages = []
            lasts = []
            levels = 0
            for m in $@
              m = @context.workspace.filter_backtrace(m) unless irb_bug
              if m
                if messages.size < @context.back_trace_limit
                  messages.push "\tfrom "+m
                else
                  lasts.push "\tfrom "+m
                  if lasts.size > @context.back_trace_limit
                    lasts.shift
                    levels += 1
                  end
                end
              end
            end
            print messages.join("\n"), "\n"
            unless lasts.empty?
              printf "... %d levels...\n", levels if levels > 0
              print lasts.join("\n")
            end
            print "Maybe IRB bug!!\n" if irb_bug
          end
          if $SAFE > 2
            warn "Error: irb does not work for $SAFE level higher than 2"
            exit 1
          end
        end
      end
    end


suspend_name (IRB::Irb)

# File lib/irb.rb, line 193
    def suspend_name(path = nil, name = nil)
      @context.irb_path, back_path = path, @context.irb_path if path
      @context.irb_name, back_name = name, @context.irb_name if name
      begin
        yield back_path, back_name
      ensure
        @context.irb_path = back_path if path
        @context.irb_name = back_name if name
      end
    end


suspend_workspace (IRB::Irb)

# File lib/irb.rb, line 204
    def suspend_workspace(workspace)
      @context.workspace, back_workspace = workspace, @context.workspace
      begin
        yield back_workspace
      ensure
        @context.workspace = back_workspace
      end
    end


suspend_input_method (IRB::Irb)

# File lib/irb.rb, line 213
    def suspend_input_method(input_method)
      back_io = @context.io
      @context.instance_eval{@io = input_method}
      begin
        yield back_io
      ensure
        @context.instance_eval{@io = back_io}
      end
    end


suspend_context (IRB::Irb)

# File lib/irb.rb, line 223
    def suspend_context(context)
      @context, back_context = context, @context
      begin
        yield back_context
      ensure
        @context = back_context
      end
    end


signal_handle (IRB::Irb)

# File lib/irb.rb, line 232
    def signal_handle
      unless @context.ignore_sigint?
        print "\nabort!!\n" if @context.verbose?
        exit
      end

      case @signal_status
      when :IN_INPUT
        print "^C\n"
        raise RubyLex::TerminateLineInput
      when :IN_EVAL
        IRB.irb_abort(self)
      when :IN_LOAD
        IRB.irb_abort(self, LoadAbort)
      when :IN_IRB
        # ignore
      else
        # ignore other cases as well
      end
    end


signal_status (IRB::Irb)

# File lib/irb.rb, line 253
    def signal_status(status)
      return yield if @signal_status == :IN_LOAD

      signal_status_back = @signal_status
      @signal_status = status
      begin
        yield
      ensure
        @signal_status = signal_status_back
      end
    end


prompt (IRB::Irb)

# File lib/irb.rb, line 265
    def prompt(prompt, ltype, indent, line_no)
      p = prompt.dup
      p.gsub!(/%([0-9]+)?([a-zA-Z])/) do
        case $2
        when "N"
          @context.irb_name
        when "m"
          @context.main.to_s
        when "M"
          @context.main.inspect
        when "l"
          ltype
        when "i"
          if $1
            format("%" + $1 + "d", indent)
          else
            indent.to_s
          end
        when "n"
          if $1
            format("%" + $1 + "d", line_no)
          else
            line_no.to_s
          end
        when "%"
          "%"
        end
      end
      p
    end


output_value (IRB::Irb)

# File lib/irb.rb, line 296
    def output_value
      if @context.inspect?
        printf @context.return_format, @context.last_value.inspect
      else
        printf @context.return_format, @context.last_value
      end
    end


inspect (IRB::Irb)

# File lib/irb.rb, line 304
    def inspect
      ary = []
      for iv in instance_variables
        case iv
        when "@signal_status"
          ary.push format("%s=:%s", iv, @signal_status.id2name)
        when "@context"
          ary.push format("%s=%s", iv, eval(iv).__to_s__)
        else
          ary.push format("%s=%s", iv, eval(iv))
        end
      end
      format("#<%s: %s>", self.class, ary.join(", "))
    end


irb_load (IRB::IrbLoader)

# File lib/irb/ext/loader.rb, line 23
    def irb_load(fn, priv = nil)
      path = search_file_from_ruby_path(fn)
      raise LoadError, "No such file to load -- #{fn}" unless path

      load_file(path, priv)
    end


search_file_from_ruby_path (IRB::IrbLoader)

# File lib/irb/ext/loader.rb, line 30
    def search_file_from_ruby_path(fn)
      if /^#{Regexp.quote(File::Separator)}/ =~ fn
        return fn if File.exist?(fn)
        return nil
      end

      for path in $:
        if File.exist?(f = File.join(path, fn))
          return f
        end
      end
      return nil
    end


source_file (IRB::IrbLoader)

# File lib/irb/ext/loader.rb, line 44
    def source_file(path)
      irb.suspend_name(path, File.basename(path)) do
        irb.suspend_input_method(FileInputMethod.new(path)) do
          |back_io|
          irb.signal_status(:IN_LOAD) do
            if back_io.kind_of?(FileInputMethod)
              irb.eval_input
            else
              begin
                irb.eval_input
              rescue LoadAbort
                print "load abort!!\n"
              end
            end
          end
        end
      end
    end


load_file (IRB::IrbLoader)

# File lib/irb/ext/loader.rb, line 63
    def load_file(path, priv = nil)
      irb.suspend_name(path, File.basename(path)) do

        if priv
          ws = WorkSpace.new(Module.new)
        else
          ws = WorkSpace.new
        end
        irb.suspend_workspace(ws) do
          irb.suspend_input_method(FileInputMethod.new(path)) do
            |back_io|
            irb.signal_status(:IN_LOAD) do
#             p irb.conf
              if back_io.kind_of?(FileInputMethod)
                irb.eval_input
              else
                begin
                  irb.eval_input
                rescue LoadAbort
                  print "load abort!!\n"
                end
              end
            end
          end
        end
      end
    end


old (IRB::IrbLoader)

# File lib/irb/ext/loader.rb, line 91
    def old
      back_io = @io
      back_path = @irb_path
      back_name = @irb_name
      back_scanner = @irb.scanner
      begin
        @io = FileInputMethod.new(path)
        @irb_name = File.basename(path)
        @irb_path = path
        @irb.signal_status(:IN_LOAD) do
          if back_io.kind_of?(FileInputMethod)
            @irb.eval_input
          else
            begin
              @irb.eval_input
            rescue LoadAbort
              print "load abort!!\n"
            end
          end
        end
      ensure
        @io = back_io
        @irb_name = back_name
        @irb_path = back_path
        @irb.scanner = back_scanner
      end
    end


new (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 20
    def initialize
      # @jobs = [[thread, irb],...]
      @jobs = []
      @current_job = nil
    end


n_jobs (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 28
    def n_jobs
      @jobs.size
    end


thread (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 32
    def thread(key)
      th, irb = search(key)
      th
    end


irb (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 37
    def irb(key)
      th, irb = search(key)
      irb
    end


main_thread (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 42
    def main_thread
      @jobs[0][0]
    end


main_irb (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 46
    def main_irb
      @jobs[0][1]
    end


insert (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 50
    def insert(irb)
      @jobs.push [Thread.current, irb]
    end


switch (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 54
    def switch(key)
      th, irb = search(key)
      IRB.fail IrbAlreadyDead unless th.alive?
      IRB.fail IrbSwitchedToCurrentThread if th == Thread.current
      @current_job = irb
      th.run
      Thread.stop
      @current_job = irb(Thread.current)
    end


kill (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 64
    def kill(*keys)
      for key in keys
        th, irb = search(key)
        IRB.fail IrbAlreadyDead unless th.alive?
        th.exit
      end
    end


search (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 72
    def search(key)
      case key
      when Integer
        @jobs[key]
      when Irb
        @jobs.find{|k, v| v.equal?(key)}
      when Thread
        @jobs.assoc(key)
      else
        assoc = @jobs.find{|k, v| v.context.main.equal?(key)}
        IRB.fail NoSuchJob, key if assoc.nil?
        assoc
      end
    end


delete (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 87
    def delete(key)
      case key
      when Integer
        IRB.fail NoSuchJob, key unless @jobs[key]
        @jobs[key] = nil
      else
        catch(:EXISTS) do
          @jobs.each_index do
            |i|
            if @jobs[i] and (@jobs[i][0] == key ||
                             @jobs[i][1] == key ||
                             @jobs[i][1].context.main.equal?(key))
              @jobs[i] = nil
              throw :EXISTS
            end
          end
          IRB.fail NoSuchJob, key
        end
      end
      until assoc = @jobs.pop; end unless @jobs.empty?
      @jobs.push assoc
    end


inspect (IRB::JobManager)

# File lib/irb/ext/multi-irb.rb, line 110
    def inspect
      ary = []
      @jobs.each_index do
        |i|
        th, irb = @jobs[i]
        next if th.nil?

        if th.alive?
          if th.stop?
            t_status = "stop"
          else
            t_status = "running"
          end
        else
          t_status = "exited"
        end
        ary.push format("#%d->%s on %s (%s: %s)",
                        i,
                        irb.context.irb_name,
                        irb.context.main,
                        th,
                        t_status)
      end
      ary.join("\n")
    end


new (IRB::Locale)

# File lib/irb/locale.rb, line 22
    def initialize(locale = nil)
      @lang = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C"
    end


String (IRB::Locale)

# File lib/irb/locale.rb, line 40
    def String(mes)
      mes = super(mes)
      case @lang
      when /^ja/
        mes = Kconv::kconv(mes, lc2kconv(@lang))
      else
        mes
      end
      mes
    end


format (IRB::Locale)

# File lib/irb/locale.rb, line 51
    def format(*opts)
      String(super(*opts))
    end


gets (IRB::Locale)

# File lib/irb/locale.rb, line 55
    def gets(*rs)
      String(super(*rs))
    end


readline (IRB::Locale)

# File lib/irb/locale.rb, line 59
    def readline(*rs)
      String(super(*rs))
    end


print (IRB::Locale)

# File lib/irb/locale.rb, line 63
    def print(*opts)
      ary = opts.collect{|opt| String(opt)}
      super(*ary)
    end


printf (IRB::Locale)

# File lib/irb/locale.rb, line 68
    def printf(*opts)
      s = format(*opts)
      print s
    end


puts (IRB::Locale)

# File lib/irb/locale.rb, line 73
    def puts(*opts)
      ary = opts.collect{|opt| String(opt)}
      super(*ary)
    end


require (IRB::Locale)

# File lib/irb/locale.rb, line 78
    def require(file, priv = nil)
      rex = Regexp.new("lc/#{Regexp.quote(file)}\.(so|o|sl|rb)?")
      return false if $".find{|f| f =~ rex}

      case file
      when /\.rb$/
        begin
          load(file, priv)
          $".push file
          return true
        rescue LoadError
        end
      when /\.(so|o|sl)$/
        return super
      end

      begin
        load(f = file + ".rb")
        $".push f  #"
        return true
      rescue LoadError
        return ruby_require(file)
      end
    end


load (IRB::Locale)

# File lib/irb/locale.rb, line 105
    def load(file, priv=nil)
      dir = File.dirname(file)
      dir = "" if dir == "."
      base = File.basename(file)

      if /^ja(_JP)?$/ =~ @lang
        back, @lang = @lang, "C"
      end
      begin
        if dir[0] == ?/ #/
          lc_path = search_file(dir, base)
          return real_load(lc_path, priv) if lc_path
        end

        for path in $:
          lc_path = search_file(path + "/" + dir, base)
          return real_load(lc_path, priv) if lc_path
        end
      ensure
        @lang = back if back
      end
      raise LoadError, "No such file to load -- #{file}"
    end


find (IRB::Locale)

# File lib/irb/locale.rb, line 139
    def find(file , paths = $:)
      dir = File.dirname(file)
      dir = "" if dir == "."
      base = File.basename(file)
      if dir[0] == ?/ #/
          return lc_path = search_file(dir, base)
      else
        for path in $:
          if lc_path = search_file(path + "/" + dir, base)
            return lc_path
          end
        end
      end
      nil
    end


def_pre_proc (IRB::MethodExtender)

# File lib/irb/extend-command.rb, line 222
    def def_pre_proc(base_method, extend_method)
      base_method = base_method.to_s
      extend_method = extend_method.to_s

      alias_name = new_alias_name(base_method)
      module_eval %[
        alias_method alias_name, base_method
        def #{base_method}(*opts)
          send :#{extend_method}, *opts
          send :#{alias_name}, *opts
        end
      ]
    end


def_post_proc (IRB::MethodExtender)

# File lib/irb/extend-command.rb, line 236
    def def_post_proc(base_method, extend_method)
      base_method = base_method.to_s
      extend_method = extend_method.to_s

      alias_name = new_alias_name(base_method)
      module_eval %[
        alias_method alias_name, base_method
        def #{base_method}(*opts)
          send :#{alias_name}, *opts
          send :#{extend_method}, *opts
        end
      ]
    end


new_alias_name (IRB::MethodExtender)

# File lib/irb/extend-command.rb, line 251
    def new_alias_name(name, prefix = "__alias_of__", postfix = "__")
      base_name = "#{prefix}#{name}#{postfix}"
      all_methods = instance_methods(true) + private_instance_methods(true)
      same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/)
      return base_name if same_methods.empty?
      no = same_methods.size
      while !same_methods.include?(alias_name = base_name + no)
        no += 1
      end
      alias_name
    end


new (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 30
      def initialize(prefix, base_notifier)
        @prefix = prefix
        @base_notifier = base_notifier
      end


notify? (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 37
      def notify?
        true
      end


print (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 41
      def print(*opts)
        @base_notifier.print prefix, *opts if notify?
      end


printn (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 45
      def printn(*opts)
        @base_notifier.printn prefix, *opts if notify?
      end


printf (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 49
      def printf(format, *opts)
        @base_notifier.printf(prefix + format, *opts) if notify?
      end


puts (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 53
      def puts(*objs)
        if notify?
          @base_notifier.puts(*objs.collect{|obj| prefix + obj.to_s})
        end
      end


pp (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 59
      def pp(*objs)
        if notify?
          @base_notifier.ppx @prefix, *objs
        end
      end


ppx (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 65
      def ppx(prefix, *objs)
        if notify?
          @base_notifier.ppx @prefix+prefix, *objs
        end
      end


exec_if (IRB::Notifier::AbstructNotifier)

# File lib/irb/notifier.rb, line 71
      def exec_if
        yield(@base_notifier) if notify?
      end


new (IRB::Notifier::CompositeNotifier)

# File lib/irb/notifier.rb, line 77
      def initialize(prefix, base_notifier)
        super

        @notifiers = [D_NOMSG]
        @level_notifier = D_NOMSG
      end


def_notifier (IRB::Notifier::CompositeNotifier)

# File lib/irb/notifier.rb, line 86
      def def_notifier(level, prefix = "")
        notifier = LeveledNotifier.new(self, level, prefix)
        @notifiers[level] = notifier
        notifier
      end


level_notifier= (IRB::Notifier::CompositeNotifier)

# File lib/irb/notifier.rb, line 95
      def level_notifier=(value)
        case value
        when AbstructNotifier
          @level_notifier = value
        when Integer
          l = @notifiers[value]
          Notifier.Raise ErrUndefinedNotifer, value unless l
          @level_notifier = l
        else
          Notifier.Raise ErrUnrecognizedLevel, value unless l
        end
      end


new (IRB::Notifier::LeveledNotifier)

# File lib/irb/notifier.rb, line 114
      def initialize(base, level, prefix)
        super(prefix, base)

        @level = level
      end


<=> (IRB::Notifier::LeveledNotifier)

# File lib/irb/notifier.rb, line 122
      def <=>(other)
        @level <=> other.level
      end


notify? (IRB::Notifier::LeveledNotifier)

# File lib/irb/notifier.rb, line 126
      def notify?
        @base_notifier.level >= self
      end


new (IRB::Notifier::NoMsgNotifier)

# File lib/irb/notifier.rb, line 132
      def initialize
        @base_notifier = nil
        @level = 0
        @prefix = ""
      end


notify? (IRB::Notifier::NoMsgNotifier)

# File lib/irb/notifier.rb, line 138
      def notify?
        false
      end


def_notifier (IRB::Notifier)

# File lib/irb/notifier.rb, line 24
    def def_notifier(prefix = "", output_method = StdioOutputMethod.new)
      CompositeNotifier.new(prefix, output_method)
    end


print (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 22
    def print(*opts)
      IRB.fail NotImplementError, "print"
    end


printn (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 26
    def printn(*opts)
      print opts.join(" "), "\n"
    end


printf (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 31
    def printf(format, *opts)
      if /(%*)%I/ =~ format
        format, opts = parse_printf_format(format, opts)
      end
      print sprintf(format, *opts)
    end


parse_printf_format (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 44
    def parse_printf_format(format, opts)
      return format, opts if $1.size % 2 == 1
    end


foo (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 48
    def foo(format)
      pos = 0
      inspects = []
      format.scan(/%[#0\-+ ]?(\*(?=[^0-9])|\*[1-9][0-9]*\$|[1-9][0-9]*(?=[^0-9]))?(\.(\*(?=[^0-9])|\*[1-9][0-9]*\$|[1-9][0-9]*(?=[^0-9])))?(([1-9][0-9]*\$)*)([diouxXeEfgGcsb%])/) {|f, p, pp, pos, new_pos, c|
        puts [f, p, pp, pos, new_pos, c].join("!")
        pos = new_pos if new_pos
        if c == "I"
          inspects.push pos.to_i
          (f||"")+(p||"")+(pp||"")+(pos||"")+"s"
        else
          $&
        end
      }
    end


puts (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 63
    def puts(*objs)
      for obj in objs
        print(*obj)
        print "\n"
      end
    end


pp (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 70
    def pp(*objs)
      puts(*objs.collect{|obj| obj.inspect})
    end


ppx (IRB::OutputMethod)

# File lib/irb/output-method.rb, line 74
    def ppx(prefix, *objs)
      puts(*objs.collect{|obj| prefix+obj.inspect})
    end


new (IRB::ReadlineInputMethod)

# File lib/irb/input-method.rb, line 88
      def initialize
        super

        @line_no = 0
        @line = []
        @eof = false
      end


gets (IRB::ReadlineInputMethod)

# File lib/irb/input-method.rb, line 96
      def gets
        if l = readline(@prompt, false)
          HISTORY.push(l) if !l.empty?
          @line[@line_no += 1] = l + "\n"
        else
          @eof = true
          l
        end
      end


eof? (IRB::ReadlineInputMethod)

# File lib/irb/input-method.rb, line 106
      def eof?
        @eof
      end


readable_atfer_eof? (IRB::ReadlineInputMethod)

# File lib/irb/input-method.rb, line 110
      def readable_atfer_eof?
        true
      end


line (IRB::ReadlineInputMethod)

# File lib/irb/input-method.rb, line 114
      def line(line_no)
        @line[line_no]
      end


new (IRB::SLex::Node)

# File lib/irb/slex.rb, line 95
      def initialize(preproc = nil, postproc = nil)
        @Tree = {}
        @preproc = preproc
        @postproc = postproc
      end


search (IRB::SLex::Node)

# File lib/irb/slex.rb, line 104
      def search(chrs, opt = nil)
        return self if chrs.empty?
        ch = chrs.shift
        if node = @Tree[ch]
          node.search(chrs, opt)
        else
          if opt
            chrs.unshift ch
            self.create_subnode(chrs)
          else
            SLex.fail ErrNodeNothing
          end
        end
      end


create_subnode (IRB::SLex::Node)

# File lib/irb/slex.rb, line 119
      def create_subnode(chrs, preproc = nil, postproc = nil)
        if chrs.empty?
          if @postproc
            D_DETAIL.pp node
            SLex.fail ErrNodeAlreadyExists
          else
            D_DEBUG.puts "change abstract node to real node."
            @preproc = preproc
            @postproc = postproc
          end
          return self
        end

        ch = chrs.shift
        if node = @Tree[ch]
          if chrs.empty?
            if node.postproc
              DebugLogger.pp node
              DebugLogger.pp self
              DebugLogger.pp ch
              DebugLogger.pp chrs
              SLex.fail ErrNodeAlreadyExists
            else
              D_WARN.puts "change abstract node to real node"
              node.preproc = preproc
              node.postproc = postproc
            end
          else
            node.create_subnode(chrs, preproc, postproc)
          end
        else
          if chrs.empty?
            node = Node.new(preproc, postproc)
          else
            node = Node.new
            node.create_subnode(chrs, preproc, postproc)
          end
          @Tree[ch] = node
        end
        node
      end


match (IRB::SLex::Node)

# File lib/irb/slex.rb, line 167
      def match(chrs, op = "")
        D_DETAIL.print "match>: ", chrs, "op:", op, "\n"
        if chrs.empty?
          if @preproc.nil? || @preproc.call(op, chrs)
            DOUT.printf(D_DETAIL, "op1: %s\n", op)
            @postproc.call(op, chrs)
          else
            nil
          end
        else
          ch = chrs.shift
          if node = @Tree[ch]
            if ret = node.match(chrs, op+ch)
              return ret
            else
              chrs.unshift ch
              if @postproc and @preproc.nil? || @preproc.call(op, chrs)
                DOUT.printf(D_DETAIL, "op2: %s\n", op.inspect)
                ret = @postproc.call(op, chrs)
                return ret
              else
                return nil
              end
            end
          else
            chrs.unshift ch
            if @postproc and @preproc.nil? || @preproc.call(op, chrs)
              DOUT.printf(D_DETAIL, "op3: %s\n", op)
              @postproc.call(op, chrs)
              return ""
            else
              return nil
            end
          end
        end
      end


match_io (IRB::SLex::Node)

# File lib/irb/slex.rb, line 204
      def match_io(io, op = "")
        if op == ""
          ch = io.getc
          if ch == nil
            return nil
          end
        else
          ch = io.getc_of_rests
        end
        if ch.nil?
          if @preproc.nil? || @preproc.call(op, io)
            D_DETAIL.printf("op1: %s\n", op)
            @postproc.call(op, io)
          else
            nil
          end
        else
          if node = @Tree[ch]
            if ret = node.match_io(io, op+ch)
              ret
            else
              io.ungetc ch
              if @postproc and @preproc.nil? || @preproc.call(op, io)
                DOUT.exec_if{D_DETAIL.printf "op2: %s\n", op.inspect}
                @postproc.call(op, io)
              else
                nil
              end
            end
          else
            io.ungetc ch
            if @postproc and @preproc.nil? || @preproc.call(op, io)
              D_DETAIL.printf("op3: %s\n", op)
              @postproc.call(op, io)
            else
              nil
            end
          end
        end
      end


new (IRB::SLex)

# File lib/irb/slex.rb, line 31
    def initialize
      @head = Node.new("")
    end


def_rule (IRB::SLex)

# File lib/irb/slex.rb, line 35
    def def_rule(token, preproc = nil, postproc = nil, &block)
      D_DETAIL.pp token

      postproc = block if block_given?
      node = create(token, preproc, postproc)
    end


def_rules (IRB::SLex)

# File lib/irb/slex.rb, line 42
    def def_rules(*tokens, &block)
      if block_given?
        p = block
      end
      for token in tokens
        def_rule(token, nil, p)
      end
    end


preproc (IRB::SLex)

# File lib/irb/slex.rb, line 51
    def preproc(token, proc)
      node = search(token)
      node.preproc=proc
    end


postproc (IRB::SLex)

# File lib/irb/slex.rb, line 57
    def postproc(token)
      node = search(token, proc)
      node.postproc=proc
    end


search (IRB::SLex)

# File lib/irb/slex.rb, line 62
    def search(token)
      @head.search(token.split(//))
    end


create (IRB::SLex)

# File lib/irb/slex.rb, line 66
    def create(token, preproc = nil, postproc = nil)
      @head.create_subnode(token.split(//), preproc, postproc)
    end


match (IRB::SLex)

# File lib/irb/slex.rb, line 70
    def match(token)
      case token
      when Array
      when String
        return match(token.split(//))
      else
        return @head.match_io(token)
      end
      ret = @head.match(token)
      D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect}
      ret
    end


inspect (IRB::SLex)

# File lib/irb/slex.rb, line 83
    def inspect
      format("<SLex: @head = %s>", @head.inspect)
    end


new (IRB::StdioInputMethod)

# File lib/irb/input-method.rb, line 41
    def initialize
      super
      @line_no = 0
      @line = []
    end


gets (IRB::StdioInputMethod)

# File lib/irb/input-method.rb, line 47
    def gets
      print @prompt
      @line[@line_no += 1] = $stdin.gets
    end


eof? (IRB::StdioInputMethod)

# File lib/irb/input-method.rb, line 52
    def eof?
      $stdin.eof?
    end


readable_atfer_eof? (IRB::StdioInputMethod)

# File lib/irb/input-method.rb, line 56
    def readable_atfer_eof?
      true
    end


line (IRB::StdioInputMethod)

# File lib/irb/input-method.rb, line 60
    def line(line_no)
      @line[line_no]
    end


print (IRB::StdioOutputMethod)

# File lib/irb/output-method.rb, line 81
    def print(*opts)
      STDOUT.print(*opts)
    end


evaluate (IRB::WorkSpace)

# File lib/irb/ext/tracer.rb, line 45
    def evaluate(context, statements, file = nil, line = nil)
      if context.use_tracer? && file != nil && line != nil
        Tracer.on
        begin
          __evaluate__(context, statements, file, line)
        ensure
          Tracer.off
        end
      else
        __evaluate__(context, statements, file || __FILE__, line || __LINE__)
      end
    end


new (IRB::WorkSpace)

# File lib/irb/workspace.rb, line 16
    def initialize(*main)
      if main[0].kind_of?(Binding)
        @binding = main.shift
      elsif IRB.conf[:SINGLE_IRB]
        @binding = TOPLEVEL_BINDING
      else
        case IRB.conf[:CONTEXT_MODE]
        when 0 # binding in proc on TOPLEVEL_BINDING
          @binding = eval("proc{binding}.call",
                      TOPLEVEL_BINDING,
                      __FILE__,
                      __LINE__)
        when 1 # binding in loaded file
          require "tempfile"
          f = Tempfile.open("irb-binding")
          f.print "          $binding = binding\n"
          f.close
          load f.path
          @binding = $binding

        when 2 # binding in loaded file(thread use)
          unless defined? BINDING_QUEUE
            require "thread"

            IRB.const_set("BINDING_QUEUE", SizedQueue.new(1))
            Thread.abort_on_exception = true
            Thread.start do
              eval "require \"irb/ws-for-case-2\"", TOPLEVEL_BINDING, __FILE__, __LINE__
            end
            Thread.pass
          end
          @binding = BINDING_QUEUE.pop

        when 3 # binging in function on TOPLEVEL_BINDING(default)
          @binding = eval("def irb_binding; binding; end; irb_binding",
                      TOPLEVEL_BINDING,
                      __FILE__,
                      __LINE__ - 3)
        end
      end
      if main.empty?
        @main = eval("self", @binding)
      else
        @main = main[0]
        IRB.conf[:__MAIN__] = @main
        case @main
        when Module
          @binding = eval("IRB.conf[:__MAIN__].module_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__)
        else
          begin
            @binding = eval("IRB.conf[:__MAIN__].instance_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__)
          rescue TypeError
            IRB.fail CantChangeBinding, @main.inspect
          end
        end
      end
      eval("_=nil", @binding)
    end


evaluate (IRB::WorkSpace)

# File lib/irb/workspace.rb, line 81
    def evaluate(context, statements, file = __FILE__, line = __LINE__)
      eval(statements, @binding, file, line)
    end


filter_backtrace (IRB::WorkSpace)

# File lib/irb/workspace.rb, line 86
    def filter_backtrace(bt)
      case IRB.conf[:CONTEXT_MODE]
      when 0
        return nil if bt =~ /\(irb_local_binding\)/
      when 1
        if(bt =~ %r!/tmp/irb-binding! or
           bt =~ %r!irb/.*\.rb! or
           bt =~ /irb\.rb/)
          return nil
        end
      when 2
        return nil if bt =~ /irb\/.*\.rb/
      when 3
        return nil if bt =~ /irb\/.*\.rb/
        bt.sub!(/:\s*in `irb_binding'/){""}
      end
      bt
    end


JobManager (IRB)

# File lib/irb/ext/multi-irb.rb, line 139
  def IRB.JobManager
    @JobManager
  end


CurrentContext (IRB)

# File lib/irb/ext/multi-irb.rb, line 143
  def IRB.CurrentContext
    IRB.JobManager.irb(Thread.current).context
  end


irb (IRB)

# File lib/irb/ext/multi-irb.rb, line 148
  def IRB.irb(file = nil, *main)
    workspace = WorkSpace.new(*main)
    parent_thread = Thread.current
    Thread.start do
      begin
        irb = Irb.new(workspace, file)
      rescue
        print "Subirb can't start with context(self): ", workspace.main.inspect, "\n"
        print "return to main irb\n"
        Thread.pass
        Thread.main.wakeup
        Thread.exit
      end
      @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
      @JobManager.insert(irb)
      @JobManager.current_job = irb
      begin
        system_exit = false
        catch(:IRB_EXIT) do
          irb.eval_input
        end
      rescue SystemExit
        system_exit = true
        raise
        #fail
      ensure
        unless system_exit
          @JobManager.delete(irb)
          if parent_thread.alive?
            @JobManager.current_job = @JobManager.irb(parent_thread)
            parent_thread.run
          else
            @JobManager.current_job = @JobManager.main_irb
            @JobManager.main_thread.run
          end
        end
      end
    end
    Thread.stop
    @JobManager.current_job = @JobManager.irb(Thread.current)
  end


initialize_tracer (IRB)

# File lib/irb/ext/tracer.rb, line 17
  def IRB.initialize_tracer
    Tracer.verbose = false
    Tracer.add_filter {
      |event, file, line, id, binding, *rests|
      /^#{Regexp.quote(@CONF[:IRB_LIB_PATH])}/ !~ file and
        File::basename(file) != "irb.rb"
    }
  end


setup (IRB)

# File lib/irb/init.rb, line 16
  def IRB.setup(ap_path)
    IRB.init_config(ap_path)
    IRB.init_error
    IRB.parse_opts
    IRB.run_config
    IRB.load_modules

    unless @CONF[:PROMPT][@CONF[:PROMPT_MODE]]
      IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE])
    end
  end


init_config (IRB)

# File lib/irb/init.rb, line 29
  def IRB.init_config(ap_path)
    # class instance variables
    @TRACER_INITIALIZED = false

    # default configurations
    unless ap_path and @CONF[:AP_NAME]
      ap_path = File.join(File.dirname(File.dirname(__FILE__)), "irb.rb")
    end
    @CONF[:AP_NAME] = File::basename(ap_path, ".rb")

    @CONF[:IRB_NAME] = "irb"
    @CONF[:IRB_LIB_PATH] = File.dirname(__FILE__)

    @CONF[:RC] = true
    @CONF[:LOAD_MODULES] = []
    @CONF[:IRB_RC] = nil

    @CONF[:MATH_MODE] = false
    @CONF[:USE_READLINE] = false unless defined?(ReadlineInputMethod)
    @CONF[:INSPECT_MODE] = nil
    @CONF[:USE_TRACER] = false
    @CONF[:USE_LOADER] = false
    @CONF[:IGNORE_SIGINT] = true
    @CONF[:IGNORE_EOF] = false
    @CONF[:ECHO] = nil
    @CONF[:VERBOSE] = nil

    @CONF[:EVAL_HISTORY] = nil
    @CONF[:SAVE_HISTORY] = nil

    @CONF[:BACK_TRACE_LIMIT] = 16

    @CONF[:PROMPT] = {
      :NULL => {
        :PROMPT_I => nil,
        :PROMPT_N => nil,
        :PROMPT_S => nil,
        :PROMPT_C => nil,
        :RETURN => "%s\n"
      },
      :DEFAULT => {
        :PROMPT_I => "%N(%m):%03n:%i> ",
        :PROMPT_N => "%N(%m):%03n:%i> ",
        :PROMPT_S => "%N(%m):%03n:%i%l ",
        :PROMPT_C => "%N(%m):%03n:%i* ",
        :RETURN => "=> %s\n"
      },
      :CLASSIC => {
        :PROMPT_I => "%N(%m):%03n:%i> ",
        :PROMPT_N => "%N(%m):%03n:%i> ",
        :PROMPT_S => "%N(%m):%03n:%i%l ",
        :PROMPT_C => "%N(%m):%03n:%i* ",
        :RETURN => "%s\n"
      },
      :SIMPLE => {
        :PROMPT_I => ">> ",
        :PROMPT_N => ">> ",
        :PROMPT_S => nil,
        :PROMPT_C => "?> ",
        :RETURN => "=> %s\n"
      },
      :INF_RUBY => {
        :PROMPT_I => "%N(%m):%03n:%i> ",
#       :PROMPT_N => "%N(%m):%03n:%i> ",
        :PROMPT_N => nil,
        :PROMPT_S => nil,
        :PROMPT_C => nil,
        :RETURN => "%s\n",
        :AUTO_INDENT => true
      },
      :XMP => {
        :PROMPT_I => nil,
        :PROMPT_N => nil,
        :PROMPT_S => nil,
        :PROMPT_C => nil,
        :RETURN => "    ==>%s\n"
      }
    }

    @CONF[:PROMPT_MODE] = (STDIN.tty? ? :DEFAULT : :NULL)
    @CONF[:AUTO_INDENT] = false

    @CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING
    @CONF[:SINGLE_IRB] = false

#    @CONF[:LC_MESSAGES] = "en"
    @CONF[:LC_MESSAGES] = Locale.new

    @CONF[:DEBUG_LEVEL] = 1
  end


init_error (IRB)

# File lib/irb/init.rb, line 120
  def IRB.init_error
    @CONF[:LC_MESSAGES].load("irb/error.rb")
  end


parse_opts (IRB)

# File lib/irb/init.rb, line 127
  def IRB.parse_opts
    load_path = []
    while opt = ARGV.shift
      case opt
      when "-f"
        @CONF[:RC] = false
      when "-m"
        @CONF[:MATH_MODE] = true
      when "-d"
        $DEBUG = true
      when /^-r(.+)?/
        opt = $1 || ARGV.shift
        @CONF[:LOAD_MODULES].push opt if opt
      when /^-I(.+)?/
        opt = $1 || ARGV.shift
        load_path.concat(opt.split(File::PATH_SEPARATOR)) if opt
      when /^-K(.)/
        $KCODE = $1
      when "--inspect"
        @CONF[:INSPECT_MODE] = true
      when "--noinspect"
        @CONF[:INSPECT_MODE] = false
      when "--readline"
        @CONF[:USE_READLINE] = true
      when "--noreadline"
        @CONF[:USE_READLINE] = false
      when "--echo"
        @CONF[:ECHO] = true
      when "--noecho"
        @CONF[:ECHO] = false
      when "--verbose"
        @CONF[:VERBOSE] = true
      when "--noverbose"
        @CONF[:VERBOSE] = false
      when "--prompt-mode", "--prompt"
        prompt_mode = ARGV.shift.upcase.tr("-", "_").intern
        @CONF[:PROMPT_MODE] = prompt_mode
      when "--noprompt"
        @CONF[:PROMPT_MODE] = :NULL
      when "--inf-ruby-mode"
        @CONF[:PROMPT_MODE] = :INF_RUBY
      when "--sample-book-mode", "--simple-prompt"
        @CONF[:PROMPT_MODE] = :SIMPLE
      when "--tracer"
        @CONF[:USE_TRACER] = true
      when "--back-trace-limit"
        @CONF[:BACK_TRACE_LIMIT] = ARGV.shift.to_i
      when "--context-mode"
        @CONF[:CONTEXT_MODE] = ARGV.shift.to_i
      when "--single-irb"
        @CONF[:SINGLE_IRB] = true
      when "--irb_debug"
        @CONF[:DEBUG_LEVEL] = ARGV.shift.to_i
      when "-v", "--version"
        print IRB.version, "\n"
        exit 0
      when "-h", "--help"
        require "irb/help"
        IRB.print_usage
        exit 0
      when /^-/
        IRB.fail UnrecognizedSwitch, opt
      else
        @CONF[:SCRIPT] = opt
        $0 = opt
        break
      end
    end
    if RUBY_VERSION >= FEATURE_IOPT_CHANGE_VERSION
      load_path.collect! do |path|
        /\A\.\// =~ path ? path : File.expand_path(path)
      end
    end
    $LOAD_PATH.unshift(*load_path)
  end


run_config (IRB)

# File lib/irb/init.rb, line 204
  def IRB.run_config
    if @CONF[:RC]
      begin
        load rc_file
      rescue LoadError, Errno::ENOENT
      rescue
        print "load error: #{rc_file}\n"
        print $!.class, ": ", $!, "\n"
        for err in $@[0, $@.size - 2]
          print "\t", err, "\n"
        end
      end
    end
  end


rc_file (IRB)

# File lib/irb/init.rb, line 220
  def IRB.rc_file(ext = IRBRC_EXT)
    if !@CONF[:RC_NAME_GENERATOR]
      rc_file_generators do |rcgen|
        @CONF[:RC_NAME_GENERATOR] ||= rcgen
        if File.exist?(rcgen.call(IRBRC_EXT))
          @CONF[:RC_NAME_GENERATOR] = rcgen
          break
        end
      end
    end
    @CONF[:RC_NAME_GENERATOR].call ext
  end


rc_file_generators (IRB)

# File lib/irb/init.rb, line 234
  def IRB.rc_file_generators
    if irbrc = ENV["IRBRC"]
      yield proc{|rc|  rc == "rc" ? irbrc : irbrc+rc}
    end
    if home = ENV["HOME"]
      yield proc{|rc| home+"/.irb#{rc}"}
    end
    home = Dir.pwd
    yield proc{|rc| home+"/.irb#{rc}"}
    yield proc{|rc| home+"/irb#{rc.sub(/\A_?/, '.')}"}
    yield proc{|rc| home+"/_irb#{rc}"}
    yield proc{|rc| home+"/$irb#{rc}"}
  end


load_modules (IRB)

# File lib/irb/init.rb, line 249
  def IRB.load_modules
    for m in @CONF[:LOAD_MODULES]
      begin
        require m
      rescue
        print $@[0], ":", $!.class, ": ", $!, "\n"
      end
    end
  end


print_usage (IRB)

# File lib/irb/help.rb, line 14
  def IRB.print_usage
    lc = IRB.conf[:LC_MESSAGES]
    path = lc.find("irb/help-message")
    space_line = false
    File.foreach(path) do
      |l|
      if /^\s*$/ =~ l
        lc.puts l unless space_line
        space_line = true
        next
      end
      space_line = false

      l.sub!(/#.*$/, "")
      next if /^\s*$/ =~ l
      lc.puts l
    end
  end


delete_caller (IRB)

# File lib/irb/workspace.rb, line 105
    def IRB.delete_caller
    end


conf (IRB)

# File lib/irb.rb, line 33
  def IRB.conf
    @CONF
  end


version (IRB)

# File lib/irb.rb, line 38
  def IRB.version
    if v = @CONF[:VERSION] then return v end

    require "irb/version"
    rv = @RELEASE_VERSION.sub(/\.0/, "")
    @CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE)
  end


CurrentContext (IRB)

# File lib/irb.rb, line 46
  def IRB.CurrentContext
    IRB.conf[:MAIN_CONTEXT]
  end


start (IRB)

# File lib/irb.rb, line 51
  def IRB.start(ap_path = nil)
    $0 = File::basename(ap_path, ".rb") if ap_path

    IRB.setup(ap_path)

    if @CONF[:SCRIPT]
      irb = Irb.new(nil, @CONF[:SCRIPT])
    else
      irb = Irb.new
    end

    @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
    @CONF[:MAIN_CONTEXT] = irb.context

    trap("SIGINT") do
      irb.signal_handle
    end

    catch(:IRB_EXIT) do
      irb.eval_input
    end
#    print "\n"
  end


irb_exit (IRB)

# File lib/irb.rb, line 75
  def IRB.irb_exit(irb, ret)
    throw :IRB_EXIT, ret
  end


irb_abort (IRB)

# File lib/irb.rb, line 79
  def IRB.irb_abort(irb, exception = Abort)
    if defined? Thread
      irb.context.thread.raise exception, "abort then interrupt!!"
    else
      raise exception, "abort then interrupt!!"
    end
  end


nodeName (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1762
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1770
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1778
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1786
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1794
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1802
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1810
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1818
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1826
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1834
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1842
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1850
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1858
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1866
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1874
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1882
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1890
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1898
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1906
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1914
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1922
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1930
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


name (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1938
  def name()
    ret = _getproperty(118, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


value (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1946
  def value()
    ret = _getproperty(120, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1954
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1962
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1970
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1978
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


value= (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1986
  def value=(arg0)
    ret = _setproperty(120, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 1996
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2006
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2015
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2024
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2031
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2039
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2048
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2057
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2066
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMAttribute)

# File ext/win32ole/sample/xml.rb, line 2076
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3537
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3545
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3553
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3561
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3569
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3577
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3585
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3593
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3601
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3609
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3617
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3625
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3633
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3641
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3649
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3657
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3665
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3673
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3681
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3689
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3697
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3705
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3713
  def data()
    ret = _getproperty(109, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


length (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3721
  def length()
    ret = _getproperty(110, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3729
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3737
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3745
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3753
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data= (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3761
  def data=(arg0)
    ret = _setproperty(109, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3771
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3781
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3790
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3799
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3806
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3814
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3823
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3832
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3841
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3851
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


substringData (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3861
  def substringData(arg0, arg1)
    ret = _invoke(111, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendData (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3870
  def appendData(arg0)
    ret = _invoke(112, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertData (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3880
  def insertData(arg0, arg1)
    ret = _invoke(113, [arg0, arg1], [VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


deleteData (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3890
  def deleteData(arg0, arg1)
    ret = _invoke(114, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceData (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3901
  def replaceData(arg0, arg1, arg2)
    ret = _invoke(115, [arg0, arg1, arg2], [VT_I4, VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


splitText (IXMLDOMCDATASection)

# File ext/win32ole/sample/xml.rb, line 3910
  def splitText(arg0)
    ret = _invoke(123, [arg0], [VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2781
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2789
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2797
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2805
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2813
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2821
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2829
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2837
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2845
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2853
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2861
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2869
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2877
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2885
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2893
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2901
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2909
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2917
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2925
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2933
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2941
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2949
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2957
  def data()
    ret = _getproperty(109, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


length (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2965
  def length()
    ret = _getproperty(110, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2973
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2981
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2989
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 2997
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data= (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3005
  def data=(arg0)
    ret = _setproperty(109, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3015
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3025
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3034
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3043
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3050
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3058
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3067
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3076
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3085
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3095
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


substringData (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3105
  def substringData(arg0, arg1)
    ret = _invoke(111, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendData (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3114
  def appendData(arg0)
    ret = _invoke(112, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertData (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3124
  def insertData(arg0, arg1)
    ret = _invoke(113, [arg0, arg1], [VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


deleteData (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3134
  def deleteData(arg0, arg1)
    ret = _invoke(114, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceData (IXMLDOMCharacterData)

# File ext/win32ole/sample/xml.rb, line 3145
  def replaceData(arg0, arg1, arg2)
    ret = _invoke(115, [arg0, arg1, arg2], [VT_I4, VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3159
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3167
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3175
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3183
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3191
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3199
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3207
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3215
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3223
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3231
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3239
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3247
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3255
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3263
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3271
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3279
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3287
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3295
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3303
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3311
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3319
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3327
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3335
  def data()
    ret = _getproperty(109, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


length (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3343
  def length()
    ret = _getproperty(110, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3351
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3359
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3367
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3375
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data= (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3383
  def data=(arg0)
    ret = _setproperty(109, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3393
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3403
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3412
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3421
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3428
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3436
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3445
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3454
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3463
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3473
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


substringData (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3483
  def substringData(arg0, arg1)
    ret = _invoke(111, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendData (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3492
  def appendData(arg0)
    ret = _invoke(112, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertData (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3502
  def insertData(arg0, arg1)
    ret = _invoke(113, [arg0, arg1], [VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


deleteData (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3512
  def deleteData(arg0, arg1)
    ret = _invoke(114, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceData (IXMLDOMComment)

# File ext/win32ole/sample/xml.rb, line 3523
  def replaceData(arg0, arg1, arg2)
    ret = _invoke(115, [arg0, arg1, arg2], [VT_I4, VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 474
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 482
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 490
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 498
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 506
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 514
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 522
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 530
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 538
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 546
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 554
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 562
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 570
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 578
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 586
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 594
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 602
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 610
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 618
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 626
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 634
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 642
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


doctype (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 650
  def doctype()
    ret = _getproperty(38, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


implementation (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 658
  def implementation()
    ret = _getproperty(39, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


documentElement (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 666
  def documentElement()
    ret = _getproperty(40, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


readyState (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 674
  def readyState()
    ret = _getproperty(-525, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parseError (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 682
  def parseError()
    ret = _getproperty(59, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


url (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 690
  def url()
    ret = _getproperty(60, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 698
  def async()
    ret = _getproperty(61, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


validateOnParse (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 706
  def validateOnParse()
    ret = _getproperty(65, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


resolveExternals (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 714
  def resolveExternals()
    ret = _getproperty(66, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


preserveWhiteSpace (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 722
  def preserveWhiteSpace()
    ret = _getproperty(67, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 730
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 738
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 746
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 754
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 762
  def async=(arg0)
    ret = _setproperty(61, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


validateOnParse= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 770
  def validateOnParse=(arg0)
    ret = _setproperty(65, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


resolveExternals= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 778
  def resolveExternals=(arg0)
    ret = _setproperty(66, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


preserveWhiteSpace= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 786
  def preserveWhiteSpace=(arg0)
    ret = _setproperty(67, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 794
  def onreadystatechange=(arg0)
    ret = _setproperty(68, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ondataavailable= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 802
  def ondataavailable=(arg0)
    ret = _setproperty(69, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ontransformnode= (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 810
  def ontransformnode=(arg0)
    ret = _setproperty(70, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 820
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 830
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 839
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 848
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 855
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 863
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 872
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 881
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 890
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 900
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createElement (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 909
  def createElement(arg0)
    ret = _invoke(41, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createDocumentFragment (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 917
  def createDocumentFragment()
    ret = _invoke(42, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createTextNode (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 926
  def createTextNode(arg0)
    ret = _invoke(43, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createComment (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 935
  def createComment(arg0)
    ret = _invoke(44, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createCDATASection (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 944
  def createCDATASection(arg0)
    ret = _invoke(45, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createProcessingInstruction (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 954
  def createProcessingInstruction(arg0, arg1)
    ret = _invoke(46, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createAttribute (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 963
  def createAttribute(arg0)
    ret = _invoke(47, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createEntityReference (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 972
  def createEntityReference(arg0)
    ret = _invoke(49, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getElementsByTagName (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 981
  def getElementsByTagName(arg0)
    ret = _invoke(50, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createNode (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 992
  def createNode(arg0, arg1, arg2)
    ret = _invoke(54, [arg0, arg1, arg2], [VT_VARIANT, VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeFromID (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 1001
  def nodeFromID(arg0)
    ret = _invoke(56, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


load (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 1010
  def load(arg0)
    ret = _invoke(58, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


abort (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 1018
  def abort()
    ret = _invoke(62, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


loadXML (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 1027
  def loadXML(arg0)
    ret = _invoke(63, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


save (IXMLDOMDocument)

# File ext/win32ole/sample/xml.rb, line 1036
  def save(arg0)
    ret = _invoke(64, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2090
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2098
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2106
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2114
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2122
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2130
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2138
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2146
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2154
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2162
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2170
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2178
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2186
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2194
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2202
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2210
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2218
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2226
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2234
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2242
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2250
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2258
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2266
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2274
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2282
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2290
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2300
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2310
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2319
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2328
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2335
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2343
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2352
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2361
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2370
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMDocumentFragment)

# File ext/win32ole/sample/xml.rb, line 2380
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1050
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1058
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1066
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1074
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1082
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1090
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1098
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1106
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1114
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1122
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1130
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1138
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1146
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1154
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1162
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1170
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1178
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1186
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1194
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1202
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1210
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1218
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


name (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1226
  def name()
    ret = _getproperty(131, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


entities (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1234
  def entities()
    ret = _getproperty(132, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


notations (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1242
  def notations()
    ret = _getproperty(133, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1250
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1258
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1266
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1274
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1284
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1294
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1303
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1312
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1319
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1327
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1336
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1345
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1354
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMDocumentType)

# File ext/win32ole/sample/xml.rb, line 1364
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1378
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1386
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1394
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1402
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1410
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1418
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1426
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1434
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1442
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1450
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1458
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1466
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1474
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1482
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1490
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1498
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1506
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1514
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1522
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1530
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1538
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1546
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


tagName (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1554
  def tagName()
    ret = _getproperty(97, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1562
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1570
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1578
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1586
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1596
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1606
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1615
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1624
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1631
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1639
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1648
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1657
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1666
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1676
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getAttribute (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1685
  def getAttribute(arg0)
    ret = _invoke(99, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


setAttribute (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1695
  def setAttribute(arg0, arg1)
    ret = _invoke(100, [arg0, arg1], [VT_BSTR, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeAttribute (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1704
  def removeAttribute(arg0)
    ret = _invoke(101, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getAttributeNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1713
  def getAttributeNode(arg0)
    ret = _invoke(102, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


setAttributeNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1722
  def setAttributeNode(arg0)
    ret = _invoke(103, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeAttributeNode (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1731
  def removeAttributeNode(arg0)
    ret = _invoke(104, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getElementsByTagName (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1740
  def getElementsByTagName(arg0)
    ret = _invoke(105, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


normalize (IXMLDOMElement)

# File ext/win32ole/sample/xml.rb, line 1748
  def normalize()
    ret = _invoke(106, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4938
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4946
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4954
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4962
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4970
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4978
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4986
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 4994
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5002
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5010
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5018
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5026
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5034
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5042
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5050
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5058
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5066
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5074
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5082
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5090
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5098
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5106
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


publicId (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5114
  def publicId()
    ret = _getproperty(140, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


systemId (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5122
  def systemId()
    ret = _getproperty(141, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


notationName (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5130
  def notationName()
    ret = _getproperty(142, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5138
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5146
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5154
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5162
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5172
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5182
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5191
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5200
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5207
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5215
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5224
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5233
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5242
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMEntity)

# File ext/win32ole/sample/xml.rb, line 5252
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4252
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4260
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4268
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4276
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4284
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4292
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4300
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4308
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4316
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4324
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4332
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4340
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4348
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4356
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4364
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4372
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4380
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4388
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4396
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4404
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4412
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4420
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4428
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4436
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4444
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4452
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4462
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4472
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4481
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4490
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4497
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4505
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4514
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4523
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4532
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMEntityReference)

# File ext/win32ole/sample/xml.rb, line 4542
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasFeature (IXMLDOMImplementation)

# File ext/win32ole/sample/xml.rb, line 16
  def hasFeature(arg0, arg1)
    ret = _invoke(145, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


length (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 390
  def length()
    ret = _getproperty(74, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


item (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 399
  def item
    OLEProperty.new(self, 0, [VT_I4], [VT_I4, VT_BYREF|VT_DISPATCH])
  end


getNamedItem (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 406
  def getNamedItem(arg0)
    ret = _invoke(83, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


setNamedItem (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 415
  def setNamedItem(arg0)
    ret = _invoke(84, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeNamedItem (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 424
  def removeNamedItem(arg0)
    ret = _invoke(85, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getQualifiedItem (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 434
  def getQualifiedItem(arg0, arg1)
    ret = _invoke(87, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeQualifiedItem (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 444
  def removeQualifiedItem(arg0, arg1)
    ret = _invoke(88, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextNode (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 452
  def nextNode()
    ret = _invoke(89, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


reset (IXMLDOMNamedNodeMap)

# File ext/win32ole/sample/xml.rb, line 460
  def reset()
    ret = _invoke(90, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 30
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 38
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 46
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 54
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 62
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 70
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 78
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 86
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 94
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 102
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 110
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 118
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 126
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 134
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 142
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 150
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 158
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 166
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 174
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 182
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 190
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 198
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 206
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 214
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 222
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 230
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 240
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 250
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 259
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 268
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 275
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 283
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 292
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 301
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 310
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMNode)

# File ext/win32ole/sample/xml.rb, line 320
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


length (IXMLDOMNodeList)

# File ext/win32ole/sample/xml.rb, line 353
  def length()
    ret = _getproperty(74, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


item (IXMLDOMNodeList)

# File ext/win32ole/sample/xml.rb, line 362
  def item
    OLEProperty.new(self, 0, [VT_I4], [VT_I4, VT_BYREF|VT_DISPATCH])
  end


nextNode (IXMLDOMNodeList)

# File ext/win32ole/sample/xml.rb, line 368
  def nextNode()
    ret = _invoke(76, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


reset (IXMLDOMNodeList)

# File ext/win32ole/sample/xml.rb, line 376
  def reset()
    ret = _invoke(77, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4618
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4626
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4634
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4642
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4650
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4658
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4666
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4674
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4682
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4690
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4698
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4706
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4714
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4722
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4730
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4738
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4746
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4754
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4762
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4770
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4778
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4786
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


publicId (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4794
  def publicId()
    ret = _getproperty(136, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


systemId (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4802
  def systemId()
    ret = _getproperty(137, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4810
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4818
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4826
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4834
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4844
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4854
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4863
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4872
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4879
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4887
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4896
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4905
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4914
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMNotation)

# File ext/win32ole/sample/xml.rb, line 4924
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


errorCode (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4556
  def errorCode()
    ret = _getproperty(0, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


url (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4564
  def url()
    ret = _getproperty(179, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


reason (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4572
  def reason()
    ret = _getproperty(180, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


srcText (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4580
  def srcText()
    ret = _getproperty(181, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


line (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4588
  def line()
    ret = _getproperty(182, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


linepos (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4596
  def linepos()
    ret = _getproperty(183, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


filepos (IXMLDOMParseError)

# File ext/win32ole/sample/xml.rb, line 4604
  def filepos()
    ret = _getproperty(184, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3924
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3932
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3940
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3948
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3956
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3964
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3972
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3980
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3988
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 3996
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4004
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4012
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4020
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4028
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4036
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4044
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4052
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4060
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4068
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4076
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4084
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4092
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


target (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4100
  def target()
    ret = _getproperty(127, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4108
  def data()
    ret = _getproperty(128, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4116
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4124
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4132
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4140
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data= (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4148
  def data=(arg0)
    ret = _setproperty(128, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4158
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4168
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4177
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4186
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4193
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4201
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4210
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4219
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4228
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMProcessingInstruction)

# File ext/win32ole/sample/xml.rb, line 4238
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2394
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2402
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2410
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2418
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2426
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2434
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2442
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2450
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2458
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2466
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2474
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2482
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2490
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2498
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2506
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2514
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2522
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2530
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2538
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2546
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2554
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2562
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2570
  def data()
    ret = _getproperty(109, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


length (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2578
  def length()
    ret = _getproperty(110, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2586
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2594
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2602
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2610
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


data= (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2618
  def data=(arg0)
    ret = _setproperty(109, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2628
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2638
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2647
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2656
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2663
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2671
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2680
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2689
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2698
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2708
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


substringData (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2718
  def substringData(arg0, arg1)
    ret = _invoke(111, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendData (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2727
  def appendData(arg0)
    ret = _invoke(112, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertData (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2737
  def insertData(arg0, arg1)
    ret = _invoke(113, [arg0, arg1], [VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


deleteData (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2747
  def deleteData(arg0, arg1)
    ret = _invoke(114, [arg0, arg1], [VT_I4, VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceData (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2758
  def replaceData(arg0, arg1, arg2)
    ret = _invoke(115, [arg0, arg1, arg2], [VT_I4, VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


splitText (IXMLDOMText)

# File ext/win32ole/sample/xml.rb, line 2767
  def splitText(arg0)
    ret = _invoke(123, [arg0], [VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


status (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6863
  def status()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


statusText (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6871
  def statusText()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseXML (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6879
  def responseXML()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseText (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6887
  def responseText()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseBody (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6895
  def responseBody()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseStream (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6903
  def responseStream()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


readyState (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6911
  def readyState()
    ret = _getproperty(13, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange= (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6919
  def onreadystatechange=(arg0)
    ret = _setproperty(14, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


open (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6932
  def open(arg0, arg1, arg2=nil, arg3=nil, arg4=nil)
    ret = _invoke(1, [arg0, arg1, arg2, arg3, arg4], [VT_BSTR, VT_BSTR, VT_VARIANT, VT_VARIANT, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


setRequestHeader (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6942
  def setRequestHeader(arg0, arg1)
    ret = _invoke(2, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getResponseHeader (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6951
  def getResponseHeader(arg0)
    ret = _invoke(3, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getAllResponseHeaders (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6959
  def getAllResponseHeaders()
    ret = _invoke(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


send (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6968
  def send(arg0=nil)
    ret = _invoke(5, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


abort (IXMLHttpRequest)

# File ext/win32ole/sample/xml.rb, line 6976
  def abort()
    ret = _invoke(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeName (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5266
  def nodeName()
    ret = _getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5274
  def nodeValue()
    ret = _getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5282
  def nodeType()
    ret = _getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5290
  def parentNode()
    ret = _getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5298
  def childNodes()
    ret = _getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5306
  def firstChild()
    ret = _getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5314
  def lastChild()
    ret = _getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5322
  def previousSibling()
    ret = _getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5330
  def nextSibling()
    ret = _getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5338
  def attributes()
    ret = _getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5346
  def ownerDocument()
    ret = _getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5354
  def nodeTypeString()
    ret = _getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5362
  def text()
    ret = _getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5370
  def specified()
    ret = _getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5378
  def definition()
    ret = _getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5386
  def nodeTypedValue()
    ret = _getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5394
  def dataType()
    ret = _getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5402
  def xml()
    ret = _getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5410
  def parsed()
    ret = _getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5418
  def namespaceURI()
    ret = _getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5426
  def prefix()
    ret = _getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5434
  def baseName()
    ret = _getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5442
  def nodeValue=(arg0)
    ret = _setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5450
  def text=(arg0)
    ret = _setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5458
  def nodeTypedValue=(arg0)
    ret = _setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5466
  def dataType=(arg0)
    ret = _setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5476
  def insertBefore(arg0, arg1)
    ret = _invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5486
  def replaceChild(arg0, arg1)
    ret = _invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5495
  def removeChild(arg0)
    ret = _invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5504
  def appendChild(arg0)
    ret = _invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5511
  def hasChildNodes()
    ret = _invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5519
  def cloneNode(arg0)
    ret = _invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5528
  def transformNode(arg0)
    ret = _invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5537
  def selectNodes(arg0)
    ret = _invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5546
  def selectSingleNode(arg0)
    ret = _invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5556
  def transformNodeToObject(arg0, arg1)
    ret = _invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


uniqueID (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5564
  def uniqueID(arg0)
    ret = _invoke(187, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


depth (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5572
  def depth(arg0)
    ret = _invoke(188, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNumber (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5580
  def childNumber(arg0)
    ret = _invoke(189, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ancestorChildNumber (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5589
  def ancestorChildNumber(arg0, arg1)
    ret = _invoke(190, [arg0, arg1], [VT_BSTR, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


absoluteChildNumber (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5597
  def absoluteChildNumber(arg0)
    ret = _invoke(191, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


formatIndex (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5606
  def formatIndex(arg0, arg1)
    ret = _invoke(192, [arg0, arg1], [VT_I4, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


formatNumber (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5615
  def formatNumber(arg0, arg1)
    ret = _invoke(193, [arg0, arg1], [VT_R8, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


formatDate (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5625
  def formatDate(arg0, arg1, arg2=nil)
    ret = _invoke(194, [arg0, arg1, arg2], [VT_VARIANT, VT_BSTR, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


formatTime (IXTLRuntime)

# File ext/win32ole/sample/xml.rb, line 5635
  def formatTime(arg0, arg1, arg2=nil)
    ret = _invoke(195, [arg0, arg1, arg2], [VT_VARIANT, VT_BSTR, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


kconv (Kconv)

# File ext/nkf/lib/kconv.rb, line 95
  def kconv(str, out_code, in_code = AUTO)
    opt = '-'
    case in_code
    when ::NKF::JIS
      opt << 'J'
    when ::NKF::EUC
      opt << 'E'
    when ::NKF::SJIS
      opt << 'S'
    when ::NKF::UTF8
      opt << 'W'
    when ::NKF::UTF16
      opt << 'W16'
    end

    case out_code
    when ::NKF::JIS
      opt << 'j'
    when ::NKF::EUC
      opt << 'e'
    when ::NKF::SJIS
      opt << 's'
    when ::NKF::UTF8
      opt << 'w'
    when ::NKF::UTF16
      opt << 'w16'
    when ::NKF::NOCONV
      return str
    end

    opt = '' if opt == '-'

    ::NKF::nkf(opt, str)
  end


tojis (Kconv)

# File ext/nkf/lib/kconv.rb, line 144
  def tojis(str)
    ::NKF::nkf('-jm', str)
  end


toeuc (Kconv)

# File ext/nkf/lib/kconv.rb, line 158
  def toeuc(str)
    ::NKF::nkf('-em', str)
  end


tosjis (Kconv)

# File ext/nkf/lib/kconv.rb, line 172
  def tosjis(str)
    ::NKF::nkf('-sm', str)
  end


toutf8 (Kconv)

# File ext/nkf/lib/kconv.rb, line 186
  def toutf8(str)
    ::NKF::nkf('-wm', str)
  end


toutf16 (Kconv)

# File ext/nkf/lib/kconv.rb, line 200
  def toutf16(str)
    ::NKF::nkf('-w16m', str)
  end


guess (Kconv)

# File ext/nkf/lib/kconv.rb, line 213
  def guess(str)
    ::NKF::guess(str)
  end


guess_old (Kconv)

# File ext/nkf/lib/kconv.rb, line 222
  def guess_old(str)
    ::NKF::guess1(str)
  end


iseuc (Kconv)

# File ext/nkf/lib/kconv.rb, line 237
  def iseuc(str)
    RegexpEucjp.match( str )
  end


issjis (Kconv)

# File ext/nkf/lib/kconv.rb, line 248
  def issjis(str)
    RegexpShiftjis.match( str )
  end


isutf8 (Kconv)

# File ext/nkf/lib/kconv.rb, line 259
  def isutf8(str)
    RegexpUtf8.match( str )
  end


eval (Kernel)

/*
 *  call-seq:
 *     eval(string [, binding [, filename [,lineno]]])  => obj
 *
 *  Evaluates the Ruby expression(s) in <em>string</em>. If
 *  <em>binding</em> is given, the evaluation is performed in its
 *  context. The binding may be a <code>Binding</code> object or a
 *  <code>Proc</code> object. If the optional <em>filename</em> and
 *  <em>lineno</em> parameters are present, they will be used when
 *  reporting syntax errors.
 *
 *     def getBinding(str)
 *       return binding
 *     end
 *     str = "hello"
 *     eval "str + ' Fred'"                      #=> "hello Fred"
 *     eval "str + ' Fred'", getBinding("bye")   #=> "bye Fred"
 */

static VALUE
rb_f_eval(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE src, scope, vfile, vline;
    char *file = "(eval)";
    int line = 1;

    rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
    if (ruby_safe_level >= 4) {
        StringValue(src);
        if (!NIL_P(scope) && !OBJ_TAINTED(scope)) {
            rb_raise(rb_eSecurityError, "Insecure: can't modify trusted binding");
        }
    }
    else {
        SafeStringValue(src);
    }
    if (argc >= 3) {
        StringValue(vfile);
    }
    if (argc >= 4) {
        line = NUM2INT(vline);
    }

    if (!NIL_P(vfile)) file = RSTRING(vfile)->ptr;
    if (NIL_P(scope) && ruby_frame->prev) {
        struct FRAME *prev;
        VALUE val;

        prev = ruby_frame;
        PUSH_FRAME();
        *ruby_frame = *prev->prev;
        ruby_frame->prev = prev;
        val = eval(self, src, scope, file, line);
        POP_FRAME();

        return val;
    }
    return eval(self, src, scope, file, line);
}


iterator? (Kernel)

/*
 *  call-seq:
 *     block_given?   => true or false
 *     iterator?      => true or false
 *
 *  Returns <code>true</code> if <code>yield</code> would execute a
 *  block in the current context. The <code>iterator?</code> form
 *  is mildly deprecated.
 *
 *     def try
 *       if block_given?
 *         yield
 *       else
 *         "no block"
 *       end
 *     end
 *     try                  #=> "no block"
 *     try { "hello" }      #=> "hello"
 *     try do "hello" end   #=> "hello"
 */

static VALUE
rb_f_block_given_p()
{
    if (ruby_frame->prev && ruby_frame->prev->iter == ITER_CUR && ruby_block)
        return Qtrue;
    return Qfalse;
}


block_given? (Kernel)

/*
 *  call-seq:
 *     block_given?   => true or false
 *     iterator?      => true or false
 *
 *  Returns <code>true</code> if <code>yield</code> would execute a
 *  block in the current context. The <code>iterator?</code> form
 *  is mildly deprecated.
 *
 *     def try
 *       if block_given?
 *         yield
 *       else
 *         "no block"
 *       end
 *     end
 *     try                  #=> "no block"
 *     try { "hello" }      #=> "hello"
 *     try do "hello" end   #=> "hello"
 */

static VALUE
rb_f_block_given_p()
{
    if (ruby_frame->prev && ruby_frame->prev->iter == ITER_CUR && ruby_block)
        return Qtrue;
    return Qfalse;
}


method_missing (Kernel)

/*
 *  call-seq:
 *     obj.method_missing(symbol [, *args] )   => result
 *
 *  Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
 *  <i>symbol</i> is the symbol for the method called, and <i>args</i>
 *  are any arguments that were passed to it. By default, the interpreter
 *  raises an error when this method is called. However, it is possible
 *  to override the method to provide more dynamic behavior.
 *  The example below creates
 *  a class <code>Roman</code>, which responds to methods with names
 *  consisting of roman numerals, returning the corresponding integer
 *  values.
 *
 *     class Roman
 *       def romanToInt(str)
 *         # ...
 *       end
 *       def method_missing(methId)
 *         str = methId.id2name
 *         romanToInt(str)
 *       end
 *     end
 *
 *     r = Roman.new
 *     r.iv      #=> 4
 *     r.xxiii   #=> 23
 *     r.mm      #=> 2000
 */

static VALUE
rb_method_missing(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    ID id;
    VALUE exc = rb_eNoMethodError;
    char *format = 0;
    NODE *cnode = ruby_current_node;

    if (argc == 0 || !SYMBOL_P(argv[0])) {
        rb_raise(rb_eArgError, "no id given");
    }

    stack_check();

    id = SYM2ID(argv[0]);

    if (last_call_status & CSTAT_PRIV) {
        format = "private method `%s' called for %s";
    }
    else if (last_call_status & CSTAT_PROT) {
        format = "protected method `%s' called for %s";
    }
    else if (last_call_status & CSTAT_VCALL) {
        format = "undefined local variable or method `%s' for %s";
        exc = rb_eNameError;
    }
    else if (last_call_status & CSTAT_SUPER) {
        format = "super: no superclass method `%s'";
    }
    if (!format) {
        format = "undefined method `%s' for %s";
    }

    ruby_current_node = cnode;
    {
        int n = 0;
        VALUE args[3];

        args[n++] = rb_funcall(rb_const_get(exc, rb_intern("message")), '!',
                               3, rb_str_new2(format), obj, argv[0]);
        args[n++] = argv[0];
        if (exc == rb_eNoMethodError) {
            args[n++] = rb_ary_new4(argc-1, argv+1);
        }
        exc = rb_class_new_instance(n, args, exc);
        ruby_frame = ruby_frame->prev; /* pop frame for "method_missing" */
        rb_exc_raise(exc);
    }

    return Qnil;                /* not reached */
}


loop (Kernel)

/*
 *  call-seq:
 *     loop {|| block }
 *
 *  Repeatedly executes the block.
 *
 *     loop do
 *       print "Input: "
 *       line = gets
 *       break if !line or line =~ /^qQ/
 *       # ...
 *     end
 */

static VALUE
rb_f_loop()
{
    for (;;) {
        rb_yield_0(Qundef, 0, 0, 0, Qfalse);
        CHECK_INTS;
    }
    return Qnil;                /* dummy */
}


raise (Kernel)

/*
 *  call-seq:
 *     raise
 *     raise(string)
 *     raise(exception [, string [, array]])
 *     fail
 *     fail(string)
 *     fail(exception [, string [, array]])
 *
 *  With no arguments, raises the exception in <code>$!</code> or raises
 *  a <code>RuntimeError</code> if <code>$!</code> is +nil+.
 *  With a single +String+ argument, raises a
 *  +RuntimeError+ with the string as a message. Otherwise,
 *  the first parameter should be the name of an +Exception+
 *  class (or an object that returns an +Exception+ object when sent
 *  an +exception+ message). The optional second parameter sets the
 *  message associated with the exception, and the third parameter is an
 *  array of callback information. Exceptions are caught by the
 *  +rescue+ clause of <code>begin...end</code> blocks.
 *
 *     raise "Failed to create socket"
 *     raise ArgumentError, "No parameters", caller
 */

static VALUE
rb_f_raise(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_raise_jump(rb_make_exception(argc, argv));
    return Qnil;                /* not reached */
}


fail (Kernel)

/*
 *  call-seq:
 *     raise
 *     raise(string)
 *     raise(exception [, string [, array]])
 *     fail
 *     fail(string)
 *     fail(exception [, string [, array]])
 *
 *  With no arguments, raises the exception in <code>$!</code> or raises
 *  a <code>RuntimeError</code> if <code>$!</code> is +nil+.
 *  With a single +String+ argument, raises a
 *  +RuntimeError+ with the string as a message. Otherwise,
 *  the first parameter should be the name of an +Exception+
 *  class (or an object that returns an +Exception+ object when sent
 *  an +exception+ message). The optional second parameter sets the
 *  message associated with the exception, and the third parameter is an
 *  array of callback information. Exceptions are caught by the
 *  +rescue+ clause of <code>begin...end</code> blocks.
 *
 *     raise "Failed to create socket"
 *     raise ArgumentError, "No parameters", caller
 */

static VALUE
rb_f_raise(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_raise_jump(rb_make_exception(argc, argv));
    return Qnil;                /* not reached */
}


caller (Kernel)

/*
 *  call-seq:
 *     caller(start=1)    => array
 *
 *  Returns the current execution stack---an array containing strings in
 *  the form ``<em>file:line</em>'' or ``<em>file:line: in
 *  `method'</em>''. The optional _start_ parameter
 *  determines the number of initial stack entries to omit from the
 *  result.
 *
 *     def a(skip)
 *       caller(skip)
 *     end
 *     def b(skip)
 *       a(skip)
 *     end
 *     def c(skip)
 *       b(skip)
 *     end
 *     c(0)   #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
 *     c(1)   #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
 *     c(2)   #=> ["prog:8:in `c'", "prog:12"]
 *     c(3)   #=> ["prog:13"]
 */

static VALUE
rb_f_caller(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE level;
    int lev;

    rb_scan_args(argc, argv, "01", &level);

    if (NIL_P(level)) lev = 1;
    else lev = NUM2INT(level);
    if (lev < 0) rb_raise(rb_eArgError, "negative level (%d)", lev);

    return backtrace(lev);
}


exit (Kernel)

/*
 *  call-seq:
 *     exit(integer=0)
 *     Kernel::exit(integer=0)
 *     Process::exit(integer=0)
 *
 *  Initiates the termination of the Ruby script by raising the
 *  <code>SystemExit</code> exception. This exception may be caught. The
 *  optional parameter is used to return a status code to the invoking
 *  environment.
 *
 *     begin
 *       exit
 *       puts "never get here"
 *     rescue SystemExit
 *       puts "rescued a SystemExit exception"
 *     end
 *     puts "after begin block"
 *
 *  <em>produces:</em>
 *
 *     rescued a SystemExit exception
 *     after begin block
 *
 *  Just prior to termination, Ruby executes any <code>at_exit</code> functions
 *  (see Kernel::at_exit) and runs any object finalizers (see
 *  ObjectSpace::define_finalizer).
 *
 *     at_exit { puts "at_exit function" }
 *     ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
 *     exit
 *
 *  <em>produces:</em>
 *
 *     at_exit function
 *     in finalizer
 */

VALUE
rb_f_exit(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE status;
    int istatus;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &status) == 1) {
        switch (status) {
          case Qtrue:
            istatus = EXIT_SUCCESS;
            break;
          case Qfalse:
            istatus = EXIT_FAILURE;
            break;
          default:
            istatus = NUM2INT(status);
#if EXIT_SUCCESS != 0
            if (istatus == 0) istatus = EXIT_SUCCESS;
#endif
            break;
        }
    }
    else {
        istatus = EXIT_SUCCESS;
    }
    rb_exit(istatus);
    return Qnil;                /* not reached */
}


abort (Kernel)

/*
 *  call-seq:
 *     abort
 *     Kernel::abort
 *     Process::abort
 *
 *  Terminate execution immediately, effectively by calling
 *  <code>Kernel.exit(1)</code>. If _msg_ is given, it is written
 *  to STDERR prior to terminating.
 */

VALUE
rb_f_abort(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_secure(4);
    if (argc == 0) {
        if (!NIL_P(ruby_errinfo)) {
            error_print();
        }
        rb_exit(EXIT_FAILURE);
    }
    else {
        VALUE mesg;

        rb_scan_args(argc, argv, "1", &mesg);
        StringValue(mesg);
        rb_io_puts(1, &mesg, rb_stderr);
        terminate_process(EXIT_FAILURE, mesg);
    }
    return Qnil;                /* not reached */
}


at_exit (Kernel)

/*
 *  call-seq:
 *     at_exit { block } -> proc
 *
 *  Converts _block_ to a +Proc+ object (and therefore
 *  binds it at the point of call) and registers it for execution when
 *  the program exits. If multiple handlers are registered, they are
 *  executed in reverse order of registration.
 *
 *     def do_at_exit(str1)
 *       at_exit { print str1 }
 *     end
 *     at_exit { puts "cruel world" }
 *     do_at_exit("goodbye ")
 *     exit
 *
 *  <em>produces:</em>
 *
 *     goodbye cruel world
 */

static VALUE
rb_f_at_exit()
{
    VALUE proc;

    if (!rb_block_given_p()) {
        rb_raise(rb_eArgError, "called without a block");
    }
    proc = rb_block_proc();
    rb_set_end_proc(call_end_proc, proc);
    return proc;
}


catch (Kernel)

/*
 *  call-seq:
 *     catch(symbol) {| | block }  > obj
 *
 *  +catch+ executes its block. If a +throw+ is
 *  executed, Ruby searches up its stack for a +catch+ block
 *  with a tag corresponding to the +throw+'s
 *  _symbol_. If found, that block is terminated, and
 *  +catch+ returns the value given to +throw+. If
 *  +throw+ is not called, the block terminates normally, and
 *  the value of +catch+ is the value of the last expression
 *  evaluated. +catch+ expressions may be nested, and the
 *  +throw+ call need not be in lexical scope.
 *
 *     def routine(n)
 *       puts n
 *       throw :done if n <= 0
 *       routine(n-1)
 *     end
 *
 *
 *     catch(:done) { routine(3) }
 *
 *  <em>produces:</em>
 *
 *     3
 *     2
 *     1
 *     0
 */

static VALUE
rb_f_catch(dmy, tag)
    VALUE dmy, tag;
{
    int state;
    VALUE val = Qnil;           /* OK */

    tag = ID2SYM(rb_to_id(tag));
    PUSH_TAG(tag);
    if ((state = EXEC_TAG()) == 0) {
        val = rb_yield_0(tag, 0, 0, 0, Qfalse);
    }
    else if (state == TAG_THROW && tag == prot_tag->dst) {
        val = prot_tag->retval;
        state = 0;
    }
    POP_TAG();
    if (state) JUMP_TAG(state);

    return val;
}


throw (Kernel)

/*
 *  call-seq:
 *     throw(symbol [, obj])
 *
 *  Transfers control to the end of the active +catch+ block
 *  waiting for _symbol_. Raises +NameError+ if there
 *  is no +catch+ block for the symbol. The optional second
 *  parameter supplies a return value for the +catch+ block,
 *  which otherwise defaults to +nil+. For examples, see
 *  <code>Kernel::catch</code>.
 */

static VALUE
rb_f_throw(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE tag, value;
    struct tag *tt = prot_tag;

    rb_scan_args(argc, argv, "11", &tag, &value);
    tag = ID2SYM(rb_to_id(tag));

    while (tt) {
        if (tt->tag == tag) {
            tt->dst = tag;
            tt->retval = value;
            break;
        }
        if (tt->tag == PROT_THREAD) {
            rb_raise(rb_eThreadError, "uncaught throw `%s' in thread 0x%lx",
                     rb_id2name(SYM2ID(tag)),
                     curr_thread);
        }
        tt = tt->prev;
    }
    if (!tt) {
        rb_name_error(SYM2ID(tag), "uncaught throw `%s'", rb_id2name(SYM2ID(tag)));
    }
    rb_trap_restore_mask();
    JUMP_TAG(TAG_THROW);
#ifndef __GNUC__
    return Qnil;                /* not reached */
#endif
}


global_variables (Kernel)

/*
 *  call-seq:
 *     global_variables    => array
 *
 *  Returns an array of the names of global variables.
 *
 *     global_variables.grep /std/   #=> ["$stderr", "$stdout", "$stdin"]
 */

VALUE
rb_f_global_variables()
{
    VALUE ary = rb_ary_new();
    char buf[4];
    char *s = "&`'+123456789";

    st_foreach(rb_global_tbl, gvar_i, ary);
    if (!NIL_P(rb_backref_get())) {
    while (*s) {
        sprintf(buf, "$%c", *s++);
        rb_ary_push(ary, rb_str_new2(buf));
    }
    }
    return ary;
}


local_variables (Kernel)

/*
 *  call-seq:
 *     local_variables    => array
 *
 *  Returns the names of the current local variables.
 *
 *     fred = 1
 *     for i in 1..10
 *        # ...
 *     end
 *     local_variables   #=> ["fred", "i"]
 */

static VALUE
rb_f_local_variables()
{
    ID *tbl;
    int n, i;
    VALUE ary = rb_ary_new();
    struct RVarmap *vars;

    tbl = ruby_scope->local_tbl;
    if (tbl) {
        n = *tbl++;
        for (i=2; i<n; i++) {  /* skip first 2 ($_ and $~) */
            if (!rb_is_local_id(tbl[i])) continue; /* skip flip states */
            rb_ary_push(ary, rb_str_new2(rb_id2name(tbl[i])));
        }
    }

    vars = ruby_dyna_vars;
    while (vars) {
        if (vars->id && rb_is_local_id(vars->id)) { /* skip $_, $~ and flip states */
            rb_ary_push(ary, rb_str_new2(rb_id2name(vars->id)));
        }
        vars = vars->next;
    }

    return ary;
}


trace_var (Kernel)

/*
 *  call-seq:
 *     trace_var(symbol, cmd )             => nil
 *     trace_var(symbol) {|val| block }    => nil
 *
 *  Controls tracing of assignments to global variables. The parameter
 *  +symbol_ identifies the variable (as either a string name or a
 *  symbol identifier). _cmd_ (which may be a string or a
 *  +Proc+ object) or block is executed whenever the variable
 *  is assigned. The block or +Proc+ object receives the
 *  variable's new value as a parameter. Also see
 *  <code>Kernel::untrace_var</code>.
 *
 *     trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
 *     $_ = "hello"
 *     $_ = ' there'
 *
 *  <em>produces:</em>
 *
 *     $_ is now 'hello'
 *     $_ is now ' there'
 */

VALUE
rb_f_trace_var(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE var, cmd;
    struct global_entry *entry;
    struct trace_var *trace;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) {
    cmd = rb_block_proc();
    }
    if (NIL_P(cmd)) {
    return rb_f_untrace_var(argc, argv);
    }
    entry = rb_global_entry(rb_to_id(var));
    if (OBJ_TAINTED(cmd)) {
    rb_raise(rb_eSecurityError, "Insecure: tainted variable trace");
    }
    trace = ALLOC(struct trace_var);
    trace->next = entry->var->trace;
    trace->func = rb_trace_eval;
    trace->data = cmd;
    trace->removed = 0;
    entry->var->trace = trace;

    return Qnil;
}


untrace_var (Kernel)

/*
 *  call-seq:
 *     untrace_var(symbol [, cmd] )   => array or nil
 *
 *  Removes tracing for the specified command on the given global
 *  variable and returns +nil+. If no command is specified,
 *  removes all tracing for that variable and returns an array
 *  containing the commands actually removed.
 */

VALUE
rb_f_untrace_var(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE var, cmd;
    ID id;
    struct global_entry *entry;
    struct trace_var *trace;

    rb_scan_args(argc, argv, "11", &var, &cmd);
    id = rb_to_id(var);
    if (!st_lookup(rb_global_tbl, id, (st_data_t *)&entry)) {
    rb_name_error(id, "undefined global variable %s", rb_id2name(id));
    }

    trace = entry->var->trace;
    if (NIL_P(cmd)) {
    VALUE ary = rb_ary_new();

    while (trace) {
        struct trace_var *next = trace->next;
        rb_ary_push(ary, (VALUE)trace->data);
        trace->removed = 1;
        trace = next;
    }

    if (!entry->var->block_trace) remove_trace(entry->var);
    return ary;
    }
    else {
    while (trace) {
        if (trace->data == cmd) {
        trace->removed = 1;
        if (!entry->var->block_trace) remove_trace(entry->var);
        return rb_ary_new3(1, cmd);
        }
        trace = trace->next;
    }
    }
    return Qnil;
}


set_trace_func (Kernel)

/*
 *  call-seq:
 *     set_trace_func(proc)    => proc
 *     set_trace_func(nil)     => nil
 *
 *  Establishes _proc_ as the handler for tracing, or disables
 *  tracing if the parameter is +nil+. _proc_ takes up
 *  to six parameters: an event name, a filename, a line number, an
 *  object id, a binding, and the name of a class. _proc_ is
 *  invoked whenever an event occurs. Events are: <code>c-call</code>
 *  (call a C-language routine), <code>c-return</code> (return from a
 *  C-language routine), <code>call</code> (call a Ruby method),
 *  <code>class</code> (start a class or module definition),
 *  <code>end</code> (finish a class or module definition),
 *  <code>line</code> (execute code on a new line), <code>raise</code>
 *  (raise an exception), and <code>return</code> (return from a Ruby
 *  method). Tracing is disabled within the context of _proc_.
 *
 *      class Test
 *      def test
 *        a = 1
 *        b = 2
 *      end
 *      end
 *
 *      set_trace_func proc { |event, file, line, id, binding, classname|
 *         printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
 *      }
 *      t = Test.new
 *      t.test
 *
 *        line prog.rb:11               false
 *      c-call prog.rb:11        new    Class
 *      c-call prog.rb:11 initialize   Object
 *    c-return prog.rb:11 initialize   Object
 *    c-return prog.rb:11        new    Class
 *        line prog.rb:12               false
 *        call prog.rb:2        test     Test
 *        line prog.rb:3        test     Test
 *        line prog.rb:4        test     Test
 *      return prog.rb:4        test     Test
 */

static VALUE
set_trace_func(obj, trace)
    VALUE obj, trace;
{
    rb_event_hook_t *hook;

    rb_secure(4);
    if (NIL_P(trace)) {
        trace_func = 0;
        rb_remove_event_hook(call_trace_func);
        return Qnil;
    }
    if (!rb_obj_is_proc(trace)) {
        rb_raise(rb_eTypeError, "trace_func needs to be Proc");
    }
    trace_func = trace;
    for (hook = event_hooks; hook; hook = hook->next) {
        if (hook->func == call_trace_func)
            return trace;
    }
    rb_add_event_hook(call_trace_func, RUBY_EVENT_ALL);
    return trace;
}


load (Kernel)

/*
 *  call-seq:
 *     load(filename, wrap=false)   => true
 *
 *  Loads and executes the Ruby
 *  program in the file _filename_. If the filename does not
 *  resolve to an absolute path, the file is searched for in the library
 *  directories listed in <code>$:</code>. If the optional _wrap_
 *  parameter is +true+, the loaded script will be executed
 *  under an anonymous module, protecting the calling program's global
 *  namespace. In no circumstance will any local variables in the loaded
 *  file be propagated to the loading environment.
 */

static VALUE
rb_f_load(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, wrap;

    rb_scan_args(argc, argv, "11", &fname, &wrap);
    rb_load(fname, RTEST(wrap));
    return Qtrue;
}


require (Kernel)

/*
 *  call-seq:
 *     require(string)    => true or false
 *
 *  Ruby tries to load the library named _string_, returning
 *  +true+ if successful. If the filename does not resolve to
 *  an absolute path, it will be searched for in the directories listed
 *  in <code>$:</code>. If the file has the extension ``.rb'', it is
 *  loaded as a source file; if the extension is ``.so'', ``.o'', or
 *  ``.dll'', or whatever the default shared library extension is on
 *  the current platform, Ruby loads the shared library as a Ruby
 *  extension. Otherwise, Ruby tries adding ``.rb'', ``.so'', and so on
 *  to the name. The name of the loaded feature is added to the array in
 *  <code>$"</code>. A feature will not be loaded if it's name already
 *  appears in <code>$"</code>. However, the file name is not converted
 *  to an absolute path, so that ``<code>require 'a';require
 *  './a'</code>'' will load <code>a.rb</code> twice.
 *
 *     require "my-library.rb"
 *     require "db-driver"
 */

VALUE
rb_f_require(obj, fname)
    VALUE obj, fname;
{
    return rb_require_safe(fname, ruby_safe_level);
}


autoload (Kernel)

/*
 *  call-seq:
 *     autoload(module, filename)   => nil
 *
 *  Registers _filename_ to be loaded (using <code>Kernel::require</code>)
 *  the first time that _module_ (which may be a <code>String</code> or
 *  a symbol) is accessed.
 *
 *     autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
 */

static VALUE
rb_f_autoload(obj, sym, file)
    VALUE obj;
    VALUE sym;
    VALUE file;
{
    if (NIL_P(ruby_cbase)) {
        rb_raise(rb_eTypeError, "no class/module for autoload target");
    }
    return rb_mod_autoload(ruby_cbase, sym, file);
}


autoload? (Kernel)

/*
 *  call-seq:
 *     autoload(module, filename)   => nil
 *
 *  Registers _filename_ to be loaded (using <code>Kernel::require</code>)
 *  the first time that _module_ (which may be a <code>String</code> or
 *  a symbol) is accessed.
 *
 *     autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
 */

static VALUE
rb_f_autoload_p(obj, sym)
    VALUE obj;
    VALUE sym;
{
    /* use ruby_cbase as same as rb_f_autoload. */
    if (NIL_P(ruby_cbase)) {
        return Qfalse;
    }
    return rb_mod_autoload_p(ruby_cbase, sym);
}


proc (Kernel)

/*
 * call-seq:
 *   proc   { |...| block }  => a_proc
 *   lambda { |...| block }  => a_proc
 *
 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
 * check the number of parameters passed when called.
 */

static VALUE
proc_lambda()
{
    return proc_alloc(rb_cProc, Qtrue);
}


lambda (Kernel)

/*
 * call-seq:
 *   proc   { |...| block }  => a_proc
 *   lambda { |...| block }  => a_proc
 *
 * Equivalent to <code>Proc.new</code>, except the resulting Proc objects
 * check the number of parameters passed when called.
 */

static VALUE
proc_lambda()
{
    return proc_alloc(rb_cProc, Qtrue);
}


binding (Kernel)

/*
 *  call-seq:
 *     binding -> a_binding
 *
 *  Returns a +Binding+ object, describing the variable and
 *  method bindings at the point of call. This object can be used when
 *  calling +eval+ to execute the evaluated command in this
 *  environment. Also see the description of class +Binding+.
 *
 *     def getBinding(param)
 *       return binding
 *     end
 *     b = getBinding("hello")
 *     eval("param", b)   #=> "hello"
 */

static VALUE
rb_f_binding(self)
    VALUE self;
{
    struct BLOCK *data, *p;
    struct RVarmap *vars;
    VALUE bind;

    PUSH_BLOCK(0,0);
    bind = Data_Make_Struct(rb_cBinding,struct BLOCK,blk_mark,blk_free,data);
    *data = *ruby_block;

    data->orig_thread = rb_thread_current();
    data->wrapper = ruby_wrapper;
    data->iter = rb_f_block_given_p();
    frame_dup(&data->frame);
    if (ruby_frame->prev) {
        data->frame.last_func = ruby_frame->prev->last_func;
        data->frame.last_class = ruby_frame->prev->last_class;
        data->frame.orig_func = ruby_frame->prev->orig_func;
    }

    if (data->iter) {
        blk_copy_prev(data);
    }
    else {
        data->prev = 0;
    }

    for (p = data; p; p = p->prev) {
        for (vars = p->dyna_vars; vars; vars = vars->next) {
            if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
            FL_SET(vars, DVAR_DONT_RECYCLE);
        }
    }
    scope_dup(data->scope);
    POP_BLOCK();

    return bind;
}


callcc (Kernel)

/*
 *  call-seq:
 *     callcc {|cont| block }   =>  obj
 *
 *  Generates a <code>Continuation</code> object, which it passes to the
 *  associated block. Performing a <em>cont</em><code>.call</code> will
 *  cause the <code>callcc</code> to return (as will falling through the
 *  end of the block). The value returned by the <code>callcc</code> is
 *  the value of the block, or the value passed to
 *  <em>cont</em><code>.call</code>. See class <code>Continuation</code>
 *  for more details. Also see <code>Kernel::throw</code> for
 *  an alternative mechanism for unwinding a call stack.
 */

static VALUE
rb_callcc(self)
    VALUE self;
{
    volatile VALUE cont;
    rb_thread_t th;
    volatile rb_thread_t th_save;
    struct tag *tag;
    struct RVarmap *vars;

    THREAD_ALLOC(th);
    cont = Data_Wrap_Struct(rb_cCont, thread_mark, thread_free, th);

    scope_dup(ruby_scope);
    for (tag=prot_tag; tag; tag=tag->prev) {
        scope_dup(tag->scope);
    }
    th->thread = curr_thread->thread;
    th->thgroup = cont_protect;

    for (vars = ruby_dyna_vars; vars; vars = vars->next) {
        if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
        FL_SET(vars, DVAR_DONT_RECYCLE);
    }
    th_save = th;
    if (THREAD_SAVE_CONTEXT(th)) {
        return th_save->result;
    }
    else {
        return rb_yield(cont);
    }
}


warn (Kernel)

/*
 * call-seq:
 *    warn(msg)   => nil
 *
 * Display the given message (followed by a newline) on STDERR unless
 * warnings are disabled (for example with the <code>-W0</code> flag).
 */

static VALUE
rb_warn_m(self, mesg)
    VALUE self, mesg;
{
    if (!NIL_P(ruby_verbose)) {
        rb_io_write(rb_stderr, mesg);
        rb_io_write(rb_stderr, rb_default_rs);
    }
    return Qnil;
}


test (Kernel)

/*
 *  call-seq:
 *     test(int_cmd, file1 [, file2] ) => obj
 *
 *  Uses the integer <i>aCmd</i> to perform various tests on
 *  <i>file1</i> (first table below) or on <i>file1</i> and
 *  <i>file2</i> (second table).
 *
 *  File tests on a single file:
 *
 *    Test   Returns   Meaning
 *     ?A  | Time    | Last access time for file1
 *     ?b  | boolean | True if file1 is a block device
 *     ?c  | boolean | True if file1 is a character device
 *     ?C  | Time    | Last change time for file1
 *     ?d  | boolean | True if file1 exists and is a directory
 *     ?e  | boolean | True if file1 exists
 *     ?f  | boolean | True if file1 exists and is a regular file
 *     ?g  | boolean | True if file1 has the \CF{setgid} bit
 *         |         | set (false under NT)
 *     ?G  | boolean | True if file1 exists and has a group
 *         |         | ownership equal to the caller's group
 *     ?k  | boolean | True if file1 exists and has the sticky bit set
 *     ?l  | boolean | True if file1 exists and is a symbolic link
 *     ?M  | Time    | Last modification time for file1
 *     ?o  | boolean | True if file1 exists and is owned by
 *         |         | the caller's effective uid
 *     ?O  | boolean | True if file1 exists and is owned by
 *         |         | the caller's real uid
 *     ?p  | boolean | True if file1 exists and is a fifo
 *     ?r  | boolean | True if file1 is readable by the effective
 *         |         | uid/gid of the caller
 *     ?R  | boolean | True if file is readable by the real
 *         |         | uid/gid of the caller
 *     ?s  | int/nil | If file1 has nonzero size, return the size,
 *         |         | otherwise return nil
 *     ?S  | boolean | True if file1 exists and is a socket
 *     ?u  | boolean | True if file1 has the setuid bit set
 *     ?w  | boolean | True if file1 exists and is writable by
 *         |         | the effective uid/gid
 *     ?W  | boolean | True if file1 exists and is writable by
 *         |         | the real uid/gid
 *     ?x  | boolean | True if file1 exists and is executable by
 *         |         | the effective uid/gid
 *     ?X  | boolean | True if file1 exists and is executable by
 *         |         | the real uid/gid
 *     ?z  | boolean | True if file1 exists and has a zero length
 *
 * Tests that take two files:
 *
 *     ?-  | boolean | True if file1 and file2 are identical
 *     ?=  | boolean | True if the modification times of file1
 *         |         | and file2 are equal
 *     ?<  | boolean | True if the modification time of file1
 *         |         | is prior to that of file2
 *     ?>  | boolean | True if the modification time of file1
 *         |         | is after that of file2
 */

static VALUE
rb_f_test(argc, argv)
    int argc;
    VALUE *argv;
{
    int cmd;

    if (argc == 0) rb_raise(rb_eArgError, "wrong number of arguments");
#if 0 /* 1.7 behavior? */
    if (argc == 1) {
        return RTEST(argv[0]) ? Qtrue : Qfalse;
    }
#endif
    cmd = NUM2CHR(argv[0]);
    if (cmd == 0) return Qfalse;
    if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
        CHECK(1);
        switch (cmd) {
          case 'b':
            return test_b(0, argv[1]);

          case 'c':
            return test_c(0, argv[1]);

          case 'd':
            return test_d(0, argv[1]);

          case 'a':
          case 'e':
            return test_e(0, argv[1]);

          case 'f':
            return test_f(0, argv[1]);

          case 'g':
            return test_sgid(0, argv[1]);

          case 'G':
            return test_grpowned(0, argv[1]);

          case 'k':
            return test_sticky(0, argv[1]);

          case 'l':
            return test_l(0, argv[1]);

          case 'o':
            return test_owned(0, argv[1]);

          case 'O':
            return test_rowned(0, argv[1]);

          case 'p':
            return test_p(0, argv[1]);

          case 'r':
            return test_r(0, argv[1]);

          case 'R':
            return test_R(0, argv[1]);

          case 's':
            return test_s(0, argv[1]);

          case 'S':
            return test_S(0, argv[1]);

          case 'u':
            return test_suid(0, argv[1]);

          case 'w':
            return test_w(0, argv[1]);

          case 'W':
            return test_W(0, argv[1]);

          case 'x':
            return test_x(0, argv[1]);

          case 'X':
            return test_X(0, argv[1]);

          case 'z':
            return test_z(0, argv[1]);
        }
    }

    if (strchr("MAC", cmd)) {
        struct stat st;

        CHECK(1);
        if (rb_stat(argv[1], &st) == -1) {
            rb_sys_fail(RSTRING(argv[1])->ptr);
        }

        switch (cmd) {
          case 'A':
            return rb_time_new(st.st_atime, 0);
          case 'M':
            return rb_time_new(st.st_mtime, 0);
          case 'C':
            return rb_time_new(st.st_ctime, 0);
        }
    }

    if (cmd == '-') {
        CHECK(2);
        return test_identical(0, argv[1], argv[2]);
    }

    if (strchr("=<>", cmd)) {
        struct stat st1, st2;

        CHECK(2);
        if (rb_stat(argv[1], &st1) < 0) return Qfalse;
        if (rb_stat(argv[2], &st2) < 0) return Qfalse;

        switch (cmd) {
          case '=':
            if (st1.st_mtime == st2.st_mtime) return Qtrue;
            return Qfalse;

          case '>':
            if (st1.st_mtime > st2.st_mtime) return Qtrue;
            return Qfalse;

          case '<':
            if (st1.st_mtime < st2.st_mtime) return Qtrue;
            return Qfalse;
        }
    }
    /* unknown command */
    rb_raise(rb_eArgError, "unknown command ?%c", cmd);
    return Qnil;                /* not reached */
}


srand (Kernel)

/*
 *  call-seq:
 *     srand(number=0)    => old_seed
 *
 *  Seeds the pseudorandom number generator to the value of
 *  <i>number</i>.<code>to_i.abs</code>. If <i>number</i> is omitted,
 *  seeds the generator using a combination of the time, the
 *  process id, and a sequence number. (This is also the behavior if
 *  <code>Kernel::rand</code> is called without previously calling
 *  <code>srand</code>, but without the sequence.) By setting the seed
 *  to a known value, scripts can be made deterministic during testing.
 *  The previous seed value is returned. Also see <code>Kernel::rand</code>.
 */

static VALUE
rb_f_srand(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE seed, old;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &seed) == 0) {
        seed = random_seed();
    }
    old = rand_init(seed);

    return old;
}


rand (Kernel)

/*
 *  call-seq:
 *     rand(max=0)    => number
 *
 *  Converts <i>max</i> to an integer using max1 =
 *  max<code>.to_i.abs</code>. If the result is zero, returns a
 *  pseudorandom floating point number greater than or equal to 0.0 and
 *  less than 1.0. Otherwise, returns a pseudorandom integer greater
 *  than or equal to zero and less than max1. <code>Kernel::srand</code>
 *  may be used to ensure repeatable sequences of random numbers between
 *  different runs of the program. Ruby currently uses a modified
 *  Mersenne Twister with a period of 2**19937-1.
 *
 *     srand 1234                 #=> 0
 *     [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
 *     [ rand(10), rand(1000) ]   #=> [6, 817]
 *     srand 1234                 #=> 1234
 *     [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
 */

static VALUE
rb_f_rand(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE vmax;
    long val, max;

    rb_scan_args(argc, argv, "01", &vmax);
    if (first) {
        rand_init(random_seed());
    }
    switch (TYPE(vmax)) {
      case T_FLOAT:
        if (RFLOAT(vmax)->value <= LONG_MAX && RFLOAT(vmax)->value >= LONG_MIN) {
            max = (long)RFLOAT(vmax)->value;
            break;
        }
        if (RFLOAT(vmax)->value < 0)
            vmax = rb_dbl2big(-RFLOAT(vmax)->value);
        else
            vmax = rb_dbl2big(RFLOAT(vmax)->value);
        /* fall through */
      case T_BIGNUM:
      bignum:
        {
            struct RBignum *limit = (struct RBignum *)vmax;
            if (!limit->sign) {
                limit = (struct RBignum *)rb_big_clone(vmax);
                limit->sign = 1;
            }
            limit = (struct RBignum *)rb_big_minus((VALUE)limit, INT2FIX(1));
            if (FIXNUM_P((VALUE)limit)) {
                if (FIX2LONG((VALUE)limit) == -1)
                    return rb_float_new(genrand_real());
                return LONG2NUM(limited_rand(FIX2LONG((VALUE)limit)));
            }
            return limited_big_rand(limit);
        }
      case T_NIL:
        max = 0;
        break;
      default:
        vmax = rb_Integer(vmax);
        if (TYPE(vmax) == T_BIGNUM) goto bignum;
        /* fall through */
      case T_FIXNUM:
        max = FIX2LONG(vmax);
        break;
    }

    if (max == 0) {
        return rb_float_new(genrand_real());
    }
    if (max < 0) max = -max;
    val = limited_rand(max-1);
    return LONG2NUM(val);
}


trap (Kernel)

/*
 * call-seq:
 *   Signal.trap( signal, proc ) => obj
 *   Signal.trap( signal ) {| | block } => obj
 *
 * Specifies the handling of signals. The first parameter is a signal
 * name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a
 * signal number. The characters ``SIG'' may be omitted from the
 * signal name. The command or block specifies code to be run when the
 * signal is raised. If the command is the string ``IGNORE'' or
 * ``SIG_IGN'', the signal will be ignored. If the command is
 * ``DEFAULT'' or ``SIG_DFL'', the operating system's default handler
 * will be invoked. If the command is ``EXIT'', the script will be
 * terminated by the signal. Otherwise, the given command or block
 * will be run.
 * The special signal name ``EXIT'' or signal number zero will be
 * invoked just prior to program termination.
 * trap returns the previous handler for the given signal.
 *
 *     Signal.trap(0, proc { puts "Terminating: #{$$}" })
 *     Signal.trap("CLD")  { puts "Child died" }
 *     fork && Process.wait
 *
 * produces:
 *     Terminating: 27461
 *     Child died
 *     Terminating: 27460
 */
static VALUE
sig_trap(argc, argv)
    int argc;
    VALUE *argv;
{
    struct trap_arg arg;

    rb_secure(2);
    if (argc == 0 || argc > 2) {
        rb_raise(rb_eArgError, "wrong number of arguments -- trap(sig, cmd)/trap(sig){...}");
    }

    arg.sig = argv[0];
    if (argc == 1) {
        arg.cmd = rb_block_proc();
    }
    else if (argc == 2) {
        arg.cmd = argv[1];
    }

    if (OBJ_TAINTED(arg.cmd)) {
        rb_raise(rb_eSecurityError, "Insecure: tainted signal trap");
    }
#ifndef _WIN32
    /* disable interrupt */
# ifdef HAVE_SIGPROCMASK
    sigfillset(&arg.mask);
    sigprocmask(SIG_BLOCK, &arg.mask, &arg.mask);
# else
    arg.mask = sigblock(~0);
# endif

    return rb_ensure(trap, (VALUE)&arg, trap_ensure, (VALUE)&arg);
#else
    return trap(&arg);
#endif
}


exec (Kernel)

/*
 *  call-seq:
 *     exec(command [, arg, ...])
 *
 *  Replaces the current process by running the given external _command_.
 *  If +exec+ is given a single argument, that argument is
 *  taken as a line that is subject to shell expansion before being
 *  executed. If multiple arguments are given, the second and subsequent
 *  arguments are passed as parameters to _command_ with no shell
 *  expansion. If the first argument is a two-element array, the first
 *  element is the command to be executed, and the second argument is
 *  used as the <code>argv[0]</code> value, which may show up in process
 *  listings. In MSDOS environments, the command is executed in a
 *  subshell; otherwise, one of the <code>exec(2)</code> system calls is
 *  used, so the running command may inherit some of the environment of
 *  the original program (including open file descriptors).
 *
 *     exec "echo *"       # echoes list of files in current directory
 *     # never get here
 *
 *
 *     exec "echo", "*"    # echoes an asterisk
 *     # never get here
 */

VALUE
rb_f_exec(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE prog = 0;
    VALUE tmp;

    if (argc == 0) {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    tmp = rb_check_array_type(argv[0]);
    if (!NIL_P(tmp)) {
        if (RARRAY(tmp)->len != 2) {
            rb_raise(rb_eArgError, "wrong first argument");
        }
        prog = RARRAY(tmp)->ptr[0];
        argv[0] = RARRAY(tmp)->ptr[1];
        SafeStringValue(prog);
    }
    if (argc == 1 && prog == 0) {
        VALUE cmd = argv[0];

        SafeStringValue(cmd);
        rb_proc_exec(RSTRING(cmd)->ptr);
    }
    else {
        proc_exec_n(argc, argv, prog);
    }
    rb_sys_fail(RSTRING(argv[0])->ptr);
    return Qnil;                /* dummy */
}


fork (Kernel)

/*
 *  call-seq:
 *     Kernel.fork  [{ block }]   => fixnum or nil
 *     Process.fork [{ block }]   => fixnum or nil
 *
 *  Creates a subprocess. If a block is specified, that block is run
 *  in the subprocess, and the subprocess terminates with a status of
 *  zero. Otherwise, the +fork+ call returns twice, once in
 *  the parent, returning the process ID of the child, and once in
 *  the child, returning _nil_. The child process can exit using
 *  <code>Kernel.exit!</code> to avoid running any
 *  <code>at_exit</code> functions. The parent process should
 *  use <code>Process.wait</code> to collect the termination statuses
 *  of its children or use <code>Process.detach</code> to register
 *  disinterest in their status; otherwise, the operating system
 *  may accumulate zombie processes.
 *
 *  The thread calling fork is the only thread in the created child process.
 *  fork doesn't copy other threads.
 */

static VALUE
rb_f_fork(obj)
    VALUE obj;
{
#if !defined(__human68k__) && !defined(_WIN32) && !defined(__MACOS__) && !defined(__EMX__) && !defined(__VMS)
    int pid;

    rb_secure(2);

#ifndef __VMS
    fflush(stdout);
    fflush(stderr);
#endif

    switch (pid = fork()) {
      case 0:
#ifdef linux
        after_exec();
#endif
        rb_thread_atfork();
        if (rb_block_given_p()) {
            int status;

            rb_protect(rb_yield, Qundef, &status);
            ruby_stop(status);
        }
        return Qnil;

      case -1:
        rb_sys_fail("fork(2)");
        return Qnil;

      default:
        return INT2FIX(pid);
    }
#else
    rb_notimplement();
#endif
}


exit! (Kernel)

/*
 *  call-seq:
 *     Process.exit!(fixnum=-1)
 *
 *  Exits the process immediately. No exit handlers are
 *  run. <em>fixnum</em> is returned to the underlying system as the
 *  exit status.
 *
 *     Process.exit!(0)
 */

static VALUE
rb_f_exit_bang(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE status;
    int istatus;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &status) == 1) {
        switch (status) {
          case Qtrue:
            istatus = EXIT_SUCCESS;
            break;
          case Qfalse:
            istatus = EXIT_FAILURE;
            break;
          default:
            istatus = NUM2INT(status);
            break;
        }
    }
    else {
        istatus = EXIT_FAILURE;
    }
    _exit(istatus);

    return Qnil;                /* not reached */
}


system (Kernel)

/*
 *  call-seq:
 *     system(cmd [, arg, ...])    => true or false
 *
 *  Executes _cmd_ in a subshell, returning +true+ if
 *  the command was found and ran successfully, +false+
 *  otherwise. An error status is available in <code>$?</code>. The
 *  arguments are processed in the same way as for
 *  <code>Kernel::exec</code>.
 *
 *     system("echo *")
 *     system("echo", "*")
 *
 *  <em>produces:</em>
 *
 *     config.h main.rb
 *     *
 */

static VALUE
rb_f_system(argc, argv)
    int argc;
    VALUE *argv;
{
    int status;
#if defined(__EMX__)
    VALUE cmd;

    fflush(stdout);
    fflush(stderr);
    if (argc == 0) {
        rb_last_status = Qnil;
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
        if (RARRAY(argv[0])->len != 2) {
            rb_raise(rb_eArgError, "wrong first argument");
        }
        argv[0] = RARRAY(argv[0])->ptr[0];
    }
    cmd = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));

    SafeStringValue(cmd);
    status = do_spawn(RSTRING(cmd)->ptr);
    last_status_set(status, 0);
#elif defined(__human68k__) || defined(__DJGPP__) || defined(_WIN32)
    volatile VALUE prog = 0;

    fflush(stdout);
    fflush(stderr);
    if (argc == 0) {
        rb_last_status = Qnil;
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
        if (RARRAY(argv[0])->len != 2) {
            rb_raise(rb_eArgError, "wrong first argument");
        }
        prog = RARRAY(argv[0])->ptr[0];
        argv[0] = RARRAY(argv[0])->ptr[1];
    }

    if (argc == 1 && prog == 0) {
#if defined(_WIN32)
        SafeStringValue(argv[0]);
        status = do_spawn(P_WAIT, StringValueCStr(argv[0]));
#else
        status = proc_spawn(argv[0]);
#endif
    }
    else {
        status = proc_spawn_n(argc, argv, prog);
    }
#if !defined(_WIN32)
    last_status_set(status == -1 ? 127 : status, 0);
#endif
#elif defined(__VMS)
    VALUE cmd;

    if (argc == 0) {
        rb_last_status = Qnil;
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
        if (RARRAY(argv[0])->len != 2) {
            rb_raise(rb_eArgError, "wrong first argument");
        }
        argv[0] = RARRAY(argv[0])->ptr[0];
    }
    cmd = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));

    SafeStringValue(cmd);
    status = system(StringValueCStr(cmd));
    last_status_set((status & 0xff) << 8, 0);
#else
    volatile VALUE prog = 0;
    int pid;
    int i;
    RETSIGTYPE (*chfunc)(int);

    fflush(stdout);
    fflush(stderr);
    if (argc == 0) {
        rb_last_status = Qnil;
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    if (TYPE(argv[0]) == T_ARRAY) {
        if (RARRAY(argv[0])->len != 2) {
            rb_raise(rb_eArgError, "wrong first argument");
        }
        prog = RARRAY(argv[0])->ptr[0];
        argv[0] = RARRAY(argv[0])->ptr[1];
    }

    if (prog) {
        SafeStringValue(prog);
        StringValueCStr(prog);
    }
    for (i = 0; i < argc; i++) {
        SafeStringValue(argv[i]);
        StringValueCStr(argv[i]);
    }
    security(RSTRING(prog ? prog : argv[0])->ptr);
    chfunc = signal(SIGCHLD, SIG_DFL);
  retry:
    pid = fork();
    if (pid == 0) {
        /* child process */
        if (argc == 1 && prog == 0) {
            rb_proc_exec(RSTRING(argv[0])->ptr);
        }
        else {
            proc_exec_n(argc, argv, prog);
        }
        _exit(127);
    }
    if (pid < 0) {
        if (errno == EAGAIN) {
            rb_thread_sleep(1);
            goto retry;
        }
    }
    else {
        rb_syswait(pid);
    }
    signal(SIGCHLD, chfunc);
    if (pid < 0) rb_sys_fail(0);
    status = NUM2INT(rb_last_status);
#endif

    if (status == EXIT_SUCCESS) return Qtrue;
    return Qfalse;
}


sleep (Kernel)

/*
 *  call-seq:
 *     sleep([duration])    => fixnum
 *
 *  Suspends the current thread for _duration_ seconds (which may be any number,
 *  including a +Float+ with fractional seconds). Returns the actual number of
 *  seconds slept (rounded), which may be less than that asked for if another
 *  thread calls <code>Thread#run</code>. Zero arguments causes +sleep+ to sleep
 *  forever.
 *
 *     Time.new    #=> Wed Apr 09 08:56:32 CDT 2003
 *     sleep 1.2   #=> 1
 *     Time.new    #=> Wed Apr 09 08:56:33 CDT 2003
 *     sleep 1.9   #=> 2
 *     Time.new    #=> Wed Apr 09 08:56:35 CDT 2003
 */

static VALUE
rb_f_sleep(argc, argv)
    int argc;
    VALUE *argv;
{
    int beg, end;

    beg = time(0);
    if (argc == 0) {
        rb_thread_sleep_forever();
    }
    else if (argc == 1) {
        rb_thread_wait_for(rb_time_interval(argv[0]));
    }
    else {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }

    end = time(0) - beg;

    return INT2FIX(end);
}


sprintf (Kernel)

/*
 *  call-seq:
 *     format(format_string [, arguments...] )   => string
 *     sprintf(format_string [, arguments...] )  => string
 *
 *  Returns the string resulting from applying <i>format_string</i> to
 *  any additional arguments. Within the format string, any characters
 *  other than format sequences are copied to the result. A format
 *  sequence consists of a percent sign, followed by optional flags,
 *  width, and precision indicators, then terminated with a field type
 *  character. The field type controls how the corresponding
 *  <code>sprintf</code> argument is to be interpreted, while the flags
 *  modify that interpretation. The field type characters are listed
 *  in the table at the end of this section. The flag characters are:
 *
 *    Flag     | Applies to   | Meaning
 *    ---------+--------------+-----------------------------------------
 *    space    | bdeEfgGiouxX | Leave a space at the start of
 *             |              | positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    (digit)$ | all          | Specifies the absolute argument number
 *             |              | for this field. Absolute and relative
 *             |              | argument numbers cannot be mixed in a
 *             |              | sprintf string.
 *    ---------+--------------+-----------------------------------------
 *     #       | beEfgGoxX    | Use an alternative format. For the
 *             |              | conversions `o', `x', `X', and `b',
 *             |              | prefix the result with ``0'', ``0x'', ``0X'',
 *             |              |  and ``0b'', respectively. For `e',
 *             |              | `E', `f', `g', and 'G', force a decimal
 *             |              | point to be added, even if no digits follow.
 *             |              | For `g' and 'G', do not remove trailing zeros.
 *    ---------+--------------+-----------------------------------------
 *    +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    -        | all          | Left-justify the result of this conversion.
 *    ---------+--------------+-----------------------------------------
 *    0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
 *    ---------+--------------+-----------------------------------------
 *    *        | all          | Use the next argument as the field width.
 *             |              | If negative, left-justify the result. If the
 *             |              | asterisk is followed by a number and a dollar
 *             |              | sign, use the indicated argument as the width.
 *
 *
 *  The field width is an optional integer, followed optionally by a
 *  period and a precision. The width specifies the minimum number of
 *  characters that will be written to the result for this field. For
 *  numeric fields, the precision controls the number of decimal places
 *  displayed. For string fields, the precision determines the maximum
 *  number of characters to be copied from the string. (Thus, the format
 *  sequence <code>%10.10s</code> will always contribute exactly ten
 *  characters to the result.)
 *
 *  The field types are:
 *
 *      Field |  Conversion
 *      ------+--------------------------------------------------------------
 *        b   | Convert argument as a binary number.
 *        c   | Argument is the numeric code for a single character.
 *        d   | Convert argument as a decimal number.
 *        E   | Equivalent to `e', but uses an uppercase E to indicate
 *            | the exponent.
 *        e   | Convert floating point argument into exponential notation
 *            | with one digit before the decimal point. The precision
 *            | determines the number of fractional digits (defaulting to six).
 *        f   | Convert floating point argument as [-]ddd.ddd,
 *            |  where the precision determines the number of digits after
 *            | the decimal point.
 *        G   | Equivalent to `g', but use an uppercase `E' in exponent form.
 *        g   | Convert a floating point number using exponential form
 *            | if the exponent is less than -4 or greater than or
 *            | equal to the precision, or in d.dddd form otherwise.
 *        i   | Identical to `d'.
 *        o   | Convert argument as an octal number.
 *        p   | The valuing of argument.inspect.
 *        s   | Argument is a string to be substituted. If the format
 *            | sequence contains a precision, at most that many characters
 *            | will be copied.
 *        u   | Treat argument as an unsigned decimal number. Negative integers
 *            | are displayed as a 32 bit two's complement plus one for the
 *            | underlying architecture; that is, 2 ** 32 + n.  However, since
 *            | Ruby has no inherent limit on bits used to represent the
 *            | integer, this value is preceded by two dots (..) in order to
 *            | indicate a infinite number of leading sign bits.
 *        X   | Convert argument as a hexadecimal number using uppercase
 *            | letters. Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'FF's.
 *        x   | Convert argument as a hexadecimal number.
 *            | Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'ff's.
 *
 *  Examples:
 *
 *     sprintf("%d %04x", 123, 123)               #=> "123 007b"
 *     sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
 *     sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
 *     sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
 *     sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
 *     sprintf("%u", -123)                        #=> "..4294967173"
 */

VALUE
rb_f_sprintf(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fmt;
    const char *p, *end;
    char *buf;
    int blen, bsiz;
    VALUE result;

    int width, prec, flags = FNONE;
    int nextarg = 1;
    int posarg = 0;
    int tainted = 0;
    VALUE nextvalue;
    VALUE tmp;
    VALUE str;

#define CHECK_FOR_WIDTH(f)				 \
    if ((f) & FWIDTH) {					 \
    rb_raise(rb_eArgError, "width given twice");	 \
    }							 \
    if ((f) & FPREC0) {					 \
    rb_raise(rb_eArgError, "width after precision"); \
    }
#define CHECK_FOR_FLAGS(f)				 \
    if ((f) & FWIDTH) {					 \
    rb_raise(rb_eArgError, "flag after width");	 \
    }							 \
    if ((f) & FPREC0) {					 \
    rb_raise(rb_eArgError, "flag after precision"); \
    }

    fmt = GETNTHARG(0);
    if (OBJ_TAINTED(fmt)) tainted = 1;
    StringValue(fmt);
    fmt = rb_str_new4(fmt);
    p = RSTRING(fmt)->ptr;
    end = p + RSTRING(fmt)->len;
    blen = 0;
    bsiz = 120;
    result = rb_str_buf_new(bsiz);
    buf = RSTRING(result)->ptr;

    for (; p < end; p++) {
    const char *t;
    int n;

    for (t = p; t < end && *t != '%'; t++) ;
    PUSH(p, t - p);
    if (t >= end) {
        /* end of fmt string */
        goto sprint_exit;
    }
    p = t + 1;		/* skip `%' */

    width = prec = -1;
    nextvalue = Qundef;
      retry:
    switch (*p) {
      default:
        if (ISPRINT(*p))
        rb_raise(rb_eArgError, "malformed format string - %%%c", *p);
        else
        rb_raise(rb_eArgError, "malformed format string");
        break;

      case ' ':
        CHECK_FOR_FLAGS(flags);
        flags |= FSPACE;
        p++;
        goto retry;

      case '#':
        CHECK_FOR_FLAGS(flags);
        flags |= FSHARP;
        p++;
        goto retry;

      case '+':
        CHECK_FOR_FLAGS(flags);
        flags |= FPLUS;
        p++;
        goto retry;

      case '-':
        CHECK_FOR_FLAGS(flags);
        flags |= FMINUS;
        p++;
        goto retry;

      case '0':
        CHECK_FOR_FLAGS(flags);
        flags |= FZERO;
        p++;
        goto retry;

      case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        n = 0;
        GETNUM(n, width);
        if (*p == '$') {
        if (nextvalue != Qundef) {
            rb_raise(rb_eArgError, "value given twice - %d$", n);
        }
        nextvalue = GETPOSARG(n);
        p++;
        goto retry;
        }
        CHECK_FOR_WIDTH(flags);
        width = n;
        flags |= FWIDTH;
        goto retry;

      case '*':
        CHECK_FOR_WIDTH(flags);
        flags |= FWIDTH;
        GETASTER(width);
        if (width < 0) {
        flags |= FMINUS;
        width = -width;
        }
        p++;
        goto retry;

      case '.':
        if (flags & FPREC0) {
        rb_raise(rb_eArgError, "precision given twice");
        }
        flags |= FPREC|FPREC0;

        prec = 0;
        p++;
        if (*p == '*') {
        GETASTER(prec);
        if (prec < 0) {	/* ignore negative precision */
            flags &= ~FPREC;
        }
        p++;
        goto retry;
        }

        GETNUM(prec, precision);
        goto retry;

      case '\n':
      case '\0':
        p--;
      case '%':
        if (flags != FNONE) {
        rb_raise(rb_eArgError, "illegal format character - %%");
        }
        PUSH("%", 1);
        break;

      case 'c':
        {
        VALUE val = GETARG();
        char c;

        if (!(flags & FMINUS))
            while (--width > 0)
            PUSH(" ", 1);
        c = NUM2INT(val) & 0xff;
        PUSH(&c, 1);
        while (--width > 0)
            PUSH(" ", 1);
        }
        break;

      case 's':
      case 'p':
        {
        VALUE arg = GETARG();
        long len;

        if (*p == 'p') arg = rb_inspect(arg);
        str = rb_obj_as_string(arg);
        if (OBJ_TAINTED(str)) tainted = 1;
        len = RSTRING(str)->len;
        if (flags&FPREC) {
            if (prec < len) {
            len = prec;
            }
        }
        /* need to adjust multi-byte string pos */
        if (flags&FWIDTH) {
            if (width > len) {
            CHECK(width);
            width -= len;
            if (!(flags&FMINUS)) {
                while (width--) {
                buf[blen++] = ' ';
                }
            }
            memcpy(&buf[blen], RSTRING_PTR(str), len);
            blen += len;
            if (flags&FMINUS) {
                while (width--) {
                buf[blen++] = ' ';
                }
            }
            break;
            }
        }
        PUSH(RSTRING(str)->ptr, len);
        }
        break;

      case 'd':
      case 'i':
      case 'o':
      case 'x':
      case 'X':
      case 'b':
      case 'B':
      case 'u':
        {
        volatile VALUE val = GETARG();
        char fbuf[32], nbuf[64], *s, *t;
        const char *prefix = 0;
        int sign = 0;
        char sc = 0;
        long v = 0;
        int base, bignum = 0;
        int len, pos;
        VALUE tmp;
                volatile VALUE tmp1;

        switch (*p) {
          case 'd':
          case 'i':
            sign = 1; break;
          case 'o':
          case 'x':
          case 'X':
          case 'b':
          case 'B':
          case 'u':
          default:
            if (flags&(FPLUS|FSPACE)) sign = 1;
            break;
        }
        if (flags & FSHARP) {
            switch (*p) {
              case 'o':
            prefix = "0"; break;
              case 'x':
            prefix = "0x"; break;
              case 'X':
            prefix = "0X"; break;
              case 'b':
            prefix = "0b"; break;
              case 'B':
            prefix = "0B"; break;
            }
            if (prefix) {
            width -= strlen(prefix);
            }
        }

          bin_retry:
        switch (TYPE(val)) {
          case T_FLOAT:
            val = rb_dbl2big(RFLOAT(val)->value);
            if (FIXNUM_P(val)) goto bin_retry;
            bignum = 1;
            break;
          case T_STRING:
            val = rb_str_to_inum(val, 0, Qtrue);
            goto bin_retry;
          case T_BIGNUM:
            bignum = 1;
            break;
          case T_FIXNUM:
            v = FIX2LONG(val);
            break;
          default:
            val = rb_Integer(val);
            goto bin_retry;
        }

        switch (*p) {
          case 'o':
            base = 8; break;
          case 'x':
          case 'X':
            base = 16; break;
          case 'b':
          case 'B':
            base = 2; break;
          case 'u':
          case 'd':
          case 'i':
          default:
            base = 10; break;
        }

        if (!bignum) {
            if (base == 2) {
            val = rb_int2big(v);
            goto bin_retry;
            }
            if (sign) {
            char c = *p;
            if (c == 'i') c = 'd'; /* %d and %i are identical */
            if (v < 0) {
                v = -v;
                sc = '-';
                width--;
            }
            else if (flags & FPLUS) {
                sc = '+';
                width--;
            }
            else if (flags & FSPACE) {
                sc = ' ';
                width--;
            }
            sprintf(fbuf, "%%l%c", c);
            sprintf(nbuf, fbuf, v);
            s = nbuf;
            goto format_integer;
            }
            s = nbuf;
            if (v < 0) {
            if (base == 10) {
                rb_warning("negative number for %%u specifier");
            }
            if (!(flags&(FPREC|FZERO))) {
                strcpy(s, "..");
                s += 2;
            }
            }
            sprintf(fbuf, "%%l%c", *p == 'X' ? 'x' : *p);
            sprintf(s, fbuf, v);
            if (v < 0) {
            char d = 0;

            remove_sign_bits(s, base);
            switch (base) {
              case 16:
                d = 'f'; break;
              case 8:
                d = '7'; break;
            }
            if (d && *s != d) {
                memmove(s+1, s, strlen(s)+1);
                *s = d;
            }
            }
            s = nbuf;
            goto format_integer;
        }

        if (sign) {
            tmp = rb_big2str(val, base);
            s = RSTRING(tmp)->ptr;
            if (s[0] == '-') {
            s++;
            sc = '-';
                        width--;
            }
            else if (flags & FPLUS) {
            sc = '+';
                        width--;
            }
            else if (flags & FSPACE) {
            sc = ' ';
                        width--;
            }
            goto format_integer;
        }
        if (!RBIGNUM(val)->sign) {
            val = rb_big_clone(val);
            rb_big_2comp(val);
        }
        tmp1 = tmp = rb_big2str0(val, base, RBIGNUM(val)->sign);
        s = RSTRING(tmp)->ptr;
        if (*s == '-') {
            if (base == 10) {
            rb_warning("negative number for %%u specifier");
            }
            remove_sign_bits(++s, base);
            tmp = rb_str_new(0, 3+strlen(s));
            t = RSTRING(tmp)->ptr;
            if (!(flags&(FPREC|FZERO))) {
            strcpy(t, "..");
            t += 2;
            }
            switch (base) {
              case 16:
            if (s[0] != 'f') strcpy(t++, "f"); break;
              case 8:
            if (s[0] != '7') strcpy(t++, "7"); break;
              case 2:
            if (s[0] != '1') strcpy(t++, "1"); break;
            }
            strcpy(t, s);
            bignum = 2;
        }
        s = RSTRING(tmp)->ptr;

          format_integer:
        pos = -1;
        len = strlen(s);

        if (*p == 'X') {
            char *pp = s;
            while (*pp) {
            *pp = toupper(*pp);
            pp++;
            }
        }
        if ((flags&(FZERO|FPREC)) == FZERO) {
            prec = width;
            width = 0;
        }
        else {
            if (prec < len) prec = len;
            width -= prec;
        }
        if (!(flags&FMINUS)) {
            CHECK(width);
            while (width-- > 0) {
            buf[blen++] = ' ';
            }
        }
        if (sc) PUSH(&sc, 1);
        if (prefix) {
            int plen = strlen(prefix);
            PUSH(prefix, plen);
        }
        CHECK(prec - len);
        if (!bignum && v < 0) {
            char c = sign_bits(base, p);
            while (len < prec--) {
            buf[blen++] = c;
            }
        }
        else {
            char c;

            if (!sign && bignum && !RBIGNUM(val)->sign)
            c = sign_bits(base, p);
            else
            c = '0';
            while (len < prec--) {
            buf[blen++] = c;
            }
        }
        PUSH(s, len);
        CHECK(width);
        while (width-- > 0) {
            buf[blen++] = ' ';
        }
        }
        break;

      case 'f':
      case 'g':
      case 'G':
      case 'e':
      case 'E':
        {
        VALUE val = GETARG();
        double fval;
        int i, need = 6;
        char fbuf[32];

        fval = RFLOAT(rb_Float(val))->value;
#if defined(_WIN32) && !defined(__BORLANDC__)
        if (isnan(fval) || isinf(fval)) {
            char *expr;

            if  (isnan(fval)) {
            expr = "NaN";
            }
            else {
            expr = "Inf";
            }
            need = strlen(expr);
            if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
            need++;
            if ((flags & FWIDTH) && need < width)
            need = width;

            CHECK(need);
            sprintf(&buf[blen], "%*s", need, "");
            if (flags & FMINUS) {
            if (!isnan(fval) && fval < 0.0)
                buf[blen++] = '-';
            else if (flags & FPLUS)
                buf[blen++] = '+';
            else if (flags & FSPACE)
                blen++;
            strncpy(&buf[blen], expr, strlen(expr));
            }
            else if (flags & FZERO) {
            if (!isnan(fval) && fval < 0.0) {
                buf[blen++] = '-';
                need--;
            }
            else if (flags & FPLUS) {
                buf[blen++] = '+';
                need--;
            }
            else if (flags & FSPACE) {
                blen++;
                need--;
            }
            while (need-- - strlen(expr) > 0) {
                buf[blen++] = '0';
            }
            strncpy(&buf[blen], expr, strlen(expr));
            }
            else {
            if (!isnan(fval) && fval < 0.0)
                buf[blen + need - strlen(expr) - 1] = '-';
            else if (flags & FPLUS)
                buf[blen + need - strlen(expr) - 1] = '+';
            strncpy(&buf[blen + need - strlen(expr)], expr,
                strlen(expr));
            }
            blen += strlen(&buf[blen]);
            break;
        }
#endif	/* defined(_WIN32) && !defined(__BORLANDC__) */
        fmt_setup(fbuf, *p, flags, width, prec);
        need = 0;
        if (*p != 'e' && *p != 'E') {
            i = INT_MIN;
            frexp(fval, &i);
            if (i > 0)
            need = BIT_DIGITS(i);
        }
        need += (flags&FPREC) ? prec : 6;
        if ((flags&FWIDTH) && need < width)
            need = width;
        need += 20;

        CHECK(need);
        sprintf(&buf[blen], fbuf, fval);
        blen += strlen(&buf[blen]);
        }
        break;
    }
    flags = FNONE;
    }

  sprint_exit:
    /* XXX - We cannot validiate the number of arguments if (digit)$ style used.
     */
    if (posarg >= 0 && nextarg < argc) {
    const char *mesg = "too many arguments for format string";
    if (RTEST(ruby_debug)) rb_raise(rb_eArgError, mesg);
    if (RTEST(ruby_verbose)) rb_warn(mesg);
    }
    rb_str_resize(result, blen);

    if (tainted) OBJ_TAINT(result);
    return result;
}


format (Kernel)

/*
 *  call-seq:
 *     format(format_string [, arguments...] )   => string
 *     sprintf(format_string [, arguments...] )  => string
 *
 *  Returns the string resulting from applying <i>format_string</i> to
 *  any additional arguments. Within the format string, any characters
 *  other than format sequences are copied to the result. A format
 *  sequence consists of a percent sign, followed by optional flags,
 *  width, and precision indicators, then terminated with a field type
 *  character. The field type controls how the corresponding
 *  <code>sprintf</code> argument is to be interpreted, while the flags
 *  modify that interpretation. The field type characters are listed
 *  in the table at the end of this section. The flag characters are:
 *
 *    Flag     | Applies to   | Meaning
 *    ---------+--------------+-----------------------------------------
 *    space    | bdeEfgGiouxX | Leave a space at the start of
 *             |              | positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    (digit)$ | all          | Specifies the absolute argument number
 *             |              | for this field. Absolute and relative
 *             |              | argument numbers cannot be mixed in a
 *             |              | sprintf string.
 *    ---------+--------------+-----------------------------------------
 *     #       | beEfgGoxX    | Use an alternative format. For the
 *             |              | conversions `o', `x', `X', and `b',
 *             |              | prefix the result with ``0'', ``0x'', ``0X'',
 *             |              |  and ``0b'', respectively. For `e',
 *             |              | `E', `f', `g', and 'G', force a decimal
 *             |              | point to be added, even if no digits follow.
 *             |              | For `g' and 'G', do not remove trailing zeros.
 *    ---------+--------------+-----------------------------------------
 *    +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
 *    ---------+--------------+-----------------------------------------
 *    -        | all          | Left-justify the result of this conversion.
 *    ---------+--------------+-----------------------------------------
 *    0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
 *    ---------+--------------+-----------------------------------------
 *    *        | all          | Use the next argument as the field width.
 *             |              | If negative, left-justify the result. If the
 *             |              | asterisk is followed by a number and a dollar
 *             |              | sign, use the indicated argument as the width.
 *
 *
 *  The field width is an optional integer, followed optionally by a
 *  period and a precision. The width specifies the minimum number of
 *  characters that will be written to the result for this field. For
 *  numeric fields, the precision controls the number of decimal places
 *  displayed. For string fields, the precision determines the maximum
 *  number of characters to be copied from the string. (Thus, the format
 *  sequence <code>%10.10s</code> will always contribute exactly ten
 *  characters to the result.)
 *
 *  The field types are:
 *
 *      Field |  Conversion
 *      ------+--------------------------------------------------------------
 *        b   | Convert argument as a binary number.
 *        c   | Argument is the numeric code for a single character.
 *        d   | Convert argument as a decimal number.
 *        E   | Equivalent to `e', but uses an uppercase E to indicate
 *            | the exponent.
 *        e   | Convert floating point argument into exponential notation
 *            | with one digit before the decimal point. The precision
 *            | determines the number of fractional digits (defaulting to six).
 *        f   | Convert floating point argument as [-]ddd.ddd,
 *            |  where the precision determines the number of digits after
 *            | the decimal point.
 *        G   | Equivalent to `g', but use an uppercase `E' in exponent form.
 *        g   | Convert a floating point number using exponential form
 *            | if the exponent is less than -4 or greater than or
 *            | equal to the precision, or in d.dddd form otherwise.
 *        i   | Identical to `d'.
 *        o   | Convert argument as an octal number.
 *        p   | The valuing of argument.inspect.
 *        s   | Argument is a string to be substituted. If the format
 *            | sequence contains a precision, at most that many characters
 *            | will be copied.
 *        u   | Treat argument as an unsigned decimal number. Negative integers
 *            | are displayed as a 32 bit two's complement plus one for the
 *            | underlying architecture; that is, 2 ** 32 + n.  However, since
 *            | Ruby has no inherent limit on bits used to represent the
 *            | integer, this value is preceded by two dots (..) in order to
 *            | indicate a infinite number of leading sign bits.
 *        X   | Convert argument as a hexadecimal number using uppercase
 *            | letters. Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'FF's.
 *        x   | Convert argument as a hexadecimal number.
 *            | Negative numbers will be displayed with two
 *            | leading periods (representing an infinite string of
 *            | leading 'ff's.
 *
 *  Examples:
 *
 *     sprintf("%d %04x", 123, 123)               #=> "123 007b"
 *     sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
 *     sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
 *     sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
 *     sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
 *     sprintf("%u", -123)                        #=> "..4294967173"
 */

VALUE
rb_f_sprintf(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fmt;
    const char *p, *end;
    char *buf;
    int blen, bsiz;
    VALUE result;

    int width, prec, flags = FNONE;
    int nextarg = 1;
    int posarg = 0;
    int tainted = 0;
    VALUE nextvalue;
    VALUE tmp;
    VALUE str;

#define CHECK_FOR_WIDTH(f)				 \
    if ((f) & FWIDTH) {					 \
    rb_raise(rb_eArgError, "width given twice");	 \
    }							 \
    if ((f) & FPREC0) {					 \
    rb_raise(rb_eArgError, "width after precision"); \
    }
#define CHECK_FOR_FLAGS(f)				 \
    if ((f) & FWIDTH) {					 \
    rb_raise(rb_eArgError, "flag after width");	 \
    }							 \
    if ((f) & FPREC0) {					 \
    rb_raise(rb_eArgError, "flag after precision"); \
    }

    fmt = GETNTHARG(0);
    if (OBJ_TAINTED(fmt)) tainted = 1;
    StringValue(fmt);
    fmt = rb_str_new4(fmt);
    p = RSTRING(fmt)->ptr;
    end = p + RSTRING(fmt)->len;
    blen = 0;
    bsiz = 120;
    result = rb_str_buf_new(bsiz);
    buf = RSTRING(result)->ptr;

    for (; p < end; p++) {
    const char *t;
    int n;

    for (t = p; t < end && *t != '%'; t++) ;
    PUSH(p, t - p);
    if (t >= end) {
        /* end of fmt string */
        goto sprint_exit;
    }
    p = t + 1;		/* skip `%' */

    width = prec = -1;
    nextvalue = Qundef;
      retry:
    switch (*p) {
      default:
        if (ISPRINT(*p))
        rb_raise(rb_eArgError, "malformed format string - %%%c", *p);
        else
        rb_raise(rb_eArgError, "malformed format string");
        break;

      case ' ':
        CHECK_FOR_FLAGS(flags);
        flags |= FSPACE;
        p++;
        goto retry;

      case '#':
        CHECK_FOR_FLAGS(flags);
        flags |= FSHARP;
        p++;
        goto retry;

      case '+':
        CHECK_FOR_FLAGS(flags);
        flags |= FPLUS;
        p++;
        goto retry;

      case '-':
        CHECK_FOR_FLAGS(flags);
        flags |= FMINUS;
        p++;
        goto retry;

      case '0':
        CHECK_FOR_FLAGS(flags);
        flags |= FZERO;
        p++;
        goto retry;

      case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        n = 0;
        GETNUM(n, width);
        if (*p == '$') {
        if (nextvalue != Qundef) {
            rb_raise(rb_eArgError, "value given twice - %d$", n);
        }
        nextvalue = GETPOSARG(n);
        p++;
        goto retry;
        }
        CHECK_FOR_WIDTH(flags);
        width = n;
        flags |= FWIDTH;
        goto retry;

      case '*':
        CHECK_FOR_WIDTH(flags);
        flags |= FWIDTH;
        GETASTER(width);
        if (width < 0) {
        flags |= FMINUS;
        width = -width;
        }
        p++;
        goto retry;

      case '.':
        if (flags & FPREC0) {
        rb_raise(rb_eArgError, "precision given twice");
        }
        flags |= FPREC|FPREC0;

        prec = 0;
        p++;
        if (*p == '*') {
        GETASTER(prec);
        if (prec < 0) {	/* ignore negative precision */
            flags &= ~FPREC;
        }
        p++;
        goto retry;
        }

        GETNUM(prec, precision);
        goto retry;

      case '\n':
      case '\0':
        p--;
      case '%':
        if (flags != FNONE) {
        rb_raise(rb_eArgError, "illegal format character - %%");
        }
        PUSH("%", 1);
        break;

      case 'c':
        {
        VALUE val = GETARG();
        char c;

        if (!(flags & FMINUS))
            while (--width > 0)
            PUSH(" ", 1);
        c = NUM2INT(val) & 0xff;
        PUSH(&c, 1);
        while (--width > 0)
            PUSH(" ", 1);
        }
        break;

      case 's':
      case 'p':
        {
        VALUE arg = GETARG();
        long len;

        if (*p == 'p') arg = rb_inspect(arg);
        str = rb_obj_as_string(arg);
        if (OBJ_TAINTED(str)) tainted = 1;
        len = RSTRING(str)->len;
        if (flags&FPREC) {
            if (prec < len) {
            len = prec;
            }
        }
        /* need to adjust multi-byte string pos */
        if (flags&FWIDTH) {
            if (width > len) {
            CHECK(width);
            width -= len;
            if (!(flags&FMINUS)) {
                while (width--) {
                buf[blen++] = ' ';
                }
            }
            memcpy(&buf[blen], RSTRING_PTR(str), len);
            blen += len;
            if (flags&FMINUS) {
                while (width--) {
                buf[blen++] = ' ';
                }
            }
            break;
            }
        }
        PUSH(RSTRING(str)->ptr, len);
        }
        break;

      case 'd':
      case 'i':
      case 'o':
      case 'x':
      case 'X':
      case 'b':
      case 'B':
      case 'u':
        {
        volatile VALUE val = GETARG();
        char fbuf[32], nbuf[64], *s, *t;
        const char *prefix = 0;
        int sign = 0;
        char sc = 0;
        long v = 0;
        int base, bignum = 0;
        int len, pos;
        VALUE tmp;
                volatile VALUE tmp1;

        switch (*p) {
          case 'd':
          case 'i':
            sign = 1; break;
          case 'o':
          case 'x':
          case 'X':
          case 'b':
          case 'B':
          case 'u':
          default:
            if (flags&(FPLUS|FSPACE)) sign = 1;
            break;
        }
        if (flags & FSHARP) {
            switch (*p) {
              case 'o':
            prefix = "0"; break;
              case 'x':
            prefix = "0x"; break;
              case 'X':
            prefix = "0X"; break;
              case 'b':
            prefix = "0b"; break;
              case 'B':
            prefix = "0B"; break;
            }
            if (prefix) {
            width -= strlen(prefix);
            }
        }

          bin_retry:
        switch (TYPE(val)) {
          case T_FLOAT:
            val = rb_dbl2big(RFLOAT(val)->value);
            if (FIXNUM_P(val)) goto bin_retry;
            bignum = 1;
            break;
          case T_STRING:
            val = rb_str_to_inum(val, 0, Qtrue);
            goto bin_retry;
          case T_BIGNUM:
            bignum = 1;
            break;
          case T_FIXNUM:
            v = FIX2LONG(val);
            break;
          default:
            val = rb_Integer(val);
            goto bin_retry;
        }

        switch (*p) {
          case 'o':
            base = 8; break;
          case 'x':
          case 'X':
            base = 16; break;
          case 'b':
          case 'B':
            base = 2; break;
          case 'u':
          case 'd':
          case 'i':
          default:
            base = 10; break;
        }

        if (!bignum) {
            if (base == 2) {
            val = rb_int2big(v);
            goto bin_retry;
            }
            if (sign) {
            char c = *p;
            if (c == 'i') c = 'd'; /* %d and %i are identical */
            if (v < 0) {
                v = -v;
                sc = '-';
                width--;
            }
            else if (flags & FPLUS) {
                sc = '+';
                width--;
            }
            else if (flags & FSPACE) {
                sc = ' ';
                width--;
            }
            sprintf(fbuf, "%%l%c", c);
            sprintf(nbuf, fbuf, v);
            s = nbuf;
            goto format_integer;
            }
            s = nbuf;
            if (v < 0) {
            if (base == 10) {
                rb_warning("negative number for %%u specifier");
            }
            if (!(flags&(FPREC|FZERO))) {
                strcpy(s, "..");
                s += 2;
            }
            }
            sprintf(fbuf, "%%l%c", *p == 'X' ? 'x' : *p);
            sprintf(s, fbuf, v);
            if (v < 0) {
            char d = 0;

            remove_sign_bits(s, base);
            switch (base) {
              case 16:
                d = 'f'; break;
              case 8:
                d = '7'; break;
            }
            if (d && *s != d) {
                memmove(s+1, s, strlen(s)+1);
                *s = d;
            }
            }
            s = nbuf;
            goto format_integer;
        }

        if (sign) {
            tmp = rb_big2str(val, base);
            s = RSTRING(tmp)->ptr;
            if (s[0] == '-') {
            s++;
            sc = '-';
                        width--;
            }
            else if (flags & FPLUS) {
            sc = '+';
                        width--;
            }
            else if (flags & FSPACE) {
            sc = ' ';
                        width--;
            }
            goto format_integer;
        }
        if (!RBIGNUM(val)->sign) {
            val = rb_big_clone(val);
            rb_big_2comp(val);
        }
        tmp1 = tmp = rb_big2str0(val, base, RBIGNUM(val)->sign);
        s = RSTRING(tmp)->ptr;
        if (*s == '-') {
            if (base == 10) {
            rb_warning("negative number for %%u specifier");
            }
            remove_sign_bits(++s, base);
            tmp = rb_str_new(0, 3+strlen(s));
            t = RSTRING(tmp)->ptr;
            if (!(flags&(FPREC|FZERO))) {
            strcpy(t, "..");
            t += 2;
            }
            switch (base) {
              case 16:
            if (s[0] != 'f') strcpy(t++, "f"); break;
              case 8:
            if (s[0] != '7') strcpy(t++, "7"); break;
              case 2:
            if (s[0] != '1') strcpy(t++, "1"); break;
            }
            strcpy(t, s);
            bignum = 2;
        }
        s = RSTRING(tmp)->ptr;

          format_integer:
        pos = -1;
        len = strlen(s);

        if (*p == 'X') {
            char *pp = s;
            while (*pp) {
            *pp = toupper(*pp);
            pp++;
            }
        }
        if ((flags&(FZERO|FPREC)) == FZERO) {
            prec = width;
            width = 0;
        }
        else {
            if (prec < len) prec = len;
            width -= prec;
        }
        if (!(flags&FMINUS)) {
            CHECK(width);
            while (width-- > 0) {
            buf[blen++] = ' ';
            }
        }
        if (sc) PUSH(&sc, 1);
        if (prefix) {
            int plen = strlen(prefix);
            PUSH(prefix, plen);
        }
        CHECK(prec - len);
        if (!bignum && v < 0) {
            char c = sign_bits(base, p);
            while (len < prec--) {
            buf[blen++] = c;
            }
        }
        else {
            char c;

            if (!sign && bignum && !RBIGNUM(val)->sign)
            c = sign_bits(base, p);
            else
            c = '0';
            while (len < prec--) {
            buf[blen++] = c;
            }
        }
        PUSH(s, len);
        CHECK(width);
        while (width-- > 0) {
            buf[blen++] = ' ';
        }
        }
        break;

      case 'f':
      case 'g':
      case 'G':
      case 'e':
      case 'E':
        {
        VALUE val = GETARG();
        double fval;
        int i, need = 6;
        char fbuf[32];

        fval = RFLOAT(rb_Float(val))->value;
#if defined(_WIN32) && !defined(__BORLANDC__)
        if (isnan(fval) || isinf(fval)) {
            char *expr;

            if  (isnan(fval)) {
            expr = "NaN";
            }
            else {
            expr = "Inf";
            }
            need = strlen(expr);
            if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
            need++;
            if ((flags & FWIDTH) && need < width)
            need = width;

            CHECK(need);
            sprintf(&buf[blen], "%*s", need, "");
            if (flags & FMINUS) {
            if (!isnan(fval) && fval < 0.0)
                buf[blen++] = '-';
            else if (flags & FPLUS)
                buf[blen++] = '+';
            else if (flags & FSPACE)
                blen++;
            strncpy(&buf[blen], expr, strlen(expr));
            }
            else if (flags & FZERO) {
            if (!isnan(fval) && fval < 0.0) {
                buf[blen++] = '-';
                need--;
            }
            else if (flags & FPLUS) {
                buf[blen++] = '+';
                need--;
            }
            else if (flags & FSPACE) {
                blen++;
                need--;
            }
            while (need-- - strlen(expr) > 0) {
                buf[blen++] = '0';
            }
            strncpy(&buf[blen], expr, strlen(expr));
            }
            else {
            if (!isnan(fval) && fval < 0.0)
                buf[blen + need - strlen(expr) - 1] = '-';
            else if (flags & FPLUS)
                buf[blen + need - strlen(expr) - 1] = '+';
            strncpy(&buf[blen + need - strlen(expr)], expr,
                strlen(expr));
            }
            blen += strlen(&buf[blen]);
            break;
        }
#endif	/* defined(_WIN32) && !defined(__BORLANDC__) */
        fmt_setup(fbuf, *p, flags, width, prec);
        need = 0;
        if (*p != 'e' && *p != 'E') {
            i = INT_MIN;
            frexp(fval, &i);
            if (i > 0)
            need = BIT_DIGITS(i);
        }
        need += (flags&FPREC) ? prec : 6;
        if ((flags&FWIDTH) && need < width)
            need = width;
        need += 20;

        CHECK(need);
        sprintf(&buf[blen], fbuf, fval);
        blen += strlen(&buf[blen]);
        }
        break;
    }
    flags = FNONE;
    }

  sprint_exit:
    /* XXX - We cannot validiate the number of arguments if (digit)$ style used.
     */
    if (posarg >= 0 && nextarg < argc) {
    const char *mesg = "too many arguments for format string";
    if (RTEST(ruby_debug)) rb_raise(rb_eArgError, mesg);
    if (RTEST(ruby_verbose)) rb_warn(mesg);
    }
    rb_str_resize(result, blen);

    if (tainted) OBJ_TAINT(result);
    return result;
}


Integer (Kernel)

/*
 *  call-seq:
 *     Integer(arg)    => integer
 *
 *  Converts <i>arg</i> to a <code>Fixnum</code> or <code>Bignum</code>.
 *  Numeric types are converted directly (with floating point numbers
 *  being truncated). If <i>arg</i> is a <code>String</code>, leading
 *  radix indicators (<code>0</code>, <code>0b</code>, and
 *  <code>0x</code>) are honored. Others are converted using
 *  <code>to_int</code> and <code>to_i</code>. This behavior is
 *  different from that of <code>String#to_i</code>.
 *
 *     Integer(123.999)    #=> 123
 *     Integer("0x1a")     #=> 26
 *     Integer(Time.new)   #=> 1049896590
 */

static VALUE
rb_f_integer(obj, arg)
    VALUE obj, arg;
{
    return rb_Integer(arg);
}


Float (Kernel)

/*
 *  call-seq:
 *     Float(arg)    => float
 *
 *  Returns <i>arg</i> converted to a float. Numeric types are converted
 *  directly, the rest are converted using <i>arg</i>.to_f. As of Ruby
 *  1.8, converting <code>nil</code> generates a <code>TypeError</code>.
 *
 *     Float(1)           #=> 1.0
 *     Float("123.456")   #=> 123.456
 */

static VALUE
rb_f_float(obj, arg)
    VALUE obj, arg;
{
    return rb_Float(arg);
}


String (Kernel)

/*
 *  call-seq:
 *     String(arg)   => string
 *
 *  Converts <i>arg</i> to a <code>String</code> by calling its
 *  <code>to_s</code> method.
 *
 *     String(self)        #=> "main"
 *     String(self.class   #=> "Object"
 *     String(123456)      #=> "123456"
 */

static VALUE
rb_f_string(obj, arg)
    VALUE obj, arg;
{
    return rb_String(arg);
}


Array (Kernel)

/*
 *  call-seq:
 *     Array(arg)    => array
 *
 *  Returns <i>arg</i> as an <code>Array</code>. First tries to call
 *  <i>arg</i><code>.to_ary</code>, then <i>arg</i><code>.to_a</code>.
 *  If both fail, creates a single element array containing <i>arg</i>
 *  (unless <i>arg</i> is <code>nil</code>).
 *
 *     Array(1..5)   #=> [1, 2, 3, 4, 5]
 */

static VALUE
rb_f_array(obj, arg)
    VALUE obj, arg;
{
    return rb_Array(arg);
}


syscall (Kernel)

/*
 *  call-seq:
 *     syscall(fixnum [, args...])   => integer
 *
 *  Calls the operating system function identified by _fixnum_,
 *  passing in the arguments, which must be either +String+
 *  objects, or +Integer+ objects that ultimately fit within
 *  a native +long+. Up to nine parameters may be passed (14
 *  on the Atari-ST). The function identified by _fixnum_ is system
 *  dependent. On some Unix systems, the numbers may be obtained from a
 *  header file called <code>syscall.h</code>.
 *
 *     syscall 4, 1, "hello\n", 6   # '4' is write(2) on our box
 *
 *  <em>produces:</em>
 *
 *     hello
 */

static VALUE
rb_f_syscall(argc, argv)
    int argc;
    VALUE *argv;
{
#if defined(HAVE_SYSCALL) && !defined(__CHECKER__)
#ifdef atarist
    unsigned long arg[14]; /* yes, we really need that many ! */
#else
    unsigned long arg[8];
#endif
    int retval = -1;
    int i = 1;
    int items = argc - 1;

    /* This probably won't work on machines where sizeof(long) != sizeof(int)
     * or where sizeof(long) != sizeof(char*).  But such machines will
     * not likely have syscall implemented either, so who cares?
     */

    rb_secure(2);
    if (argc == 0)
        rb_raise(rb_eArgError, "too few arguments for syscall");
    if (argc > sizeof(arg) / sizeof(arg[0]))
        rb_raise(rb_eArgError, "too many arguments for syscall");
    arg[0] = NUM2LONG(argv[0]); argv++;
    while (items--) {
        VALUE v = rb_check_string_type(*argv);

        if (!NIL_P(v)) {
            StringValue(v);
            rb_str_modify(v);
            arg[i] = (unsigned long)RSTRING(v)->ptr;
        }
        else {
            arg[i] = (unsigned long)NUM2LONG(*argv);
        }
        argv++;
        i++;
    }
    TRAP_BEG;
    switch (argc) {
      case 1:
        retval = syscall(arg[0]);
        break;
      case 2:
        retval = syscall(arg[0],arg[1]);
        break;
      case 3:
        retval = syscall(arg[0],arg[1],arg[2]);
        break;
      case 4:
        retval = syscall(arg[0],arg[1],arg[2],arg[3]);
        break;
      case 5:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4]);
        break;
      case 6:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
        break;
      case 7:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
        break;
      case 8:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7]);
        break;
#ifdef atarist
      case 9:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7], arg[8]);
        break;
      case 10:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7], arg[8], arg[9]);
        break;
      case 11:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7], arg[8], arg[9], arg[10]);
        break;
      case 12:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7], arg[8], arg[9], arg[10], arg[11]);
        break;
      case 13:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7], arg[8], arg[9], arg[10], arg[11], arg[12]);
        break;
      case 14:
        retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
          arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13]);
        break;
#endif /* atarist */
    }
    TRAP_END;
    if (retval < 0) rb_sys_fail(0);
    return INT2NUM(retval);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


open (Kernel)

/*
 *  call-seq:
 *     open(path [, mode [, perm]] )                => io or nil
 *     open(path [, mode [, perm]] ) {|io| block }  => obj
 *
 *  Creates an <code>IO</code> object connected to the given stream,
 *  file, or subprocess.
 *
 *  If <i>path</i> does not start with a pipe character
 *  (``<code>|</code>''), treat it as the name of a file to open using
 *  the specified mode (defaulting to ``<code>r</code>''). (See the table
 *  of valid modes on page 331.) If a file is being created, its initial
 *  permissions may be set using the integer third parameter.
 *
 *  If a block is specified, it will be invoked with the
 *  <code>File</code> object as a parameter, and the file will be
 *  automatically closed when the block terminates. The call
 *  returns the value of the block.
 *
 *  If <i>path</i> starts with a pipe character, a subprocess is
 *  created, connected to the caller by a pair of pipes. The returned
 *  <code>IO</code> object may be used to write to the standard input
 *  and read from the standard output of this subprocess. If the command
 *  following the ``<code>|</code>'' is a single minus sign, Ruby forks,
 *  and this subprocess is connected to the parent. In the subprocess,
 *  the <code>open</code> call returns <code>nil</code>. If the command
 *  is not ``<code>-</code>'', the subprocess runs the command. If a
 *  block is associated with an <code>open("|-")</code> call, that block
 *  will be run twice---once in the parent and once in the child. The
 *  block parameter will be an <code>IO</code> object in the parent and
 *  <code>nil</code> in the child. The parent's <code>IO</code> object
 *  will be connected to the child's <code>$stdin</code> and
 *  <code>$stdout</code>. The subprocess will be terminated at the end
 *  of the block.
 *
 *     open("testfile") do |f|
 *       print f.gets
 *     end
 *
 *  <em>produces:</em>
 *
 *     This is line one
 *
 *  Open a subprocess and read its output:
 *
 *     cmd = open("|date")
 *     print cmd.gets
 *     cmd.close
 *
 *  <em>produces:</em>
 *
 *     Wed Apr  9 08:56:31 CDT 2003
 *
 *  Open a subprocess running the same Ruby program:
 *
 *     f = open("|-", "w+")
 *     if f == nil
 *       puts "in Child"
 *       exit
 *     else
 *       puts "Got: #{f.gets}"
 *     end
 *
 *  <em>produces:</em>
 *
 *     Got: in Child
 *
 *  Open a subprocess using a block to receive the I/O object:
 *
 *     open("|-") do |f|
 *       if f == nil
 *         puts "in Child"
 *       else
 *         puts "Got: #{f.gets}"
 *       end
 *     end
 *
 *  <em>produces:</em>
 *
 *     Got: in Child
 */

static VALUE
rb_f_open(argc, argv)
    int argc;
    VALUE *argv;
{
    if (argc >= 1) {
        char *str = StringValuePtr(argv[0]);

        if (str[0] == '|') {
            VALUE tmp = rb_str_new(str+1, RSTRING(argv[0])->len-1);
            OBJ_INFECT(tmp, argv[0]);
            argv[0] = tmp;
            return rb_io_s_popen(argc, argv, rb_cIO);
        }
    }
    return rb_io_s_open(argc, argv, rb_cFile);
}


printf (Kernel)

/*
 *  call-seq:
 *     printf(io, string [, obj ... ] )    => nil
 *     printf(string [, obj ... ] )        => nil
 *
 *  Equivalent to:
 *     io.write(sprintf(string, obj, ...)
 *  or
 *     $stdout.write(sprintf(string, obj, ...)
 */

static VALUE
rb_f_printf(argc, argv)
    int argc;
    VALUE argv[];
{
    VALUE out;

    if (argc == 0) return Qnil;
    if (TYPE(argv[0]) == T_STRING) {
        out = rb_stdout;
    }
    else {
        out = argv[0];
        argv++;
        argc--;
    }
    rb_io_write(out, rb_f_sprintf(argc, argv));

    return Qnil;
}


print (Kernel)

/*
 *  call-seq:
 *     print(obj, ...)    => nil
 *
 *  Prints each object in turn to <code>$stdout</code>. If the output
 *  field separator (<code>$,</code>) is not +nil+, its
 *  contents will appear between each field. If the output record
 *  separator (<code>$\\</code>) is not +nil+, it will be
 *  appended to the output. If no arguments are given, prints
 *  <code>$_</code>. Objects that aren't strings will be converted by
 *  calling their <code>to_s</code> method.
 *
 *     print "cat", [1,2,3], 99, "\n"
 *     $, = ", "
 *     $\ = "\n"
 *     print "cat", [1,2,3], 99
 *
 *  <em>produces:</em>
 *
 *     cat12399
 *     cat, 1, 2, 3, 99
 */

static VALUE
rb_f_print(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_io_print(argc, argv, rb_stdout);
    return Qnil;
}


putc (Kernel)

/*
 *  call-seq:
 *     putc(int)   => int
 *
 *  Equivalent to:
 *
 *    $stdout.putc(int)
 */

static VALUE
rb_f_putc(recv, ch)
    VALUE recv, ch;
{
    return rb_io_putc(rb_stdout, ch);
}


puts (Kernel)

/*
 *  call-seq:
 *     puts(obj, ...)    => nil
 *
 *  Equivalent to
 *
 *      $stdout.puts(obj, ...)
 */

static VALUE
rb_f_puts(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_io_puts(argc, argv, rb_stdout);
    return Qnil;
}


gets (Kernel)

/*
 *  call-seq:
 *     gets(separator=$/)    => string or nil
 *
 *  Returns (and assigns to <code>$_</code>) the next line from the list
 *  of files in +ARGV+ (or <code>$*</code>), or from standard
 *  input if no files are present on the command line. Returns
 *  +nil+ at end of file. The optional argument specifies the
 *  record separator. The separator is included with the contents of
 *  each record. A separator of +nil+ reads the entire
 *  contents, and a zero-length separator reads the input one paragraph
 *  at a time, where paragraphs are divided by two consecutive newlines.
 *  If multiple filenames are present in +ARGV+,
 *  +gets(nil)+ will read the contents one file at a time.
 *
 *     ARGV << "testfile"
 *     print while gets
 *
 *  <em>produces:</em>
 *
 *     This is line one
 *     This is line two
 *     This is line three
 *     And so on...
 *
 *  The style of programming using <code>$_</code> as an implicit
 *  parameter is gradually losing favor in the Ruby community.
 */

static VALUE
rb_f_gets(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE line;

    if (!next_argv()) return Qnil;
    if (TYPE(current_file) != T_FILE) {
        line = rb_funcall3(current_file, rb_intern("gets"), argc, argv);
    }
    else {
        line = argf_getline(argc, argv);
    }
    rb_lastline_set(line);
    return line;
}


readline (Kernel)

/*
 *  call-seq:
 *     readline(separator=$/)   => string
 *
 *  Equivalent to <code>Kernel::gets</code>, except
 *  +readline+ raises +EOFError+ at end of file.
 */

static VALUE
rb_f_readline(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE line;

    if (!next_argv()) rb_eof_error();
    ARGF_FORWARD(argc, argv);
    line = rb_f_gets(argc, argv);
    if (NIL_P(line)) {
        rb_eof_error();
    }

    return line;
}


getc (Kernel)

/*
 * obsolete
 */

static VALUE
rb_f_getc()
{
    rb_warn("getc is obsolete; use STDIN.getc instead");
    if (TYPE(rb_stdin) != T_FILE) {
        return rb_funcall3(rb_stdin, rb_intern("getc"), 0, 0);
    }
    return rb_io_getc(rb_stdin);
}


select (Kernel)

/*
 *  call-seq:
 *     IO.select(read_array
 *               [, write_array
 *               [, error_array
 *               [, timeout]]] ) =>  array  or  nil
 *
 *  See <code>Kernel#select</code>.
 */

static VALUE
rb_f_select(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE read, write, except, timeout, res, list;
    fd_set rset, wset, eset, pset;
    fd_set *rp, *wp, *ep;
    struct timeval *tp, timerec;
    OpenFile *fptr;
    long i;
    int max = 0, n;
    int interrupt_flag = 0;
    int pending = 0;

    rb_scan_args(argc, argv, "13", &read, &write, &except, &timeout);
    if (NIL_P(timeout)) {
        tp = 0;
    }
    else {
        timerec = rb_time_interval(timeout);
        tp = &timerec;
    }

    FD_ZERO(&pset);
    if (!NIL_P(read)) {
        Check_Type(read, T_ARRAY);
        rp = &rset;
        FD_ZERO(rp);
        for (i=0; i<RARRAY(read)->len; i++) {
            GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
            FD_SET(fileno(fptr->f), rp);
            if (READ_DATA_PENDING(fptr->f)) { /* check for buffered data */
                pending++;
                FD_SET(fileno(fptr->f), &pset);
            }
            if (max < fileno(fptr->f)) max = fileno(fptr->f);
        }
        if (pending) {         /* no blocking if there's buffered data */
            timerec.tv_sec = timerec.tv_usec = 0;
            tp = &timerec;
        }
    }
    else
        rp = 0;

    if (!NIL_P(write)) {
        Check_Type(write, T_ARRAY);
        wp = &wset;
        FD_ZERO(wp);
        for (i=0; i<RARRAY(write)->len; i++) {
            GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
            FD_SET(fileno(fptr->f), wp);
            if (max < fileno(fptr->f)) max = fileno(fptr->f);
            if (fptr->f2) {
                FD_SET(fileno(fptr->f2), wp);
                if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
            }
        }
    }
    else
        wp = 0;

    if (!NIL_P(except)) {
        Check_Type(except, T_ARRAY);
        ep = &eset;
        FD_ZERO(ep);
        for (i=0; i<RARRAY(except)->len; i++) {
            GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
            FD_SET(fileno(fptr->f), ep);
            if (max < fileno(fptr->f)) max = fileno(fptr->f);
            if (fptr->f2) {
                FD_SET(fileno(fptr->f2), ep);
                if (max < fileno(fptr->f2)) max = fileno(fptr->f2);
            }
        }
    }
    else {
        ep = 0;
    }

    max++;

    n = rb_thread_select(max, rp, wp, ep, tp);
    if (n < 0) {
        rb_sys_fail(0);
    }
    if (!pending && n == 0) return Qnil; /* returns nil on timeout */

    res = rb_ary_new2(3);
    rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
    rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
    rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));

    if (interrupt_flag == 0) {
        if (rp) {
            list = RARRAY(res)->ptr[0];
            for (i=0; i< RARRAY(read)->len; i++) {
                GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
                if (FD_ISSET(fileno(fptr->f), rp)
                    || FD_ISSET(fileno(fptr->f), &pset)) {
                    rb_ary_push(list, rb_ary_entry(read, i));
                }
            }
        }

        if (wp) {
            list = RARRAY(res)->ptr[1];
            for (i=0; i< RARRAY(write)->len; i++) {
                GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
                if (FD_ISSET(fileno(fptr->f), wp)) {
                    rb_ary_push(list, rb_ary_entry(write, i));
                }
                else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), wp)) {
                    rb_ary_push(list, rb_ary_entry(write, i));
                }
            }
        }

        if (ep) {
            list = RARRAY(res)->ptr[2];
            for (i=0; i< RARRAY(except)->len; i++) {
                GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
                if (FD_ISSET(fileno(fptr->f), ep)) {
                    rb_ary_push(list, rb_ary_entry(except, i));
                }
                else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), ep)) {
                    rb_ary_push(list, rb_ary_entry(except, i));
                }
            }
        }
    }

    return res;                 /* returns an empty array on interrupt */
}


readlines (Kernel)

/*
 *  call-seq:
 *     readlines(separator=$/)    => array
 *
 *  Returns an array containing the lines returned by calling
 *  <code>Kernel.gets(<i>separator</i>)</code> until the end of file.
 */

static VALUE
rb_f_readlines(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE line, ary;

    NEXT_ARGF_FORWARD(argc, argv);
    ary = rb_ary_new();
    while (!NIL_P(line = argf_getline(argc, argv))) {
        rb_ary_push(ary, line);
    }

    return ary;
}


` (Kernel)

/*
 *  call-seq:
 *     `cmd`    => string
 *
 *  Returns the standard output of running _cmd_ in a subshell.
 *  The built-in syntax <code>%x{...}</code> uses
 *  this method. Sets <code>$?</code> to the process status.
 *
 *     `date`                   #=> "Wed Apr  9 08:56:30 CDT 2003\n"
 *     `ls testdir`.split[1]    #=> "main.rb"
 *     `echo oops && exit 99`   #=> "oops\n"
 *     $?.exitstatus            #=> 99
 */

static VALUE
rb_f_backquote(obj, str)
    VALUE obj, str;
{
    volatile VALUE port;
    VALUE result;
    OpenFile *fptr;

    SafeStringValue(str);
    port = pipe_open(str, 0, "r");
    if (NIL_P(port)) return rb_str_new(0,0);

    GetOpenFile(port, fptr);
    result = read_all(fptr, remain_size(fptr), Qnil);
    rb_io_close(port);

    return result;
}


p (Kernel)

/*
 *  call-seq:
 *     p(obj, ...)    => nil
 *
 *  For each object, directly writes
 *  _obj_.+inspect+ followed by the current output
 *  record separator to the program's standard output.
 *
 *     S = Struct.new(:name, :state)
 *     s = S['dave', 'TX']
 *     p s
 *
 *  <em>produces:</em>
 *
 *     #<S name="dave", state="TX">
 */

static VALUE
rb_f_p(argc, argv)
    int argc;
    VALUE *argv;
{
    int i;

    for (i=0; i<argc; i++) {
        rb_p(argv[i]);
    }
    if (TYPE(rb_stdout) == T_FILE) {
        rb_io_flush(rb_stdout);
    }
    return Qnil;
}


sub (Kernel)

/*
 *  call-seq:
 *     sub(pattern, replacement)   => $_
 *     sub(pattern) { block }      => $_
 *
 *  Equivalent to <code>$_.sub(<i>args</i>)</code>, except that
 *  <code>$_</code> will be updated if substitution occurs.
 */

static VALUE
rb_f_sub(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str = rb_str_dup(uscore_get());

    if (NIL_P(rb_str_sub_bang(argc, argv, str)))
        return str;
    rb_lastline_set(str);
    return str;
}


gsub (Kernel)

/*
 *  call-seq:
 *     gsub(pattern, replacement)    => string
 *     gsub(pattern) {|...| block }  => string
 *
 *  Equivalent to <code>$_.gsub...</code>, except that <code>$_</code>
 *  receives the modified result.
 *
 *     $_ = "quick brown fox"
 *     gsub /[aeiou]/, '*'   #=> "q**ck br*wn f*x"
 *     $_                    #=> "q**ck br*wn f*x"
 */

static VALUE
rb_f_gsub(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str = rb_str_dup(uscore_get());

    if (NIL_P(rb_str_gsub_bang(argc, argv, str)))
        return str;
    rb_lastline_set(str);
    return str;
}


sub! (Kernel)

/*
 *  call-seq:
 *     sub!(pattern, replacement)    => $_ or nil
 *     sub!(pattern) {|...| block }  => $_ or nil
 *
 *  Equivalent to <code>$_.sub!(<i>args</i>)</code>.
 */

static VALUE
rb_f_sub_bang(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_sub_bang(argc, argv, uscore_get());
}


gsub! (Kernel)

/*
 *  call-seq:
 *     gsub!(pattern, replacement)    => string or nil
 *     gsub!(pattern) {|...| block }  => string or nil
 *
 *  Equivalent to <code>Kernel::gsub</code>, except <code>nil</code> is
 *  returned if <code>$_</code> is not modified.
 *
 *     $_ = "quick brown fox"
 *     gsub! /cat/, '*'   #=> nil
 *     $_                 #=> "quick brown fox"
 */

static VALUE
rb_f_gsub_bang(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_gsub_bang(argc, argv, uscore_get());
}


chop (Kernel)

/*
 *  call-seq:
 *     chop   => string
 *
 *  Equivalent to <code>($_.dup).chop!</code>, except <code>nil</code>
 *  is never returned. See <code>String#chop!</code>.
 *
 *     a  =  "now\r\n"
 *     $_ = a
 *     chop   #=> "now"
 *     $_     #=> "now"
 *     chop   #=> "no"
 *     chop   #=> "n"
 *     chop   #=> ""
 *     chop   #=> ""
 *     a      #=> "now\r\n"
 */

static VALUE
rb_f_chop()
{
    VALUE str = uscore_get();

    if (RSTRING(str)->len > 0) {
        str = rb_str_dup(str);
        rb_str_chop_bang(str);
        rb_lastline_set(str);
    }
    return str;
}


chop! (Kernel)

/*
 *  call-seq:
 *     chop!    => $_ or nil
 *
 *  Equivalent to <code>$_.chop!</code>.
 *
 *     a  = "now\r\n"
 *     $_ = a
 *     chop!   #=> "now"
 *     chop!   #=> "no"
 *     chop!   #=> "n"
 *     chop!   #=> ""
 *     chop!   #=> nil
 *     $_      #=> ""
 *     a       #=> ""
 */

static VALUE
rb_f_chop_bang(str)
    VALUE str;
{
    return rb_str_chop_bang(uscore_get());
}


chomp (Kernel)

/*
 *  call-seq:
 *     chomp            => $_
 *     chomp(string)    => $_
 *
 *  Equivalent to <code>$_ = $_.chomp(<em>string</em>)</code>. See
 *  <code>String#chomp</code>.
 *
 *     $_ = "now\n"
 *     chomp         #=> "now"
 *     $_            #=> "now"
 *     chomp "ow"    #=> "n"
 *     $_            #=> "n"
 *     chomp "xxx"   #=> "n"
 *     $_            #=> "n"
 */

static VALUE
rb_f_chomp(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str = uscore_get();
    VALUE dup = rb_str_dup(str);

    if (NIL_P(rb_str_chomp_bang(argc, argv, dup)))
        return str;
    rb_lastline_set(dup);
    return dup;
}


chomp! (Kernel)

/*
 *  call-seq:
 *     chomp!             => $_ or nil
 *     chomp!(string)     => $_ or nil
 *
 *  Equivalent to <code>$_.chomp!(<em>string</em>)</code>. See
 *  <code>String#chomp!</code>
 *
 *     $_ = "now\n"
 *     chomp!       #=> "now"
 *     $_           #=> "now"
 *     chomp! "x"   #=> nil
 *     $_           #=> "now"
 */

static VALUE
rb_f_chomp_bang(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_chomp_bang(argc, argv, uscore_get());
}


split (Kernel)

/*
 *  call-seq:
 *     split([pattern [, limit]])    => array
 *
 *  Equivalent to <code>$_.split(<i>pattern</i>, <i>limit</i>)</code>.
 *  See <code>String#split</code>.
 */

static VALUE
rb_f_split(argc, argv)
    int argc;
    VALUE *argv;
{
    return rb_str_split_m(argc, argv, uscore_get());
}


scan (Kernel)

/*
 *  call-seq:
 *     scan(pattern)                   => array
 *     scan(pattern) {|///| block }    => $_
 *
 *  Equivalent to calling <code>$_.scan</code>. See
 *  <code>String#scan</code>.
 */

static VALUE
rb_f_scan(self, pat)
    VALUE self, pat;
{
    return rb_str_scan(uscore_get(), pat);
}


open (Kernel)

# File lib/open-uri.rb, line 24
  def open(name, *rest, &block) # :doc:
    if name.respond_to?(:open)
      name.open(*rest, &block)
    elsif name.respond_to?(:to_str) &&
          %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name &&
          (uri = URI.parse(name)).respond_to?(:open)
      uri.open(*rest, &block)
    else
      open_uri_original_open(name, *rest, &block)
    end
  end


Pathname (Kernel)

# File lib/pathname.rb, line 1058
  def Pathname(path) # :doc:
    Pathname.new(path)
  end


pretty_inspect (Kernel)

# File lib/pp.rb, line 50
  def pretty_inspect
    PP.pp(self, '')
  end


pp (Kernel)

# File lib/pp.rb, line 58
  def pp(*objs) # :doc:
    objs.each {|obj|
      PP.pp(obj)
    }
    nil
  end


warn (Kernel)

# File lib/soap/soap.rb, line 136
    def warn(msg)
      STDERR.puts(msg + "\n") unless $VERBOSE.nil?
    end


URI (Kernel)

# File lib/uri/common.rb, line 607
  def URI(uri_str) # :doc:
    URI.parse(uri_str)
  end


new (List)

# File lib/optparse.rb, line 520
    def initialize
      @atype = {}
      @short = OptionMap.new
      @long = OptionMap.new
      @list = []
    end


accept (List)

# File lib/optparse.rb, line 530
    def accept(t, pat = /.*/nm, &block)
      if pat
        pat.respond_to?(:match) or raise TypeError, "has no `match'"
      else
        pat = t if t.respond_to?(:match)
      end
      unless block
        block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
      end
      @atype[t] = [pat, block]
    end


reject (List)

# File lib/optparse.rb, line 545
    def reject(t)
      @atype.delete(t)
    end


prepend (List)

# File lib/optparse.rb, line 578
    def prepend(*args)
      update(*args)
      @list.unshift(args[0])
    end


append (List)

# File lib/optparse.rb, line 594
    def append(*args)
      update(*args)
      @list.push(args[0])
    end


search (List)

# File lib/optparse.rb, line 603
    def search(id, key)
      if list = __send__(id)
        val = list.fetch(key) {return nil}
        block_given? ? yield(val) : val
      end
    end


complete (List)

# File lib/optparse.rb, line 616
    def complete(id, opt, icase = false, *pat, &block)
      __send__(id).complete(opt, icase, *pat, &block)
    end


each_option (List)

# File lib/optparse.rb, line 623
    def each_option(&block)
      list.each(&block)
    end


summarize (List)

# File lib/optparse.rb, line 632
    def summarize(*args, &block)
      list.each do |opt|
        if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
          opt.summarize(*args, &block)
        elsif !opt or opt.empty?
          yield("")
        else
          opt.each(&block)
        end
      end
    end


exit_value (LocalJumpError)

/*
 * call_seq:
 *   local_jump_error.exit_value  => obj
 *
 * Returns the exit value associated with this +LocalJumpError+.
 */
static VALUE
localjump_xvalue(exc)
    VALUE exc;
{
    return rb_iv_get(exc, "@exit_value");
}


reason (LocalJumpError)

/*
 * call-seq:
 *    local_jump_error.reason   => symbol
 *
 * The reason this block was terminated:
 * :break, :redo, :retry, :next, :return, or :noreason.
 */

static VALUE
localjump_reason(exc)
    VALUE exc;
{
    return rb_iv_get(exc, "@reason");
}


new (Logger::Application)

# File lib/logger.rb, line 645
    def initialize(appname = nil)
      @appname = appname
      @log = Logger.new(STDERR)
      @log.progname = @appname
      @level = @log.level
    end


start (Logger::Application)

# File lib/logger.rb, line 655
    def start
      status = -1
      begin
        log(INFO, "Start of #{ @appname }.")
        status = run
      rescue
        log(FATAL, "Detected an exception. Stopping ... #{$!} (#{$!.class})\n" << $@.join("\n"))
      ensure
        log(INFO, "End of #{ @appname }. (status: #{ status.to_s })")
      end
      status
    end


set_log (Logger::Application)

# File lib/logger.rb, line 672
    def set_log(logdev, shift_age = 0, shift_size = 1024000)
      @log = Logger.new(logdev, shift_age, shift_size)
      @log.progname = @appname
      @log.level = @level
    end


log= (Logger::Application)

# File lib/logger.rb, line 678
    def log=(logdev)
      set_log(logdev)
    end


level= (Logger::Application)

# File lib/logger.rb, line 685
    def level=(level)
      @level = level
      @log.level = @level
    end


log (Logger::Application)

# File lib/logger.rb, line 693
    def log(severity, message = nil, &block)
      @log.add(severity, message, @appname, &block) if @log
    end


new (Logger::Formatter)

# File lib/logger.rb, line 440
    def initialize
      @datetime_format = nil
    end


call (Logger::Formatter)

# File lib/logger.rb, line 444
    def call(severity, time, progname, msg)
      Format % [severity[0..0], format_datetime(time), $$, severity, progname,
        msg2str(msg)]
    end


new (Logger::LogDevice)

# File lib/logger.rb, line 481
    def initialize(log = nil, opt = {})
      @dev = @filename = @shift_age = @shift_size = nil
      @mutex = LogDeviceMutex.new
      if log.respond_to?(:write) and log.respond_to?(:close)
        @dev = log
      else
        @dev = open_logfile(log)
        @dev.sync = true
        @filename = log
        @shift_age = opt[:shift_age] || 7
        @shift_size = opt[:shift_size] || 1048576
      end
    end


write (Logger::LogDevice)

# File lib/logger.rb, line 495
    def write(message)
      @mutex.synchronize do
        if @shift_age and @dev.respond_to?(:stat)
          begin
            check_shift_log
          rescue
            raise Logger::ShiftingError.new("Shifting failed. #{$!}")
          end
        end
        @dev.write(message)
      end
    end


close (Logger::LogDevice)

# File lib/logger.rb, line 508
    def close
      @mutex.synchronize do
        @dev.close
      end
    end


datetime_format= (Logger)

# File lib/logger.rb, line 197
  def datetime_format=(datetime_format)
    @default_formatter.datetime_format = datetime_format
  end


datetime_format (Logger)

# File lib/logger.rb, line 201
  def datetime_format
    @default_formatter.datetime_format
  end


debug? (Logger)

# File lib/logger.rb, line 217
  def debug?; @level <= DEBUG; end


info? (Logger)

# File lib/logger.rb, line 221
  def info?; @level <= INFO; end


warn? (Logger)

# File lib/logger.rb, line 225
  def warn?; @level <= WARN; end


error? (Logger)

# File lib/logger.rb, line 229
  def error?; @level <= ERROR; end


fatal? (Logger)

# File lib/logger.rb, line 233
  def fatal?; @level <= FATAL; end


new (Logger)

# File lib/logger.rb, line 256
  def initialize(logdev, shift_age = 0, shift_size = 1048576)
    @progname = nil
    @level = DEBUG
    @default_formatter = Formatter.new
    @formatter = nil
    @logdev = nil
    if logdev
      @logdev = LogDevice.new(logdev, :shift_age => shift_age,
        :shift_size => shift_size)
    end
  end


add (Logger)

# File lib/logger.rb, line 312
  def add(severity, message = nil, progname = nil, &block)
    severity ||= UNKNOWN
    if @logdev.nil? or severity < @level
      return true
    end
    progname ||= @progname
    if message.nil?
      if block_given?
        message = yield
      else
        message = progname
        progname = @progname
      end
    end
    @logdev.write(
      format_message(format_severity(severity), Time.now, progname, message))
    true
  end


<< (Logger)

# File lib/logger.rb, line 336
  def <<(msg)
    unless @logdev.nil?
      @logdev.write(msg)
    end
  end


debug (Logger)

# File lib/logger.rb, line 347
  def debug(progname = nil, &block)
    add(DEBUG, nil, progname, &block)
  end


info (Logger)

# File lib/logger.rb, line 373
  def info(progname = nil, &block)
    add(INFO, nil, progname, &block)
  end


warn (Logger)

# File lib/logger.rb, line 382
  def warn(progname = nil, &block)
    add(WARN, nil, progname, &block)
  end


error (Logger)

# File lib/logger.rb, line 391
  def error(progname = nil, &block)
    add(ERROR, nil, progname, &block)
  end


fatal (Logger)

# File lib/logger.rb, line 400
  def fatal(progname = nil, &block)
    add(FATAL, nil, progname, &block)
  end


unknown (Logger)

# File lib/logger.rb, line 410
  def unknown(progname = nil, &block)
    add(UNKNOWN, nil, progname, &block)
  end


close (Logger)

# File lib/logger.rb, line 417
  def close
    @logdev.close if @logdev
  end


open (Logging)

# File lib/mkmf.rb, line 175
  def self::open
    @log ||= File::open(@logfile, 'w')
    @log.sync = true
    $stderr.reopen(@log)
    $stdout.reopen(@log)
    yield
  ensure
    $stderr.reopen(@orgerr)
    $stdout.reopen(@orgout)
  end


message (Logging)

# File lib/mkmf.rb, line 186
  def self::message(*s)
    @log ||= File::open(@logfile, 'w')
    @log.sync = true
    @log.printf(*s)
  end


logfile (Logging)

# File lib/mkmf.rb, line 192
  def self::logfile file
    @logfile = file
    if @log and not @log.closed?
      @log.flush
      @log.close
      @log = nil
    end
  end


postpone (Logging)

# File lib/mkmf.rb, line 201
  def self::postpone
    tmplog = "mkmftmp#{@postpone += 1}.log"
    open do
      log, *save = @log, @logfile, @orgout, @orgerr
      @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
      begin
        log.print(open {yield})
        @log.close
        File::open(tmplog) {|t| FileUtils.copy_stream(t, log)}
      ensure
        @log, @logfile, @orgout, @orgerr = log, *save
        @postpone -= 1
        rm_f tmplog
      end
    end
  end


new (Mail)

# File lib/mailread.rb, line 12
  def initialize(f)
    unless defined? f.gets
      f = open(f, "r")
      opened = true
    end

    @header = {}
    @body = []
    begin
      while line = f.gets()
        line.chop!
        next if /^From /=~line # skip From-line
        break if /^$/=~line    # end of header

        if /^(\S+?):\s*(.*)/=~line
          (attr = $1).capitalize!
          @header[attr] = $2
        elsif attr
          line.sub!(/^\s*/, '')
          @header[attr] += "\n" + line
        end
      end

      return unless line

      while line = f.gets()
        break if /^From /=~line
        @body.push(line)
      end
    ensure
      f.close if opened
    end
  end


header (Mail)

# File lib/mailread.rb, line 47
  def header
    return @header
  end


body (Mail)

# File lib/mailread.rb, line 52
  def body
    return @body
  end


[] (Mail)

# File lib/mailread.rb, line 59
  def [](field)
    @header[field.capitalize]
  end


dump (Marshal)

/*
 * call-seq:
 *      dump( obj [, anIO] , limit=--1 ) => anIO
 *
 * Serializes obj and all descendent objects. If anIO is
 * specified, the serialized data will be written to it, otherwise the
 * data will be returned as a String. If limit is specified, the
 * traversal of subobjects will be limited to that depth. If limit is
 * negative, no checking of depth will be performed.
 *
 *     class Klass
 *       def initialize(str)
 *         @str = str
 *       end
 *       def sayHello
 *         @str
 *       end
 *     end
 *
 * (produces no output)
 *
 *     o = Klass.new("hello\n")
 *     data = Marshal.dump(o)
 *     obj = Marshal.load(data)
 *     obj.sayHello   #=> "hello\n"
 */
static VALUE
marshal_dump(argc, argv)
    int argc;
    VALUE* argv;
{
    VALUE obj, port, a1, a2;
    int limit = -1;
    struct dump_arg arg;
    struct dump_call_arg c_arg;

    port = Qnil;
    rb_scan_args(argc, argv, "12", &obj, &a1, &a2);
    if (argc == 3) {
        if (!NIL_P(a2)) limit = NUM2INT(a2);
        if (NIL_P(a1)) goto type_error;
        port = a1;
    }
    else if (argc == 2) {
        if (FIXNUM_P(a1)) limit = FIX2INT(a1);
        else if (NIL_P(a1)) goto type_error;
        else port = a1;
    }
    arg.dest = 0;
    if (!NIL_P(port)) {
        if (!rb_respond_to(port, s_write)) {
          type_error:
            rb_raise(rb_eTypeError, "instance of IO needed");
        }
        arg.str = rb_str_buf_new(0);
        arg.dest = port;
        if (rb_respond_to(port, s_binmode)) {
            rb_funcall2(port, s_binmode, 0, 0);
        }
    }
    else {
        port = rb_str_buf_new(0);
        arg.str = port;
    }

    arg.symbols = st_init_numtable();
    arg.data    = st_init_numtable();
    arg.taint   = Qfalse;
    c_arg.obj   = obj;
    c_arg.arg   = &arg;
    c_arg.limit = limit;

    w_byte(MARSHAL_MAJOR, &arg);
    w_byte(MARSHAL_MINOR, &arg);

    rb_ensure(dump, (VALUE)&c_arg, dump_ensure, (VALUE)&arg);

    return port;
}


load (Marshal)

/*
 * call-seq:
 *     load( source [, proc] ) => obj
 *     restore( source [, proc] ) => obj
 *
 * Returns the result of converting the serialized data in source into a
 * Ruby object (possibly with associated subordinate objects). source
 * may be either an instance of IO or an object that responds to
 * to_str. If proc is specified, it will be passed each object as it
 * is deserialized.
 */
static VALUE
marshal_load(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE port, proc;
    int major, minor;
    VALUE v;
    struct load_arg arg;

    rb_scan_args(argc, argv, "11", &port, &proc);
    if (rb_respond_to(port, rb_intern("to_str"))) {
        arg.taint = OBJ_TAINTED(port); /* original taintedness */
        StringValue(port);            /* possible conversion */
    }
    else if (rb_respond_to(port, s_getc) && rb_respond_to(port, s_read)) {
        if (rb_respond_to(port, s_binmode)) {
            rb_funcall2(port, s_binmode, 0, 0);
        }
        arg.taint = Qtrue;
    }
    else {
        rb_raise(rb_eTypeError, "instance of IO needed");
    }
    arg.src = port;
    arg.offset = 0;

    major = r_byte(&arg);
    minor = r_byte(&arg);
    if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) {
        rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\
\tformat version %d.%d required; %d.%d given",
                 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
    }
    if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) {
        rb_warn("incompatible marshal file format (can be read)\n\
\tformat version %d.%d required; %d.%d given",
                MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
    }

    arg.symbols = st_init_numtable();
    arg.data   = rb_hash_new();
    if (NIL_P(proc)) arg.proc = 0;
    else             arg.proc = proc;
    v = rb_ensure(load, (VALUE)&arg, load_ensure, (VALUE)&arg);

    return v;
}


restore (Marshal)

/*
 * call-seq:
 *     load( source [, proc] ) => obj
 *     restore( source [, proc] ) => obj
 *
 * Returns the result of converting the serialized data in source into a
 * Ruby object (possibly with associated subordinate objects). source
 * may be either an instance of IO or an object that responds to
 * to_str. If proc is specified, it will be passed each object as it
 * is deserialized.
 */
static VALUE
marshal_load(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE port, proc;
    int major, minor;
    VALUE v;
    struct load_arg arg;

    rb_scan_args(argc, argv, "11", &port, &proc);
    if (rb_respond_to(port, rb_intern("to_str"))) {
        arg.taint = OBJ_TAINTED(port); /* original taintedness */
        StringValue(port);            /* possible conversion */
    }
    else if (rb_respond_to(port, s_getc) && rb_respond_to(port, s_read)) {
        if (rb_respond_to(port, s_binmode)) {
            rb_funcall2(port, s_binmode, 0, 0);
        }
        arg.taint = Qtrue;
    }
    else {
        rb_raise(rb_eTypeError, "instance of IO needed");
    }
    arg.src = port;
    arg.offset = 0;

    major = r_byte(&arg);
    minor = r_byte(&arg);
    if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) {
        rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\
\tformat version %d.%d required; %d.%d given",
                 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
    }
    if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) {
        rb_warn("incompatible marshal file format (can be read)\n\
\tformat version %d.%d required; %d.%d given",
                MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
    }

    arg.symbols = st_init_numtable();
    arg.data   = rb_hash_new();
    if (NIL_P(proc)) arg.proc = 0;
    else             arg.proc = proc;
    v = rb_ensure(load, (VALUE)&arg, load_ensure, (VALUE)&arg);

    return v;
}


size (MatchData)

/*
 *  call-seq:
 *     mtch.length   => integer
 *     mtch.size     => integer
 *
 *  Returns the number of elements in the match array.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.length   #=> 5
 *     m.size     #=> 5
 */

static VALUE
match_size(match)
    VALUE match;
{
    return INT2FIX(RMATCH(match)->regs->num_regs);
}


length (MatchData)

/*
 *  call-seq:
 *     mtch.length   => integer
 *     mtch.size     => integer
 *
 *  Returns the number of elements in the match array.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.length   #=> 5
 *     m.size     #=> 5
 */

static VALUE
match_size(match)
    VALUE match;
{
    return INT2FIX(RMATCH(match)->regs->num_regs);
}


offset (MatchData)

/*
 *  call-seq:
 *     mtch.offset(n)   => array
 *
 *  Returns a two-element array containing the beginning and ending offsets of
 *  the <em>n</em>th match.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.offset(0)   #=> [1, 7]
 *     m.offset(4)   #=> [6, 7]
 */

static VALUE
match_offset(match, n)
    VALUE match, n;
{
    int i = NUM2INT(n);

    if (i < 0 || RMATCH(match)->regs->num_regs <= i)
        rb_raise(rb_eIndexError, "index %d out of matches", i);

    if (RMATCH(match)->regs->beg[i] < 0)
        return rb_assoc_new(Qnil, Qnil);

    return rb_assoc_new(INT2FIX(RMATCH(match)->regs->beg[i]),
                        INT2FIX(RMATCH(match)->regs->end[i]));
}


begin (MatchData)

/*
 *  call-seq:
 *     mtch.begin(n)   => integer
 *
 *  Returns the offset of the start of the <em>n</em>th element of the match
 *  array in the string.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.begin(0)   #=> 1
 *     m.begin(2)   #=> 2
 */

static VALUE
match_begin(match, n)
    VALUE match, n;
{
    int i = NUM2INT(n);

    if (i < 0 || RMATCH(match)->regs->num_regs <= i)
        rb_raise(rb_eIndexError, "index %d out of matches", i);

    if (RMATCH(match)->regs->beg[i] < 0)
        return Qnil;

    return INT2FIX(RMATCH(match)->regs->beg[i]);
}


end (MatchData)

/*
 *  call-seq:
 *     mtch.end(n)   => integer
 *
 *  Returns the offset of the character immediately following the end of the
 *  <em>n</em>th element of the match array in the string.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.end(0)   #=> 7
 *     m.end(2)   #=> 3
 */

static VALUE
match_end(match, n)
    VALUE match, n;
{
    int i = NUM2INT(n);

    if (i < 0 || RMATCH(match)->regs->num_regs <= i)
        rb_raise(rb_eIndexError, "index %d out of matches", i);

    if (RMATCH(match)->regs->beg[i] < 0)
        return Qnil;

    return INT2FIX(RMATCH(match)->regs->end[i]);
}


to_a (MatchData)

/*
 *  call-seq:
 *     mtch.to_a   => anArray
 *
 *  Returns the array of matches.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.to_a   #=> ["HX1138", "H", "X", "113", "8"]
 *
 *  Because <code>to_a</code> is called when expanding
 *  <code>*</code><em>variable</em>, there's a useful assignment
 *  shortcut for extracting matched fields. This is slightly slower than
 *  accessing the fields directly (as an intermediate array is
 *  generated).
 *
 *     all,f1,f2,f3 = *(/(.)(.)(\d+)(\d)/.match("THX1138."))
 *     all   #=> "HX1138"
 *     f1    #=> "H"
 *     f2    #=> "X"
 *     f3    #=> "113"
 */

static VALUE
match_to_a(match)
    VALUE match;
{
    return match_array(match, 0);
}


[] (MatchData)

/*
 *  call-seq:
 *     mtch[i]               => obj
 *     mtch[start, length]   => array
 *     mtch[range]           => array
 *
 *  Match Reference---<code>MatchData</code> acts as an array, and may be
 *  accessed using the normal array indexing techniques.  <i>mtch</i>[0] is
 *  equivalent to the special variable <code>$&</code>, and returns the entire
 *  matched string.  <i>mtch</i>[1], <i>mtch</i>[2], and so on return the values
 *  of the matched backreferences (portions of the pattern between parentheses).
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m[0]       #=> "HX1138"
 *     m[1, 2]    #=> ["H", "X"]
 *     m[1..3]    #=> ["H", "X", "113"]
 *     m[-3, 2]   #=> ["X", "113"]
 */

static VALUE
match_aref(argc, argv, match)
    int argc;
    VALUE *argv;
    VALUE match;
{
    VALUE idx, rest;

    rb_scan_args(argc, argv, "11", &idx, &rest);

    if (!NIL_P(rest) || !FIXNUM_P(idx) || FIX2INT(idx) < 0) {
        return rb_ary_aref(argc, argv, match_to_a(match));
    }
    return rb_reg_nth_match(FIX2INT(idx), match);
}


captures (MatchData)

/*
 *  call-seq:
 *     mtch.captures   => array
 *
 *  Returns the array of captures; equivalent to <code>mtch.to_a[1..-1]</code>.
 *
 *     f1,f2,f3,f4 = /(.)(.)(\d+)(\d)/.match("THX1138.").captures
 *     f1    #=> "H"
 *     f2    #=> "X"
 *     f3    #=> "113"
 *     f4    #=> "8"
 */
static VALUE
match_captures(match)
    VALUE match;
{
    return match_array(match, 1);
}


select (MatchData)

/*
 *  call-seq:
 *     mtch.select([index]*)   => array
 *
 *  Uses each <i>index</i> to access the matching values, returning an
 *  array of the corresponding matches.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
 *     m.to_a               #=> ["HX1138", "H", "X", "113", "8"]
 *     m.select(0, 2, -2)   #=> ["HX1138", "X", "113"]
 */

static VALUE
match_select(argc, argv, match)
    int argc;
    VALUE *argv;
    VALUE match;
{
    if (argc > 0) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
    }
    else {
        struct re_registers *regs = RMATCH(match)->regs;
        VALUE target = RMATCH(match)->str;
        VALUE result = rb_ary_new();
        int i;
        int taint = OBJ_TAINTED(match);

        for (i=0; i<regs->num_regs; i++) {
            VALUE str = rb_str_substr(target, regs->beg[i], regs->end[i]-regs->beg[i]);
            if (taint) OBJ_TAINT(str);
            if (RTEST(rb_yield(str))) {
                rb_ary_push(result, str);
            }
        }
        return result;
    }
}


values_at (MatchData)

/*
 *  call-seq:
 *     mtch.select([index]*)   => array
 *
 *  Uses each <i>index</i> to access the matching values, returning an array of
 *  the corresponding matches.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
 *     m.to_a               #=> ["HX1138", "H", "X", "113", "8"]
 *     m.select(0, 2, -2)   #=> ["HX1138", "X", "113"]
 */

static VALUE
match_values_at(argc, argv, match)
    int argc;
    VALUE *argv;
    VALUE match;
{
    return rb_values_at(match, RMATCH(match)->regs->num_regs, argc, argv, match_entry);
}


pre_match (MatchData)

/*
 *  call-seq:
 *     mtch.pre_match   => str
 *
 *  Returns the portion of the original string before the current match.
 *  Equivalent to the special variable <code>$`</code>.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.pre_match   #=> "T"
 */

VALUE
rb_reg_match_pre(match)
    VALUE match;
{
    VALUE str;

    if (NIL_P(match)) return Qnil;
    if (RMATCH(match)->BEG(0) == -1) return Qnil;
    str = rb_str_substr(RMATCH(match)->str, 0, RMATCH(match)->BEG(0));
    if (OBJ_TAINTED(match)) OBJ_TAINT(str);
    return str;
}


post_match (MatchData)

/*
 *  call-seq:
 *     mtch.post_match   => str
 *
 *  Returns the portion of the original string after the current match.
 *  Equivalent to the special variable <code>$'</code>.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
 *     m.post_match   #=> ": The Movie"
 */

VALUE
rb_reg_match_post(match)
    VALUE match;
{
    VALUE str;
    long pos;

    if (NIL_P(match)) return Qnil;
    if (RMATCH(match)->BEG(0) == -1) return Qnil;
    str = RMATCH(match)->str;
    pos = RMATCH(match)->END(0);
    str = rb_str_substr(str, pos, RSTRING(str)->len - pos);
    if (OBJ_TAINTED(match)) OBJ_TAINT(str);
    return str;
}


to_s (MatchData)

/*
 *  call-seq:
 *     mtch.to_s   => str
 *
 *  Returns the entire matched string.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.to_s   #=> "HX1138"
 */

static VALUE
match_to_s(match)
    VALUE match;
{
    VALUE str = rb_reg_last_match(match);

    if (NIL_P(str)) str = rb_str_new(0,0);
    if (OBJ_TAINTED(match)) OBJ_TAINT(str);
    if (OBJ_TAINTED(RMATCH(match)->str)) OBJ_TAINT(str);
    return str;
}


inspect (MatchData)

/*
 *  call-seq:
 *     obj.to_s    => string
 *
 *  Returns a string representing <i>obj</i>. The default
 *  <code>to_s</code> prints the object's class and an encoding of the
 *  object id. As a special case, the top-level object that is the
 *  initial execution context of Ruby programs returns ``main.''
 */

VALUE
rb_any_to_s(obj)
    VALUE obj;
{
    char *cname = rb_obj_classname(obj);
    size_t len;
    VALUE str;

    len = strlen(cname)+6+16;
    str = rb_str_new(0, len); /* 6:tags 16:addr */
    snprintf(RSTRING(str)->ptr, len+1, "#<%s:0x%lx>", cname, obj);
    RSTRING(str)->len = strlen(RSTRING(str)->ptr);
    if (OBJ_TAINTED(obj)) OBJ_TAINT(str);

    return str;
}


string (MatchData)

/*
 *  call-seq:
 *     mtch.string   => str
 *
 *  Returns a frozen copy of the string passed in to <code>match</code>.
 *
 *     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
 *     m.string   #=> "THX1138."
 */

static VALUE
match_string(match)
    VALUE match;
{
    return RMATCH(match)->str;  /* str is frozen */
}


pretty_print (MatchData)

# File lib/pp.rb, line 443
  def pretty_print(q)
    q.object_group(self) {
      q.breakable
      q.seplist(1..self.size, lambda { q.breakable }) {|i|
        q.pp self[i-1]
      }
    }
  end


atan2 (Math)

/*
 *  call-seq:
 *     Math.atan2(y, x)  => float
 *
 *  Computes the arc tangent given <i>y</i> and <i>x</i>. Returns
 *  -PI..PI.
 *
 */

static VALUE
math_atan2(obj, y, x)
    VALUE obj, x, y;
{
    Need_Float2(y, x);
    return rb_float_new(atan2(RFLOAT(y)->value, RFLOAT(x)->value));
}


cos (Math)

/*
 *  call-seq:
 *     Math.cos(x)    => float
 *
 *  Computes the cosine of <i>x</i> (expressed in radians). Returns
 *  -1..1.
 */

static VALUE
math_cos(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(cos(RFLOAT(x)->value));
}


sin (Math)

/*
 *  call-seq:
 *     Math.sin(x)    => float
 *
 *  Computes the sine of <i>x</i> (expressed in radians). Returns
 *  -1..1.
 */

static VALUE
math_sin(obj, x)
    VALUE obj, x;
{
    Need_Float(x);

    return rb_float_new(sin(RFLOAT(x)->value));
}


tan (Math)

/*
 *  call-seq:
 *     Math.tan(x)    => float
 *
 *  Returns the tangent of <i>x</i> (expressed in radians).
 */

static VALUE
math_tan(obj, x)
    VALUE obj, x;
{
    Need_Float(x);

    return rb_float_new(tan(RFLOAT(x)->value));
}


acos (Math)

/*
 *  call-seq:
 *     Math.acos(x)    => float
 *
 *  Computes the arc cosine of <i>x</i>. Returns 0..PI.
 */

static VALUE
math_acos(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = acos(RFLOAT(x)->value);
    domain_check(d, "acos");
    return rb_float_new(d);
}


asin (Math)

/*
 *  call-seq:
 *     Math.asin(x)    => float
 *
 *  Computes the arc sine of <i>x</i>. Returns 0..PI.
 */

static VALUE
math_asin(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = asin(RFLOAT(x)->value);
    domain_check(d, "asin");
    return rb_float_new(d);
}


atan (Math)

/*
 *  call-seq:
 *     Math.atan(x)    => float
 *
 *  Computes the arc tangent of <i>x</i>. Returns -{PI/2} .. {PI/2}.
 */

static VALUE
math_atan(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(atan(RFLOAT(x)->value));
}


cosh (Math)

/*
 *  call-seq:
 *     Math.cosh(x)    => float
 *
 *  Computes the hyperbolic cosine of <i>x</i> (expressed in radians).
 */

static VALUE
math_cosh(obj, x)
    VALUE obj, x;
{
    Need_Float(x);

    return rb_float_new(cosh(RFLOAT(x)->value));
}


sinh (Math)

/*
 *  call-seq:
 *     Math.sinh(x)    => float
 *
 *  Computes the hyperbolic sine of <i>x</i> (expressed in
 *  radians).
 */

static VALUE
math_sinh(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(sinh(RFLOAT(x)->value));
}


tanh (Math)

/*
 *  call-seq:
 *     Math.tanh()    => float
 *
 *  Computes the hyperbolic tangent of <i>x</i> (expressed in
 *  radians).
 */

static VALUE
math_tanh(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(tanh(RFLOAT(x)->value));
}


acosh (Math)

/*
 *  call-seq:
 *     Math.acosh(x)    => float
 *
 *  Computes the inverse hyperbolic cosine of <i>x</i>.
 */

static VALUE
math_acosh(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = acosh(RFLOAT(x)->value);
    domain_check(d, "acosh");
    return rb_float_new(d);
}


asinh (Math)

/*
 *  call-seq:
 *     Math.asinh(x)    => float
 *
 *  Computes the inverse hyperbolic sine of <i>x</i>.
 */

static VALUE
math_asinh(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(asinh(RFLOAT(x)->value));
}


atanh (Math)

/*
 *  call-seq:
 *     Math.atanh(x)    => float
 *
 *  Computes the inverse hyperbolic tangent of <i>x</i>.
 */

static VALUE
math_atanh(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = atanh(RFLOAT(x)->value);
    domain_check(d, "atanh");
    return rb_float_new(d);
}


exp (Math)

/*
 *  call-seq:
 *     Math.exp(x)    => float
 *
 *  Returns e**x.
 */

static VALUE
math_exp(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(exp(RFLOAT(x)->value));
}


log (Math)

/*
 *  call-seq:
 *     Math.log(numeric)    => float
 *
 *  Returns the natural logarithm of <i>numeric</i>.
 */

static VALUE
math_log(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = log(RFLOAT(x)->value);
    domain_check(d, "log");
    return rb_float_new(d);
}


log10 (Math)

/*
 *  call-seq:
 *     Math.log10(numeric)    => float
 *
 *  Returns the base 10 logarithm of <i>numeric</i>.
 */

static VALUE
math_log10(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = log10(RFLOAT(x)->value);
    domain_check(d, "log10");
    return rb_float_new(d);
}


sqrt (Math)

/*
 *  call-seq:
 *     Math.sqrt(numeric)    => float
 *
 *  Returns the non-negative square root of <i>numeric</i>.
 */

static VALUE
math_sqrt(obj, x)
    VALUE obj, x;
{
    double d;

    Need_Float(x);
    errno = 0;
    d = sqrt(RFLOAT(x)->value);
    domain_check(d, "sqrt");
    return rb_float_new(d);
}


frexp (Math)

/*
 *  call-seq:
 *     Math.frexp(numeric)    => [ fraction, exponent ]
 *
 *  Returns a two-element array containing the normalized fraction (a
 *  <code>Float</code>) and exponent (a <code>Fixnum</code>) of
 *  <i>numeric</i>.
 *
 *     fraction, exponent = Math.frexp(1234)   #=> [0.6025390625, 11]
 *     fraction * 2**exponent                  #=> 1234.0
 */

static VALUE
math_frexp(obj, x)
    VALUE obj, x;
{
    double d;
    int exp;

    Need_Float(x);

    d = frexp(RFLOAT(x)->value, &exp);
    return rb_assoc_new(rb_float_new(d), INT2NUM(exp));
}


ldexp (Math)

/*
 *  call-seq:
 *     Math.ldexp(flt, int) -> float
 *
 *  Returns the value of <i>flt</i>*(2**<i>int</i>).
 *
 *     fraction, exponent = Math.frexp(1234)
 *     Math.ldexp(fraction, exponent)   #=> 1234.0
 */

static VALUE
math_ldexp(obj, x, n)
    VALUE obj, x, n;
{
    Need_Float(x);
    return rb_float_new(ldexp(RFLOAT(x)->value, NUM2INT(n)));
}


hypot (Math)

/*
 *  call-seq:
 *     Math.hypot(x, y)    => float
 *
 *  Returns sqrt(x**2 + y**2), the hypotenuse of a right-angled triangle
 *  with sides <i>x</i> and <i>y</i>.
 *
 *     Math.hypot(3, 4)   #=> 5.0
 */

static VALUE
math_hypot(obj, x, y)
    VALUE obj, x, y;
{
    Need_Float2(x, y);
    return rb_float_new(hypot(RFLOAT(x)->value, RFLOAT(y)->value));
}


erf (Math)

/*
 * call-seq:
 *    Math.erf(x)  => float
 *
 *  Calculates the error function of x.
 */

static VALUE
math_erf(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(erf(RFLOAT(x)->value));
}


erfc (Math)

/*
 * call-seq:
 *    Math.erfc(x)  => float
 *
 *  Calculates the complementary error function of x.
 */

static VALUE
math_erfc(obj, x)
    VALUE obj, x;
{
    Need_Float(x);
    return rb_float_new(erfc(RFLOAT(x)->value));
}


sqrt (Math)

# File lib/complex.rb, line 435
  def sqrt(z)
    if Complex.generic?(z)
      if z >= 0
        sqrt!(z)
      else
        Complex(0,sqrt!(-z))
      end
    else
      if z.image < 0
        sqrt(z.conjugate).conjugate
      else
        r = z.abs
        x = z.real
        Complex( sqrt!((r+x)/2), sqrt!((r-x)/2) )
      end
    end
  end


exp (Math)

# File lib/complex.rb, line 454
  def exp(z)
    if Complex.generic?(z)
      exp!(z)
    else
      Complex(exp!(z.real) * cos!(z.image), exp!(z.real) * sin!(z.image))
    end
  end


cos (Math)

# File lib/complex.rb, line 463
  def cos(z)
    if Complex.generic?(z)
      cos!(z)
    else
      Complex(cos!(z.real)*cosh!(z.image),
              -sin!(z.real)*sinh!(z.image))
    end
  end


sin (Math)

# File lib/complex.rb, line 473
  def sin(z)
    if Complex.generic?(z)
      sin!(z)
    else
      Complex(sin!(z.real)*cosh!(z.image),
              cos!(z.real)*sinh!(z.image))
    end
  end


tan (Math)

# File lib/complex.rb, line 483
  def tan(z)
    if Complex.generic?(z)
      tan!(z)
    else
      sin(z)/cos(z)
    end
  end


sinh (Math)

# File lib/complex.rb, line 491
  def sinh(z)
    if Complex.generic?(z)
      sinh!(z)
    else
      Complex( sinh!(z.real)*cos!(z.image), cosh!(z.real)*sin!(z.image) )
    end
  end


cosh (Math)

# File lib/complex.rb, line 499
  def cosh(z)
    if Complex.generic?(z)
      cosh!(z)
    else
      Complex( cosh!(z.real)*cos!(z.image), sinh!(z.real)*sin!(z.image) )
    end
  end


tanh (Math)

# File lib/complex.rb, line 507
  def tanh(z)
    if Complex.generic?(z)
      tanh!(z)
    else
      sinh(z)/cosh(z)
    end
  end


log (Math)

# File lib/complex.rb, line 516
  def log(z)
    if Complex.generic?(z) and z >= 0
      log!(z)
    else
      r, theta = z.polar
      Complex(log!(r.abs), theta)
    end
  end


log10 (Math)

# File lib/complex.rb, line 526
  def log10(z)
    if Complex.generic?(z)
      log10!(z)
    else
      log(z)/log!(10)
    end
  end


acos (Math)

# File lib/complex.rb, line 534
  def acos(z)
    if Complex.generic?(z) and z >= -1 and z <= 1
      acos!(z)
    else
      -1.0.im * log( z + 1.0.im * sqrt(1.0-z*z) )
    end
  end


asin (Math)

# File lib/complex.rb, line 542
  def asin(z)
    if Complex.generic?(z) and z >= -1 and z <= 1
      asin!(z)
    else
      -1.0.im * log( 1.0.im * z + sqrt(1.0-z*z) )
    end
  end


atan (Math)

# File lib/complex.rb, line 550
  def atan(z)
    if Complex.generic?(z)
      atan!(z)
    else
      1.0.im * log( (1.0.im+z) / (1.0.im-z) ) / 2.0
    end
  end


atan2 (Math)

# File lib/complex.rb, line 558
  def atan2(y,x)
    if Complex.generic?(y) and Complex.generic?(x)
      atan2!(y,x)
    else
      -1.0.im * log( (x+1.0.im*y) / sqrt(x*x+y*y) )
    end
  end


acosh (Math)

# File lib/complex.rb, line 566
  def acosh(z)
    if Complex.generic?(z) and z >= 1
      acosh!(z)
    else
      log( z + sqrt(z*z-1.0) )
    end
  end


asinh (Math)

# File lib/complex.rb, line 574
  def asinh(z)
    if Complex.generic?(z)
      asinh!(z)
    else
      log( z + sqrt(1.0+z*z) )
    end
  end


atanh (Math)

# File lib/complex.rb, line 582
  def atanh(z)
    if Complex.generic?(z) and z >= -1 and z <= 1
      atanh!(z)
    else
      log( (1.0+z) / (1.0-z) ) / 2.0
    end
  end


sqrt (Math)

# File lib/mathn.rb, line 233
  def sqrt(a)
    if a.kind_of?(Complex)
      abs = sqrt(a.real*a.real + a.image*a.image)
#      if not abs.kind_of?(Rational)
#       return a**Rational(1,2)
#      end
      x = sqrt((a.real + abs)/Rational(2))
      y = sqrt((-a.real + abs)/Rational(2))
#      if !(x.kind_of?(Rational) and y.kind_of?(Rational))
#       return a**Rational(1,2)
#      end
      if a.image >= 0
        Complex(x, y)
      else
        Complex(x, -y)
      end
    elsif a >= 0
      rsqrt(a)
    else
      Complex(0,rsqrt(-a))
    end
  end


rsqrt (Math)

# File lib/mathn.rb, line 256
  def rsqrt(a)
    if a.kind_of?(Float)
      sqrt!(a)
    elsif a.kind_of?(Rational)
      rsqrt(a.numerator)/rsqrt(a.denominator)
    else
      src = a
      max = 2 ** 32
      byte_a = [src & 0xffffffff]
      # ruby's bug
      while (src >= max) and (src >>= 32)
        byte_a.unshift src & 0xffffffff
      end

      answer = 0
      main = 0
      side = 0
      for elm in byte_a
        main = (main << 32) + elm
        side <<= 16
        if answer != 0
          if main * 4  < side * side
            applo = main.div(side)
          else
            applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
          end
        else
          applo = sqrt!(main).to_i + 1
        end

        while (x = (side + applo) * applo) > main
          applo -= 1
        end
        main -= x
        answer = (answer << 16) + applo
        side += applo * 2
      end
      if main == 0
        answer
      else
        sqrt!(a)
      end
    end
  end


[] (Matrix)

# File lib/matrix.rb, line 122
  def Matrix.[](*rows)
    new(:init_rows, rows, false)
  end


rows (Matrix)

# File lib/matrix.rb, line 133
  def Matrix.rows(rows, copy = true)
    new(:init_rows, rows, copy)
  end


columns (Matrix)

# File lib/matrix.rb, line 144
  def Matrix.columns(columns)
    rows = (0 .. columns[0].size - 1).collect {
      |i|
      (0 .. columns.size - 1).collect {
        |j|
        columns[j][i]
      }
    }
    Matrix.rows(rows, false)
  end


diagonal (Matrix)

# File lib/matrix.rb, line 162
  def Matrix.diagonal(*values)
    size = values.size
    rows = (0 .. size  - 1).collect {
      |j|
      row = Array.new(size).fill(0, 0, size)
      row[j] = values[j]
      row
    }
    rows(rows, false)
  end


scalar (Matrix)

# File lib/matrix.rb, line 180
  def Matrix.scalar(n, value)
    Matrix.diagonal(*Array.new(n).fill(value, 0, n))
  end


identity (Matrix)

# File lib/matrix.rb, line 190
  def Matrix.identity(n)
    Matrix.scalar(n, 1)
  end


zero (Matrix)

# File lib/matrix.rb, line 204
  def Matrix.zero(n)
    Matrix.scalar(n, 0)
  end


row_vector (Matrix)

# File lib/matrix.rb, line 214
  def Matrix.row_vector(row)
    case row
    when Vector
      Matrix.rows([row.to_a], false)
    when Array
      Matrix.rows([row.dup], false)
    else
      Matrix.rows([[row]], false)
    end
  end


column_vector (Matrix)

# File lib/matrix.rb, line 233
  def Matrix.column_vector(column)
    case column
    when Vector
      Matrix.columns([column.to_a])
    when Array
      Matrix.columns([column])
    else
      Matrix.columns([[column]])
    end
  end


new (Matrix)

# File lib/matrix.rb, line 248
  def initialize(init_method, *argv)
    self.send(init_method, *argv)
  end


[] (Matrix)

# File lib/matrix.rb, line 265
  def [](i, j)
    @rows[i][j]
  end


row_size (Matrix)

# File lib/matrix.rb, line 272
  def row_size
    @rows.size
  end


column_size (Matrix)

# File lib/matrix.rb, line 282
  def column_size
    @rows[0].size
  end


row (Matrix)

# File lib/matrix.rb, line 290
  def row(i) # :yield: e
    if block_given?
      for e in @rows[i]
        yield e
      end
    else
      Vector.elements(@rows[i])
    end
  end


column (Matrix)

# File lib/matrix.rb, line 305
  def column(j) # :yield: e
    if block_given?
      0.upto(row_size - 1) do
        |i|
        yield @rows[i][j]
      end
    else
      col = (0 .. row_size - 1).collect {
        |i|
        @rows[i][j]
      }
      Vector.elements(col, false)
    end
  end


collect (Matrix)

# File lib/matrix.rb, line 327
  def collect # :yield: e
    rows = @rows.collect{|row| row.collect{|e| yield e}}
    Matrix.rows(rows, false)
  end


minor (Matrix)

# File lib/matrix.rb, line 342
  def minor(*param)
    case param.size
    when 2
      from_row = param[0].first
      size_row = param[0].end - from_row
      size_row += 1 unless param[0].exclude_end?
      from_col = param[1].first
      size_col = param[1].end - from_col
      size_col += 1 unless param[1].exclude_end?
    when 4
      from_row = param[0]
      size_row = param[1]
      from_col = param[2]
      size_col = param[3]
    else
      Matrix.Raise ArgumentError, param.inspect
    end

    rows = @rows[from_row, size_row].collect{
      |row|
      row[from_col, size_col]
    }
    Matrix.rows(rows, false)
  end


regular? (Matrix)

# File lib/matrix.rb, line 374
  def regular?
    square? and rank == column_size
  end


singular? (Matrix)

# File lib/matrix.rb, line 381
  def singular?
    not regular?
  end


square? (Matrix)

# File lib/matrix.rb, line 389
  def square?
    column_size == row_size
  end


== (Matrix)

# File lib/matrix.rb, line 400
  def ==(other)
    return false unless Matrix === other

    other.compare_by_row_vectors(@rows)
  end


compare_by_row_vectors (Matrix)

# File lib/matrix.rb, line 410
  def compare_by_row_vectors(rows)
    return false unless @rows.size == rows.size

    0.upto(@rows.size - 1) do
      |i|
      return false unless @rows[i] == rows[i]
    end
    true
  end


clone (Matrix)

# File lib/matrix.rb, line 424
  def clone
    Matrix.rows(@rows)
  end


hash (Matrix)

# File lib/matrix.rb, line 431
  def hash
    value = 0
    for row in @rows
      for e in row
        value ^= e.hash
      end
    end
    return value
  end


* (Matrix)

# File lib/matrix.rb, line 451
  def *(m) # m is matrix or vector or number
    case(m)
    when Numeric
      rows = @rows.collect {
        |row|
        row.collect {
          |e|
          e * m
        }
      }
      return Matrix.rows(rows, false)
    when Vector
      m = Matrix.column_vector(m)
      r = self * m
      return r.column(0)
    when Matrix
      Matrix.Raise ErrDimensionMismatch if column_size != m.row_size

      rows = (0 .. row_size - 1).collect {
        |i|
        (0 .. m.column_size - 1).collect {
          |j|
          vij = 0
          0.upto(column_size - 1) do
            |k|
            vij += self[i, k] * m[k, j]
          end
          vij
        }
      }
      return Matrix.rows(rows, false)
    else
      x, y = m.coerce(self)
      return x * y
    end
  end


+ (Matrix)

# File lib/matrix.rb, line 494
  def +(m)
    case m
    when Numeric
      Matrix.Raise ErrOperationNotDefined, "+"
    when Vector
      m = Matrix.column_vector(m)
    when Matrix
    else
      x, y = m.coerce(self)
      return x + y
    end

    Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size

    rows = (0 .. row_size - 1).collect {
      |i|
      (0 .. column_size - 1).collect {
        |j|
        self[i, j] + m[i, j]
      }
    }
    Matrix.rows(rows, false)
  end


- (Matrix)

# File lib/matrix.rb, line 524
  def -(m)
    case m
    when Numeric
      Matrix.Raise ErrOperationNotDefined, "-"
    when Vector
      m = Matrix.column_vector(m)
    when Matrix
    else
      x, y = m.coerce(self)
      return x - y
    end

    Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size

    rows = (0 .. row_size - 1).collect {
      |i|
      (0 .. column_size - 1).collect {
        |j|
        self[i, j] - m[i, j]
      }
    }
    Matrix.rows(rows, false)
  end


/ (Matrix)

# File lib/matrix.rb, line 554
  def /(other)
    case other
    when Numeric
      rows = @rows.collect {
        |row|
        row.collect {
          |e|
          e / other
        }
      }
      return Matrix.rows(rows, false)
    when Matrix
      return self * other.inverse
    else
      x, y = other.coerce(self)
      rerurn x / y
    end
  end


inverse (Matrix)

# File lib/matrix.rb, line 579
  def inverse
    Matrix.Raise ErrDimensionMismatch unless square?
    Matrix.I(row_size).inverse_from(self)
  end


inverse_from (Matrix)

# File lib/matrix.rb, line 588
  def inverse_from(src)
    size = row_size - 1
    a = src.to_a

    for k in 0..size
      if (akk = a[k][k]) == 0
        i = k
        begin
          Matrix.Raise ErrNotRegular if (i += 1) > size
        end while a[i][k] == 0
        a[i], a[k] = a[k], a[i]
        @rows[i], @rows[k] = @rows[k], @rows[i]
        akk = a[k][k]
      end

      for i in 0 .. size
        next if i == k
        q = a[i][k] / akk
        a[i][k] = 0

        (k + 1).upto(size) do
          |j|
          a[i][j] -= a[k][j] * q
        end
        0.upto(size) do
          |j|
          @rows[i][j] -= @rows[k][j] * q
        end
      end

      (k + 1).upto(size) do
        |j|
        a[k][j] /= akk
      end
      0.upto(size) do
        |j|
        @rows[k][j] /= akk
      end
    end
    self
  end


** (Matrix)

# File lib/matrix.rb, line 638
  def ** (other)
    if other.kind_of?(Integer)
      x = self
      if other <= 0
        x = self.inverse
        return Matrix.identity(self.column_size) if other == 0
        other = -other
      end
      z = x
      n = other  - 1
      while n != 0
        while (div, mod = n.divmod(2)
               mod == 0)
          x = x * x
          n = div
        end
        z *= x
        n -= 1
      end
      z
    elsif other.kind_of?(Float) || defined?(Rational) && other.kind_of?(Rational)
      Matrix.Raise ErrOperationNotDefined, "**"
    else
      Matrix.Raise ErrOperationNotDefined, "**"
    end
  end


determinant (Matrix)

# File lib/matrix.rb, line 675
  def determinant
    return 0 unless square?

    size = row_size - 1
    a = to_a

    det = 1
    k = 0
    begin
      if (akk = a[k][k]) == 0
        i = k
        begin
          return 0 if (i += 1) > size
        end while a[i][k] == 0
        a[i], a[k] = a[k], a[i]
        akk = a[k][k]
        det *= -1
      end
      (k + 1).upto(size) do
        |i|
        q = a[i][k] / akk
        (k + 1).upto(size) do
          |j|
          a[i][j] -= a[k][j] * q
        end
      end
      det *= akk
    end while (k += 1) <= size
    det
  end


rank (Matrix)

# File lib/matrix.rb, line 714
  def rank
    if column_size > row_size
      a = transpose.to_a
      a_column_size = row_size
      a_row_size = column_size
    else
      a = to_a
      a_column_size = column_size
      a_row_size = row_size
    end
    rank = 0
    k = 0
    begin
      if (akk = a[k][k]) == 0
        i = k
        exists = true
        begin
          if (i += 1) > a_column_size - 1
            exists = false
            break
          end
        end while a[i][k] == 0
        if exists
          a[i], a[k] = a[k], a[i]
          akk = a[k][k]
        else
          i = k
          exists = true
          begin
            if (i += 1) > a_row_size - 1
              exists = false
              break
            end
          end while a[k][i] == 0
          if exists
            k.upto(a_column_size - 1) do
              |j|
              a[j][k], a[j][i] = a[j][i], a[j][k]
            end
            akk = a[k][k]
          else
            next
          end
        end
      end
      (k + 1).upto(a_row_size - 1) do
        |i|
        q = a[i][k] / akk
        (k + 1).upto(a_column_size - 1) do
          |j|
          a[i][j] -= a[k][j] * q
        end
      end
      rank += 1
    end while (k += 1) <= a_column_size - 1
    return rank
  end


trace (Matrix)

# File lib/matrix.rb, line 777
  def trace
    tr = 0
    0.upto(column_size - 1) do
      |i|
      tr += @rows[i][i]
    end
    tr
  end


transpose (Matrix)

# File lib/matrix.rb, line 797
  def transpose
    Matrix.columns(@rows)
  end


coerce (Matrix)

# File lib/matrix.rb, line 809
  def coerce(other)
    case other
    when Numeric
      return Scalar.new(other), self
    else
      raise TypeError, "#{self.class} can't be coerced into #{other.class}"
    end
  end


row_vectors (Matrix)

# File lib/matrix.rb, line 821
  def row_vectors
    rows = (0 .. row_size - 1).collect {
      |i|
      row(i)
    }
    rows
  end


column_vectors (Matrix)

# File lib/matrix.rb, line 832
  def column_vectors
    columns = (0 .. column_size - 1).collect {
      |i|
      column(i)
    }
    columns
  end


to_a (Matrix)

# File lib/matrix.rb, line 843
  def to_a
    @rows.collect{|row| row.collect{|e| e}}
  end


to_s (Matrix)

# File lib/matrix.rb, line 854
  def to_s
    "Matrix[" + @rows.collect{
      |row|
      "[" + row.collect{|e| e.to_s}.join(", ") + "]"
    }.join(", ")+"]"
  end


inspect (Matrix)

# File lib/matrix.rb, line 864
  def inspect
    "Matrix"+@rows.inspect
  end


== (Method)

/*
 * call-seq:
 *   meth == other_meth  => true or false
 *
 * Two method objects are equal if that are bound to the same
 * object and contain the same body.
 */

static VALUE
method_eq(method, other)
    VALUE method, other;
{
    struct METHOD *m1, *m2;

    if (TYPE(other) != T_DATA || RDATA(other)->dmark != (RUBY_DATA_FUNC)bm_mark)
        return Qfalse;
    if (CLASS_OF(method) != CLASS_OF(other))
        return Qfalse;

    Data_Get_Struct(method, struct METHOD, m1);
    Data_Get_Struct(other, struct METHOD, m2);

    if (m1->klass != m2->klass || m1->rklass != m2->rklass ||
        m1->recv != m2->recv || m1->body != m2->body)
        return Qfalse;

    return Qtrue;
}


clone (Method)

/*
 * MISSING: documentation
 */

static VALUE
method_clone(self)
    VALUE self;
{
    VALUE clone;
    struct METHOD *orig, *data;

    Data_Get_Struct(self, struct METHOD, orig);
    clone = Data_Make_Struct(CLASS_OF(self),struct METHOD, bm_mark, free, data);
    CLONESETUP(clone, self);
    *data = *orig;

    return clone;
}


call (Method)

/*
 *  call-seq:
 *     meth.call(args, ...)    => obj
 *     meth[args, ...]         => obj
 *
 *  Invokes the <i>meth</i> with the specified arguments, returning the
 *  method's return value.
 *
 *     m = 12.method("+")
 *     m.call(3)    #=> 15
 *     m.call(20)   #=> 32
 */

static VALUE
method_call(argc, argv, method)
    int argc;
    VALUE *argv;
    VALUE method;
{
    VALUE result = Qnil;        /* OK */
    struct METHOD *data;
    int safe;

    Data_Get_Struct(method, struct METHOD, data);
    if (data->recv == Qundef) {
        rb_raise(rb_eTypeError, "can't call unbound method; bind first");
    }
    if (OBJ_TAINTED(method)) {
        safe = NOEX_WITH(data->safe_level, 4)|NOEX_TAINTED;
    }
    else {
        safe = data->safe_level;
    }
    PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
    result = rb_call0(data->klass,data->recv,data->id,data->oid,argc,argv,data->body,safe);
    POP_ITER();
    return result;
}


[] (Method)

/*
 *  call-seq:
 *     meth.call(args, ...)    => obj
 *     meth[args, ...]         => obj
 *
 *  Invokes the <i>meth</i> with the specified arguments, returning the
 *  method's return value.
 *
 *     m = 12.method("+")
 *     m.call(3)    #=> 15
 *     m.call(20)   #=> 32
 */

static VALUE
method_call(argc, argv, method)
    int argc;
    VALUE *argv;
    VALUE method;
{
    VALUE result = Qnil;        /* OK */
    struct METHOD *data;
    int safe;

    Data_Get_Struct(method, struct METHOD, data);
    if (data->recv == Qundef) {
        rb_raise(rb_eTypeError, "can't call unbound method; bind first");
    }
    if (OBJ_TAINTED(method)) {
        safe = NOEX_WITH(data->safe_level, 4)|NOEX_TAINTED;
    }
    else {
        safe = data->safe_level;
    }
    PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
    result = rb_call0(data->klass,data->recv,data->id,data->oid,argc,argv,data->body,safe);
    POP_ITER();
    return result;
}


arity (Method)

/*
 *  call-seq:
 *     meth.arity    => fixnum
 *
 *  Returns an indication of the number of arguments accepted by a
 *  method. Returns a nonnegative integer for methods that take a fixed
 *  number of arguments. For Ruby methods that take a variable number of
 *  arguments, returns -n-1, where n is the number of required
 *  arguments. For methods written in C, returns -1 if the call takes a
 *  variable number of arguments.
 *
 *     class C
 *       def one;    end
 *       def two(a); end
 *       def three(*a);  end
 *       def four(a, b); end
 *       def five(a, b, *c);    end
 *       def six(a, b, *c, &d); end
 *     end
 *     c = C.new
 *     c.method(:one).arity     #=> 0
 *     c.method(:two).arity     #=> 1
 *     c.method(:three).arity   #=> -1
 *     c.method(:four).arity    #=> 2
 *     c.method(:five).arity    #=> -3
 *     c.method(:six).arity     #=> -3
 *
 *     "cat".method(:size).arity      #=> 0
 *     "cat".method(:replace).arity   #=> 1
 *     "cat".method(:squeeze).arity   #=> -1
 *     "cat".method(:count).arity     #=> -1
 */

static VALUE
method_arity(method)
    VALUE method;
{
    struct METHOD *data;
    NODE *body;
    int n;

    Data_Get_Struct(method, struct METHOD, data);

    body = data->body;
    switch (nd_type(body)) {
      case NODE_CFUNC:
        if (body->nd_argc < 0) return INT2FIX(-1);
        return INT2FIX(body->nd_argc);
      case NODE_ZSUPER:
        return INT2FIX(-1);
      case NODE_ATTRSET:
        return INT2FIX(1);
      case NODE_IVAR:
        return INT2FIX(0);
      case NODE_BMETHOD:
        return proc_arity(body->nd_cval);
      case NODE_DMETHOD:
        return method_arity(body->nd_cval);
      case NODE_SCOPE:
        body = body->nd_next;  /* skip NODE_SCOPE */
        if (nd_type(body) == NODE_BLOCK)
            body = body->nd_head;
        if (!body) return INT2FIX(0);
        n = body->nd_cnt;
        if (body->nd_opt || body->nd_rest)
            n = -n-1;
        return INT2FIX(n);
      default:
        rb_raise(rb_eArgError, "invalid node 0x%x", nd_type(body));
   }
}


inspect (Method)

/*
 *  call-seq:
 *   meth.to_s      =>  string
 *   meth.inspect   =>  string
 *
 *  Show the name of the underlying method.
 *
 *    "cat".method(:count).inspect   #=> "#<Method: String#count>"
 */

static VALUE
method_inspect(method)
    VALUE method;
{
    struct METHOD *data;
    VALUE str;
    const char *s;
    char *sharp = "#";

    Data_Get_Struct(method, struct METHOD, data);
    str = rb_str_buf_new2("#<");
    s = rb_obj_classname(method);
    rb_str_buf_cat2(str, s);
    rb_str_buf_cat2(str, ": ");

    if (FL_TEST(data->klass, FL_SINGLETON)) {
        VALUE v = rb_iv_get(data->klass, "__attached__");

        if (data->recv == Qundef) {
            rb_str_buf_append(str, rb_inspect(data->klass));
        }
        else if (data->recv == v) {
            rb_str_buf_append(str, rb_inspect(v));
            sharp = ".";
        }
        else {
            rb_str_buf_append(str, rb_inspect(data->recv));
            rb_str_buf_cat2(str, "(");
            rb_str_buf_append(str, rb_inspect(v));
            rb_str_buf_cat2(str, ")");
            sharp = ".";
        }
    }
    else {
        rb_str_buf_cat2(str, rb_class2name(data->rklass));
        if (data->rklass != data->klass) {
            VALUE klass = data -> klass;
            if (TYPE(klass) == T_ICLASS) {
                klass = RBASIC(klass)->klass;
            }
            rb_str_buf_cat2(str, "(");
            rb_str_buf_cat2(str, rb_class2name(klass));
            rb_str_buf_cat2(str, ")");
        }
    }
    rb_str_buf_cat2(str, sharp);
    rb_str_buf_cat2(str, rb_id2name(data->oid));
    rb_str_buf_cat2(str, ">");

    return str;
}


to_s (Method)

/*
 *  call-seq:
 *   meth.to_s      =>  string
 *   meth.inspect   =>  string
 *
 *  Show the name of the underlying method.
 *
 *    "cat".method(:count).inspect   #=> "#<Method: String#count>"
 */

static VALUE
method_inspect(method)
    VALUE method;
{
    struct METHOD *data;
    VALUE str;
    const char *s;
    char *sharp = "#";

    Data_Get_Struct(method, struct METHOD, data);
    str = rb_str_buf_new2("#<");
    s = rb_obj_classname(method);
    rb_str_buf_cat2(str, s);
    rb_str_buf_cat2(str, ": ");

    if (FL_TEST(data->klass, FL_SINGLETON)) {
        VALUE v = rb_iv_get(data->klass, "__attached__");

        if (data->recv == Qundef) {
            rb_str_buf_append(str, rb_inspect(data->klass));
        }
        else if (data->recv == v) {
            rb_str_buf_append(str, rb_inspect(v));
            sharp = ".";
        }
        else {
            rb_str_buf_append(str, rb_inspect(data->recv));
            rb_str_buf_cat2(str, "(");
            rb_str_buf_append(str, rb_inspect(v));
            rb_str_buf_cat2(str, ")");
            sharp = ".";
        }
    }
    else {
        rb_str_buf_cat2(str, rb_class2name(data->rklass));
        if (data->rklass != data->klass) {
            VALUE klass = data -> klass;
            if (TYPE(klass) == T_ICLASS) {
                klass = RBASIC(klass)->klass;
            }
            rb_str_buf_cat2(str, "(");
            rb_str_buf_cat2(str, rb_class2name(klass));
            rb_str_buf_cat2(str, ")");
        }
    }
    rb_str_buf_cat2(str, sharp);
    rb_str_buf_cat2(str, rb_id2name(data->oid));
    rb_str_buf_cat2(str, ">");

    return str;
}


to_proc (Method)

/*
 *  call-seq:
 *     meth.to_proc    => prc
 *
 *  Returns a <code>Proc</code> object corresponding to this method.
 */

static VALUE
method_proc(method)
    VALUE method;
{
    VALUE proc;
    struct METHOD *mdata;
    struct BLOCK *bdata;

    proc = rb_iterate((VALUE(*)_((VALUE)))mproc, 0, bmcall, method);
    Data_Get_Struct(method, struct METHOD, mdata);
    Data_Get_Struct(proc, struct BLOCK, bdata);
    bdata->body->nd_file = mdata->body->nd_file;
    nd_set_line(bdata->body, nd_line(mdata->body));
    bdata->body->nd_state = YIELD_FUNC_SVALUE;

    return proc;
}


unbind (Method)

/*
 *  call-seq:
 *     meth.unbind    => unbound_method
 *
 *  Dissociates <i>meth</i> from it's current receiver. The resulting
 *  <code>UnboundMethod</code> can subsequently be bound to a new object
 *  of the same class (see <code>UnboundMethod</code>).
 */

static VALUE
method_unbind(obj)
    VALUE obj;
{
    VALUE method;
    struct METHOD *orig, *data;

    Data_Get_Struct(obj, struct METHOD, orig);
    method = Data_Make_Struct(rb_cUnboundMethod, struct METHOD, bm_mark, free, data);
    data->klass = orig->klass;
    data->recv = Qundef;
    data->id = orig->id;
    data->body = orig->body;
    data->rklass = orig->rklass;
    data->oid = orig->oid;
    OBJ_INFECT(method, obj);

    return method;
}


new (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6257
  def initialize(obj = nil)
    @clsid = "{2933BF91-7B36-11D2-B20E-00C04F983E60}"
    @progid = "Microsoft.FreeThreadedXMLDOM.1.0"
    if obj.nil?
      @dispatch = WIN32OLE.new(@progid)
    else
      @dispatch = obj
    end
  end


method_missing (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6267
  def method_missing(cmd, *arg)
    @dispatch.method_missing(cmd, *arg)
  end


nodeName (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6273
  def nodeName()
    ret = @dispatch._getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6281
  def nodeValue()
    ret = @dispatch._getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6289
  def nodeType()
    ret = @dispatch._getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6297
  def parentNode()
    ret = @dispatch._getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6305
  def childNodes()
    ret = @dispatch._getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6313
  def firstChild()
    ret = @dispatch._getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6321
  def lastChild()
    ret = @dispatch._getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6329
  def previousSibling()
    ret = @dispatch._getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6337
  def nextSibling()
    ret = @dispatch._getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6345
  def attributes()
    ret = @dispatch._getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6353
  def ownerDocument()
    ret = @dispatch._getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6361
  def nodeTypeString()
    ret = @dispatch._getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6369
  def text()
    ret = @dispatch._getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6377
  def specified()
    ret = @dispatch._getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6385
  def definition()
    ret = @dispatch._getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6393
  def nodeTypedValue()
    ret = @dispatch._getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6401
  def dataType()
    ret = @dispatch._getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6409
  def xml()
    ret = @dispatch._getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6417
  def parsed()
    ret = @dispatch._getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6425
  def namespaceURI()
    ret = @dispatch._getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6433
  def prefix()
    ret = @dispatch._getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6441
  def baseName()
    ret = @dispatch._getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


doctype (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6449
  def doctype()
    ret = @dispatch._getproperty(38, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


implementation (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6457
  def implementation()
    ret = @dispatch._getproperty(39, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


documentElement (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6465
  def documentElement()
    ret = @dispatch._getproperty(40, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


readyState (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6473
  def readyState()
    ret = @dispatch._getproperty(-525, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parseError (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6481
  def parseError()
    ret = @dispatch._getproperty(59, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


url (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6489
  def url()
    ret = @dispatch._getproperty(60, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6497
  def async()
    ret = @dispatch._getproperty(61, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


validateOnParse (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6505
  def validateOnParse()
    ret = @dispatch._getproperty(65, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


resolveExternals (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6513
  def resolveExternals()
    ret = @dispatch._getproperty(66, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


preserveWhiteSpace (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6521
  def preserveWhiteSpace()
    ret = @dispatch._getproperty(67, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6529
  def nodeValue=(arg0)
    ret = @dispatch._setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6537
  def text=(arg0)
    ret = @dispatch._setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6545
  def nodeTypedValue=(arg0)
    ret = @dispatch._setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6553
  def dataType=(arg0)
    ret = @dispatch._setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6561
  def async=(arg0)
    ret = @dispatch._setproperty(61, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


validateOnParse= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6569
  def validateOnParse=(arg0)
    ret = @dispatch._setproperty(65, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


resolveExternals= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6577
  def resolveExternals=(arg0)
    ret = @dispatch._setproperty(66, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


preserveWhiteSpace= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6585
  def preserveWhiteSpace=(arg0)
    ret = @dispatch._setproperty(67, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6593
  def onreadystatechange=(arg0)
    ret = @dispatch._setproperty(68, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ondataavailable= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6601
  def ondataavailable=(arg0)
    ret = @dispatch._setproperty(69, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ontransformnode= (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6609
  def ontransformnode=(arg0)
    ret = @dispatch._setproperty(70, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6619
  def insertBefore(arg0, arg1)
    ret = @dispatch._invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6629
  def replaceChild(arg0, arg1)
    ret = @dispatch._invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6638
  def removeChild(arg0)
    ret = @dispatch._invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6647
  def appendChild(arg0)
    ret = @dispatch._invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6654
  def hasChildNodes()
    ret = @dispatch._invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6662
  def cloneNode(arg0)
    ret = @dispatch._invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6671
  def transformNode(arg0)
    ret = @dispatch._invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6680
  def selectNodes(arg0)
    ret = @dispatch._invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6689
  def selectSingleNode(arg0)
    ret = @dispatch._invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6699
  def transformNodeToObject(arg0, arg1)
    ret = @dispatch._invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createElement (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6708
  def createElement(arg0)
    ret = @dispatch._invoke(41, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createDocumentFragment (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6716
  def createDocumentFragment()
    ret = @dispatch._invoke(42, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createTextNode (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6725
  def createTextNode(arg0)
    ret = @dispatch._invoke(43, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createComment (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6734
  def createComment(arg0)
    ret = @dispatch._invoke(44, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createCDATASection (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6743
  def createCDATASection(arg0)
    ret = @dispatch._invoke(45, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createProcessingInstruction (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6753
  def createProcessingInstruction(arg0, arg1)
    ret = @dispatch._invoke(46, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createAttribute (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6762
  def createAttribute(arg0)
    ret = @dispatch._invoke(47, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createEntityReference (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6771
  def createEntityReference(arg0)
    ret = @dispatch._invoke(49, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getElementsByTagName (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6780
  def getElementsByTagName(arg0)
    ret = @dispatch._invoke(50, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createNode (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6791
  def createNode(arg0, arg1, arg2)
    ret = @dispatch._invoke(54, [arg0, arg1, arg2], [VT_VARIANT, VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeFromID (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6800
  def nodeFromID(arg0)
    ret = @dispatch._invoke(56, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


load (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6809
  def load(arg0)
    ret = @dispatch._invoke(58, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


abort (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6817
  def abort()
    ret = @dispatch._invoke(62, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


loadXML (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6826
  def loadXML(arg0)
    ret = @dispatch._invoke(63, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


save (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6835
  def save(arg0)
    ret = @dispatch._invoke(64, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ondataavailable (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6842
  def ondataavailable()
    ret = @dispatch._invoke(198, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange (Microsoft_FreeThreadedXMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6849
  def onreadystatechange()
    ret = @dispatch._invoke(-609, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


new (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5650
  def initialize(obj = nil)
    @clsid = "{2933BF90-7B36-11D2-B20E-00C04F983E60}"
    @progid = "Microsoft.XMLDOM.1.0"
    if obj.nil?
      @dispatch = WIN32OLE.new(@progid)
    else
      @dispatch = obj
    end
  end


method_missing (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5660
  def method_missing(cmd, *arg)
    @dispatch.method_missing(cmd, *arg)
  end


nodeName (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5666
  def nodeName()
    ret = @dispatch._getproperty(2, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5674
  def nodeValue()
    ret = @dispatch._getproperty(3, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeType (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5682
  def nodeType()
    ret = @dispatch._getproperty(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parentNode (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5690
  def parentNode()
    ret = @dispatch._getproperty(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


childNodes (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5698
  def childNodes()
    ret = @dispatch._getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


firstChild (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5706
  def firstChild()
    ret = @dispatch._getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


lastChild (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5714
  def lastChild()
    ret = @dispatch._getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


previousSibling (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5722
  def previousSibling()
    ret = @dispatch._getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nextSibling (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5730
  def nextSibling()
    ret = @dispatch._getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


attributes (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5738
  def attributes()
    ret = @dispatch._getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ownerDocument (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5746
  def ownerDocument()
    ret = @dispatch._getproperty(18, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypeString (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5754
  def nodeTypeString()
    ret = @dispatch._getproperty(21, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5762
  def text()
    ret = @dispatch._getproperty(24, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


specified (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5770
  def specified()
    ret = @dispatch._getproperty(22, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


definition (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5778
  def definition()
    ret = @dispatch._getproperty(23, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5786
  def nodeTypedValue()
    ret = @dispatch._getproperty(25, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5794
  def dataType()
    ret = @dispatch._getproperty(26, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


xml (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5802
  def xml()
    ret = @dispatch._getproperty(27, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parsed (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5810
  def parsed()
    ret = @dispatch._getproperty(31, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


namespaceURI (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5818
  def namespaceURI()
    ret = @dispatch._getproperty(32, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


prefix (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5826
  def prefix()
    ret = @dispatch._getproperty(33, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


baseName (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5834
  def baseName()
    ret = @dispatch._getproperty(34, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


doctype (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5842
  def doctype()
    ret = @dispatch._getproperty(38, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


implementation (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5850
  def implementation()
    ret = @dispatch._getproperty(39, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


documentElement (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5858
  def documentElement()
    ret = @dispatch._getproperty(40, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


readyState (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5866
  def readyState()
    ret = @dispatch._getproperty(-525, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


parseError (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5874
  def parseError()
    ret = @dispatch._getproperty(59, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


url (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5882
  def url()
    ret = @dispatch._getproperty(60, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5890
  def async()
    ret = @dispatch._getproperty(61, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


validateOnParse (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5898
  def validateOnParse()
    ret = @dispatch._getproperty(65, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


resolveExternals (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5906
  def resolveExternals()
    ret = @dispatch._getproperty(66, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


preserveWhiteSpace (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5914
  def preserveWhiteSpace()
    ret = @dispatch._getproperty(67, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeValue= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5922
  def nodeValue=(arg0)
    ret = @dispatch._setproperty(3, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


text= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5930
  def text=(arg0)
    ret = @dispatch._setproperty(24, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeTypedValue= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5938
  def nodeTypedValue=(arg0)
    ret = @dispatch._setproperty(25, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


dataType= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5946
  def dataType=(arg0)
    ret = @dispatch._setproperty(26, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5954
  def async=(arg0)
    ret = @dispatch._setproperty(61, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


validateOnParse= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5962
  def validateOnParse=(arg0)
    ret = @dispatch._setproperty(65, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


resolveExternals= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5970
  def resolveExternals=(arg0)
    ret = @dispatch._setproperty(66, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


preserveWhiteSpace= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5978
  def preserveWhiteSpace=(arg0)
    ret = @dispatch._setproperty(67, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5986
  def onreadystatechange=(arg0)
    ret = @dispatch._setproperty(68, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ondataavailable= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 5994
  def ondataavailable=(arg0)
    ret = @dispatch._setproperty(69, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ontransformnode= (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6002
  def ontransformnode=(arg0)
    ret = @dispatch._setproperty(70, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


insertBefore (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6012
  def insertBefore(arg0, arg1)
    ret = @dispatch._invoke(13, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


replaceChild (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6022
  def replaceChild(arg0, arg1)
    ret = @dispatch._invoke(14, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


removeChild (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6031
  def removeChild(arg0)
    ret = @dispatch._invoke(15, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


appendChild (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6040
  def appendChild(arg0)
    ret = @dispatch._invoke(16, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


hasChildNodes (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6047
  def hasChildNodes()
    ret = @dispatch._invoke(17, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


cloneNode (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6055
  def cloneNode(arg0)
    ret = @dispatch._invoke(19, [arg0], [VT_BOOL])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNode (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6064
  def transformNode(arg0)
    ret = @dispatch._invoke(28, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectNodes (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6073
  def selectNodes(arg0)
    ret = @dispatch._invoke(29, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


selectSingleNode (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6082
  def selectSingleNode(arg0)
    ret = @dispatch._invoke(30, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


transformNodeToObject (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6092
  def transformNodeToObject(arg0, arg1)
    ret = @dispatch._invoke(35, [arg0, arg1], [VT_BYREF|VT_DISPATCH, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createElement (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6101
  def createElement(arg0)
    ret = @dispatch._invoke(41, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createDocumentFragment (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6109
  def createDocumentFragment()
    ret = @dispatch._invoke(42, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createTextNode (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6118
  def createTextNode(arg0)
    ret = @dispatch._invoke(43, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createComment (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6127
  def createComment(arg0)
    ret = @dispatch._invoke(44, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createCDATASection (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6136
  def createCDATASection(arg0)
    ret = @dispatch._invoke(45, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createProcessingInstruction (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6146
  def createProcessingInstruction(arg0, arg1)
    ret = @dispatch._invoke(46, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createAttribute (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6155
  def createAttribute(arg0)
    ret = @dispatch._invoke(47, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createEntityReference (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6164
  def createEntityReference(arg0)
    ret = @dispatch._invoke(49, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getElementsByTagName (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6173
  def getElementsByTagName(arg0)
    ret = @dispatch._invoke(50, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


createNode (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6184
  def createNode(arg0, arg1, arg2)
    ret = @dispatch._invoke(54, [arg0, arg1, arg2], [VT_VARIANT, VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


nodeFromID (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6193
  def nodeFromID(arg0)
    ret = @dispatch._invoke(56, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


load (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6202
  def load(arg0)
    ret = @dispatch._invoke(58, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


abort (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6210
  def abort()
    ret = @dispatch._invoke(62, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


loadXML (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6219
  def loadXML(arg0)
    ret = @dispatch._invoke(63, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


save (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6228
  def save(arg0)
    ret = @dispatch._invoke(64, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


ondataavailable (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6235
  def ondataavailable()
    ret = @dispatch._invoke(198, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange (Microsoft_XMLDOM_1_0)

# File ext/win32ole/sample/xml.rb, line 6242
  def onreadystatechange()
    ret = @dispatch._invoke(-609, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


new (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7135
  def initialize(obj = nil)
    @clsid = "{550DDA30-0541-11D2-9CA9-0060B0EC3D39}"
    @progid = "Microsoft.XMLDSO.1.0"
    if obj.nil?
      @dispatch = WIN32OLE.new(@progid)
    else
      @dispatch = obj
    end
  end


method_missing (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7145
  def method_missing(cmd, *arg)
    @dispatch.method_missing(cmd, *arg)
  end


XMLDocument (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7150
  def XMLDocument()
    ret = @dispatch._getproperty(65537, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


JavaDSOCompatible (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7157
  def JavaDSOCompatible()
    ret = @dispatch._getproperty(65538, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


readyState (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7164
  def readyState()
    ret = @dispatch._getproperty(-525, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


XMLDocument= (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7171
  def XMLDocument=(arg0)
    ret = @dispatch._setproperty(65537, [arg0], [VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


JavaDSOCompatible= (Microsoft_XMLDSO_1_0)

# File ext/win32ole/sample/xml.rb, line 7178
  def JavaDSOCompatible=(arg0)
    ret = @dispatch._setproperty(65538, [arg0], [VT_I4])
    @lastargs = WIN32OLE::ARGV
    ret
  end


new (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 6991
  def initialize(obj = nil)
    @clsid = "{ED8C108E-4349-11D2-91A4-00C04F7969E8}"
    @progid = "Microsoft.XMLHTTP.1"
    if obj.nil?
      @dispatch = WIN32OLE.new(@progid)
    else
      @dispatch = obj
    end
  end


method_missing (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7001
  def method_missing(cmd, *arg)
    @dispatch.method_missing(cmd, *arg)
  end


status (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7007
  def status()
    ret = @dispatch._getproperty(7, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


statusText (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7015
  def statusText()
    ret = @dispatch._getproperty(8, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseXML (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7023
  def responseXML()
    ret = @dispatch._getproperty(9, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseText (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7031
  def responseText()
    ret = @dispatch._getproperty(10, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseBody (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7039
  def responseBody()
    ret = @dispatch._getproperty(11, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


responseStream (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7047
  def responseStream()
    ret = @dispatch._getproperty(12, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


readyState (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7055
  def readyState()
    ret = @dispatch._getproperty(13, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


onreadystatechange= (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7063
  def onreadystatechange=(arg0)
    ret = @dispatch._setproperty(14, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


open (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7076
  def open(arg0, arg1, arg2=nil, arg3=nil, arg4=nil)
    ret = @dispatch._invoke(1, [arg0, arg1, arg2, arg3, arg4], [VT_BSTR, VT_BSTR, VT_VARIANT, VT_VARIANT, VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


setRequestHeader (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7086
  def setRequestHeader(arg0, arg1)
    ret = @dispatch._invoke(2, [arg0, arg1], [VT_BSTR, VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getResponseHeader (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7095
  def getResponseHeader(arg0)
    ret = @dispatch._invoke(3, [arg0], [VT_BSTR])
    @lastargs = WIN32OLE::ARGV
    ret
  end


getAllResponseHeaders (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7103
  def getAllResponseHeaders()
    ret = @dispatch._invoke(4, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


send (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7112
  def send(arg0=nil)
    ret = @dispatch._invoke(5, [arg0], [VT_VARIANT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


abort (Microsoft_XMLHTTP_1)

# File ext/win32ole/sample/xml.rb, line 7120
  def abort()
    ret = @dispatch._invoke(6, [], [])
    @lastargs = WIN32OLE::ARGV
    ret
  end


append_features (Module)

/*
 *  call-seq:
 *     append_features(mod)   => mod
 *
 *  When this module is included in another, Ruby calls
 *  <code>append_features</code> in this module, passing it the
 *  receiving module in _mod_. Ruby's default implementation is
 *  to add the constants, methods, and module variables of this module
 *  to _mod_ if this module has not already been added to
 *  _mod_ or one of its ancestors. See also <code>Module#include</code>.
 */

static VALUE
rb_mod_append_features(module, include)
    VALUE module, include;
{
    switch (TYPE(include)) {
      case T_CLASS:
      case T_MODULE:
        break;
      default:
        Check_Type(include, T_CLASS);
        break;
    }
    rb_include_module(include, module);

    return module;
}


extend_object (Module)

/*
 *  call-seq:
 *     extend_object(obj)    => obj
 *
 *  Extends the specified object by adding this module's constants and
 *  methods (which are added as singleton methods). This is the callback
 *  method used by <code>Object#extend</code>.
 *
 *     module Picky
 *       def Picky.extend_object(o)
 *         if String === o
 *           puts "Can't add Picky to a String"
 *         else
 *           puts "Picky added to #{o.class}"
 *           super
 *         end
 *       end
 *     end
 *     (s = Array.new).extend Picky  # Call Object.extend
 *     (s = "quick brown fox").extend Picky
 *
 *  <em>produces:</em>
 *
 *     Picky added to Array
 *     Can't add Picky to a String
 */

static VALUE
rb_mod_extend_object(mod, obj)
    VALUE mod, obj;
{
    rb_extend_object(obj, mod);
    return obj;
}


include (Module)

/*
 *  call-seq:
 *     include(module, ...)    => self
 *
 *  Invokes <code>Module.append_features</code> on each parameter in turn.
 */

static VALUE
rb_mod_include(argc, argv, module)
    int argc;
    VALUE *argv;
    VALUE module;
{
    int i;

    for (i=0; i<argc; i++) Check_Type(argv[i], T_MODULE);
    while (argc--) {
        rb_funcall(argv[argc], rb_intern("append_features"), 1, module);
        rb_funcall(argv[argc], rb_intern("included"), 1, module);
    }
    return module;
}


public (Module)

/*
 *  call-seq:
 *     public                 => self
 *     public(symbol, ...)    => self
 *
 *  With no arguments, sets the default visibility for subsequently
 *  defined methods to public. With arguments, sets the named methods to
 *  have public visibility.
 */

static VALUE
rb_mod_public(argc, argv, module)
    int argc;
    VALUE *argv;
    VALUE module;
{
    secure_visibility(module);
    if (argc == 0) {
        SCOPE_SET(SCOPE_PUBLIC);
    }
    else {
        set_method_visibility(module, argc, argv, NOEX_PUBLIC);
    }
    return module;
}


protected (Module)

/*
 *  call-seq:
 *     protected                => self
 *     protected(symbol, ...)   => self
 *
 *  With no arguments, sets the default visibility for subsequently
 *  defined methods to protected. With arguments, sets the named methods
 *  to have protected visibility.
 */

static VALUE
rb_mod_protected(argc, argv, module)
    int argc;
    VALUE *argv;
    VALUE module;
{
    secure_visibility(module);
    if (argc == 0) {
        SCOPE_SET(SCOPE_PROTECTED);
    }
    else {
        set_method_visibility(module, argc, argv, NOEX_PROTECTED);
    }
    return module;
}


private (Module)

/*
 *  call-seq:
 *     private                 => self
 *     private(symbol, ...)    => self
 *
 *  With no arguments, sets the default visibility for subsequently
 *  defined methods to private. With arguments, sets the named methods
 *  to have private visibility.
 *
 *     module Mod
 *       def a()  end
 *       def b()  end
 *       private
 *       def c()  end
 *       private :a
 *     end
 *     Mod.private_instance_methods   #=> ["a", "c"]
 */

static VALUE
rb_mod_private(argc, argv, module)
    int argc;
    VALUE *argv;
    VALUE module;
{
    secure_visibility(module);
    if (argc == 0) {
        SCOPE_SET(SCOPE_PRIVATE);
    }
    else {
        set_method_visibility(module, argc, argv, NOEX_PRIVATE);
    }
    return module;
}


module_function (Module)

/*
 *  call-seq:
 *     module_function(symbol, ...)    => self
 *
 *  Creates module functions for the named methods. These functions may
 *  be called with the module as a receiver, and also become available
 *  as instance methods to classes that mix in the module. Module
 *  functions are copies of the original, and so may be changed
 *  independently. The instance-method versions are made private. If
 *  used with no arguments, subsequently defined methods become module
 *  functions.
 *
 *     module Mod
 *       def one
 *         "This is one"
 *       end
 *       module_function :one
 *     end
 *     class Cls
 *       include Mod
 *       def callOne
 *         one
 *       end
 *     end
 *     Mod.one     #=> "This is one"
 *     c = Cls.new
 *     c.callOne   #=> "This is one"
 *     module Mod
 *       def one
 *         "This is the new one"
 *       end
 *     end
 *     Mod.one     #=> "This is one"
 *     c.callOne   #=> "This is the new one"
 */

static VALUE
rb_mod_modfunc(argc, argv, module)
    int argc;
    VALUE *argv;
    VALUE module;
{
    int i;
    ID id;
    NODE *body;

    if (TYPE(module) != T_MODULE) {
        rb_raise(rb_eTypeError, "module_function must be called for modules");
    }

    secure_visibility(module);
    if (argc == 0) {
        SCOPE_SET(SCOPE_MODFUNC);
        return module;
    }

    set_method_visibility(module, argc, argv, NOEX_PRIVATE);
    for (i=0; i<argc; i++) {
        VALUE m = module;

        id = rb_to_id(argv[i]);
        for (;;) {
            body = search_method(m, id, &m);
            if (body == 0) {
                body = search_method(rb_cObject, id, &m);
            }
            if (body == 0 || body->nd_body == 0) {
                rb_bug("undefined method `%s'; can't happen", rb_id2name(id));
            }
            if (nd_type(body->nd_body) != NODE_ZSUPER) {
                break;                /* normal case: need not to follow 'super' link */
            }
            m = RCLASS(m)->super;
            if (!m) break;
        }
        rb_add_method(rb_singleton_class(module), id, body->nd_body, NOEX_PUBLIC);
    }
    return module;
}


method_defined? (Module)

/*
 *  call-seq:
 *     mod.method_defined?(symbol)    => true or false
 *
 *  Returns +true+ if the named method is defined by
 *  _mod_ (or its included modules and, if _mod_ is a class,
 *  its ancestors). Public and protected methods are matched.
 *
 *     module A
 *       def method1()  end
 *     end
 *     class B
 *       def method2()  end
 *     end
 *     class C < B
 *       include A
 *       def method3()  end
 *     end
 *
 *     A.method_defined? :method1    #=> true
 *     C.method_defined? "method1"   #=> true
 *     C.method_defined? "method2"   #=> true
 *     C.method_defined? "method3"   #=> true
 *     C.method_defined? "method4"   #=> false
 */

static VALUE
rb_mod_method_defined(mod, mid)
    VALUE mod, mid;
{
    return rb_method_boundp(mod, rb_to_id(mid), 1);
}


public_method_defined? (Module)

/*
 *  call-seq:
 *     mod.public_method_defined?(symbol)   => true or false
 *
 *  Returns +true+ if the named public method is defined by
 *  _mod_ (or its included modules and, if _mod_ is a class,
 *  its ancestors).
 *
 *     module A
 *       def method1()  end
 *     end
 *     class B
 *       protected
 *       def method2()  end
 *     end
 *     class C < B
 *       include A
 *       def method3()  end
 *     end
 *
 *     A.method_defined? :method1           #=> true
 *     C.public_method_defined? "method1"   #=> true
 *     C.public_method_defined? "method2"   #=> false
 *     C.method_defined? "method2"          #=> true
 */

static VALUE
rb_mod_public_method_defined(mod, mid)
    VALUE mod, mid;
{
    ID id = rb_to_id(mid);
    int noex;

    if (rb_get_method_body(&mod, &id, &noex)) {
        if (VISI_CHECK(noex, NOEX_PUBLIC))
            return Qtrue;
    }
    return Qfalse;
}


private_method_defined? (Module)

/*
 *  call-seq:
 *     mod.private_method_defined?(symbol)    => true or false
 *
 *  Returns +true+ if the named private method is defined by
 *  _ mod_ (or its included modules and, if _mod_ is a class,
 *  its ancestors).
 *
 *     module A
 *       def method1()  end
 *     end
 *     class B
 *       private
 *       def method2()  end
 *     end
 *     class C < B
 *       include A
 *       def method3()  end
 *     end
 *
 *     A.method_defined? :method1            #=> true
 *     C.private_method_defined? "method1"   #=> false
 *     C.private_method_defined? "method2"   #=> true
 *     C.method_defined? "method2"           #=> false
 */

static VALUE
rb_mod_private_method_defined(mod, mid)
    VALUE mod, mid;
{
    ID id = rb_to_id(mid);
    int noex;

    if (rb_get_method_body(&mod, &id, &noex)) {
        if (VISI_CHECK(noex, NOEX_PRIVATE))
            return Qtrue;
    }
    return Qfalse;
}


protected_method_defined? (Module)

/*
 *  call-seq:
 *     mod.protected_method_defined?(symbol)   => true or false
 *
 *  Returns +true+ if the named protected method is defined
 *  by _mod_ (or its included modules and, if _mod_ is a
 *  class, its ancestors).
 *
 *     module A
 *       def method1()  end
 *     end
 *     class B
 *       protected
 *       def method2()  end
 *     end
 *     class C < B
 *       include A
 *       def method3()  end
 *     end
 *
 *     A.method_defined? :method1              #=> true
 *     C.protected_method_defined? "method1"   #=> false
 *     C.protected_method_defined? "method2"   #=> true
 *     C.method_defined? "method2"             #=> true
 */

static VALUE
rb_mod_protected_method_defined(mod, mid)
    VALUE mod, mid;
{
    ID id = rb_to_id(mid);
    int noex;

    if (rb_get_method_body(&mod, &id, &noex)) {
        if (VISI_CHECK(noex, NOEX_PROTECTED))
            return Qtrue;
    }
    return Qfalse;
}


public_class_method (Module)

/*
 *  call-seq:
 *     mod.public_class_method(symbol, ...)    => mod
 *
 *  Makes a list of existing class methods public.
 */

static VALUE
rb_mod_public_method(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PUBLIC);
    return obj;
}


private_class_method (Module)

/*
 *  call-seq:
 *     mod.private_class_method(symbol, ...)   => mod
 *
 *  Makes existing class methods private. Often used to hide the default
 *  constructor <code>new</code>.
 *
 *     class SimpleSingleton  # Not thread safe
 *       private_class_method :new
 *       def SimpleSingleton.create(*args, &block)
 *         @me = new(*args, &block) if ! @me
 *         @me
 *       end
 *     end
 */

static VALUE
rb_mod_private_method(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    set_method_visibility(CLASS_OF(obj), argc, argv, NOEX_PRIVATE);
    return obj;
}


module_eval (Module)

/*
 *  call-seq:
 *     mod.class_eval(string [, filename [, lineno]])  => obj
 *     mod.module_eval {|| block }                     => obj
 *
 *  Evaluates the string or block in the context of _mod_. This can
 *  be used to add methods to a class. <code>module_eval</code> returns
 *  the result of evaluating its argument. The optional _filename_
 *  and _lineno_ parameters set the text for error messages.
 *
 *     class Thing
 *     end
 *     a = %q{def hello() "Hello there!" end}
 *     Thing.module_eval(a)
 *     puts Thing.new.hello()
 *     Thing.module_eval("invalid code", "dummy", 123)
 *
 *  <em>produces:</em>
 *
 *     Hello there!
 *     dummy:123:in `module_eval': undefined local variable
 *         or method `code' for Thing:Class
 */

VALUE
rb_mod_module_eval(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    return specific_eval(argc, argv, mod, mod);
}


class_eval (Module)

/*
 *  call-seq:
 *     mod.class_eval(string [, filename [, lineno]])  => obj
 *     mod.module_eval {|| block }                     => obj
 *
 *  Evaluates the string or block in the context of _mod_. This can
 *  be used to add methods to a class. <code>module_eval</code> returns
 *  the result of evaluating its argument. The optional _filename_
 *  and _lineno_ parameters set the text for error messages.
 *
 *     class Thing
 *     end
 *     a = %q{def hello() "Hello there!" end}
 *     Thing.module_eval(a)
 *     puts Thing.new.hello()
 *     Thing.module_eval("invalid code", "dummy", 123)
 *
 *  <em>produces:</em>
 *
 *     Hello there!
 *     dummy:123:in `module_eval': undefined local variable
 *         or method `code' for Thing:Class
 */

VALUE
rb_mod_module_eval(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    return specific_eval(argc, argv, mod, mod);
}


remove_method (Module)

/*
 *  call-seq:
 *     remove_method(symbol)   => self
 *
 *  Removes the method identified by _symbol_ from the current
 *  class. For an example, see <code>Module.undef_method</code>.
 */

static VALUE
rb_mod_remove_method(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    int i;

    for (i=0; i<argc; i++) {
        remove_method(mod, rb_to_id(argv[i]));
    }
    return mod;
}


undef_method (Module)

/*
 *  call-seq:
 *     undef_method(symbol)    => self
 *
 *  Prevents the current class from responding to calls to the named
 *  method. Contrast this with <code>remove_method</code>, which deletes
 *  the method from the particular class; Ruby will still search
 *  superclasses and mixed-in modules for a possible receiver.
 *
 *     class Parent
 *       def hello
 *         puts "In parent"
 *       end
 *     end
 *     class Child < Parent
 *       def hello
 *         puts "In child"
 *       end
 *     end
 *
 *
 *     c = Child.new
 *     c.hello
 *
 *
 *     class Child
 *       remove_method :hello  # remove from child, still in parent
 *     end
 *     c.hello
 *
 *
 *     class Child
 *       undef_method :hello   # prevent any calls to 'hello'
 *     end
 *     c.hello
 *
 *  <em>produces:</em>
 *
 *     In child
 *     In parent
 *     prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)
 */

static VALUE
rb_mod_undef_method(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    int i;

    for (i=0; i<argc; i++) {
        rb_undef(mod, rb_to_id(argv[i]));
    }
    return mod;
}


alias_method (Module)

/*
 *  call-seq:
 *     alias_method(new_name, old_name)   => self
 *
 *  Makes <i>new_name</i> a new copy of the method <i>old_name</i>. This can
 *  be used to retain access to methods that are overridden.
 *
 *     module Mod
 *       alias_method :orig_exit, :exit
 *       def exit(code=0)
 *         puts "Exiting with code #{code}"
 *         orig_exit(code)
 *       end
 *     end
 *     include Mod
 *     exit(99)
 *
 *  <em>produces:</em>
 *
 *     Exiting with code 99
 */

static VALUE
rb_mod_alias_method(mod, newname, oldname)
    VALUE mod, newname, oldname;
{
    rb_alias(mod, rb_to_id(newname), rb_to_id(oldname));
    return mod;
}


define_method (Module)

/*
 *  call-seq:
 *     define_method(symbol, method)     => new_method
 *     define_method(symbol) { block }   => proc
 *
 *  Defines an instance method in the receiver. The _method_
 *  parameter can be a +Proc+ or +Method+ object.
 *  If a block is specified, it is used as the method body. This block
 *  is evaluated using <code>instance_eval</code>, a point that is
 *  tricky to demonstrate because <code>define_method</code> is private.
 *  (This is why we resort to the +send+ hack in this example.)
 *
 *     class A
 *       def fred
 *         puts "In Fred"
 *       end
 *       def create_method(name, &block)
 *         self.class.send(:define_method, name, &block)
 *       end
 *       define_method(:wilma) { puts "Charge it!" }
 *     end
 *     class B < A
 *       define_method(:barney, instance_method(:fred))
 *     end
 *     a = B.new
 *     a.barney
 *     a.wilma
 *     a.create_method(:betty) { p self }
 *     a.betty
 *
 *  <em>produces:</em>
 *
 *     In Fred
 *     Charge it!
 *     #<B:0x401b39e8>
 */

static VALUE
rb_mod_define_method(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    ID id;
    VALUE body;
    NODE *node;
    int noex;

    if (argc == 1) {
        id = rb_to_id(argv[0]);
        body = proc_lambda();
    }
    else if (argc == 2) {
        id = rb_to_id(argv[0]);
        body = argv[1];
        if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) {
            rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc/Method)",
                     rb_obj_classname(body));
        }
    }
    else {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    if (RDATA(body)->dmark == (RUBY_DATA_FUNC)bm_mark) {
        node = NEW_DMETHOD(method_unbind(body));
    }
    else if (RDATA(body)->dmark == (RUBY_DATA_FUNC)blk_mark) {
        struct BLOCK *block;

        body = proc_clone(body);
        Data_Get_Struct(body, struct BLOCK, block);
        block->frame.last_func = id;
        block->frame.orig_func = id;
        block->frame.last_class = mod;
        node = NEW_BMETHOD(body);
    }
    else {
        /* type error */
        rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)");
    }

    noex = NOEX_PUBLIC;
    if (ruby_cbase == mod) {
        if (SCOPE_TEST(SCOPE_PRIVATE)) {
            noex = NOEX_PRIVATE;
        }
        else if (SCOPE_TEST(SCOPE_PROTECTED)) {
            noex = NOEX_PROTECTED;
        }
    }
    rb_add_method(mod, id, node, noex);
    return body;
}


nesting (Module)

/*
 *  call-seq:
 *     Module.nesting    => array
 *
 *  Returns the list of +Modules+ nested at the point of call.
 *
 *     module M1
 *       module M2
 *         $a = Module.nesting
 *       end
 *     end
 *     $a           #=> [M1::M2, M1]
 *     $a[0].name   #=> "M1::M2"
 */

static VALUE
rb_mod_nesting()
{
    NODE *cbase = ruby_cref;
    VALUE ary = rb_ary_new();

    while (cbase && cbase->nd_next) {
        if (!NIL_P(cbase->nd_clss)) rb_ary_push(ary, cbase->nd_clss);
        cbase = cbase->nd_next;
    }
    if (ruby_wrapper && RARRAY(ary)->len == 0) {
        rb_ary_push(ary, ruby_wrapper);
    }
    return ary;
}


constants (Module)

/*
 *  call-seq:
 *     Module.constants   => array
 *
 *  Returns an array of the names of all constants defined in the
 *  system. This list includes the names of all modules and classes.
 *
 *     p Module.constants.sort[1..5]
 *
 *  <em>produces:</em>
 *
 *     ["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]
 */

static VALUE
rb_mod_s_constants()
{
    NODE *cbase = ruby_cref;
    void *data = 0;

    while (cbase) {
        if (!NIL_P(cbase->nd_clss)) {
            data = rb_mod_const_at(cbase->nd_clss, data);
        }
        cbase = cbase->nd_next;
    }

    if (!NIL_P(ruby_cbase)) {
        data = rb_mod_const_of(ruby_cbase, data);
    }
    return rb_const_list(data);
}


autoload (Module)

/*
 *  call-seq:
 *     mod.autoload(name, filename)   => nil
 *
 *  Registers _filename_ to be loaded (using <code>Kernel::require</code>)
 *  the first time that _name_ (which may be a <code>String</code> or
 *  a symbol) is accessed in the namespace of _mod_.
 *
 *     module A
 *     end
 *     A.autoload(:B, "b")
 *     A::B.doit            # autoloads "b"
 */

static VALUE
rb_mod_autoload(mod, sym, file)
    VALUE mod;
    VALUE sym;
    VALUE file;
{
    ID id = rb_to_id(sym);

    Check_SafeStr(file);
    rb_autoload(mod, id, RSTRING(file)->ptr);
    return Qnil;
}


autoload? (Module)

/*
 *  call-seq:
 *     mod.autoload?(name)   => String or nil
 *
 *  Returns _filename_ to be loaded if _name_ is registered as
 *  +autoload+ in the namespace of _mod_.
 *
 *     module A
 *     end
 *     A.autoload(:B, "b")
 *     A.autoload?(:B)            # => "b"
 */

static VALUE
rb_mod_autoload_p(mod, sym)
    VALUE mod, sym;
{
    return rb_autoload_p(mod, rb_to_id(sym));
}


instance_method (Module)

/*
 *  call-seq:
 *     mod.instance_method(symbol)   => unbound_method
 *
 *  Returns an +UnboundMethod+ representing the given
 *  instance method in _mod_.
 *
 *     class Interpreter
 *       def do_a() print "there, "; end
 *       def do_d() print "Hello ";  end
 *       def do_e() print "!\n";     end
 *       def do_v() print "Dave";    end
 *       Dispatcher = {
 *        ?a => instance_method(:do_a),
 *        ?d => instance_method(:do_d),
 *        ?e => instance_method(:do_e),
 *        ?v => instance_method(:do_v)
 *       }
 *       def interpret(string)
 *         string.each_byte {|b| Dispatcher[b].bind(self).call }
 *       end
 *     end
 *
 *
 *     interpreter = Interpreter.new
 *     interpreter.interpret('dave')
 *
 *  <em>produces:</em>
 *
 *     Hello there, Dave!
 */

static VALUE
rb_mod_method(mod, vid)
    VALUE mod;
    VALUE vid;
{
    return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod);
}


included (Module)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


extended (Module)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


method_added (Module)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


method_removed (Module)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


method_undefined (Module)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


freeze (Module)

/*
 *  call-seq:
 *     mod.freeze
 *
 *  Prevents further modifications to <i>mod</i>.
 */

static VALUE
rb_mod_freeze(mod)
    VALUE mod;
{
    rb_mod_to_s(mod);
    return rb_obj_freeze(mod);
}


=== (Module)

/*
 *  call-seq:
 *     mod === obj    => true or false
 *
 *  Case Equality---Returns <code>true</code> if <i>anObject</i> is an
 *  instance of <i>mod</i> or one of <i>mod</i>'s descendents. Of
 *  limited use for modules, but can be used in <code>case</code>
 *  statements to classify objects by class.
 */

static VALUE
rb_mod_eqq(mod, arg)
    VALUE mod, arg;
{
    return rb_obj_is_kind_of(arg, mod);
}


== (Module)

/*
 *  call-seq:
 *     obj == other        => true or false
 *     obj.equal?(other)   => true or false
 *     obj.eql?(other)     => true or false
 *
 *  Equality---At the <code>Object</code> level, <code>==</code> returns
 *  <code>true</code> only if <i>obj</i> and <i>other</i> are the
 *  same object. Typically, this method is overridden in descendent
 *  classes to provide class-specific meaning.
 *
 *  Unlike <code>==</code>, the <code>equal?</code> method should never be
 *  overridden by subclasses: it is used to determine object identity
 *  (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same
 *  object as <code>b</code>).
 *
 *  The <code>eql?</code> method returns <code>true</code> if
    <i>obj</i> and <i>anObject</i> have the
 *  same value. Used by <code>Hash</code> to test members for equality.
 *  For objects of class <code>Object</code>, <code>eql?</code> is
 *  synonymous with <code>==</code>. Subclasses normally continue this
 *  tradition, but there are exceptions. <code>Numeric</code> types, for
 *  example, perform type conversion across <code>==</code>, but not
 *  across <code>eql?</code>, so:
 *
 *     1 == 1.0     #=> true
 *     1.eql? 1.0   #=> false
 */

static VALUE
rb_obj_equal(obj1, obj2)
    VALUE obj1, obj2;
{
    if (obj1 == obj2) return Qtrue;
    return Qfalse;
}


<=> (Module)

/*
 *  call-seq:
 *     mod <=> other_mod   => -1, 0, +1, or nil
 *
 *  Comparison---Returns -1 if <i>mod</i> includes <i>other_mod</i>, 0 if
 *  <i>mod</i> is the same as <i>other_mod</i>, and +1 if <i>mod</i> is
 *  included by <i>other_mod</i> or if <i>mod</i> has no relationship with
 *  <i>other_mod</i>. Returns <code>nil</code> if <i>other_mod</i> is
 *  not a module.
 */

static VALUE
rb_mod_cmp(mod, arg)
    VALUE mod, arg;
{
    VALUE cmp;

    if (mod == arg) return INT2FIX(0);
    switch (TYPE(arg)) {
      case T_MODULE:
      case T_CLASS:
        break;
      default:
        return Qnil;
    }

    cmp = rb_class_inherited_p(mod, arg);
    if (NIL_P(cmp)) return Qnil;
    if (cmp) {
        return INT2FIX(-1);
    }
    return INT2FIX(1);
}


< (Module)

/*
 * call-seq:
 *   mod < other   =>  true, false, or nil
 *
 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
 * <code>nil</code> if there's no relationship between the two.
 * (Think of the relationship in terms of the class definition:
 * "class A<B" implies "A<B").
 *
 */

static VALUE
rb_mod_lt(mod, arg)
    VALUE mod, arg;
{
    if (mod == arg) return Qfalse;
    return rb_class_inherited_p(mod, arg);
}


<= (Module)

/*
 * call-seq:
 *   mod <= other   =>  true, false, or nil
 *
 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
 * is the same as <i>other</i>. Returns
 * <code>nil</code> if there's no relationship between the two.
 * (Think of the relationship in terms of the class definition:
 * "class A<B" implies "A<B").
 *
 */

VALUE
rb_class_inherited_p(mod, arg)
    VALUE mod, arg;
{
    VALUE start = mod;

    if (mod == arg) return Qtrue;
    switch (TYPE(arg)) {
      case T_MODULE:
      case T_CLASS:
        break;
      default:
        rb_raise(rb_eTypeError, "compared with non class/module");
    }

    if (FL_TEST(mod, FL_SINGLETON)) {
        if (RCLASS(mod)->m_tbl == RCLASS(arg)->m_tbl)
            return Qtrue;
        mod = RBASIC(mod)->klass;
    }
    while (mod) {
        if (RCLASS(mod)->m_tbl == RCLASS(arg)->m_tbl)
            return Qtrue;
        mod = RCLASS(mod)->super;
    }
    /* not mod < arg; check if mod > arg */
    while (arg) {
        if (RCLASS(arg)->m_tbl == RCLASS(start)->m_tbl)
            return Qfalse;
        arg = RCLASS(arg)->super;
    }
    return Qnil;
}


> (Module)

/*
 * call-seq:
 *   mod > other   =>  true, false, or nil
 *
 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
 * <code>nil</code> if there's no relationship between the two.
 * (Think of the relationship in terms of the class definition:
 * "class A<B" implies "B>A").
 *
 */

static VALUE
rb_mod_gt(mod, arg)
    VALUE mod, arg;
{
    if (mod == arg) return Qfalse;
    return rb_mod_ge(mod, arg);
}


>= (Module)

/*
 * call-seq:
 *   mod >= other   =>  true, false, or nil
 *
 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
 * two modules are the same. Returns
 * <code>nil</code> if there's no relationship between the two.
 * (Think of the relationship in terms of the class definition:
 * "class A<B" implies "B>A").
 *
 */

static VALUE
rb_mod_ge(mod, arg)
    VALUE mod, arg;
{
    switch (TYPE(arg)) {
      case T_MODULE:
      case T_CLASS:
        break;
      default:
        rb_raise(rb_eTypeError, "compared with non class/module");
    }

    return rb_class_inherited_p(arg, mod);
}


to_s (Module)

/*
 * call-seq:
 *   mod.to_s   => string
 *
 * Return a string representing this module or class. For basic
 * classes and modules, this is the name. For singletons, we
 * show information on the thing we're attached to as well.
 */

static VALUE
rb_mod_to_s(klass)
    VALUE klass;

{
    if (FL_TEST(klass, FL_SINGLETON)) {
        VALUE s = rb_str_new2("#<");
        VALUE v = rb_iv_get(klass, "__attached__");

        rb_str_cat2(s, "Class:");
        switch (TYPE(v)) {
          case T_CLASS: case T_MODULE:
            rb_str_append(s, rb_inspect(v));
            break;
          default:
            rb_str_append(s, rb_any_to_s(v));
            break;
        }
        rb_str_cat2(s, ">");

        return s;
    }
    return rb_str_dup(rb_class_name(klass));
}


included_modules (Module)

/*
 *  call-seq:
 *     mod.included_modules -> array
 *
 *  Returns the list of modules included in <i>mod</i>.
 *
 *     module Mixin
 *     end
 *
 *     module Outer
 *       include Mixin
 *     end
 *
 *     Mixin.included_modules   #=> []
 *     Outer.included_modules   #=> [Mixin]
 */

VALUE
rb_mod_included_modules(mod)
    VALUE mod;
{
    VALUE ary = rb_ary_new();
    VALUE p;

    for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) {
    if (BUILTIN_TYPE(p) == T_ICLASS) {
        rb_ary_push(ary, RBASIC(p)->klass);
    }
    }
    return ary;
}


include? (Module)

/*
 *  call-seq:
 *     mod.include?(module)    => true or false
 *
 *  Returns <code>true</code> if <i>module</i> is included in
 *  <i>mod</i> or one of <i>mod</i>'s ancestors.
 *
 *     module A
 *     end
 *     class B
 *       include A
 *     end
 *     class C < B
 *     end
 *     B.include?(A)   #=> true
 *     C.include?(A)   #=> true
 *     A.include?(A)   #=> false
 */

VALUE
rb_mod_include_p(mod, mod2)
    VALUE mod;
    VALUE mod2;
{
    VALUE p;

    Check_Type(mod2, T_MODULE);
    for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) {
    if (BUILTIN_TYPE(p) == T_ICLASS) {
        if (RBASIC(p)->klass == mod2) return Qtrue;
    }
    }
    return Qfalse;
}


name (Module)

/*
 *  call-seq:
 *     mod.name    => string
 *
 *  Returns the name of the module <i>mod</i>.
 */

VALUE
rb_mod_name(mod)
    VALUE mod;
{
    VALUE path = classname(mod);

    if (!NIL_P(path)) return rb_str_dup(path);
    return rb_str_new(0,0);
}


ancestors (Module)

/*
 *  call-seq:
 *     mod.ancestors -> array
 *
 *  Returns a list of modules included in <i>mod</i> (including
 *  <i>mod</i> itself).
 *
 *     module Mod
 *       include Math
 *       include Comparable
 *     end
 *
 *     Mod.ancestors    #=> [Mod, Comparable, Math]
 *     Math.ancestors   #=> [Math]
 */

VALUE
rb_mod_ancestors(mod)
    VALUE mod;
{
    VALUE p, ary = rb_ary_new();

    for (p = mod; p; p = RCLASS(p)->super) {
    if (FL_TEST(p, FL_SINGLETON))
        continue;
    if (BUILTIN_TYPE(p) == T_ICLASS) {
        rb_ary_push(ary, RBASIC(p)->klass);
    }
    else {
        rb_ary_push(ary, p);
    }
    }
    return ary;
}


attr (Module)

/*
 *  call-seq:
 *     attr(symbol, writable=false)    => nil
 *
 *  Defines a named attribute for this module, where the name is
 *  <i>symbol.</i><code>id2name</code>, creating an instance variable
 *  (<code>@name</code>) and a corresponding access method to read it.
 *  If the optional <i>writable</i> argument is <code>true</code>, also
 *  creates a method called <code>name=</code> to set the attribute.
 *
 *     module Mod
 *       attr  :size, true
 *     end
 *
 *  <em>is equivalent to:</em>
 *
 *     module Mod
 *       def size
 *         @size
 *       end
 *       def size=(val)
 *         @size = val
 *       end
 *     end
 */

static VALUE
rb_mod_attr(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE name, pub;

    rb_scan_args(argc, argv, "11", &name, &pub);
    rb_attr(klass, rb_to_id(name), 1, RTEST(pub), Qtrue);
    return Qnil;
}


attr_reader (Module)

/*
 *  call-seq:
 *     attr_reader(symbol, ...)    => nil
 *
 *  Creates instance variables and corresponding methods that return the
 *  value of each instance variable. Equivalent to calling
 *  ``<code>attr</code><i>:name</i>'' on each name in turn.
 */

static VALUE
rb_mod_attr_reader(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    int i;

    for (i=0; i<argc; i++) {
        rb_attr(klass, rb_to_id(argv[i]), 1, 0, Qtrue);
    }
    return Qnil;
}


attr_writer (Module)

/*
 *  call-seq:
 *      attr_writer(symbol, ...)    => nil
 *
 *  Creates an accessor method to allow assignment to the attribute
 *  <i>aSymbol</i><code>.id2name</code>.
 */

static VALUE
rb_mod_attr_writer(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    int i;

    for (i=0; i<argc; i++) {
        rb_attr(klass, rb_to_id(argv[i]), 0, 1, Qtrue);
    }
    return Qnil;
}


attr_accessor (Module)

/*
 *  call-seq:
 *     attr_accessor(symbol, ...)    => nil
 *
 *  Equivalent to calling ``<code>attr</code><i>symbol</i><code>,
 *  true</code>'' on each <i>symbol</i> in turn.
 *
 *     module Mod
 *       attr_accessor(:one, :two)
 *     end
 *     Mod.instance_methods.sort   #=> ["one", "one=", "two", "two="]
 */

static VALUE
rb_mod_attr_accessor(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    int i;

    for (i=0; i<argc; i++) {
        rb_attr(klass, rb_to_id(argv[i]), 1, 1, Qtrue);
    }
    return Qnil;
}


new (Module)

/*
 *  call-seq:
 *    Module.new                  => mod
 *    Module.new {|mod| block }   => mod
 *
 *  Creates a new anonymous module. If a block is given, it is passed
 *  the module object, and the block is evaluated in the context of this
 *  module using <code>module_eval</code>.
 *
 *     Fred = Module.new do
 *       def meth1
 *         "hello"
 *       end
 *       def meth2
 *         "bye"
 *       end
 *     end
 *     a = "my string"
 *     a.extend(Fred)   #=> "my string"
 *     a.meth1          #=> "hello"
 *     a.meth2          #=> "bye"
 */

static VALUE
rb_mod_initialize(module)
    VALUE module;
{
    if (rb_block_given_p()) {
        rb_mod_module_eval(0, 0, module);
    }
    return Qnil;
}


instance_methods (Module)

/*
 *  call-seq:
 *     mod.instance_methods(include_super=true)   => array
 *
 *  Returns an array containing the names of public instance methods in
 *  the receiver. For a module, these are the public methods; for a
 *  class, they are the instance (not singleton) methods. With no
 *  argument, or with an argument that is <code>false</code>, the
 *  instance methods in <i>mod</i> are returned, otherwise the methods
 *  in <i>mod</i> and <i>mod</i>'s superclasses are returned.
 *
 *     module A
 *       def method1()  end
 *     end
 *     class B
 *       def method2()  end
 *     end
 *     class C < B
 *       def method3()  end
 *     end
 *
 *     A.instance_methods                #=> ["method1"]
 *     B.instance_methods(false)         #=> ["method2"]
 *     C.instance_methods(false)         #=> ["method3"]
 *     C.instance_methods(true).length   #=> 43
 */

VALUE
rb_class_instance_methods(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    return class_instance_method_list(argc, argv, mod, ins_methods_i);
}


public_instance_methods (Module)

/*
 *  call-seq:
 *     mod.public_instance_methods(include_super=true)   => array
 *
 *  Returns a list of the public instance methods defined in <i>mod</i>.
 *  If the optional parameter is not <code>false</code>, the methods of
 *  any ancestors are included.
 */

VALUE
rb_class_public_instance_methods(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    return class_instance_method_list(argc, argv, mod, ins_methods_pub_i);
}


protected_instance_methods (Module)

/*
 *  call-seq:
 *     mod.protected_instance_methods(include_super=true)   => array
 *
 *  Returns a list of the protected instance methods defined in
 *  <i>mod</i>. If the optional parameter is not <code>false</code>, the
 *  methods of any ancestors are included.
 */

VALUE
rb_class_protected_instance_methods(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    return class_instance_method_list(argc, argv, mod, ins_methods_prot_i);
}


private_instance_methods (Module)

/*
 *  call-seq:
 *     mod.private_instance_methods(include_super=true)    => array
 *
 *  Returns a list of the private instance methods defined in
 *  <i>mod</i>. If the optional parameter is not <code>false</code>, the
 *  methods of any ancestors are included.
 *
 *     module Mod
 *       def method1()  end
 *       private :method1
 *       def method2()  end
 *     end
 *     Mod.instance_methods           #=> ["method2"]
 *     Mod.private_instance_methods   #=> ["method1"]
 */

VALUE
rb_class_private_instance_methods(argc, argv, mod)
    int argc;
    VALUE *argv;
    VALUE mod;
{
    return class_instance_method_list(argc, argv, mod, ins_methods_priv_i);
}


class_variable_defined? (Module)

/*
 *  call-seq:
 *     obj.class_variable_defined?(symbol)    => true or false
 *
 *  Returns <code>true</code> if the given class variable is defined
 *  in <i>obj</i>.
 *
 *     class Fred
 *       @@foo = 99
 *     end
 *     Fred.class_variable_defined?(:@@foo)    #=> true
 *     Fred.class_variable_defined?(:@@bar)    #=> false
 */

static VALUE
rb_mod_cvar_defined(obj, iv)
    VALUE obj, iv;
{
    ID id = rb_to_id(iv);

    if (!rb_is_class_id(id)) {
        rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id));
    }
    return rb_cvar_defined(obj, id);
}


constants (Module)

/*
 *  call-seq:
 *     mod.constants    => array
 *
 *  Returns an array of the names of the constants accessible in
 *  <i>mod</i>. This includes the names of constants in any included
 *  modules (example at start of section).
 */

VALUE
rb_mod_constants(mod)
    VALUE mod;
{
    return rb_const_list(rb_mod_const_of(mod, 0));
}


const_get (Module)

/*
 *  call-seq:
 *     mod.const_get(sym)    => obj
 *
 *  Returns the value of the named constant in <i>mod</i>.
 *
 *     Math.const_get(:PI)   #=> 3.14159265358979
 */

static VALUE
rb_mod_const_get(mod, name)
    VALUE mod, name;
{
    ID id = rb_to_id(name);

    if (!rb_is_const_id(id)) {
        rb_name_error(id, "wrong constant name %s", rb_id2name(id));
    }
    return rb_const_get(mod, id);
}


const_set (Module)

/*
 *  call-seq:
 *     mod.const_set(sym, obj)    => obj
 *
 *  Sets the named constant to the given object, returning that object.
 *  Creates a new constant if no constant with the given name previously
 *  existed.
 *
 *     Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)   #=> 3.14285714285714
 *     Math::HIGH_SCHOOL_PI - Math::PI              #=> 0.00126448926734968
 */

static VALUE
rb_mod_const_set(mod, name, value)
    VALUE mod, name, value;
{
    ID id = rb_to_id(name);

    if (!rb_is_const_id(id)) {
        rb_name_error(id, "wrong constant name %s", rb_id2name(id));
    }
    rb_const_set(mod, id, value);
    return value;
}


const_defined? (Module)

/*
 *  call-seq:
 *     mod.const_defined?(sym)   => true or false
 *
 *  Returns <code>true</code> if a constant with the given name is
 *  defined by <i>mod</i>.
 *
 *     Math.const_defined? "PI"   #=> true
 */

static VALUE
rb_mod_const_defined(mod, name)
    VALUE mod, name;
{
    ID id = rb_to_id(name);

    if (!rb_is_const_id(id)) {
        rb_name_error(id, "wrong constant name %s", rb_id2name(id));
    }
    return rb_const_defined_at(mod, id);
}


remove_const (Module)

/*
 *  call-seq:
 *     remove_const(sym)   => obj
 *
 *  Removes the definition of the given constant, returning that
 *  constant's value. Predefined classes and singleton objects (such as
 *  <i>true</i>) cannot be removed.
 */

VALUE
rb_mod_remove_const(mod, name)
    VALUE mod, name;
{
    ID id = rb_to_id(name);
    VALUE val;

    if (!rb_is_const_id(id)) {
    rb_name_error(id, "`%s' is not allowed as a constant name", rb_id2name(id));
    }
    if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
    rb_raise(rb_eSecurityError, "Insecure: can't remove constant");
    if (OBJ_FROZEN(mod)) rb_error_frozen("class/module");

    if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, (st_data_t*)&id, &val)) {
    if (val == Qundef) {
        autoload_delete(mod, id);
        val = Qnil;
    }
    return val;
    }
    if (rb_const_defined_at(mod, id)) {
    rb_name_error(id, "cannot remove %s::%s",
         rb_class2name(mod), rb_id2name(id));
    }
    rb_name_error(id, "constant %s::%s not defined",
          rb_class2name(mod), rb_id2name(id));
    return Qnil;		/* not reached */
}


const_missing (Module)

/*
 * call-seq:
 *    mod.const_missing(sym)    => obj
 *
 *  Invoked when a reference is made to an undefined constant in
 *  <i>mod</i>. It is passed a symbol for the undefined constant, and
 *  returns a value to be used for that constant. The
 *  following code is a (very bad) example: if reference is made to
 *  an undefined constant, it attempts to load a file whose name is
 *  the lowercase version of the constant (thus class <code>Fred</code> is
 *  assumed to be in file <code>fred.rb</code>). If found, it returns the
 *  value of the loaded class. It therefore implements a perverse
 *  kind of autoload facility.
 *
 *    def Object.const_missing(name)
 *      @looked_for ||= {}
 *      str_name = name.to_s
 *      raise "Class not found: #{name}" if @looked_for[str_name]
 *      @looked_for[str_name] = 1
 *      file = str_name.downcase
 *      require file
 *      klass = const_get(name)
 *      return klass if klass
 *      raise "Class not found: #{name}"
 *    end
 *
 */

VALUE
rb_mod_const_missing(klass, name)
    VALUE klass, name;
{
    ruby_frame = ruby_frame->prev; /* pop frame for "const_missing" */
    uninitialized_constant(klass, rb_to_id(name));
    return Qnil;		/* not reached */
}


class_variables (Module)

/*
 *  call-seq:
 *     mod.class_variables   => array
 *
 *  Returns an array of the names of class variables in <i>mod</i> and
 *  the ancestors of <i>mod</i>.
 *
 *     class One
 *       @@var1 = 1
 *     end
 *     class Two < One
 *       @@var2 = 2
 *     end
 *     One.class_variables   #=> ["@@var1"]
 *     Two.class_variables   #=> ["@@var2", "@@var1"]
 */

VALUE
rb_mod_class_variables(obj)
    VALUE obj;
{
    VALUE ary = rb_ary_new();

    for (;;) {
    if (RCLASS(obj)->iv_tbl) {
        st_foreach_safe(RCLASS(obj)->iv_tbl, cv_i, ary);
    }
    obj = RCLASS(obj)->super;
    if (!obj) break;
    }
    return ary;
}


remove_class_variable (Module)

/*
 *  call-seq:
 *     remove_class_variable(sym)    => obj
 *
 *  Removes the definition of the <i>sym</i>, returning that
 *  constant's value.
 *
 *     class Dummy
 *       @@var = 99
 *       puts @@var
 *       remove_class_variable(:@@var)
 *       puts(defined? @@var)
 *     end
 *
 *  <em>produces:</em>
 *
 *     99
 *     nil
 */

VALUE
rb_mod_remove_cvar(mod, name)
    VALUE mod, name;
{
    ID id = rb_to_id(name);
    VALUE val;

    if (!rb_is_class_id(id)) {
    rb_name_error(id, "wrong class variable name %s", rb_id2name(id));
    }
    if (!OBJ_TAINTED(mod) && rb_safe_level() >= 4)
    rb_raise(rb_eSecurityError, "Insecure: can't remove class variable");
    if (OBJ_FROZEN(mod)) rb_error_frozen("class/module");

    if (RCLASS(mod)->iv_tbl && st_delete(ROBJECT(mod)->iv_tbl, (st_data_t*)&id, &val)) {
    return val;
    }
    if (rb_cvar_defined(mod, id)) {
    rb_name_error(id, "cannot remove %s for %s",
         rb_id2name(id), rb_class2name(mod));
    }
    rb_name_error(id, "class variable %s not defined for %s",
          rb_id2name(id), rb_class2name(mod));
    return Qnil;		/* not reached */
}


class_variable_get (Module)

/*
 *  call-seq:
 *     mod.class_variable_get(symbol)    => obj
 *
 *  Returns the value of the given class variable (or throws a
 *  <code>NameError</code> exception). The <code>@@</code> part of the
 *  variable name should be included for regular class variables
 *
 *     class Fred
 *       @@foo = 99
 *     end
 *
 *     def Fred.foo
 *       class_variable_get(:@@foo)     #=> 99
 *     end
 */

static VALUE
rb_mod_cvar_get(obj, iv)
    VALUE obj, iv;
{
    ID id = rb_to_id(iv);

    if (!rb_is_class_id(id)) {
        rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id));
    }
    return rb_cvar_get(obj, id);
}


class_variable_set (Module)

/*
 *  call-seq:
 *     obj.class_variable_set(symbol, obj)    => obj
 *
 *  Sets the class variable names by <i>symbol</i> to
 *  <i>object</i>.
 *
 *     class Fred
 *       @@foo = 99
 *       def foo
 *         @@foo
 *       end
 *     end
 *
 *     def Fred.foo
 *       class_variable_set(:@@foo, 101)      #=> 101
 *     end
 *     Fred.foo
 *     Fred.new.foo                             #=> 101
 */

static VALUE
rb_mod_cvar_set(obj, iv, val)
    VALUE obj, iv, val;
{
    ID id = rb_to_id(iv);

    if (!rb_is_class_id(id)) {
        rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id));
    }
    rb_cvar_set(obj, id, val, Qfalse);
    return val;
}


wait (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 93
    def wait(timeout = nil)
      @monitor.instance_eval {mon_check_owner()}
      timer = create_timer(timeout)

      Thread.critical = true
      count = @monitor.instance_eval {mon_exit_for_cond()}
      @waiters.push(Thread.current)

      begin
        Thread.stop
        return true
      rescue Timeout
        return false
      ensure
        Thread.critical = true
        begin
          if timer && timer.alive?
            Thread.kill(timer)
          end
          if @waiters.include?(Thread.current)  # interrupted?
            @waiters.delete(Thread.current)
          end
          @monitor.instance_eval {mon_enter_for_cond(count)}
        ensure
          Thread.critical = false
        end
      end
    end


wait_while (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 124
    def wait_while
      while yield
        wait
      end
    end


wait_until (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 131
    def wait_until
      until yield
        wait
      end
    end


signal (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 138
    def signal
      @monitor.instance_eval {mon_check_owner()}
      Thread.critical = true
      t = @waiters.shift
      t.wakeup if t
      Thread.critical = false
      Thread.pass
    end


broadcast (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 148
    def broadcast
      @monitor.instance_eval {mon_check_owner()}
      Thread.critical = true
      for t in @waiters
        t.wakeup
      end
      @waiters.clear
      Thread.critical = false
      Thread.pass
    end


count_waiters (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 159
    def count_waiters
      return @waiters.length
    end


new (MonitorMixin::ConditionVariable)

# File lib/monitor.rb, line 165
    def initialize(monitor)
      @monitor = monitor
      @waiters = []
    end


extend_object (MonitorMixin)

# File lib/monitor.rb, line 185
  def self.extend_object(obj)
    super(obj)
    obj.instance_eval {mon_initialize()}
  end


mon_try_enter (MonitorMixin)

# File lib/monitor.rb, line 193
  def mon_try_enter
    result = false
    Thread.critical = true
    if @mon_owner.nil?
      @mon_owner = Thread.current
    end
    if @mon_owner == Thread.current
      @mon_count += 1
      result = true
    end
    Thread.critical = false
    return result
  end


mon_enter (MonitorMixin)

# File lib/monitor.rb, line 212
  def mon_enter
    Thread.critical = true
    mon_acquire(@mon_entering_queue)
    @mon_count += 1
  ensure
    Thread.critical = false
  end


mon_exit (MonitorMixin)

# File lib/monitor.rb, line 223
  def mon_exit
    mon_check_owner
    Thread.critical = true
    @mon_count -= 1
    if @mon_count == 0
      mon_release
    end
    Thread.critical = false
    Thread.pass
  end


mon_synchronize (MonitorMixin)

# File lib/monitor.rb, line 239
  def mon_synchronize
    mon_enter
    begin
      yield
    ensure
      mon_exit
    end
  end


new_cond (MonitorMixin)

# File lib/monitor.rb, line 255
  def new_cond
    return ConditionVariable.new(self)
  end


new (MonitorMixin)

# File lib/monitor.rb, line 261
  def initialize(*args)
    super
    mon_initialize
  end


new (Msxml)

# File ext/win32ole/sample/xml.rb, line 7206
  def initialize(obj = nil)
    @clsid = "{CFC399AF-D876-11D0-9C10-00C04FC99C8E}"
    @progid = "Msxml"
    if obj.nil?
      @dispatch = WIN32OLE.new(@progid)
    else
      @dispatch = obj
    end
  end


method_missing (Msxml)

# File ext/win32ole/sample/xml.rb, line 7216
  def method_missing(cmd, *arg)
    @dispatch.method_missing(cmd, *arg)
  end


url= (Msxml)

# File ext/win32ole/sample/xml.rb, line 7223
  def url=(arg0)
    ret = @dispatch._setproperty(65641, [arg0], [VT_BSTR, VT_HRESULT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


charset= (Msxml)

# File ext/win32ole/sample/xml.rb, line 7232
  def charset=(arg0)
    ret = @dispatch._setproperty(65645, [arg0], [VT_BSTR, VT_HRESULT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


async= (Msxml)

# File ext/win32ole/sample/xml.rb, line 7241
  def async=(arg0)
    ret = @dispatch._setproperty(65649, [arg0], [VT_BOOL, VT_HRESULT])
    @lastargs = WIN32OLE::ARGV
    ret
  end


root (Msxml)

# File ext/win32ole/sample/xml.rb, line 7250
  def root
    OLEProperty.new(@dispatch, 65637, [VT_BYREF|VT_BYREF|VT_DISPATCH], [VT_BYREF|VT_BYREF|VT_DISPATCH, VT_HRESULT])
  end


url (Msxml)

# File ext/win32ole/sample/xml.rb, line 7257
  def url
    OLEProperty.new(@dispatch, 65641, [VT_BYREF|VT_BSTR], [VT_BYREF|VT_BSTR, VT_HRESULT])
  end


readyState (Msxml)

# File ext/win32ole/sample/xml.rb, line 7264
  def readyState
    OLEProperty.new(@dispatch, 65643, [VT_BYREF|VT_I4], [VT_BYREF|VT_I4, VT_HRESULT])
  end


charset (Msxml)

# File ext/win32ole/sample/xml.rb, line 7271
  def charset
    OLEProperty.new(@dispatch, 65645, [VT_BYREF|VT_BSTR], [VT_BYREF|VT_BSTR, VT_HRESULT])
  end


version (Msxml)

# File ext/win32ole/sample/xml.rb, line 7278
  def version
    OLEProperty.new(@dispatch, 65646, [VT_BYREF|VT_BSTR], [VT_BYREF|VT_BSTR, VT_HRESULT])
  end


doctype (Msxml)

# File ext/win32ole/sample/xml.rb, line 7285
  def doctype
    OLEProperty.new(@dispatch, 65647, [VT_BYREF|VT_BSTR], [VT_BYREF|VT_BSTR, VT_HRESULT])
  end


async (Msxml)

# File ext/win32ole/sample/xml.rb, line 7292
  def async
    OLEProperty.new(@dispatch, 65649, [VT_BYREF|VT_BOOL], [VT_BYREF|VT_BOOL, VT_HRESULT])
  end


createElement (Msxml)

# File ext/win32ole/sample/xml.rb, line 7301
  def createElement(arg0, arg1=nil, arg2=nil)
    ret = @dispatch._invoke(65644, [arg0, arg1, arg2], [VT_VARIANT, VT_VARIANT, VT_BYREF|VT_BYREF|VT_DISPATCH])
    @lastargs = WIN32OLE::ARGV
    ret
  end


new (Mutex)

# File lib/thread.rb, line 60
  def initialize
    @waiting = []
    @locked = false;
    @waiting.taint              # enable tainted comunication
    self.taint
  end


locked? (Mutex)

# File lib/thread.rb, line 70
  def locked?
    @locked
  end


try_lock (Mutex)

# File lib/thread.rb, line 78
  def try_lock
    result = false
    Thread.critical = true
    unless @locked
      @locked = true
      result = true
    end
    Thread.critical = false
    result
  end


lock (Mutex)

# File lib/thread.rb, line 92
  def lock
    while (Thread.critical = true; @locked)
      @waiting.push Thread.current
      Thread.stop
    end
    @locked = true
    Thread.critical = false
    self
  end


unlock (Mutex)

# File lib/thread.rb, line 105
  def unlock
    return unless @locked
    Thread.critical = true
    @locked = false
    begin
      t = @waiting.shift
      t.wakeup if t
    rescue ThreadError
      retry
    end
    Thread.critical = false
    begin
      t.run if t
    rescue ThreadError
    end
    self
  end


synchronize (Mutex)

# File lib/thread.rb, line 127
  def synchronize
    lock
    begin
      yield
    ensure
      unlock
    end
  end


exclusive_unlock (Mutex)

# File lib/thread.rb, line 140
  def exclusive_unlock
    return unless @locked
    Thread.exclusive do
      @locked = false
      begin
        t = @waiting.shift
        t.wakeup if t
      rescue ThreadError
        retry
      end
      yield
    end
    self
  end


define_aliases (Mutex_m)

# File lib/mutex_m.rb, line 32
  def Mutex_m.define_aliases(cl)
    cl.module_eval %q{
      alias locked? mu_locked?
      alias lock mu_lock
      alias unlock mu_unlock
      alias try_lock mu_try_lock
      alias synchronize mu_synchronize
    }
  end


append_features (Mutex_m)

# File lib/mutex_m.rb, line 42
  def Mutex_m.append_features(cl)
    super
    define_aliases(cl) unless cl.instance_of?(Module)
  end


extend_object (Mutex_m)

# File lib/mutex_m.rb, line 47
  def Mutex_m.extend_object(obj)
    super
    obj.mu_extended
  end


mu_extended (Mutex_m)

# File lib/mutex_m.rb, line 52
  def mu_extended
    unless (defined? locked? and
            defined? lock and
            defined? unlock and
            defined? try_lock and
            defined? synchronize)
      Mutex_m.define_aliases(class<<self;self;end)
    end
    mu_initialize
  end


mu_synchronize (Mutex_m)

# File lib/mutex_m.rb, line 64
  def mu_synchronize
    begin
      mu_lock
      yield
    ensure
      mu_unlock
    end
  end


mu_locked? (Mutex_m)

# File lib/mutex_m.rb, line 73
  def mu_locked?
    @mu_locked
  end


mu_try_lock (Mutex_m)

# File lib/mutex_m.rb, line 77
  def mu_try_lock
    result = false
    Thread.critical = true
    unless @mu_locked
      @mu_locked = true
      result = true
    end
    Thread.critical = false
    result
  end


mu_lock (Mutex_m)

# File lib/mutex_m.rb, line 88
  def mu_lock
    while (Thread.critical = true; @mu_locked)
      @mu_waiting.push Thread.current
      Thread.stop
    end
    @mu_locked = true
    Thread.critical = false
    self
  end


mu_unlock (Mutex_m)

# File lib/mutex_m.rb, line 98
  def mu_unlock
    return unless @mu_locked
    Thread.critical = true
    wait = @mu_waiting
    @mu_waiting = []
    @mu_locked = false
    Thread.critical = false
    for w in wait
      w.run
    end
    self
  end


new (Mutex_m)

# File lib/mutex_m.rb, line 118
  def initialize(*args)
    mu_initialize
    super
  end


new (MyExcel)

# File ext/win32ole/tests/testWIN32OLE.rb, line 319
    def MyExcel.new
        super "Excel.Application"
    end


connect (MyExcel)

# File ext/win32ole/tests/testWIN32OLE.rb, line 322
    def MyExcel.connect
        super "Excel.Application"
    end


new (NameDescriptor)

# File lib/rdoc/ri/ri_util.rb, line 28
  def initialize(arg)
    @class_names = []
    separator = nil

    tokens = arg.split(/(\.|::|#)/)

    # Skip leading '::', '#' or '.', but remember it might
    # be a method name qualifier
    separator = tokens.shift if tokens[0] =~ /^(\.|::|#)/

    # Skip leading '::', but remember we potentially have an inst

    # leading stuff must be class names

    while tokens[0] =~ /^[A-Z]/
      @class_names << tokens.shift
      unless tokens.empty?
        separator = tokens.shift
        break unless separator == "::"
      end
    end

    # Now must have a single token, the method name, or an empty
    # array
    unless tokens.empty?
      @method_name = tokens.shift
      # We may now have a trailing !, ?, or = to roll into
      # the method name
      if !tokens.empty? && tokens[0] =~ /^[!?=]$/
        @method_name << tokens.shift
      end

      if @method_name =~ /::|\.|#/ or !tokens.empty?
        raise RiError.new("Bad argument: #{arg}")
      end
      if separator && separator != '.'
        @is_class_method = separator == "::"
      end
    end
  end


full_class_name (NameDescriptor)

# File lib/rdoc/ri/ri_util.rb, line 72
  def full_class_name
    @class_names.join("::")
  end


new (NameError)

/*
 * call-seq:
 *   NameError.new(msg [, name])  => name_error
 *
 * Construct a new NameError exception. If given the <i>name</i>
 * parameter may subsequently be examined using the <code>NameError.name</code>
 * method.
 */

static VALUE
name_err_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE name;

    name = (argc > 1) ? argv[--argc] : Qnil;
    rb_call_super(argc, argv);
    rb_iv_set(self, "name", name);
    return self;
}


name (NameError)

/*
 *  call-seq:
 *    name_error.name    =>  string or nil
 *
 *  Return the name associated with this NameError exception.
 */

static VALUE
name_err_name(self)
    VALUE self;
{
    return rb_attr_get(self, rb_intern("name"));
}


to_s (NameError)

/*
 * call-seq:
 *  name_error.to_s   => string
 *
 * Produce a nicely-formated string representing the +NameError+.
 */

static VALUE
name_err_to_s(exc)
    VALUE exc;
{
    VALUE mesg = rb_attr_get(exc, rb_intern("mesg")), str = mesg;

    if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
    StringValue(str);
    if (str != mesg) {
        rb_iv_set(exc, "mesg", mesg = str);
    }
    if (OBJ_TAINTED(exc)) OBJ_TAINT(mesg);
    return mesg;
}


apop? (Net::APOP)

# File lib/net/pop.rb, line 586
    def apop?
      true
    end


open (Net::FTP)

# File lib/net/ftp.rb, line 111
    def FTP.open(host, user = nil, passwd = nil, acct = nil)
      if block_given?
        ftp = new(host, user, passwd, acct)
        begin
          yield ftp
        ensure
          ftp.close
        end
      else
        new(host, user, passwd, acct)
      end
    end


new (Net::FTP)

# File lib/net/ftp.rb, line 129
    def initialize(host = nil, user = nil, passwd = nil, acct = nil)
      super()
      @binary = true
      @passive = false
      @debug_mode = false
      @resume = false
      if host
        connect(host)
        if user
          login(user, passwd, acct)
        end
      end
    end


return_code (Net::FTP)

# File lib/net/ftp.rb, line 144
    def return_code
      $stderr.puts("warning: Net::FTP#return_code is obsolete and do nothing")
      return "\n"
    end


return_code= (Net::FTP)

# File lib/net/ftp.rb, line 150
    def return_code=(s)
      $stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing")
    end


connect (Net::FTP)

# File lib/net/ftp.rb, line 170
    def connect(host, port = FTP_PORT)
      if @debug_mode
        print "connect: ", host, ", ", port, "\n"
      end
      synchronize do
        @sock = open_socket(host, port)
        voidresp
      end
    end


set_socket (Net::FTP)

# File lib/net/ftp.rb, line 183
    def set_socket(sock, get_greeting = true)
      synchronize do
        @sock = sock
        if get_greeting
          voidresp
        end
      end
    end


sendcmd (Net::FTP)

# File lib/net/ftp.rb, line 261
    def sendcmd(cmd)
      synchronize do
        putline(cmd)
        return getresp
      end
    end


voidcmd (Net::FTP)

# File lib/net/ftp.rb, line 271
    def voidcmd(cmd)
      synchronize do
        putline(cmd)
        voidresp
      end
    end


login (Net::FTP)

# File lib/net/ftp.rb, line 371
    def login(user = "anonymous", passwd = nil, acct = nil)
      if user == "anonymous" and passwd == nil
        passwd = getaddress
      end

      resp = ""
      synchronize do
        resp = sendcmd('USER ' + user)
        if resp[0] == ?3
          resp = sendcmd('PASS ' + passwd)
        end
        if resp[0] == ?3
          resp = sendcmd('ACCT ' + acct)
        end
      end
      if resp[0] != ?2
        raise FTPReplyError, resp
      end
      @welcome = resp
    end


retrbinary (Net::FTP)

# File lib/net/ftp.rb, line 398
    def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
      synchronize do
        voidcmd("TYPE I")
        conn = transfercmd(cmd, rest_offset)
        loop do
          data = conn.read(blocksize)
          break if data == nil
          yield(data)
        end
        conn.close
        voidresp
      end
    end


retrlines (Net::FTP)

# File lib/net/ftp.rb, line 418
    def retrlines(cmd) # :yield: line
      synchronize do
        voidcmd("TYPE A")
        conn = transfercmd(cmd)
        loop do
          line = conn.gets
          break if line == nil
          if line[-2, 2] == CRLF
            line = line[0 .. -3]
          elsif line[-1] == ?\n
            line = line[0 .. -2]
          end
          yield(line)
        end
        conn.close
        voidresp
      end
    end


storbinary (Net::FTP)

# File lib/net/ftp.rb, line 443
    def storbinary(cmd, file, blocksize, rest_offset = nil, &block) # :yield: data
      if rest_offset
        file.seek(rest_offset, IO::SEEK_SET)
      end
      synchronize do
        voidcmd("TYPE I")
        conn = transfercmd(cmd, rest_offset)
        loop do
          buf = file.read(blocksize)
          break if buf == nil
          conn.write(buf)
          yield(buf) if block
        end
        conn.close
        voidresp
      end
    end


storlines (Net::FTP)

# File lib/net/ftp.rb, line 467
    def storlines(cmd, file, &block) # :yield: line
      synchronize do
        voidcmd("TYPE A")
        conn = transfercmd(cmd)
        loop do
          buf = file.gets
          break if buf == nil
          if buf[-2, 2] != CRLF
            buf = buf.chomp + CRLF
          end
          conn.write(buf)
          yield(buf) if block
        end
        conn.close
        voidresp
      end
    end


getbinaryfile (Net::FTP)

# File lib/net/ftp.rb, line 490
    def getbinaryfile(remotefile, localfile = File.basename(remotefile),
                      blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      if @resume
        rest_offset = File.size?(localfile)
        f = open(localfile, "a")
      else
        rest_offset = nil
        f = open(localfile, "w")
      end
      begin
        f.binmode
        retrbinary("RETR " + remotefile, blocksize, rest_offset) do |data|
          f.write(data)
          yield(data) if block
        end
      ensure
        f.close
      end
    end


gettextfile (Net::FTP)

# File lib/net/ftp.rb, line 515
    def gettextfile(remotefile, localfile = File.basename(remotefile), &block) # :yield: line
      f = open(localfile, "w")
      begin
        retrlines("RETR " + remotefile) do |line|
          f.puts(line)
          yield(line) if block
        end
      ensure
        f.close
      end
    end


get (Net::FTP)

# File lib/net/ftp.rb, line 531
    def get(remotefile, localfile = File.basename(remotefile),
            blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      unless @binary
        gettextfile(remotefile, localfile, &block)
      else
        getbinaryfile(remotefile, localfile, blocksize, &block)
      end
    end


putbinaryfile (Net::FTP)

# File lib/net/ftp.rb, line 545
    def putbinaryfile(localfile, remotefile = File.basename(localfile),
                      blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      if @resume
        begin
          rest_offset = size(remotefile)
        rescue Net::FTPPermError
          rest_offset = nil
        end
      else
        rest_offset = nil
      end
      f = open(localfile)
      begin
        f.binmode
        storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block)
      ensure
        f.close
      end
    end


puttextfile (Net::FTP)

# File lib/net/ftp.rb, line 570
    def puttextfile(localfile, remotefile = File.basename(localfile), &block) # :yield: line
      f = open(localfile)
      begin
        storlines("STOR " + remotefile, f, &block)
      ensure
        f.close
      end
    end


put (Net::FTP)

# File lib/net/ftp.rb, line 583
    def put(localfile, remotefile = File.basename(localfile),
            blocksize = DEFAULT_BLOCKSIZE, &block)
      unless @binary
        puttextfile(localfile, remotefile, &block)
      else
        putbinaryfile(localfile, remotefile, blocksize, &block)
      end
    end


acct (Net::FTP)

# File lib/net/ftp.rb, line 595
    def acct(account)
      cmd = "ACCT " + account
      voidcmd(cmd)
    end


nlst (Net::FTP)

# File lib/net/ftp.rb, line 603
    def nlst(dir = nil)
      cmd = "NLST"
      if dir
        cmd = cmd + " " + dir
      end
      files = []
      retrlines(cmd) do |line|
        files.push(line)
      end
      return files
    end


list (Net::FTP)

# File lib/net/ftp.rb, line 619
    def list(*args, &block) # :yield: line
      cmd = "LIST"
      args.each do |arg|
        cmd = cmd + " " + arg
      end
      if block
        retrlines(cmd, &block)
      else
        lines = []
        retrlines(cmd) do |line|
          lines << line
        end
        return lines
      end
    end


rename (Net::FTP)

# File lib/net/ftp.rb, line 640
    def rename(fromname, toname)
      resp = sendcmd("RNFR " + fromname)
      if resp[0] != ?3
        raise FTPReplyError, resp
      end
      voidcmd("RNTO " + toname)
    end


delete (Net::FTP)

# File lib/net/ftp.rb, line 651
    def delete(filename)
      resp = sendcmd("DELE " + filename)
      if resp[0, 3] == "250"
        return
      elsif resp[0] == ?5
        raise FTPPermError, resp
      else
        raise FTPReplyError, resp
      end
    end


chdir (Net::FTP)

# File lib/net/ftp.rb, line 665
    def chdir(dirname)
      if dirname == ".."
        begin
          voidcmd("CDUP")
          return
        rescue FTPPermError
          if $![0, 3] != "500"
            raise FTPPermError, $!
          end
        end
      end
      cmd = "CWD " + dirname
      voidcmd(cmd)
    end


size (Net::FTP)

# File lib/net/ftp.rb, line 683
    def size(filename)
      voidcmd("TYPE I")
      resp = sendcmd("SIZE " + filename)
      if resp[0, 3] != "213"
        raise FTPReplyError, resp
      end
      return resp[3..-1].strip.to_i
    end


mtime (Net::FTP)

# File lib/net/ftp.rb, line 698
    def mtime(filename, local = false)
      str = mdtm(filename)
      ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i}
      return local ? Time.local(*ary) : Time.gm(*ary)
    end


mkdir (Net::FTP)

# File lib/net/ftp.rb, line 707
    def mkdir(dirname)
      resp = sendcmd("MKD " + dirname)
      return parse257(resp)
    end


rmdir (Net::FTP)

# File lib/net/ftp.rb, line 715
    def rmdir(dirname)
      voidcmd("RMD " + dirname)
    end


pwd (Net::FTP)

# File lib/net/ftp.rb, line 722
    def pwd
      resp = sendcmd("PWD")
      return parse257(resp)
    end


system (Net::FTP)

# File lib/net/ftp.rb, line 731
    def system
      resp = sendcmd("SYST")
      if resp[0, 3] != "215"
        raise FTPReplyError, resp
      end
      return resp[4 .. -1]
    end


abort (Net::FTP)

# File lib/net/ftp.rb, line 742
    def abort
      line = "ABOR" + CRLF
      print "put: ABOR\n" if @debug_mode
      @sock.send(line, Socket::MSG_OOB)
      resp = getmultiline
      unless ["426", "226", "225"].include?(resp[0, 3])
        raise FTPProtoError, resp
      end
      return resp
    end


status (Net::FTP)

# File lib/net/ftp.rb, line 756
    def status
      line = "STAT" + CRLF
      print "put: STAT\n" if @debug_mode
      @sock.send(line, Socket::MSG_OOB)
      return getresp
    end


mdtm (Net::FTP)

# File lib/net/ftp.rb, line 766
    def mdtm(filename)
      resp = sendcmd("MDTM " + filename)
      if resp[0, 3] == "213"
        return resp[3 .. -1].strip
      end
    end


help (Net::FTP)

# File lib/net/ftp.rb, line 776
    def help(arg = nil)
      cmd = "HELP"
      if arg
        cmd = cmd + " " + arg
      end
      sendcmd(cmd)
    end


quit (Net::FTP)

# File lib/net/ftp.rb, line 787
    def quit
      voidcmd("QUIT")
    end


noop (Net::FTP)

# File lib/net/ftp.rb, line 794
    def noop
      voidcmd("NOOP")
    end


site (Net::FTP)

# File lib/net/ftp.rb, line 801
    def site(arg)
      cmd = "SITE " + arg
      voidcmd(cmd)
    end


close (Net::FTP)

# File lib/net/ftp.rb, line 810
    def close
      @sock.close if @sock and not @sock.closed?
    end


closed? (Net::FTP)

# File lib/net/ftp.rb, line 817
    def closed?
      @sock == nil or @sock.closed?
    end


use_ssl? (Net::HTTP)

# File lib/net/https.rb, line 108
    def use_ssl?
      @use_ssl
    end


use_ssl= (Net::HTTP)

# File lib/net/https.rb, line 119
    def use_ssl=(flag)
      flag = (flag ? true : false)
      raise IOError, "use_ssl value changed, but session already started" \
          if started? and @use_ssl != flag
      if flag and not @ssl_context
        @ssl_context = OpenSSL::SSL::SSLContext.new
      end
      @use_ssl = flag
    end


ssl_context_accessor (Net::HTTP)

# File lib/net/https.rb, line 129
    def self.ssl_context_accessor(name)
      module_eval("def \#{name}\nreturn nil unless @ssl_context\n@ssl_context.\#{name}\nend\n\ndef \#{name}=(val)\n@ssl_context ||= OpenSSL::SSL::SSLContext.new\n@ssl_context.\#{name} = val\nend\n", __FILE__, __LINE__ + 1)
    end


ssl_timeout (Net::HTTP)

# File lib/net/https.rb, line 153
    def ssl_timeout
      return nil unless @ssl_context
      @ssl_context.timeout
    end


ssl_timeout= (Net::HTTP)

# File lib/net/https.rb, line 158
    def ssl_timeout=(sec)
      raise ArgumentError, 'Net::HTTP#ssl_timeout= called but use_ssl=false' \
          unless use_ssl?
      @ssl_context ||= OpenSSL::SSL::SSLContext.new
      @ssl_context.timeout = sec
    end


peer_cert (Net::HTTP)

# File lib/net/https.rb, line 168
    def peer_cert
      return nil if not use_ssl? or not @socket
      @socket.io.peer_cert
    end


version_1_2 (Net::HTTP)

# File lib/net/http.rb, line 294
    def HTTP.version_1_2
      @newimpl = true
    end


version_1_1 (Net::HTTP)

# File lib/net/http.rb, line 300
    def HTTP.version_1_1
      @newimpl = false
    end


version_1_2? (Net::HTTP)

# File lib/net/http.rb, line 306
    def HTTP.version_1_2?
      @newimpl
    end


version_1_1? (Net::HTTP)

# File lib/net/http.rb, line 312
    def HTTP.version_1_1?
      not @newimpl
    end


get_print (Net::HTTP)

# File lib/net/http.rb, line 336
    def HTTP.get_print(uri_or_host, path = nil, port = nil)
      get_response(uri_or_host, path, port) {|res|
        res.read_body do |chunk|
          $stdout.print chunk
        end
      }
      nil
    end


get (Net::HTTP)

# File lib/net/http.rb, line 355
    def HTTP.get(uri_or_host, path = nil, port = nil)
      get_response(uri_or_host, path, port).body
    end


get_response (Net::HTTP)

# File lib/net/http.rb, line 371
    def HTTP.get_response(uri_or_host, path = nil, port = nil, &block)
      if path
        host = uri_or_host
        new(host, port || HTTP.default_port).start {|http|
          return http.request_get(path, &block)
        }
      else
        uri = uri_or_host
        new(uri.host, uri.port).start {|http|
          return http.request_get(uri.request_uri, &block)
        }
      end
    end


post_form (Net::HTTP)

# File lib/net/http.rb, line 400
    def HTTP.post_form(url, params)
      req = Post.new(url.path)
      req.form_data = params
      req.basic_auth url.user, url.password if url.user
      new(url.host, url.port).start {|http|
        http.request(req)
      }
    end


default_port (Net::HTTP)

# File lib/net/http.rb, line 414
    def HTTP.default_port
      http_default_port()
    end


http_default_port (Net::HTTP)

# File lib/net/http.rb, line 419
    def HTTP.http_default_port
      80
    end


https_default_port (Net::HTTP)

# File lib/net/http.rb, line 424
    def HTTP.https_default_port
      443
    end


start (Net::HTTP)

# File lib/net/http.rb, line 439
    def HTTP.start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+
      new(address, port, p_addr, p_port, p_user, p_pass).start(&block)
    end


new (Net::HTTP)

# File lib/net/http.rb, line 450
    def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
      h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
      h.instance_eval {
        @newimpl = ::Net::HTTP.version_1_2?
      }
      h
    end


new (Net::HTTP)

# File lib/net/http.rb, line 460
    def initialize(address, port = nil)
      @address = address
      @port    = (port || HTTP.default_port)
      @curr_http_version = HTTPVersion
      @seems_1_0_server = false
      @close_on_empty_response = false
      @socket  = nil
      @started = false
      @open_timeout = nil
      @read_timeout = 60
      @debug_output = nil
      @use_ssl = false
      @ssl_context = nil
      @enable_post_connection_check = false
    end


inspect (Net::HTTP)

# File lib/net/http.rb, line 476
    def inspect
      "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
    end


set_debug_output (Net::HTTP)

# File lib/net/http.rb, line 489
    def set_debug_output(output)
      warn 'Net::HTTP#set_debug_output called after HTTP started' if started?
      @debug_output = output
    end


read_timeout= (Net::HTTP)

# File lib/net/http.rb, line 511
    def read_timeout=(sec)
      @socket.read_timeout = sec if @socket
      @read_timeout = sec
    end


started? (Net::HTTP)

# File lib/net/http.rb, line 517
    def started?
      @started
    end


use_ssl? (Net::HTTP)

# File lib/net/http.rb, line 526
    def use_ssl?
      false   # redefined in net/https
    end


start (Net::HTTP)

# File lib/net/http.rb, line 542
    def start  # :yield: http
      raise IOError, 'HTTP session already opened' if @started
      if block_given?
        begin
          do_start
          return yield(self)
        ensure
          do_finish
        end
      end
      do_start
      self
    end


finish (Net::HTTP)

# File lib/net/http.rb, line 610
    def finish
      raise IOError, 'HTTP session not yet started' unless started?
      do_finish
    end


Proxy (Net::HTTP)

# File lib/net/http.rb, line 650
    def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)
      return self unless p_addr
      delta = ProxyDelta
      proxyclass = Class.new(self)
      proxyclass.module_eval {
        include delta
        # with proxy
        @is_proxy_class = true
        @proxy_address = p_addr
        @proxy_port    = p_port || default_port()
        @proxy_user    = p_user
        @proxy_pass    = p_pass
      }
      proxyclass
    end


proxy_class? (Net::HTTP)

# File lib/net/http.rb, line 668
      def proxy_class?
        @is_proxy_class
      end


proxy? (Net::HTTP)

# File lib/net/http.rb, line 679
    def proxy?
      self.class.proxy_class?
    end


proxy_address (Net::HTTP)

# File lib/net/http.rb, line 684
    def proxy_address
      self.class.proxy_address
    end


proxy_port (Net::HTTP)

# File lib/net/http.rb, line 689
    def proxy_port
      self.class.proxy_port
    end


proxy_user (Net::HTTP)

# File lib/net/http.rb, line 694
    def proxy_user
      self.class.proxy_user
    end


proxy_pass (Net::HTTP)

# File lib/net/http.rb, line 699
    def proxy_pass
      self.class.proxy_pass
    end


get (Net::HTTP)

# File lib/net/http.rb, line 779
    def get(path, initheader = nil, dest = nil, &block) # :yield: +body_segment+
      res = nil
      request(Get.new(path, initheader)) {|r|
        r.read_body dest, &block
        res = r
      }
      unless @newimpl
        res.value
        return res, res.body
      end

      res
    end


head (Net::HTTP)

# File lib/net/http.rb, line 809
    def head(path, initheader = nil)
      res = request(Head.new(path, initheader))
      res.value unless @newimpl
      res
    end


post (Net::HTTP)

# File lib/net/http.rb, line 852
    def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
      res = nil
      request(Post.new(path, initheader), data) {|r|
        r.read_body dest, &block
        res = r
      }
      unless @newimpl
        res.value
        return res, res.body
      end
      res
    end


proppatch (Net::HTTP)

# File lib/net/http.rb, line 873
    def proppatch(path, body, initheader = nil)
      request(Proppatch.new(path, initheader), body)
    end


lock (Net::HTTP)

# File lib/net/http.rb, line 879
    def lock(path, body, initheader = nil)
      request(Lock.new(path, initheader), body)
    end


unlock (Net::HTTP)

# File lib/net/http.rb, line 885
    def unlock(path, body, initheader = nil)
      request(Unlock.new(path, initheader), body)
    end


options (Net::HTTP)

# File lib/net/http.rb, line 891
    def options(path, initheader = nil)
      request(Options.new(path, initheader))
    end


propfind (Net::HTTP)

# File lib/net/http.rb, line 897
    def propfind(path, body = nil, initheader = {'Depth' => '0'})
      request(Propfind.new(path, initheader), body)
    end


delete (Net::HTTP)

# File lib/net/http.rb, line 903
    def delete(path, initheader = {'Depth' => 'Infinity'})
      request(Delete.new(path, initheader))
    end


move (Net::HTTP)

# File lib/net/http.rb, line 909
    def move(path, initheader = nil)
      request(Move.new(path, initheader))
    end


copy (Net::HTTP)

# File lib/net/http.rb, line 915
    def copy(path, initheader = nil)
      request(Copy.new(path, initheader))
    end


mkcol (Net::HTTP)

# File lib/net/http.rb, line 921
    def mkcol(path, body = nil, initheader = nil)
      request(Mkcol.new(path, initheader), body)
    end


trace (Net::HTTP)

# File lib/net/http.rb, line 927
    def trace(path, initheader = nil)
      request(Trace.new(path, initheader))
    end


request_get (Net::HTTP)

# File lib/net/http.rb, line 956
    def request_get(path, initheader = nil, &block) # :yield: +response+
      request(Get.new(path, initheader), &block)
    end


request_head (Net::HTTP)

# File lib/net/http.rb, line 970
    def request_head(path, initheader = nil, &block)
      request(Head.new(path, initheader), &block)
    end


request_post (Net::HTTP)

# File lib/net/http.rb, line 1000
    def request_post(path, data, initheader = nil, &block) # :yield: +response+
      request Post.new(path, initheader), data, &block
    end


send_request (Net::HTTP)

# File lib/net/http.rb, line 1024
    def send_request(name, path, data = nil, header = nil)
      r = HTTPGenericRequest.new(name,(data ? true : false),true,path,header)
      request r, data
    end


request (Net::HTTP)

# File lib/net/http.rb, line 1042
    def request(req, body = nil, &block)  # :yield: +response+
      unless started?
        start {
          req['connection'] ||= 'close'
          return request(req, body, &block)
        }
      end
      if proxy_user()
        unless use_ssl?
          req.proxy_basic_auth proxy_user(), proxy_pass()
        end
      end

      req.set_body_internal body
      begin_transport req
        req.exec @socket, @curr_http_version, edit_path(req.path)
        begin
          res = HTTPResponse.read_new(@socket)
        end while res.kind_of?(HTTPContinue)
        res.reading_body(@socket, req.response_body_permitted?) {
          yield res if block_given?
        }
      end_transport req, res

      res
    end


new (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1475
    def initialize(m, reqbody, resbody, path, initheader = nil)
      @method = m
      @request_has_body = reqbody
      @response_has_body = resbody
      raise ArgumentError, "HTTP request path is empty" if path.empty?
      @path = path
      initialize_http_header initheader
      self['Accept'] ||= '*/*'
      @body = nil
      @body_stream = nil
    end


inspect (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1490
    def inspect
      "\#<#{self.class} #{@method}>"
    end


request_body_permitted? (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1494
    def request_body_permitted?
      @request_has_body
    end


response_body_permitted? (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1498
    def response_body_permitted?
      @response_has_body
    end


body_exist? (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1502
    def body_exist?
      warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?" if $VERBOSE
      response_body_permitted?
    end


body= (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1509
    def body=(str)
      @body = str
      @body_stream = nil
      str
    end


body_stream= (Net::HTTPGenericRequest)

# File lib/net/http.rb, line 1517
    def body_stream=(input)
      @body = nil
      @body_stream = input
      input
    end


initialize_http_header (Net::HTTPHeader)

# File lib/net/http.rb, line 1146
    def initialize_http_header(initheader)
      @header = {}
      return unless initheader
      initheader.each do |key, value|
        warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
        @header[key.downcase] = [value.strip]
      end
    end


[] (Net::HTTPHeader)

# File lib/net/http.rb, line 1163
    def [](key)
      a = @header[key.downcase] or return nil
      a.join(', ')
    end


[]= (Net::HTTPHeader)

# File lib/net/http.rb, line 1169
    def []=(key, val)
      unless val
        @header.delete key.downcase
        return val
      end
      @header[key.downcase] = [val]
    end


add_field (Net::HTTPHeader)

# File lib/net/http.rb, line 1192
    def add_field(key, val)
      if @header.key?(key.downcase)
        @header[key.downcase].push val
      else
        @header[key.downcase] = [val]
      end
    end


get_fields (Net::HTTPHeader)

# File lib/net/http.rb, line 1211
    def get_fields(key)
      return nil unless @header[key.downcase]
      @header[key.downcase].dup
    end


fetch (Net::HTTPHeader)

# File lib/net/http.rb, line 1219
    def fetch(key, *args, &block)   #:yield: +key+
      a = @header.fetch(key.downcase, *args, &block)
      a.join(', ')
    end


each_header (Net::HTTPHeader)

# File lib/net/http.rb, line 1225
    def each_header   #:yield: +key+, +value+
      @header.each do |k,va|
        yield k, va.join(', ')
      end
    end


each_name (Net::HTTPHeader)

# File lib/net/http.rb, line 1234
    def each_name(&block)   #:yield: +key+
      @header.each_key(&block)
    end


each_capitalized_name (Net::HTTPHeader)

# File lib/net/http.rb, line 1241
    def each_capitalized_name(&block)   #:yield: +key+
      @header.each_key do |k|
        yield capitalize(k)
      end
    end


each_value (Net::HTTPHeader)

# File lib/net/http.rb, line 1248
    def each_value   #:yield: +value+
      @header.each_value do |va|
        yield va.join(', ')
      end
    end


delete (Net::HTTPHeader)

# File lib/net/http.rb, line 1255
    def delete(key)
      @header.delete(key.downcase)
    end


key? (Net::HTTPHeader)

# File lib/net/http.rb, line 1260
    def key?(key)
      @header.key?(key.downcase)
    end


to_hash (Net::HTTPHeader)

# File lib/net/http.rb, line 1265
    def to_hash
      @header.dup
    end


each_capitalized (Net::HTTPHeader)

# File lib/net/http.rb, line 1270
    def each_capitalized
      @header.each do |k,v|
        yield capitalize(k), v.join(', ')
      end
    end


range (Net::HTTPHeader)

# File lib/net/http.rb, line 1285
    def range
      return nil unless @header['range']
      self['Range'].split(/,/).map {|spec|
        m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
                raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
        d1 = m[1].to_i
        d2 = m[2].to_i
        if    m[1] and m[2] then  d1..d2
        elsif m[1]          then  d1..-1
        elsif          m[2] then -d2..-1
        else
          raise HTTPHeaderSyntaxError, 'range is not specified'
        end
      }
    end


set_range (Net::HTTPHeader)

# File lib/net/http.rb, line 1307
    def set_range(r, e = nil)
      unless r
        @header.delete 'range'
        return r
      end
      r = (r...r+e) if e
      case r
      when Numeric
        n = r.to_i
        rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
      when Range
        first = r.first
        last = r.last
        last -= 1 if r.exclude_end?
        if last == -1
          rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
        else
          raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
          raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
          raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
          rangestr = "#{first}-#{last}"
        end
      else
        raise TypeError, 'Range/Integer is required'
      end
      @header['range'] = ["bytes=#{rangestr}"]
      r
    end


content_length (Net::HTTPHeader)

# File lib/net/http.rb, line 1340
    def content_length
      return nil unless key?('Content-Length')
      len = self['Content-Length'].slice(/\d+/) or
          raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
      len.to_i
    end


content_length= (Net::HTTPHeader)

# File lib/net/http.rb, line 1347
    def content_length=(len)
      unless len
        @header.delete 'content-length'
        return nil
      end
      @header['content-length'] = [len.to_i.to_s]
    end


chunked? (Net::HTTPHeader)

# File lib/net/http.rb, line 1359
    def chunked?
      return false unless @header['transfer-encoding']
      field = self['Transfer-Encoding']
      (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
    end


content_range (Net::HTTPHeader)

# File lib/net/http.rb, line 1368
    def content_range
      return nil unless @header['content-range']
      m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
          raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
      m[1].to_i .. m[2].to_i + 1
    end


range_length (Net::HTTPHeader)

# File lib/net/http.rb, line 1376
    def range_length
      r = content_range() or return nil
      r.end - r.begin
    end


content_type (Net::HTTPHeader)

# File lib/net/http.rb, line 1383
    def content_type
      return nil unless main_type()
      if sub_type()
      then "#{main_type()}/#{sub_type()}"
      else main_type()
      end
    end


main_type (Net::HTTPHeader)

# File lib/net/http.rb, line 1393
    def main_type
      return nil unless @header['content-type']
      self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
    end


sub_type (Net::HTTPHeader)

# File lib/net/http.rb, line 1401
    def sub_type
      return nil unless @header['content-type']
      main, sub = *self['Content-Type'].split(';').first.to_s.split('/')
      return nil unless sub
      sub.strip
    end


type_params (Net::HTTPHeader)

# File lib/net/http.rb, line 1410
    def type_params
      result = {}
      list = self['Content-Type'].to_s.split(';')
      list.shift
      list.each do |param|
        k, v = *param.split('=', 2)
        result[k.strip] = v.strip
      end
      result
    end


set_content_type (Net::HTTPHeader)

# File lib/net/http.rb, line 1423
    def set_content_type(type, params = {})
      @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
    end


set_form_data (Net::HTTPHeader)

# File lib/net/http.rb, line 1435
    def set_form_data(params, sep = '&')
      self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
      self.content_type = 'application/x-www-form-urlencoded'
    end


basic_auth (Net::HTTPHeader)

# File lib/net/http.rb, line 1448
    def basic_auth(account, password)
      @header['authorization'] = [basic_encode(account, password)]
    end


proxy_basic_auth (Net::HTTPHeader)

# File lib/net/http.rb, line 1453
    def proxy_basic_auth(account, password)
      @header['proxy-authorization'] = [basic_encode(account, password)]
    end


new (Net::HTTPRequest)

# File lib/net/http.rb, line 1596
    def initialize(path, initheader = nil)
      super self.class::METHOD,
            self.class::REQUEST_HAS_BODY,
            self.class::RESPONSE_HAS_BODY,
            path, initheader
    end


body_permitted? (Net::HTTPResponse)

# File lib/net/http.rb, line 1793
    def HTTPResponse.body_permitted?
      self::HAS_BODY
    end


inspect (Net::HTTPResponse)

# File lib/net/http.rb, line 2079
    def inspect
      "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
    end


to_ary (Net::HTTPResponse)

# File lib/net/http.rb, line 2088
    def to_ary
      warn "net/http.rb: warning: Net::HTTP v1.1 style assignment found at #{caller(1)[0]}; use `response = http.get(...)' instead." if $VERBOSE
      res = self.dup
      class << res
        undef to_ary
      end
      [res, res.body]
    end


value (Net::HTTPResponse)

# File lib/net/http.rb, line 2114
    def value
      error! unless self.kind_of?(HTTPSuccess)
    end


read_body (Net::HTTPResponse)

# File lib/net/http.rb, line 2174
    def read_body(dest = nil, &block)
      if @read
        raise IOError, "#{self.class}\#read_body called twice" if dest or block
        return @body
      end
      to = procdest(dest, block)
      stream_check
      if @body_exist
        read_body_0 to
        @body = to
      else
        @body = nil
      end
      @read = true

      @body
    end


body (Net::HTTPResponse)

# File lib/net/http.rb, line 2206
    def body
      read_body()
    end


multipart? (Net::IMAP::BodyTypeBasic)

# File lib/net/imap.rb, line 1754
      def multipart?
        return false
      end


media_subtype (Net::IMAP::BodyTypeBasic)

# File lib/net/imap.rb, line 1761
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end


multipart? (Net::IMAP::BodyTypeMessage)

# File lib/net/imap.rb, line 1812
      def multipart?
        return false
      end


media_subtype (Net::IMAP::BodyTypeMessage)

# File lib/net/imap.rb, line 1819
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end


multipart? (Net::IMAP::BodyTypeMultipart)

# File lib/net/imap.rb, line 1853
      def multipart?
        return true
      end


media_subtype (Net::IMAP::BodyTypeMultipart)

# File lib/net/imap.rb, line 1860
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end


multipart? (Net::IMAP::BodyTypeText)

# File lib/net/imap.rb, line 1782
      def multipart?
        return false
      end


media_subtype (Net::IMAP::BodyTypeText)

# File lib/net/imap.rb, line 1789
      def media_subtype
        $stderr.printf("warning: media_subtype is obsolete.\n")
        $stderr.printf("         use subtype instead.\n")
        return subtype
      end


process (Net::IMAP::CramMD5Authenticator)

# File lib/net/imap.rb, line 3154
      def process(challenge)
        digest = hmac_md5(challenge, @password)
        return @user + " " + digest
      end


new (Net::IMAP::CramMD5Authenticator)

# File lib/net/imap.rb, line 3161
      def initialize(user, password)
        @user = user
        @password = password
      end


process (Net::IMAP::LoginAuthenticator)

# File lib/net/imap.rb, line 3128
      def process(data)
        case @state
        when STATE_USER
          @state = STATE_PASSWORD
          return @user
        when STATE_PASSWORD
          return @password
        end
      end


new (Net::IMAP::LoginAuthenticator)

# File lib/net/imap.rb, line 3143
      def initialize(user, password)
        @user = user
        @password = password
        @state = STATE_USER
      end


debug (Net::IMAP)

# File lib/net/imap.rb, line 263
    def self.debug
      return @@debug
    end


debug= (Net::IMAP)

# File lib/net/imap.rb, line 268
    def self.debug=(val)
      return @@debug = val
    end


add_authenticator (Net::IMAP)

# File lib/net/imap.rb, line 281
    def self.add_authenticator(auth_type, authenticator)
      @@authenticators[auth_type] = authenticator
    end


disconnect (Net::IMAP)

# File lib/net/imap.rb, line 286
    def disconnect
      if SSL::SSLSocket === @sock
        @sock.io.shutdown
      else
        @sock.shutdown
      end
      @receiver_thread.join
      @sock.close
    end


disconnected? (Net::IMAP)

# File lib/net/imap.rb, line 297
    def disconnected?
      return @sock.closed?
    end


capability (Net::IMAP)

# File lib/net/imap.rb, line 311
    def capability
      synchronize do
        send_command("CAPABILITY")
        return @responses.delete("CAPABILITY")[-1]
      end
    end


noop (Net::IMAP)

# File lib/net/imap.rb, line 319
    def noop
      send_command("NOOP")
    end


logout (Net::IMAP)

# File lib/net/imap.rb, line 325
    def logout
      send_command("LOGOUT")
    end


authenticate (Net::IMAP)

# File lib/net/imap.rb, line 354
    def authenticate(auth_type, *args)
      auth_type = auth_type.upcase
      unless @@authenticators.has_key?(auth_type)
        raise ArgumentError,
          format('unknown auth type - "%s"', auth_type)
      end
      authenticator = @@authenticators[auth_type].new(*args)
      send_command("AUTHENTICATE", auth_type) do |resp|
        if resp.instance_of?(ContinuationRequest)
          data = authenticator.process(resp.data.text.unpack("m")[0])
          s = [data].pack("m").gsub(/\n/, "")
          send_string_data(s)
          put_string(CRLF)
        end
      end
    end


login (Net::IMAP)

# File lib/net/imap.rb, line 377
    def login(user, password)
      send_command("LOGIN", user, password)
    end


select (Net::IMAP)

# File lib/net/imap.rb, line 393
    def select(mailbox)
      synchronize do
        @responses.clear
        send_command("SELECT", mailbox)
      end
    end


examine (Net::IMAP)

# File lib/net/imap.rb, line 406
    def examine(mailbox)
      synchronize do
        @responses.clear
        send_command("EXAMINE", mailbox)
      end
    end


create (Net::IMAP)

# File lib/net/imap.rb, line 417
    def create(mailbox)
      send_command("CREATE", mailbox)
    end


delete (Net::IMAP)

# File lib/net/imap.rb, line 426
    def delete(mailbox)
      send_command("DELETE", mailbox)
    end


rename (Net::IMAP)

# File lib/net/imap.rb, line 437
    def rename(mailbox, newname)
      send_command("RENAME", mailbox, newname)
    end


subscribe (Net::IMAP)

# File lib/net/imap.rb, line 447
    def subscribe(mailbox)
      send_command("SUBSCRIBE", mailbox)
    end


unsubscribe (Net::IMAP)

# File lib/net/imap.rb, line 457
    def unsubscribe(mailbox)
      send_command("UNSUBSCRIBE", mailbox)
    end


list (Net::IMAP)

# File lib/net/imap.rb, line 483
    def list(refname, mailbox)
      synchronize do
        send_command("LIST", refname, mailbox)
        return @responses.delete("LIST")
      end
    end


getquotaroot (Net::IMAP)

# File lib/net/imap.rb, line 494
    def getquotaroot(mailbox)
      synchronize do
        send_command("GETQUOTAROOT", mailbox)
        result = []
        result.concat(@responses.delete("QUOTAROOT"))
        result.concat(@responses.delete("QUOTA"))
        return result
      end
    end


getquota (Net::IMAP)

# File lib/net/imap.rb, line 508
    def getquota(mailbox)
      synchronize do
        send_command("GETQUOTA", mailbox)
        return @responses.delete("QUOTA")
      end
    end


setquota (Net::IMAP)

# File lib/net/imap.rb, line 520
    def setquota(mailbox, quota)
      if quota.nil?
        data = '()'
      else
        data = '(STORAGE ' + quota.to_s + ')'
      end
      send_command("SETQUOTA", mailbox, RawData.new(data))
    end


setacl (Net::IMAP)

# File lib/net/imap.rb, line 533
    def setacl(mailbox, user, rights)
      if rights.nil?
        send_command("SETACL", mailbox, user, "")
      else
        send_command("SETACL", mailbox, user, rights)
      end
    end


getacl (Net::IMAP)

# File lib/net/imap.rb, line 544
    def getacl(mailbox)
      synchronize do
        send_command("GETACL", mailbox)
        return @responses.delete("ACL")[-1]
      end
    end


lsub (Net::IMAP)

# File lib/net/imap.rb, line 556
    def lsub(refname, mailbox)
      synchronize do
        send_command("LSUB", refname, mailbox)
        return @responses.delete("LSUB")
      end
    end


status (Net::IMAP)

# File lib/net/imap.rb, line 579
    def status(mailbox, attr)
      synchronize do
        send_command("STATUS", mailbox, attr)
        return @responses.delete("STATUS")[-1].attr
      end
    end


append (Net::IMAP)

# File lib/net/imap.rb, line 604
    def append(mailbox, message, flags = nil, date_time = nil)
      args = []
      if flags
        args.push(flags)
      end
      args.push(date_time) if date_time
      args.push(Literal.new(message))
      send_command("APPEND", mailbox, *args)
    end


check (Net::IMAP)

# File lib/net/imap.rb, line 618
    def check
      send_command("CHECK")
    end


close (Net::IMAP)

# File lib/net/imap.rb, line 625
    def close
      send_command("CLOSE")
    end


expunge (Net::IMAP)

# File lib/net/imap.rb, line 631
    def expunge
      synchronize do
        send_command("EXPUNGE")
        return @responses.delete("EXPUNGE")
      end
    end


search (Net::IMAP)

# File lib/net/imap.rb, line 678
    def search(keys, charset = nil)
      return search_internal("SEARCH", keys, charset)
    end


uid_search (Net::IMAP)

# File lib/net/imap.rb, line 683
    def uid_search(keys, charset = nil)
      return search_internal("UID SEARCH", keys, charset)
    end


fetch (Net::IMAP)

# File lib/net/imap.rb, line 710
    def fetch(set, attr)
      return fetch_internal("FETCH", set, attr)
    end


uid_fetch (Net::IMAP)

# File lib/net/imap.rb, line 715
    def uid_fetch(set, attr)
      return fetch_internal("UID FETCH", set, attr)
    end


store (Net::IMAP)

# File lib/net/imap.rb, line 733
    def store(set, attr, flags)
      return store_internal("STORE", set, attr, flags)
    end


uid_store (Net::IMAP)

# File lib/net/imap.rb, line 738
    def uid_store(set, attr, flags)
      return store_internal("UID STORE", set, attr, flags)
    end


copy (Net::IMAP)

# File lib/net/imap.rb, line 746
    def copy(set, mailbox)
      copy_internal("COPY", set, mailbox)
    end


uid_copy (Net::IMAP)

# File lib/net/imap.rb, line 751
    def uid_copy(set, mailbox)
      copy_internal("UID COPY", set, mailbox)
    end


sort (Net::IMAP)

# File lib/net/imap.rb, line 764
    def sort(sort_keys, search_keys, charset)
      return sort_internal("SORT", sort_keys, search_keys, charset)
    end


uid_sort (Net::IMAP)

# File lib/net/imap.rb, line 769
    def uid_sort(sort_keys, search_keys, charset)
      return sort_internal("UID SORT", sort_keys, search_keys, charset)
    end


add_response_handler (Net::IMAP)

# File lib/net/imap.rb, line 785
    def add_response_handler(handler = Proc.new)
      @response_handlers.push(handler)
    end


remove_response_handler (Net::IMAP)

# File lib/net/imap.rb, line 790
    def remove_response_handler(handler)
      @response_handlers.delete(handler)
    end


thread (Net::IMAP)

# File lib/net/imap.rb, line 807
    def thread(algorithm, search_keys, charset)
      return thread_internal("THREAD", algorithm, search_keys, charset)
    end


uid_thread (Net::IMAP)

# File lib/net/imap.rb, line 813
    def uid_thread(algorithm, search_keys, charset)
      return thread_internal("UID THREAD", algorithm, search_keys, charset)
    end


decode_utf7 (Net::IMAP)

# File lib/net/imap.rb, line 825
    def self.decode_utf7(s)
      return s.gsub(/&(.*?)-/n) {
        if $1.empty?
          "&"
        else
          base64 = $1.tr(",", "/")
          x = base64.length % 4
          if x > 0
            base64.concat("=" * (4 - x))
          end
          u16tou8(base64.unpack("m")[0])
        end
      }
    end


encode_utf7 (Net::IMAP)

# File lib/net/imap.rb, line 841
    def self.encode_utf7(s)
      return s.gsub(/(&)|([^\x20-\x25\x27-\x7e]+)/n) { |x|
        if $1
          "&-"
        else
          base64 = [u8tou16(x)].pack("m")
          "&" + base64.delete("=\n").tr("/", ",") + "-"
        end
      }
    end


new (Net::IMAP)

# File lib/net/imap.rb, line 879
    def initialize(host, port = PORT, usessl = false, certs = nil, verify = false)
      super()
      @host = host
      @port = port
      @tag_prefix = "RUBY"
      @tagno = 0
      @parser = ResponseParser.new
      @sock = TCPSocket.open(host, port)
      if usessl
        unless defined?(OpenSSL)
          raise "SSL extension not installed"
        end
        @usessl = true

        # verify the server.
        context = SSLContext::new()
        context.ca_file = certs if certs && FileTest::file?(certs)
        context.ca_path = certs if certs && FileTest::directory?(certs)
        context.verify_mode = VERIFY_PEER if verify
        if defined?(VerifyCallbackProc)
          context.verify_callback = VerifyCallbackProc
        end
        @sock = SSLSocket.new(@sock, context)
        @sock.connect   # start ssl session.
      else
        @usessl = false
      end
      @responses = Hash.new([].freeze)
      @tagged_responses = {}
      @response_handlers = []
      @response_arrival = new_cond
      @continuation_request = nil
      @logout_command_tag = nil
      @debug_output_bol = true

      @greeting = get_response
      if @greeting.name == "BYE"
        @sock.close
        raise ByeResponseError, @greeting.raw_data
      end

      @client_thread = Thread.current
      @receiver_thread = Thread.start {
        receive_responses
      }
    end


default_port (Net::POP3)

# File lib/net/pop.rb, line 200
    def POP3.default_port
      110
    end


APOP (Net::POP3)

# File lib/net/pop.rb, line 223
    def POP3.APOP( isapop )
      isapop ? APOP : POP3
    end


foreach (Net::POP3)

# File lib/net/pop.rb, line 247
    def POP3.foreach( address, port = nil,
                      account = nil, password = nil,
                      isapop = false, &block )  # :yields: message
      start(address, port, account, password, isapop) {|pop|
        pop.each_mail(&block)
      }
    end


delete_all (Net::POP3)

# File lib/net/pop.rb, line 268
    def POP3.delete_all( address, port = nil,
                         account = nil, password = nil,
                         isapop = false, &block )
      start(address, port, account, password, isapop) {|pop|
        pop.delete_all(&block)
      }
    end


auth_only (Net::POP3)

# File lib/net/pop.rb, line 290
    def POP3.auth_only( address, port = nil,
                        account = nil, password = nil,
                        isapop = false )
      new(address, port, isapop).auth_only account, password
    end


auth_only (Net::POP3)

# File lib/net/pop.rb, line 299
    def auth_only( account, password )
      raise IOError, 'opening previously opened POP session' if started?
      start(account, password) {
        ;
      }
    end


start (Net::POP3)

# File lib/net/pop.rb, line 326
    def POP3.start( address, port = nil,
                    account = nil, password = nil,
                    isapop = false, &block ) # :yield: pop
      new(address, port, isapop).start(account, password, &block)
    end


new (Net::POP3)

# File lib/net/pop.rb, line 342
    def initialize( addr, port = nil, isapop = false )
      @address = addr
      @port = port || self.class.default_port
      @apop = isapop

      @command = nil
      @socket = nil
      @started = false
      @open_timeout = 30
      @read_timeout = 60
      @debug_output = nil

      @mails = nil
      @n_mails = nil
      @n_bytes = nil
    end


apop? (Net::POP3)

# File lib/net/pop.rb, line 360
    def apop?
      @apop
    end


inspect (Net::POP3)

# File lib/net/pop.rb, line 365
    def inspect
      "#<#{self.class} #{@address}:#{@port} open=#{@started}>"
    end


set_debug_output (Net::POP3)

# File lib/net/pop.rb, line 382
    def set_debug_output( arg )
      @debug_output = arg
    end


read_timeout= (Net::POP3)

# File lib/net/pop.rb, line 403
    def read_timeout=( sec )
      @command.socket.read_timeout = sec if @command
      @read_timeout = sec
    end


started? (Net::POP3)

# File lib/net/pop.rb, line 409
    def started?
      @started
    end


start (Net::POP3)

# File lib/net/pop.rb, line 421
    def start( account, password ) # :yield: pop
      raise IOError, 'POP session already started' if @started

      if block_given?
        begin
          do_start account, password
          return yield(self)
        ensure
          do_finish
        end
      else
        do_start account, password
        return self
      end
    end


finish (Net::POP3)

# File lib/net/pop.rb, line 458
    def finish
      raise IOError, 'POP session not yet started' unless started?
      do_finish
    end


n_mails (Net::POP3)

# File lib/net/pop.rb, line 486
    def n_mails
      return @n_mails if @n_mails
      @n_mails, @n_bytes = command().stat
      @n_mails
    end


n_bytes (Net::POP3)

# File lib/net/pop.rb, line 493
    def n_bytes
      return @n_bytes if @n_bytes
      @n_mails, @n_bytes = command().stat
      @n_bytes
    end


mails (Net::POP3)

# File lib/net/pop.rb, line 505
    def mails
      return @mails.dup if @mails
      if n_mails() == 0
        # some popd raises error for LIST on the empty mailbox.
        @mails = []
        return []
      end

      @mails = command().list.map {|num, size|
        POPMail.new(num, size, self, command())
      }
      @mails.dup
    end


each_mail (Net::POP3)

# File lib/net/pop.rb, line 527
    def each_mail( &block )  # :yield: message
      mails().each(&block)
    end


delete_all (Net::POP3)

# File lib/net/pop.rb, line 549
    def delete_all # :yield: message
      mails().each do |m|
        yield m if block_given?
        m.delete unless m.deleted?
      end
    end


reset (Net::POP3)

# File lib/net/pop.rb, line 559
    def reset
      command().rset
      mails().each do |m|
        m.instance_eval {
          @deleted = false
        }
      end
    end


inspect (Net::POPMail)

# File lib/net/pop.rb, line 618
    def inspect
      "#<#{self.class} #{@number}#{@deleted ? ' deleted' : ''}>"
    end


pop (Net::POPMail)

# File lib/net/pop.rb, line 660
    def pop( dest = '', &block ) # :yield: message_chunk
      if block_given?
        @command.retr(@number, &block)
        nil
      else
        @command.retr(@number) do |chunk|
          dest << chunk
        end
        dest
      end
    end


top (Net::POPMail)

# File lib/net/pop.rb, line 680
    def top( lines, dest = '' )
      @command.top(@number, lines) do |chunk|
        dest << chunk
      end
      dest
    end


header (Net::POPMail)

# File lib/net/pop.rb, line 692
    def header( dest = '' )
      top(0, dest)
    end


delete (Net::POPMail)

# File lib/net/pop.rb, line 716
    def delete
      @command.dele @number
      @deleted = true
    end


deleted? (Net::POPMail)

# File lib/net/pop.rb, line 724
    def deleted?
      @deleted
    end


unique_id (Net::POPMail)

# File lib/net/pop.rb, line 732
    def unique_id
      return @uid if @uid
      @pop.set_all_uids
      @uid
    end


default_port (Net::SMTP)

# File lib/net/smtp.rb, line 169
    def SMTP.default_port
      25
    end


new (Net::SMTP)

# File lib/net/smtp.rb, line 184
    def initialize( address, port = nil )
      @address = address
      @port = (port || SMTP.default_port)
      @esmtp = true
      @socket = nil
      @started = false
      @open_timeout = 30
      @read_timeout = 60
      @error_occured = false
      @debug_output = nil
    end


inspect (Net::SMTP)

# File lib/net/smtp.rb, line 197
    def inspect
      "#<#{self.class} #{@address}:#{@port} started=#{@started}>"
    end


esmtp? (Net::SMTP)

# File lib/net/smtp.rb, line 202
    def esmtp?
      @esmtp
    end


esmtp= (Net::SMTP)

# File lib/net/smtp.rb, line 213
    def esmtp=( bool )
      @esmtp = bool
    end


read_timeout= (Net::SMTP)

# File lib/net/smtp.rb, line 237
    def read_timeout=( sec )
      @socket.read_timeout = sec if @socket
      @read_timeout = sec
    end


set_debug_output (Net::SMTP)

# File lib/net/smtp.rb, line 256
    def set_debug_output( arg )
      @debug_output = arg
    end


start (Net::SMTP)

# File lib/net/smtp.rb, line 312
    def SMTP.start( address, port = nil,
                    helo = 'localhost.localdomain',
                    user = nil, secret = nil, authtype = nil,
                    &block) # :yield: smtp
      new(address, port).start(helo, user, secret, authtype, &block)
    end


started? (Net::SMTP)

# File lib/net/smtp.rb, line 320
    def started?
      @started
    end


start (Net::SMTP)

# File lib/net/smtp.rb, line 374
    def start( helo = 'localhost.localdomain',
               user = nil, secret = nil, authtype = nil ) # :yield: smtp
      if block_given?
        begin
          do_start(helo, user, secret, authtype)
          return yield(self)
        ensure
          do_finish
        end
      else
        do_start(helo, user, secret, authtype)
        return self
      end
    end


finish (Net::SMTP)

# File lib/net/smtp.rb, line 420
    def finish
      raise IOError, 'not yet started' unless started?
      do_finish
    end


send_message (Net::SMTP)

# File lib/net/smtp.rb, line 471
    def send_message( msgstr, from_addr, *to_addrs )
      send0(from_addr, to_addrs.flatten) {
        @socket.write_message msgstr
      }
    end


open_message_stream (Net::SMTP)

# File lib/net/smtp.rb, line 524
    def open_message_stream( from_addr, *to_addrs, &block ) # :yield: stream
      send0(from_addr, to_addrs.flatten) {
        @socket.write_message_by_block(&block)
      }
    end


new (Net::Telnet)

# File lib/net/telnet.rb, line 275
    def initialize(options) # :yield: mesg
      @options = options
      @options["Host"]       = "localhost"   unless @options.has_key?("Host")
      @options["Port"]       = 23            unless @options.has_key?("Port")
      @options["Prompt"]     = /[$%#>] \z/n  unless @options.has_key?("Prompt")
      @options["Timeout"]    = 10            unless @options.has_key?("Timeout")
      @options["Waittime"]   = 0             unless @options.has_key?("Waittime")
      unless @options.has_key?("Binmode")
        @options["Binmode"]    = false
      else
        unless (true == @options["Binmode"] or false == @options["Binmode"])
          raise ArgumentError, "Binmode option must be true or false"
        end
      end

      unless @options.has_key?("Telnetmode")
        @options["Telnetmode"] = true
      else
        unless (true == @options["Telnetmode"] or false == @options["Telnetmode"])
          raise ArgumentError, "Telnetmode option must be true or false"
        end
      end

      @telnet_option = { "SGA" => false, "BINARY" => false }

      if @options.has_key?("Output_log")
        @log = File.open(@options["Output_log"], 'a+')
        @log.sync = true
        @log.binmode
      end

      if @options.has_key?("Dump_log")
        @dumplog = File.open(@options["Dump_log"], 'a+')
        @dumplog.sync = true
        @dumplog.binmode
        def @dumplog.log_dump(dir, x)  # :nodoc:
          len = x.length
          addr = 0
          offset = 0
          while 0 < len
            if len < 16
              line = x[offset, len]
            else
              line = x[offset, 16]
            end
            hexvals = line.unpack('H*')[0]
            hexvals += ' ' * (32 - hexvals.length)
            hexvals = format("%s %s %s %s  " * 4, *hexvals.unpack('a2' * 16))
            line = line.gsub(/[\000-\037\177-\377]/n, '.')
            printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line
            addr += 16
            offset += 16
            len -= 16
          end
          print "\n"
        end
      end

      if @options.has_key?("Proxy")
        if @options["Proxy"].kind_of?(Net::Telnet)
          @sock = @options["Proxy"].sock
        elsif @options["Proxy"].kind_of?(IO)
          @sock = @options["Proxy"]
        else
          raise "Error: Proxy must be an instance of Net::Telnet or IO."
        end
      else
        message = "Trying " + @options["Host"] + "...\n"
        yield(message) if block_given?
        @log.write(message) if @options.has_key?("Output_log")
        @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")

        begin
          if @options["Timeout"] == false
            @sock = TCPSocket.open(@options["Host"], @options["Port"])
          else
            timeout(@options["Timeout"]) do
              @sock = TCPSocket.open(@options["Host"], @options["Port"])
            end
          end
        rescue TimeoutError
          raise TimeoutError, "timed out while opening a connection to the host"
        rescue
          @log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log")
          @dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log")
          raise
        end
        @sock.sync = true
        @sock.binmode

        message = "Connected to " + @options["Host"] + ".\n"
        yield(message) if block_given?
        @log.write(message) if @options.has_key?("Output_log")
        @dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
      end

      super(@sock)
    end


telnetmode (Net::Telnet)

# File lib/net/telnet.rb, line 384
    def  telnetmodetelnetmode(mode = nil)
      case mode
      when nil
        @options["Telnetmode"]
      when true, false
        @options["Telnetmode"] = mode
      else
        raise ArgumentError, "argument must be true or false, or missing"
      end
    end


telnetmode= (Net::Telnet)

# File lib/net/telnet.rb, line 398
    def telnetmode=(mode)
      if (true == mode or false == mode)
        @options["Telnetmode"] = mode
      else
        raise ArgumentError, "argument must be true or false"
      end
    end


binmode (Net::Telnet)

# File lib/net/telnet.rb, line 408
    def binmode(mode = nil)
      case mode
      when nil
        @options["Binmode"]
      when true, false
        @options["Binmode"] = mode
      else
        raise ArgumentError, "argument must be true or false"
      end
    end


binmode= (Net::Telnet)

# File lib/net/telnet.rb, line 420
    def binmode=(mode)
      if (true == mode or false == mode)
        @options["Binmode"] = mode
      else
        raise ArgumentError, "argument must be true or false"
      end
    end


preprocess (Net::Telnet)

# File lib/net/telnet.rb, line 434
    def preprocess(string)
      # combine CR+NULL into CR
      string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]

      # combine EOL into "\n"
      string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"]

      string.gsub(/#{IAC}(
                   [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
                   [#{DO}#{DONT}#{WILL}#{WONT}]
                     [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
                   #{SB}[^#{IAC}]*#{IAC}#{SE}
                 )/xno) do
        if    IAC == $1  # handle escaped IAC characters
          IAC
        elsif AYT == $1  # respond to "IAC AYT" (are you there)
          self.write("nobody here but us pigeons" + EOL)
          ''
        elsif DO[0] == $1[0]  # respond to "IAC DO x"
          if OPT_BINARY[0] == $1[1]
            @telnet_option["BINARY"] = true
            self.write(IAC + WILL + OPT_BINARY)
          else
            self.write(IAC + WONT + $1[1..1])
          end
          ''
        elsif DONT[0] == $1[0]  # respond to "IAC DON'T x" with "IAC WON'T x"
          self.write(IAC + WONT + $1[1..1])
          ''
        elsif WILL[0] == $1[0]  # respond to "IAC WILL x"
          if    OPT_BINARY[0] == $1[1]
            self.write(IAC + DO + OPT_BINARY)
          elsif OPT_ECHO[0] == $1[1]
            self.write(IAC + DO + OPT_ECHO)
          elsif OPT_SGA[0]  == $1[1]
            @telnet_option["SGA"] = true
            self.write(IAC + DO + OPT_SGA)
          else
            self.write(IAC + DONT + $1[1..1])
          end
          ''
        elsif WONT[0] == $1[0]  # respond to "IAC WON'T x"
          if    OPT_ECHO[0] == $1[1]
            self.write(IAC + DONT + OPT_ECHO)
          elsif OPT_SGA[0]  == $1[1]
            @telnet_option["SGA"] = false
            self.write(IAC + DONT + OPT_SGA)
          else
            self.write(IAC + DONT + $1[1..1])
          end
          ''
        else
          ''
        end
      end
    end


waitfor (Net::Telnet)

# File lib/net/telnet.rb, line 524
    def waitfor(options) # :yield: recvdata
      time_out = @options["Timeout"]
      waittime = @options["Waittime"]

      if options.kind_of?(Hash)
        prompt   = if options.has_key?("Match")
                     options["Match"]
                   elsif options.has_key?("Prompt")
                     options["Prompt"]
                   elsif options.has_key?("String")
                     Regexp.new( Regexp.quote(options["String"]) )
                   end
        time_out = options["Timeout"]  if options.has_key?("Timeout")
        waittime = options["Waittime"] if options.has_key?("Waittime")
      else
        prompt = options
      end

      if time_out == false
        time_out = nil
      end

      line = ''
      buf = ''
      rest = ''
      until(prompt === line and not IO::select([@sock], nil, nil, waittime))
        unless IO::select([@sock], nil, nil, time_out)
          raise TimeoutError, "timed out while waiting for more data"
        end
        begin
          c = @sock.readpartial(1024 * 1024)
          @dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
          if @options["Telnetmode"]
            c = rest + c
            if Integer(c.rindex(/#{IAC}#{SE}/no)) <
               Integer(c.rindex(/#{IAC}#{SB}/no))
              buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
              rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
            elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no)
              buf = preprocess(c[0 ... pt])
              rest = c[pt .. -1]
            else
              buf = preprocess(c)
              rest = ''
            end
         else
           # Not Telnetmode.
           #
           # We cannot use preprocess() on this data, because that
           # method makes some Telnetmode-specific assumptions.
           buf = c
           buf.gsub!(/#{EOL}/no, "\n") unless @options["Binmode"]
           rest = ''
          end
          @log.print(buf) if @options.has_key?("Output_log")
          line += buf
          yield buf if block_given?
        rescue EOFError # End of file reached
          if line == ''
            line = nil
            yield nil if block_given?
          end
          break
        end
      end
      line
    end


write (Net::Telnet)

# File lib/net/telnet.rb, line 596
    def write(string)
      length = string.length
      while 0 < length
        IO::select(nil, [@sock])
        @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
        length -= @sock.syswrite(string[-length..-1])
      end
    end


print (Net::Telnet)

# File lib/net/telnet.rb, line 611
    def print(string)
      string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]

      if @options["Binmode"]
        self.write(string)
      else
        if @telnet_option["BINARY"] and @telnet_option["SGA"]
          # IAC WILL SGA IAC DO BIN send EOL --> CR
          self.write(string.gsub(/\n/n, CR))
        elsif @telnet_option["SGA"]
          # IAC WILL SGA send EOL --> CR+NULL
          self.write(string.gsub(/\n/n, CR + NULL))
        else
          # NONE send EOL --> CR+LF
          self.write(string.gsub(/\n/n, EOL))
        end
      end
    end


puts (Net::Telnet)

# File lib/net/telnet.rb, line 633
    def puts(string)
      self.print(string + "\n")
    end


cmd (Net::Telnet)

# File lib/net/telnet.rb, line 664
    def cmd(options) # :yield: recvdata
      match    = @options["Prompt"]
      time_out = @options["Timeout"]

      if options.kind_of?(Hash)
        string   = options["String"]
        match    = options["Match"]   if options.has_key?("Match")
        time_out = options["Timeout"] if options.has_key?("Timeout")
      else
        string = options
      end

      self.puts(string)
      if block_given?
        waitfor({"Prompt" => match, "Timeout" => time_out}){|c| yield c }
      else
        waitfor({"Prompt" => match, "Timeout" => time_out})
      end
    end


login (Net::Telnet)

# File lib/net/telnet.rb, line 706
    def login(options, password = nil) # :yield: recvdata
      login_prompt = /[Ll]ogin[: ]*\z/n
      password_prompt = /Password[: ]*\z/n
      if options.kind_of?(Hash)
        username = options["Name"]
        password = options["Password"]
        login_prompt = options["LoginPrompt"] if options["LoginPrompt"]
        password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"]
      else
        username = options
      end

      if block_given?
        line = waitfor(login_prompt){|c| yield c }
        if password
          line += cmd({"String" => username,
                       "Match" => password_prompt}){|c| yield c }
          line += cmd(password){|c| yield c }
        else
          line += cmd(username){|c| yield c }
        end
      else
        line = waitfor(login_prompt)
        if password
          line += cmd({"String" => username,
                       "Match" => password_prompt})
          line += cmd(password)
        else
          line += cmd(username)
        end
      end
      line
    end


new (Net::WriteAdapter)

# File lib/net/protocol.rb, line 333
    def initialize(socket, method)
      @socket = socket
      @method_id = method
    end


inspect (Net::WriteAdapter)

# File lib/net/protocol.rb, line 338
    def inspect
      "#<#{self.class} socket=#{@socket.inspect}>"
    end


write (Net::WriteAdapter)

# File lib/net/protocol.rb, line 342
    def write(str)
      @socket.__send__(@method_id, str)
    end


<< (Net::WriteAdapter)

# File lib/net/protocol.rb, line 348
    def <<(str)
      write str
      self
    end


puts (Net::WriteAdapter)

# File lib/net/protocol.rb, line 353
    def puts(str = '')
      write str.chomp("\n") + "\n"
    end


printf (Net::WriteAdapter)

# File lib/net/protocol.rb, line 357
    def printf(*args)
      write sprintf(*args)
    end


to_i (NilClass)

/*
 *  call-seq:
 *     nil.to_i => 0
 *
 *  Always returns zero.
 *
 *     nil.to_i   #=> 0
 */

static VALUE
nil_to_i(obj)
    VALUE obj;
{
    return INT2FIX(0);
}


to_f (NilClass)

/*
 *  call-seq:
 *     nil.to_f    => 0.0
 *
 *  Always returns zero.
 *
 *     nil.to_f   #=> 0.0
 */

static VALUE
nil_to_f(obj)
    VALUE obj;
{
    return rb_float_new(0.0);
}


to_s (NilClass)

/*
 *  call-seq:
 *     nil.to_s    => ""
 *
 *  Always returns the empty string.
 *
 *     nil.to_s   #=> ""
 */

static VALUE
nil_to_s(obj)
    VALUE obj;
{
    return rb_str_new2("");
}


to_a (NilClass)

/*
 *  call-seq:
 *     nil.to_a    => []
 *
 *  Always returns an empty array.
 *
 *     nil.to_a   #=> []
 */

static VALUE
nil_to_a(obj)
    VALUE obj;
{
    return rb_ary_new2(0);
}


inspect (NilClass)

/*
 *  call-seq:
 *    nil.inspect  => "nil"
 *
 *  Always returns the string "nil".
 */

static VALUE
nil_inspect(obj)
    VALUE obj;
{
    return rb_str_new2("nil");
}


& (NilClass)

/*
 *  call-seq:
 *     false & obj   => false
 *     nil & obj     => false
 *
 *  And---Returns <code>false</code>. <i>obj</i> is always
 *  evaluated as it is the argument to a method call---there is no
 *  short-circuit evaluation in this case.
 */

static VALUE
false_and(obj, obj2)
    VALUE obj, obj2;
{
    return Qfalse;
}


| (NilClass)

/*
 *  call-seq:
 *     false | obj   =>   true or false
 *     nil   | obj   =>   true or false
 *
 *  Or---Returns <code>false</code> if <i>obj</i> is
 *  <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
 */

static VALUE
false_or(obj, obj2)
    VALUE obj, obj2;
{
    return RTEST(obj2)?Qtrue:Qfalse;
}


^ (NilClass)

/*
 *  call-seq:
 *     false ^ obj    => true or false
 *     nil   ^ obj    => true or false
 *
 *  Exclusive Or---If <i>obj</i> is <code>nil</code> or
 *  <code>false</code>, returns <code>false</code>; otherwise, returns
 *  <code>true</code>.
 *
 */

static VALUE
false_xor(obj, obj2)
    VALUE obj, obj2;
{
    return RTEST(obj2)?Qtrue:Qfalse;
}


nil? (NilClass)

/*
 * call_seq:
 *   nil.nil?               => true
 *
 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
 */

static VALUE
rb_true(obj)
    VALUE obj;
{
    return Qtrue;
}


to_yaml (NilClass)

# File lib/yaml/rubytypes.rb, line 402
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( taguri, "", :plain )
        end
        end


nkf (NKF)

/*
 *  call-seq:
 *     NKF.nkf(opt, str)   -> string
 *
 *  Convert _str_ and return converted result.
 *  Conversion details are specified by _opt_ as String.
 *
 *     require 'nkf'
 *     output = NKF.nkf("-s", input)
 *
 *  *Note*
 *  By default, nkf decodes MIME encoded string.
 *  If you want not to decode input, use NKF.nkf with <b>-m0</b> flag.
 */

static VALUE
rb_nkf_kconv(obj, opt, src)
  VALUE obj, opt, src;
{
  char *opt_ptr, *opt_end;
  volatile VALUE v;

  reinit();
  StringValue(opt);
  opt_ptr = RSTRING(opt)->ptr;
  opt_end = opt_ptr + RSTRING(opt)->len;
  nkf_split_options(opt_ptr);

  incsize = INCSIZE;

  input_ctr = 0;
  StringValue(src);
  input = (unsigned char *)RSTRING(src)->ptr;
  i_len = RSTRING(src)->len;
  result = rb_str_new(0, i_len*3 + 10);
  v = result;

  output_ctr = 0;
  output     = (unsigned char *)RSTRING(result)->ptr;
  o_len      = RSTRING(result)->len;
  *output    = '\0';

  if(x0201_f == WISH_TRUE)
    x0201_f = ((!iso2022jp_f)? TRUE : NO_X0201);

  kanji_convert(NULL);
  RSTRING(result)->ptr[output_ctr] = '\0';
  RSTRING(result)->len = output_ctr;
  OBJ_INFECT(result, src);

  return result;
}


guess1 (NKF)

/*
 *  call-seq:
 *     NKF.guess1(str)  -> integer
 *
 *  Returns guessed encoding of _str_ as integer.
 *
 *  Algorithm described in:
 *  Ken Lunde. `Understanding Japanese Information Processing'
 *  Sebastopol, CA: O'Reilly & Associates.
 *
 *      case NKF.guess1(input)
 *      when NKF::JIS
 *        "ISO-2022-JP"
 *      when NKF::SJIS
 *        "Shift_JIS"
 *      when NKF::EUC
 *        "EUC-JP"
 *      when NKF::UNKNOWN
 *        "UNKNOWN(ASCII)"
 *      when NKF::BINARY
 *        "BINARY"
 *      end
 */

static VALUE
rb_nkf_guess1(obj, src)
  VALUE obj, src;
{
  unsigned char *p;
  unsigned char *pend;
  int sequence_counter = 0;

  StringValue(src);
  p = (unsigned char *)RSTRING(src)->ptr;
  pend = p + RSTRING(src)->len;
  if (p == pend) return INT2FIX(_UNKNOWN);

#define INCR do {\
      p++;\
      if (p==pend) return INT2FIX(_UNKNOWN);\
      sequence_counter++;\
      if (sequence_counter % 2 == 1 && *p != 0xa4)\
        sequence_counter = 0;\
      if (6 <= sequence_counter) {\
          sequence_counter = 0;\
          return INT2FIX(_EUC);\
      }\
  } while (0)

  if (*p == 0xa4)
    sequence_counter = 1;

  while (p<pend) {
    if (*p == '\033') {
      return INT2FIX(_JIS);
    }
    if (*p < '\006' || *p == 0x7f || *p == 0xff) {
      return INT2FIX(_BINARY);
    }
    if (0x81 <= *p && *p <= 0x8d) {
      return INT2FIX(_SJIS);
    }
    if (0x8f <= *p && *p <= 0x9f) {
      return INT2FIX(_SJIS);
    }
    if (*p == 0x8e) {   /* SS2 */
      INCR;
      if ((0x40 <= *p && *p <= 0x7e) ||
          (0x80 <= *p && *p <= 0xa0) ||
          (0xe0 <= *p && *p <= 0xfc))
        return INT2FIX(_SJIS);
    }
    else if (0xa1 <= *p && *p <= 0xdf) {
      INCR;
      if (0xf0 <= *p && *p <= 0xfe)
        return INT2FIX(_EUC);
      if (0xe0 <= *p && *p <= 0xef) {
        while (p < pend && *p >= 0x40) {
          if (*p >= 0x81) {
            if (*p <= 0x8d || (0x8f <= *p && *p <= 0x9f)) {
              return INT2FIX(_SJIS);
            }
            else if (0xfd <= *p && *p <= 0xfe) {
              return INT2FIX(_EUC);
            }
          }
          INCR;
        }
      }
      else if (*p <= 0x9f) {
        return INT2FIX(_SJIS);
      }
    }
    else if (0xf0 <= *p && *p <= 0xfe) {
      return INT2FIX(_EUC);
    }
    else if (0xe0 <= *p && *p <= 0xef) {
      INCR;
      if ((0x40 <= *p && *p <= 0x7e) ||
          (0x80 <= *p && *p <= 0xa0)) {
        return INT2FIX(_SJIS);
      }
      if (0xfd <= *p && *p <= 0xfe) {
        return INT2FIX(_EUC);
      }
    }
    INCR;
  }
  return INT2FIX(_UNKNOWN);
}


guess2 (NKF)

/*
 *  call-seq:
 *     NKF.guess2(str)  -> integer
 *
 *  Returns guessed encoding of _str_ as integer by nkf routine.
 *
 *     case NKF.guess(input)
 *     when NKF::ASCII
 *       "ASCII"
 *     when NKF::JIS
 *       "ISO-2022-JP"
 *     when NKF::SJIS
 *       "Shift_JIS"
 *     when NKF::EUC
 *       "EUC-JP"
 *     when NKF::UTF8
 *       "UTF-8"
 *     when NKF::UTF16
 *       "UTF-16"
 *     when NKF::UNKNOWN
 *       "UNKNOWN"
 *     when NKF::BINARY
 *       "BINARY"
 *     end
 */

static VALUE
rb_nkf_guess2(obj, src)
  VALUE obj, src;
{
  int code = _BINARY;

  reinit();

  input_ctr = 0;
  StringValue(src);
  input = (unsigned char *)RSTRING(src)->ptr;
  i_len = RSTRING(src)->len;

  if(x0201_f == WISH_TRUE)
    x0201_f = ((!iso2022jp_f)? TRUE : NO_X0201);

  guess_f = TRUE;
  kanji_convert( NULL );
  guess_f = FALSE;

  if (!is_inputcode_mixed) {
    if (strcmp(input_codename, "") == 0) {
      code = _ASCII;
    } else if (strcmp(input_codename, "ISO-2022-JP") == 0) {
      code = _JIS;
    } else if (strcmp(input_codename, "EUC-JP") == 0) {
      code = _EUC;
    } else if (strcmp(input_codename, "Shift_JIS") == 0) {
      code = _SJIS;
    } else if (strcmp(input_codename, "UTF-8") == 0) {
      code = _UTF8;
    } else if (strcmp(input_codename, "UTF-16") == 0) {
      code = _UTF16;
    } else if (strlen(input_codename) > 0) {
      code = _UNKNOWN;
    }
  }

  return INT2FIX( code );
}


new (NoMethodError)

/*
 * call-seq:
 *   NoMethodError.new(msg, name [, args])  => no_method_error
 *
 * Construct a NoMethodError exception for a method of the given name
 * called with the given arguments. The name may be accessed using
 * the <code>#name</code> method on the resulting object, and the
 * arguments using the <code>#args</code> method.
 */

static VALUE
nometh_err_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE args = (argc > 2) ? argv[--argc] : Qnil;
    name_err_initialize(argc, argv, self);
    rb_iv_set(self, "args", args);
    return self;
}


args (NoMethodError)

/*
 * call-seq:
 *   no_method_error.args  => obj
 *
 * Return the arguments passed in as the third parameter to
 * the constructor.
 */

static VALUE
nometh_err_args(self)
    VALUE self;
{
    return rb_attr_get(self, rb_intern("args"));
}


singleton_method_added (Numeric)

/*
 * Trap attempts to add methods to <code>Numeric</code> objects. Always
 * raises a <code>TypeError</code>
 */

static VALUE
num_sadded(x, name)
    VALUE x, name;
{
    ruby_frame = ruby_frame->prev; /* pop frame for "singleton_method_added" */
    /* Numerics should be values; singleton_methods should not be added to them */
    rb_raise(rb_eTypeError,
             "can't define singleton method \"%s\" for %s",
             rb_id2name(rb_to_id(name)),
             rb_obj_classname(x));
    return Qnil;                /* not reached */
}


coerce (Numeric)

/*
 *  call-seq:
 *     num.coerce(numeric)   => array
 *
 *  If <i>aNumeric</i> is the same type as <i>num</i>, returns an array
 *  containing <i>aNumeric</i> and <i>num</i>. Otherwise, returns an
 *  array with both <i>aNumeric</i> and <i>num</i> represented as
 *  <code>Float</code> objects. This coercion mechanism is used by
 *  Ruby to handle mixed-type numeric operations: it is intended to
 *  find a compatible common type between the two operands of the operator.
 *
 *     1.coerce(2.5)   #=> [2.5, 1.0]
 *     1.2.coerce(3)   #=> [3.0, 1.2]
 *     1.coerce(2)     #=> [2, 1]
 */

static VALUE
num_coerce(x, y)
    VALUE x, y;
{
    if (CLASS_OF(x) == CLASS_OF(y))
        return rb_assoc_new(y, x);
    return rb_assoc_new(rb_Float(y), rb_Float(x));
}


+@ (Numeric)

/*
 *  call-seq:
 *     +num    => num
 *
 *  Unary Plus---Returns the receiver's value.
 */

static VALUE
num_uplus(num)
    VALUE num;
{
    return num;
}


-@ (Numeric)

/*
 *  call-seq:
 *     -num    => numeric
 *
 *  Unary Minus---Returns the receiver's value, negated.
 */

static VALUE
num_uminus(num)
    VALUE num;
{
    VALUE zero;

    zero = INT2FIX(0);
    do_coerce(&zero, &num, Qtrue);

    return rb_funcall(zero, '-', 1, num);
}


<=> (Numeric)

/*
 *  call-seq:
 *     num <=> other -> 0 or nil
 *
 *  Returns zero if <i>num</i> equals <i>other</i>, <code>nil</code>
 *  otherwise.
 */

static VALUE
num_cmp(x, y)
    VALUE x, y;
{
    if (x == y) return INT2FIX(0);
    return Qnil;
}


eql? (Numeric)

/*
 *  call-seq:
 *     num.eql?(numeric)    => true or false
 *
 *  Returns <code>true</code> if <i>num</i> and <i>numeric</i> are the
 *  same type and have equal values.
 *
 *     1 == 1.0          #=> true
 *     1.eql?(1.0)       #=> false
 *     (1.0).eql?(1.0)   #=> true
 */

static VALUE
num_eql(x, y)
    VALUE x, y;
{
    if (TYPE(x) != TYPE(y)) return Qfalse;

    return rb_equal(x, y);
}


quo (Numeric)

/*
 *  call-seq:
 *     num.quo(numeric)    =>   result
 *
 *  Equivalent to <code>Numeric#/</code>, but overridden in subclasses.
 */

static VALUE
num_quo(x, y)
    VALUE x, y;
{
    return rb_funcall(x, '/', 1, y);
}


div (Numeric)

/*
 *  call-seq:
 *     num.div(numeric)    => integer
 *
 *  Uses <code>/</code> to perform division, then converts the result to
 *  an integer. <code>Numeric</code> does not define the <code>/</code>
 *  operator; this is left to subclasses.
 */

static VALUE
num_div(x, y)
    VALUE x, y;
{
    return num_floor(rb_funcall(x, '/', 1, y));
}


divmod (Numeric)

/*
 *  call-seq:
 *     num.divmod( aNumeric ) -> anArray
 *
 *  Returns an array containing the quotient and modulus obtained by
 *  dividing <i>num</i> by <i>aNumeric</i>. If <code>q, r =
 *  x.divmod(y)</code>, then
 *
 *      q = floor(float(x)/float(y))
 *      x = q*y + r
 *
 *  The quotient is rounded toward -infinity, as shown in the following table:
 *
 *     a    |  b  |  a.divmod(b)  |   a/b   | a.modulo(b) | a.remainder(b)
 *    ------+-----+---------------+---------+-------------+---------------
 *     13   |  4  |   3,    1     |   3     |    1        |     1
 *    ------+-----+---------------+---------+-------------+---------------
 *     13   | -4  |  -4,   -3     |  -3     |   -3        |     1
 *    ------+-----+---------------+---------+-------------+---------------
 *    -13   |  4  |  -4,    3     |  -4     |    3        |    -1
 *    ------+-----+---------------+---------+-------------+---------------
 *    -13   | -4  |   3,   -1     |   3     |   -1        |    -1
 *    ------+-----+---------------+---------+-------------+---------------
 *     11.5 |  4  |   2,    3.5   |   2.875 |    3.5      |     3.5
 *    ------+-----+---------------+---------+-------------+---------------
 *     11.5 | -4  |  -3,   -0.5   |  -2.875 |   -0.5      |     3.5
 *    ------+-----+---------------+---------+-------------+---------------
 *    -11.5 |  4  |  -3,    0.5   |  -2.875 |    0.5      |    -3.5
 *    ------+-----+---------------+---------+-------------+---------------
 *    -11.5 | -4  |   2    -3.5   |   2.875 |   -3.5      |    -3.5
 *
 *
 *  Examples
 *     11.divmod(3)         #=> [3, 2]
 *     11.divmod(-3)        #=> [-4, -1]
 *     11.divmod(3.5)       #=> [3, 0.5]
 *     (-11).divmod(3.5)    #=> [-4, 3.0]
 *     (11.5).divmod(3.5)   #=> [3, 1.0]
 */

static VALUE
num_divmod(x, y)
    VALUE x, y;
{
    return rb_assoc_new(num_div(x, y), rb_funcall(x, '%', 1, y));
}


modulo (Numeric)

/*
 *  call-seq:
 *     num.modulo(numeric)    => result
 *
 *  Equivalent to
 *  <i>num</i>.<code>divmod(</code><i>aNumeric</i><code>)[1]</code>.
 */

static VALUE
num_modulo(x, y)
    VALUE x, y;
{
    return rb_funcall(x, '%', 1, y);
}


remainder (Numeric)

/*
 *  call-seq:
 *     num.remainder(numeric)    => result
 *
 *  If <i>num</i> and <i>numeric</i> have different signs, returns
 *  <em>mod</em>-<i>numeric</i>; otherwise, returns <em>mod</em>. In
 *  both cases <em>mod</em> is the value
 *  <i>num</i>.<code>modulo(</code><i>numeric</i><code>)</code>. The
 *  differences between <code>remainder</code> and modulo
 *  (<code>%</code>) are shown in the table under <code>Numeric#divmod</code>.
 */

static VALUE
num_remainder(x, y)
    VALUE x, y;
{
    VALUE z = rb_funcall(x, '%', 1, y);

    if ((!rb_equal(z, INT2FIX(0))) &&
        ((RTEST(rb_funcall(x, '<', 1, INT2FIX(0))) &&
          RTEST(rb_funcall(y, '>', 1, INT2FIX(0)))) ||
         (RTEST(rb_funcall(x, '>', 1, INT2FIX(0))) &&
          RTEST(rb_funcall(y, '<', 1, INT2FIX(0)))))) {
        return rb_funcall(z, '-', 1, y);
    }
    return z;
}


abs (Numeric)

/*
 *  call-seq:
 *     num.abs   => num or numeric
 *
 *  Returns the absolute value of <i>num</i>.
 *
 *     12.abs         #=> 12
 *     (-34.56).abs   #=> 34.56
 *     -34.56.abs     #=> 34.56
 */

static VALUE
num_abs(num)
    VALUE num;
{
    if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) {
        return rb_funcall(num, rb_intern("-@"), 0);
    }
    return num;
}


to_int (Numeric)

/*
 *  call-seq:
 *     num.to_int    => integer
 *
 *  Invokes the child class's <code>to_i</code> method to convert
 *  <i>num</i> to an integer.
 */

static VALUE
num_to_int(num)
    VALUE num;
{
    return rb_funcall(num, id_to_i, 0, 0);
}


integer? (Numeric)

/*
 *  call-seq:
 *     num.integer? -> true or false
 *
 *  Returns <code>true</code> if <i>num</i> is an <code>Integer</code>
 *  (including <code>Fixnum</code> and <code>Bignum</code>).
 */

static VALUE
num_int_p(num)
    VALUE num;
{
    return Qfalse;
}


zero? (Numeric)

/*
 *  call-seq:
 *     num.zero?    => true or false
 *
 *  Returns <code>true</code> if <i>num</i> has a zero value.
 */

static VALUE
num_zero_p(num)
    VALUE num;
{
    if (rb_equal(num, INT2FIX(0))) {
        return Qtrue;
    }
    return Qfalse;
}


nonzero? (Numeric)

/*
 *  call-seq:
 *     num.nonzero?    => num or nil
 *
 *  Returns <i>num</i> if <i>num</i> is not zero, <code>nil</code>
 *  otherwise. This behavior is useful when chaining comparisons:
 *
 *     a = %w( z Bb bB bb BB a aA Aa AA A )
 *     b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
 *     b   #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
 */

static VALUE
num_nonzero_p(num)
    VALUE num;
{
    if (RTEST(rb_funcall(num, rb_intern("zero?"), 0, 0))) {
        return Qnil;
    }
    return num;
}


floor (Numeric)

/*
 *  call-seq:
 *     num.floor    => integer
 *
 *  Returns the largest integer less than or equal to <i>num</i>.
 *  <code>Numeric</code> implements this by converting <i>anInteger</i>
 *  to a <code>Float</code> and invoking <code>Float#floor</code>.
 *
 *     1.floor      #=> 1
 *     (-1).floor   #=> -1
 */

static VALUE
num_floor(num)
    VALUE num;
{
    return flo_floor(rb_Float(num));
}


ceil (Numeric)

/*
 *  call-seq:
 *     num.ceil    => integer
 *
 *  Returns the smallest <code>Integer</code> greater than or equal to
 *  <i>num</i>. Class <code>Numeric</code> achieves this by converting
 *  itself to a <code>Float</code> then invoking
 *  <code>Float#ceil</code>.
 *
 *     1.ceil        #=> 1
 *     1.2.ceil      #=> 2
 *     (-1.2).ceil   #=> -1
 *     (-1.0).ceil   #=> -1
 */

static VALUE
num_ceil(num)
    VALUE num;
{
    return flo_ceil(rb_Float(num));
}


round (Numeric)

/*
 *  call-seq:
 *     num.round    => integer
 *
 *  Rounds <i>num</i> to the nearest integer. <code>Numeric</code>
 *  implements this by converting itself to a
 *  <code>Float</code> and invoking <code>Float#round</code>.
 */

static VALUE
num_round(num)
    VALUE num;
{
    return flo_round(rb_Float(num));
}


truncate (Numeric)

/*
 *  call-seq:
 *     num.truncate    => integer
 *
 *  Returns <i>num</i> truncated to an integer. <code>Numeric</code>
 *  implements this by converting its value to a float and invoking
 *  <code>Float#truncate</code>.
 */

static VALUE
num_truncate(num)
    VALUE num;
{
    return flo_truncate(rb_Float(num));
}


step (Numeric)

/*
 *  call-seq:
 *     num.step(limit, step ) {|i| block }     => num
 *
 *  Invokes <em>block</em> with the sequence of numbers starting at
 *  <i>num</i>, incremented by <i>step</i> on each call. The loop
 *  finishes when the value to be passed to the block is greater than
 *  <i>limit</i> (if <i>step</i> is positive) or less than
 *  <i>limit</i> (if <i>step</i> is negative). If all the arguments are
 *  integers, the loop operates using an integer counter. If any of the
 *  arguments are floating point numbers, all are converted to floats,
 *  and the loop is executed <i>floor(n + n*epsilon)+ 1</i> times,
 *  where <i>n = (limit - num)/step</i>. Otherwise, the loop
 *  starts at <i>num</i>, uses either the <code><</code> or
 *  <code>></code> operator to compare the counter against
 *  <i>limit</i>, and increments itself using the <code>+</code>
 *  operator.
 *
 *     1.step(10, 2) { |i| print i, " " }
 *     Math::E.step(Math::PI, 0.2) { |f| print f, " " }
 *
 *  <em>produces:</em>
 *
 *     1 3 5 7 9
 *     2.71828182845905 2.91828182845905 3.11828182845905
 */

static VALUE
num_step(argc, argv, from)
    int argc;
    VALUE *argv;
    VALUE from;
{
    VALUE to, step;

    if (argc == 1) {
        to = argv[0];
        step = INT2FIX(1);
    }
    else {
        if (argc == 2) {
            to = argv[0];
            step = argv[1];
        }
        else {
            rb_raise(rb_eArgError, "wrong number of arguments");
        }
        if (rb_equal(step, INT2FIX(0))) {
            rb_raise(rb_eArgError, "step can't be 0");
        }
    }

    if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
        long i, end, diff;

        i = FIX2LONG(from);
        end = FIX2LONG(to);
        diff = FIX2LONG(step);

        if (diff > 0) {
            while (i <= end) {
                rb_yield(LONG2FIX(i));
                i += diff;
            }
        }
        else {
            while (i >= end) {
                rb_yield(LONG2FIX(i));
                i += diff;
            }
        }
    }
    else if (TYPE(from) == T_FLOAT || TYPE(to) == T_FLOAT || TYPE(step) == T_FLOAT) {
        const double epsilon = DBL_EPSILON;
        double beg = NUM2DBL(from);
        double end = NUM2DBL(to);
        double unit = NUM2DBL(step);
        double n = (end - beg)/unit;
        double err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
        long i;

        if (err>0.5) err=0.5;
        n = floor(n + err) + 1;
        for (i=0; i<n; i++) {
            rb_yield(rb_float_new(i*unit+beg));
        }
    }
    else {
        VALUE i = from;
        ID cmp;

        if (RTEST(rb_funcall(step, '>', 1, INT2FIX(0)))) {
            cmp = '>';
        }
        else {
            cmp = '<';
        }
        for (;;) {
            if (RTEST(rb_funcall(i, cmp, 1, to))) break;
            rb_yield(i);
            i = rb_funcall(i, '+', 1, step);
        }
    }
    return from;
}


im (Numeric)

# File lib/complex.rb, line 38
  def im
    Complex(0, self)
  end


real (Numeric)

# File lib/complex.rb, line 45
  def real
    self
  end


image (Numeric)

# File lib/complex.rb, line 52
  def image
    0
  end


arg (Numeric)

# File lib/complex.rb, line 60
  def arg
    if self >= 0
      return 0
    else
      return Math::PI
    end
  end


polar (Numeric)

# File lib/complex.rb, line 72
  def polar
    return abs, arg
  end


conjugate (Numeric)

# File lib/complex.rb, line 79
  def conjugate
    self
  end


respond_to? (Object)

/*
 *  call-seq:
 *     obj.respond_to?(symbol, include_private=false) => true or false
 *
 *  Returns +true+> if _obj_ responds to the given
 *  method. Private methods are included in the search only if the
 *  optional second parameter evaluates to +true+.
 */

static VALUE
obj_respond_to(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE mid, priv;
    ID id;

    rb_scan_args(argc, argv, "11", &mid, &priv);
    id = rb_to_id(mid);
    if (rb_method_boundp(CLASS_OF(obj), id, !RTEST(priv))) {
        return Qtrue;
    }
    return Qfalse;
}


send (Object)

/*
 *  call-seq:
 *     obj.send(symbol [, args...])        => obj
 *     obj.__send__(symbol [, args...])    => obj
 *
 *  Invokes the method identified by _symbol_, passing it any
 *  arguments specified. You can use <code>\_\_send__</code> if the name
 *  +send+ clashes with an existing method in _obj_.
 *
 *     class Klass
 *       def hello(*args)
 *         "Hello " + args.join(' ')
 *       end
 *     end
 *     k = Klass.new
 *     k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"
 */

static VALUE
rb_f_send(argc, argv, recv)
    int argc;
    VALUE *argv;
    VALUE recv;
{
    VALUE vid;

    if (argc == 0) rb_raise(rb_eArgError, "no method name given");

    vid = *argv++; argc--;
    PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
    vid = rb_call(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, 1, Qundef);
    POP_ITER();

    return vid;
}


__send__ (Object)

/*
 *  call-seq:
 *     obj.send(symbol [, args...])        => obj
 *     obj.__send__(symbol [, args...])    => obj
 *
 *  Invokes the method identified by _symbol_, passing it any
 *  arguments specified. You can use <code>\_\_send__</code> if the name
 *  +send+ clashes with an existing method in _obj_.
 *
 *     class Klass
 *       def hello(*args)
 *         "Hello " + args.join(' ')
 *       end
 *     end
 *     k = Klass.new
 *     k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"
 */

static VALUE
rb_f_send(argc, argv, recv)
    int argc;
    VALUE *argv;
    VALUE recv;
{
    VALUE vid;

    if (argc == 0) rb_raise(rb_eArgError, "no method name given");

    vid = *argv++; argc--;
    PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
    vid = rb_call(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, 1, Qundef);
    POP_ITER();

    return vid;
}


instance_eval (Object)

/*
 *  call-seq:
 *     obj.instance_eval(string [, filename [, lineno]] )   => obj
 *     obj.instance_eval {| | block }                       => obj
 *
 *  Evaluates a string containing Ruby source code, or the given block,
 *  within the context of the receiver (_obj_). In order to set the
 *  context, the variable +self+ is set to _obj_ while
 *  the code is executing, giving the code access to _obj_'s
 *  instance variables. In the version of <code>instance_eval</code>
 *  that takes a +String+, the optional second and third
 *  parameters supply a filename and starting line number that are used
 *  when reporting compilation errors.
 *
 *     class Klass
 *       def initialize
 *         @secret = 99
 *       end
 *     end
 *     k = Klass.new
 *     k.instance_eval { @secret }   #=> 99
 */

VALUE
rb_obj_instance_eval(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE klass;

    if (SPECIAL_CONST_P(self)) {
        klass = Qnil;
    }
    else {
        klass = rb_singleton_class(self);
    }
    return specific_eval(argc, argv, klass, self);
}


extend (Object)

/*
 *  call-seq:
 *     obj.extend(module, ...)    => obj
 *
 *  Adds to _obj_ the instance methods from each module given as a
 *  parameter.
 *
 *     module Mod
 *       def hello
 *         "Hello from Mod.\n"
 *       end
 *     end
 *
 *     class Klass
 *       def hello
 *         "Hello from Klass.\n"
 *       end
 *     end
 *
 *     k = Klass.new
 *     k.hello         #=> "Hello from Klass.\n"
 *     k.extend(Mod)   #=> #<Klass:0x401b3bc8>
 *     k.hello         #=> "Hello from Mod.\n"
 */

static VALUE
rb_obj_extend(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    int i;

    if (argc == 0) {
        rb_raise(rb_eArgError, "wrong number of arguments (0 for 1)");
    }
    for (i=0; i<argc; i++) Check_Type(argv[i], T_MODULE);
    while (argc--) {
        rb_funcall(argv[argc], rb_intern("extend_object"), 1, obj);
        rb_funcall(argv[argc], rb_intern("extended"), 1, obj);
    }
    return obj;
}


method (Object)

/*
 *  call-seq:
 *     obj.method(sym)    => method
 *
 *  Looks up the named method as a receiver in <i>obj</i>, returning a
 *  <code>Method</code> object (or raising <code>NameError</code>). The
 *  <code>Method</code> object acts as a closure in <i>obj</i>'s object
 *  instance, so instance variables and the value of <code>self</code>
 *  remain available.
 *
 *     class Demo
 *       def initialize(n)
 *         @iv = n
 *       end
 *       def hello()
 *         "Hello, @iv = #{@iv}"
 *       end
 *     end
 *
 *     k = Demo.new(99)
 *     m = k.method(:hello)
 *     m.call   #=> "Hello, @iv = 99"
 *
 *     l = Demo.new('Fred')
 *     m = l.method("hello")
 *     m.call   #=> "Hello, @iv = Fred"
 */

static VALUE
rb_obj_method(obj, vid)
    VALUE obj;
    VALUE vid;
{
    return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod);
}


new (Object)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


nil? (Object)

/*
 * call_seq:
 *   nil.nil?               => true
 *   <anything_else>.nil?   => false
 *
 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
 */

static VALUE
rb_false(obj)
    VALUE obj;
{
    return Qfalse;
}


== (Object)

/*
 *  call-seq:
 *     obj == other        => true or false
 *     obj.equal?(other)   => true or false
 *     obj.eql?(other)     => true or false
 *
 *  Equality---At the <code>Object</code> level, <code>==</code> returns
 *  <code>true</code> only if <i>obj</i> and <i>other</i> are the
 *  same object. Typically, this method is overridden in descendent
 *  classes to provide class-specific meaning.
 *
 *  Unlike <code>==</code>, the <code>equal?</code> method should never be
 *  overridden by subclasses: it is used to determine object identity
 *  (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same
 *  object as <code>b</code>).
 *
 *  The <code>eql?</code> method returns <code>true</code> if
    <i>obj</i> and <i>anObject</i> have the
 *  same value. Used by <code>Hash</code> to test members for equality.
 *  For objects of class <code>Object</code>, <code>eql?</code> is
 *  synonymous with <code>==</code>. Subclasses normally continue this
 *  tradition, but there are exceptions. <code>Numeric</code> types, for
 *  example, perform type conversion across <code>==</code>, but not
 *  across <code>eql?</code>, so:
 *
 *     1 == 1.0     #=> true
 *     1.eql? 1.0   #=> false
 */

static VALUE
rb_obj_equal(obj1, obj2)
    VALUE obj1, obj2;
{
    if (obj1 == obj2) return Qtrue;
    return Qfalse;
}


equal? (Object)

/*
 *  call-seq:
 *     obj == other        => true or false
 *     obj.equal?(other)   => true or false
 *     obj.eql?(other)     => true or false
 *
 *  Equality---At the <code>Object</code> level, <code>==</code> returns
 *  <code>true</code> only if <i>obj</i> and <i>other</i> are the
 *  same object. Typically, this method is overridden in descendent
 *  classes to provide class-specific meaning.
 *
 *  Unlike <code>==</code>, the <code>equal?</code> method should never be
 *  overridden by subclasses: it is used to determine object identity
 *  (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same
 *  object as <code>b</code>).
 *
 *  The <code>eql?</code> method returns <code>true</code> if
    <i>obj</i> and <i>anObject</i> have the
 *  same value. Used by <code>Hash</code> to test members for equality.
 *  For objects of class <code>Object</code>, <code>eql?</code> is
 *  synonymous with <code>==</code>. Subclasses normally continue this
 *  tradition, but there are exceptions. <code>Numeric</code> types, for
 *  example, perform type conversion across <code>==</code>, but not
 *  across <code>eql?</code>, so:
 *
 *     1 == 1.0     #=> true
 *     1.eql? 1.0   #=> false
 */

static VALUE
rb_obj_equal(obj1, obj2)
    VALUE obj1, obj2;
{
    if (obj1 == obj2) return Qtrue;
    return Qfalse;
}


=== (Object)

/*
 *  call-seq:
 *     obj === other   => true or false
 *
 *  Case Equality---For class <code>Object</code>, effectively the same
 *  as calling  <code>#==</code>, but typically overridden by descendents
 *  to provide meaningful semantics in <code>case</code> statements.
 */

VALUE
rb_equal(obj1, obj2)
    VALUE obj1, obj2;
{
    VALUE result;

    if (obj1 == obj2) return Qtrue;
    result = rb_funcall(obj1, id_eq, 1, obj2);
    if (RTEST(result)) return Qtrue;
    return Qfalse;
}


=~ (Object)

/*
 *  call-seq:
 *     obj =~ other  => false
 *
 *  Pattern Match---Overridden by descendents (notably
 *  <code>Regexp</code> and <code>String</code>) to provide meaningful
 *  pattern-match semantics.
 */

static VALUE
rb_obj_pattern_match(obj1, obj2)
    VALUE obj1, obj2;
{
    return Qfalse;
}


eql? (Object)

/*
 *  call-seq:
 *     obj == other        => true or false
 *     obj.equal?(other)   => true or false
 *     obj.eql?(other)     => true or false
 *
 *  Equality---At the <code>Object</code> level, <code>==</code> returns
 *  <code>true</code> only if <i>obj</i> and <i>other</i> are the
 *  same object. Typically, this method is overridden in descendent
 *  classes to provide class-specific meaning.
 *
 *  Unlike <code>==</code>, the <code>equal?</code> method should never be
 *  overridden by subclasses: it is used to determine object identity
 *  (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same
 *  object as <code>b</code>).
 *
 *  The <code>eql?</code> method returns <code>true</code> if
    <i>obj</i> and <i>anObject</i> have the
 *  same value. Used by <code>Hash</code> to test members for equality.
 *  For objects of class <code>Object</code>, <code>eql?</code> is
 *  synonymous with <code>==</code>. Subclasses normally continue this
 *  tradition, but there are exceptions. <code>Numeric</code> types, for
 *  example, perform type conversion across <code>==</code>, but not
 *  across <code>eql?</code>, so:
 *
 *     1 == 1.0     #=> true
 *     1.eql? 1.0   #=> false
 */

static VALUE
rb_obj_equal(obj1, obj2)
    VALUE obj1, obj2;
{
    if (obj1 == obj2) return Qtrue;
    return Qfalse;
}


id (Object)

/*
 *  call-seq:
 *     obj.id    => fixnum
 *
 *  Soon-to-be deprecated version of <code>Object#object_id</code>.
 */

VALUE
rb_obj_id_obsolete(obj)
    VALUE obj;
{
    rb_warn("Object#id will be deprecated; use Object#object_id");
    return rb_obj_id(obj);
}


type (Object)

/*
 *  call-seq:
 *     obj.type   => class
 *
 *  Deprecated synonym for <code>Object#class</code>.
 */

VALUE
rb_obj_type(obj)
    VALUE obj;
{
    rb_warn("Object#type is deprecated; use Object#class");
    return rb_class_real(CLASS_OF(obj));
}


class (Object)

/*
 *  call-seq:
 *     obj.class    => class
 *
 *  Returns the class of <i>obj</i>, now preferred over
 *  <code>Object#type</code>, as an object's type in Ruby is only
 *  loosely tied to that object's class. This method must always be
 *  called with an explicit receiver, as <code>class</code> is also a
 *  reserved word in Ruby.
 *
 *     1.class      #=> Fixnum
 *     self.class   #=> Object
 */

VALUE
rb_obj_class(obj)
    VALUE obj;
{
    return rb_class_real(CLASS_OF(obj));
}


clone (Object)

/*
 *  call-seq:
 *     obj.clone -> an_object
 *
 *  Produces a shallow copy of <i>obj</i>---the instance variables of
 *  <i>obj</i> are copied, but not the objects they reference. Copies
 *  the frozen and tainted state of <i>obj</i>. See also the discussion
 *  under <code>Object#dup</code>.
 *
 *     class Klass
 *        attr_accessor :str
 *     end
 *     s1 = Klass.new      #=> #<Klass:0x401b3a38>
 *     s1.str = "Hello"    #=> "Hello"
 *     s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
 *     s2.str[1,4] = "i"   #=> "i"
 *     s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
 *     s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"
 *
 *  This method may have class-specific behavior.  If so, that
 *  behavior will be documented under the #+initialize_copy+ method of
 *  the class.
 */

VALUE
rb_obj_clone(obj)
    VALUE obj;
{
    VALUE clone;

    if (rb_special_const_p(obj)) {
        rb_raise(rb_eTypeError, "can't clone %s", rb_obj_classname(obj));
    }
    clone = rb_obj_alloc(rb_obj_class(obj));
    RBASIC(clone)->klass = rb_singleton_class_clone(obj);
    RBASIC(clone)->flags = (RBASIC(obj)->flags | FL_TEST(clone, FL_TAINT)) & ~(FL_FREEZE|FL_FINALIZE);
    init_copy(clone, obj);
    RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE;

    return clone;
}


dup (Object)

/*
 *  call-seq:
 *     obj.dup -> an_object
 *
 *  Produces a shallow copy of <i>obj</i>---the instance variables of
 *  <i>obj</i> are copied, but not the objects they reference.
 *  <code>dup</code> copies the tainted state of <i>obj</i>. See also
 *  the discussion under <code>Object#clone</code>. In general,
 *  <code>clone</code> and <code>dup</code> may have different semantics
 *  in descendent classes. While <code>clone</code> is used to duplicate
 *  an object, including its internal state, <code>dup</code> typically
 *  uses the class of the descendent object to create the new instance.
 *
 *  This method may have class-specific behavior.  If so, that
 *  behavior will be documented under the #+initialize_copy+ method of
 *  the class.
 */

VALUE
rb_obj_dup(obj)
    VALUE obj;
{
    VALUE dup;

    if (rb_special_const_p(obj)) {
        rb_raise(rb_eTypeError, "can't dup %s", rb_obj_classname(obj));
    }
    dup = rb_obj_alloc(rb_obj_class(obj));
    init_copy(dup, obj);

    return dup;
}


taint (Object)

/*
 *  call-seq:
 *     obj.taint -> obj
 *
 *  Marks <i>obj</i> as tainted---if the <code>$SAFE</code> level is
 *  set appropriately, many method calls which might alter the running
 *  programs environment will refuse to accept tainted strings.
 */

VALUE
rb_obj_taint(obj)
    VALUE obj;
{
    rb_secure(4);
    if (!OBJ_TAINTED(obj)) {
        if (OBJ_FROZEN(obj)) {
            rb_error_frozen("object");
        }
        OBJ_TAINT(obj);
    }
    return obj;
}


tainted? (Object)

/*
 *  call-seq:
 *     obj.tainted?    => true or false
 *
 *  Returns <code>true</code> if the object is tainted.
 */

VALUE
rb_obj_tainted(obj)
    VALUE obj;
{
    if (OBJ_TAINTED(obj))
        return Qtrue;
    return Qfalse;
}


untaint (Object)

/*
 *  call-seq:
 *     obj.untaint    => obj
 *
 *  Removes the taint from <i>obj</i>.
 */

VALUE
rb_obj_untaint(obj)
    VALUE obj;
{
    rb_secure(3);
    if (OBJ_TAINTED(obj)) {
        if (OBJ_FROZEN(obj)) {
            rb_error_frozen("object");
        }
        FL_UNSET(obj, FL_TAINT);
    }
    return obj;
}


freeze (Object)

/*
 *  call-seq:
 *     obj.freeze    => obj
 *
 *  Prevents further modifications to <i>obj</i>. A
 *  <code>TypeError</code> will be raised if modification is attempted.
 *  There is no way to unfreeze a frozen object. See also
 *  <code>Object#frozen?</code>.
 *
 *     a = [ "a", "b", "c" ]
 *     a.freeze
 *     a << "z"
 *
 *  <em>produces:</em>
 *
 *     prog.rb:3:in `<<': can't modify frozen array (TypeError)
 *      from prog.rb:3
 */

VALUE
rb_obj_freeze(obj)
    VALUE obj;
{
    if (!OBJ_FROZEN(obj)) {
        if (rb_safe_level() >= 4 && !OBJ_TAINTED(obj)) {
            rb_raise(rb_eSecurityError, "Insecure: can't freeze object");
        }
        OBJ_FREEZE(obj);
    }
    return obj;
}


frozen? (Object)

/*
 *  call-seq:
 *     obj.frozen?    => true or false
 *
 *  Returns the freeze status of <i>obj</i>.
 *
 *     a = [ "a", "b", "c" ]
 *     a.freeze    #=> ["a", "b", "c"]
 *     a.frozen?   #=> true
 */

static VALUE
rb_obj_frozen_p(obj)
    VALUE obj;
{
    if (OBJ_FROZEN(obj)) return Qtrue;
    return Qfalse;
}


to_a (Object)

/*
 *  call-seq:
 *     obj.to_a -> anArray
 *
 *  Returns an array representation of <i>obj</i>. For objects of class
 *  <code>Object</code> and others that don't explicitly override the
 *  method, the return value is an array containing <code>self</code>.
 *  However, this latter behavior will soon be obsolete.
 *
 *     self.to_a       #=> -:1: warning: default `to_a' will be obsolete
 *     "hello".to_a    #=> ["hello"]
 *     Time.new.to_a   #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"]
 */

static VALUE
rb_any_to_a(obj)
    VALUE obj;
{
    rb_warn("default `to_a' will be obsolete");
    return rb_ary_new3(1, obj);
}


to_s (Object)

/*
 *  call-seq:
 *     obj.to_s    => string
 *
 *  Returns a string representing <i>obj</i>. The default
 *  <code>to_s</code> prints the object's class and an encoding of the
 *  object id. As a special case, the top-level object that is the
 *  initial execution context of Ruby programs returns ``main.''
 */

VALUE
rb_any_to_s(obj)
    VALUE obj;
{
    char *cname = rb_obj_classname(obj);
    size_t len;
    VALUE str;

    len = strlen(cname)+6+16;
    str = rb_str_new(0, len); /* 6:tags 16:addr */
    snprintf(RSTRING(str)->ptr, len+1, "#<%s:0x%lx>", cname, obj);
    RSTRING(str)->len = strlen(RSTRING(str)->ptr);
    if (OBJ_TAINTED(obj)) OBJ_TAINT(str);

    return str;
}


inspect (Object)

/*
 *  call-seq:
 *     obj.inspect   => string
 *
 *  Returns a string containing a human-readable representation of
 *  <i>obj</i>. If not overridden, uses the <code>to_s</code> method to
 *  generate the string.
 *
 *     [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
 *     Time.new.inspect                 #=> "Wed Apr 09 08:54:39 CDT 2003"
 */

static VALUE
rb_obj_inspect(obj)
    VALUE obj;
{
    if (TYPE(obj) == T_OBJECT
        && ROBJECT(obj)->iv_tbl
        && ROBJECT(obj)->iv_tbl->num_entries > 0) {
        VALUE str;
        size_t len;
        char *c;

        c = rb_obj_classname(obj);
        if (rb_inspecting_p(obj)) {
            len = strlen(c)+10+16+1;
            str = rb_str_new(0, len); /* 10:tags 16:addr 1:nul */
            snprintf(RSTRING(str)->ptr, len, "#<%s:0x%lx ...>", c, obj);
            RSTRING(str)->len = strlen(RSTRING(str)->ptr);
            return str;
        }
        len = strlen(c)+6+16+1;
        str = rb_str_new(0, len);     /* 6:tags 16:addr 1:nul */
        snprintf(RSTRING(str)->ptr, len, "-<%s:0x%lx", c, obj);
        RSTRING(str)->len = strlen(RSTRING(str)->ptr);
        return rb_protect_inspect(inspect_obj, obj, str);
    }
    return rb_funcall(obj, rb_intern("to_s"), 0, 0);
}


methods (Object)

/*
 *  call-seq:
 *     obj.methods    => array
 *
 *  Returns a list of the names of methods publicly accessible in
 *  <i>obj</i>. This will include all the methods accessible in
 *  <i>obj</i>'s ancestors.
 *
 *     class Klass
 *       def kMethod()
 *       end
 *     end
 *     k = Klass.new
 *     k.methods[0..9]    #=> ["kMethod", "freeze", "nil?", "is_a?",
 *                             "class", "instance_variable_set",
 *                              "methods", "extend", "__send__", "instance_eval"]
 *     k.methods.length   #=> 42
 */

static VALUE
rb_obj_methods(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
  retry:
    if (argc == 0) {
        VALUE args[1];

        args[0] = Qtrue;
        return rb_class_instance_methods(1, args, CLASS_OF(obj));
    }
    else {
        VALUE recur;

        rb_scan_args(argc, argv, "1", &recur);
        if (RTEST(recur)) {
            argc = 0;
            goto retry;
        }
        return rb_obj_singleton_methods(argc, argv, obj);
    }
}


singleton_methods (Object)

/*
 *  call-seq:
 *     obj.singleton_methods(all=true)    => array
 *
 *  Returns an array of the names of singleton methods for <i>obj</i>.
 *  If the optional <i>all</i> parameter is true, the list will include
 *  methods in modules included in <i>obj</i>.
 *
 *     module Other
 *       def three() end
 *     end
 *
 *     class Single
 *       def Single.four() end
 *     end
 *
 *     a = Single.new
 *
 *     def a.one()
 *     end
 *
 *     class << a
 *       include Other
 *       def two()
 *       end
 *     end
 *
 *     Single.singleton_methods    #=> ["four"]
 *     a.singleton_methods(false)  #=> ["two", "one"]
 *     a.singleton_methods         #=> ["two", "one", "three"]
 */

VALUE
rb_obj_singleton_methods(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE recur, ary, klass;
    st_table *list;

    rb_scan_args(argc, argv, "01", &recur);
    if (argc == 0) {
    recur = Qtrue;
    }
    klass = CLASS_OF(obj);
    list = st_init_numtable();
    if (klass && FL_TEST(klass, FL_SINGLETON)) {
    st_foreach(RCLASS(klass)->m_tbl, method_entry, (st_data_t)list);
    klass = RCLASS(klass)->super;
    }
    if (RTEST(recur)) {
    while (klass && (FL_TEST(klass, FL_SINGLETON) || TYPE(klass) == T_ICLASS)) {
        st_foreach(RCLASS(klass)->m_tbl, method_entry, (st_data_t)list);
        klass = RCLASS(klass)->super;
    }
    }
    ary = rb_ary_new();
    st_foreach(list, ins_methods_i, ary);
    st_free_table(list);

    return ary;
}


protected_methods (Object)

/*
 *  call-seq:
 *     obj.protected_methods(all=true)   => array
 *
 *  Returns the list of protected methods accessible to <i>obj</i>. If
 *  the <i>all</i> parameter is set to <code>false</code>, only those methods
 *  in the receiver will be listed.
 */

static VALUE
rb_obj_protected_methods(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    if (argc == 0) {            /* hack to stop warning */
        VALUE args[1];

        args[0] = Qtrue;
        return rb_class_protected_instance_methods(1, args, CLASS_OF(obj));
    }
    return rb_class_protected_instance_methods(argc, argv, CLASS_OF(obj));
}


private_methods (Object)

/*
 *  call-seq:
 *     obj.private_methods(all=true)   => array
 *
 *  Returns the list of private methods accessible to <i>obj</i>. If
 *  the <i>all</i> parameter is set to <code>false</code>, only those methods
 *  in the receiver will be listed.
 */

static VALUE
rb_obj_private_methods(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    if (argc == 0) {            /* hack to stop warning */
        VALUE args[1];

        args[0] = Qtrue;
        return rb_class_private_instance_methods(1, args, CLASS_OF(obj));
    }
    return rb_class_private_instance_methods(argc, argv, CLASS_OF(obj));
}


public_methods (Object)

/*
 *  call-seq:
 *     obj.public_methods(all=true)   => array
 *
 *  Returns the list of public methods accessible to <i>obj</i>. If
 *  the <i>all</i> parameter is set to <code>false</code>, only those methods
 *  in the receiver will be listed.
 */

static VALUE
rb_obj_public_methods(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    if (argc == 0) {            /* hack to stop warning */
        VALUE args[1];

        args[0] = Qtrue;
        return rb_class_public_instance_methods(1, args, CLASS_OF(obj));
    }
    return rb_class_public_instance_methods(argc, argv, CLASS_OF(obj));
}


instance_variables (Object)

/*
 *  call-seq:
 *     obj.instance_variables    => array
 *
 *  Returns an array of instance variable names for the receiver. Note
 *  that simply defining an accessor does not create the corresponding
 *  instance variable.
 *
 *     class Fred
 *       attr_accessor :a1
 *       def initialize
 *         @iv = 3
 *       end
 *     end
 *     Fred.new.instance_variables   #=> ["@iv"]
 */

VALUE
rb_obj_instance_variables(obj)
    VALUE obj;
{
    VALUE ary;

    ary = rb_ary_new();
    switch (TYPE(obj)) {
      case T_OBJECT:
      case T_CLASS:
      case T_MODULE:
    if (ROBJECT(obj)->iv_tbl) {
        st_foreach_safe(ROBJECT(obj)->iv_tbl, ivar_i, ary);
    }
    break;
      default:
    if (!generic_iv_tbl) break;
    if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj)) {
        st_table *tbl;

        if (st_lookup(generic_iv_tbl, obj, (st_data_t *)&tbl)) {
        st_foreach_safe(tbl, ivar_i, ary);
        }
    }
    break;
    }
    return ary;
}


instance_variable_get (Object)

/*
 *  call-seq:
 *     obj.instance_variable_get(symbol)    => obj
 *
 *  Returns the value of the given instance variable, or nil if the
 *  instance variable is not set. The <code>@</code> part of the
 *  variable name should be included for regular instance
 *  variables. Throws a <code>NameError</code> exception if the
 *  supplied symbol is not valid as an instance variable name.
 *
 *     class Fred
 *       def initialize(p1, p2)
 *         @a, @b = p1, p2
 *       end
 *     end
 *     fred = Fred.new('cat', 99)
 *     fred.instance_variable_get(:@a)    #=> "cat"
 *     fred.instance_variable_get("@b")   #=> 99
 */

static VALUE
rb_obj_ivar_get(obj, iv)
    VALUE obj, iv;
{
    ID id = rb_to_id(iv);

    if (!rb_is_instance_id(id)) {
        rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
    }
    return rb_ivar_get(obj, id);
}


instance_variable_set (Object)

/*
 *  call-seq:
 *     obj.instance_variable_set(symbol, obj)    => obj
 *
 *  Sets the instance variable names by <i>symbol</i> to
 *  <i>object</i>, thereby frustrating the efforts of the class's
 *  author to attempt to provide proper encapsulation. The variable
 *  did not have to exist prior to this call.
 *
 *     class Fred
 *       def initialize(p1, p2)
 *         @a, @b = p1, p2
 *       end
 *     end
 *     fred = Fred.new('cat', 99)
 *     fred.instance_variable_set(:@a, 'dog')   #=> "dog"
 *     fred.instance_variable_set(:@c, 'cat')   #=> "cat"
 *     fred.inspect                             #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
 */

static VALUE
rb_obj_ivar_set(obj, iv, val)
    VALUE obj, iv, val;
{
    ID id = rb_to_id(iv);

    if (!rb_is_instance_id(id)) {
        rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
    }
    return rb_ivar_set(obj, id, val);
}


instance_variable_defined? (Object)

/*
 *  call-seq:
 *     obj.instance_variable_defined?(symbol)    => true or false
 *
 *  Returns <code>true</code> if the given instance variable is
 *  defined in <i>obj</i>.
 *
 *     class Fred
 *       def initialize(p1, p2)
 *         @a, @b = p1, p2
 *       end
 *     end
 *     fred = Fred.new('cat', 99)
 *     fred.instance_variable_defined?(:@a)    #=> true
 *     fred.instance_variable_defined?("@b")   #=> true
 *     fred.instance_variable_defined?("@c")   #=> false
 */

static VALUE
rb_obj_ivar_defined(obj, iv)
    VALUE obj, iv;
{
    ID id = rb_to_id(iv);

    if (!rb_is_instance_id(id)) {
        rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
    }
    return rb_ivar_defined(obj, id);
}


remove_instance_variable (Object)

/*
 *  call-seq:
 *     obj.remove_instance_variable(symbol)    => obj
 *
 *  Removes the named instance variable from <i>obj</i>, returning that
 *  variable's value.
 *
 *     class Dummy
 *       attr_reader :var
 *       def initialize
 *         @var = 99
 *       end
 *       def remove
 *         remove_instance_variable(:@var)
 *       end
 *     end
 *     d = Dummy.new
 *     d.var      #=> 99
 *     d.remove   #=> 99
 *     d.var      #=> nil
 */

VALUE
rb_obj_remove_instance_variable(obj, name)
    VALUE obj, name;
{
    VALUE val = Qnil;
    ID id = rb_to_id(name);

    if (!OBJ_TAINTED(obj) && rb_safe_level() >= 4)
    rb_raise(rb_eSecurityError, "Insecure: can't modify instance variable");
    if (OBJ_FROZEN(obj)) rb_error_frozen("object");
    if (!rb_is_instance_id(id)) {
    rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id));
    }

    switch (TYPE(obj)) {
      case T_OBJECT:
      case T_CLASS:
      case T_MODULE:
    if (ROBJECT(obj)->iv_tbl && st_delete(ROBJECT(obj)->iv_tbl, (st_data_t*)&id, &val)) {
        return val;
    }
    break;
      default:
    if (FL_TEST(obj, FL_EXIVAR) || rb_special_const_p(obj)) {
        if (generic_ivar_remove(obj, id, &val)) {
        return val;
        }
    }
    break;
    }
    rb_name_error(id, "instance variable %s not defined", rb_id2name(id));
    return Qnil;		/* not reached */
}


instance_of? (Object)

/*
 *  call-seq:
 *     obj.instance_of?(class)    => true or false
 *
 *  Returns <code>true</code> if <i>obj</i> is an instance of the given
 *  class. See also <code>Object#kind_of?</code>.
 */

VALUE
rb_obj_is_instance_of(obj, c)
    VALUE obj, c;
{
    switch (TYPE(c)) {
      case T_MODULE:
      case T_CLASS:
      case T_ICLASS:
        break;
      default:
        rb_raise(rb_eTypeError, "class or module required");
    }

    if (rb_obj_class(obj) == c) return Qtrue;
    return Qfalse;
}


kind_of? (Object)

/*
 *  call-seq:
 *     obj.is_a?(class)       => true or false
 *     obj.kind_of?(class)    => true or false
 *
 *  Returns <code>true</code> if <i>class</i> is the class of
 *  <i>obj</i>, or if <i>class</i> is one of the superclasses of
 *  <i>obj</i> or modules included in <i>obj</i>.
 *
 *     module M;    end
 *     class A
 *       include M
 *     end
 *     class B < A; end
 *     class C < B; end
 *     b = B.new
 *     b.instance_of? A   #=> false
 *     b.instance_of? B   #=> true
 *     b.instance_of? C   #=> false
 *     b.instance_of? M   #=> false
 *     b.kind_of? A       #=> true
 *     b.kind_of? B       #=> true
 *     b.kind_of? C       #=> false
 *     b.kind_of? M       #=> true
 */

VALUE
rb_obj_is_kind_of(obj, c)
    VALUE obj, c;
{
    VALUE cl = CLASS_OF(obj);

    switch (TYPE(c)) {
      case T_MODULE:
      case T_CLASS:
      case T_ICLASS:
        break;

      default:
        rb_raise(rb_eTypeError, "class or module required");
    }

    while (cl) {
        if (cl == c || RCLASS(cl)->m_tbl == RCLASS(c)->m_tbl)
            return Qtrue;
        cl = RCLASS(cl)->super;
    }
    return Qfalse;
}


is_a? (Object)

/*
 *  call-seq:
 *     obj.is_a?(class)       => true or false
 *     obj.kind_of?(class)    => true or false
 *
 *  Returns <code>true</code> if <i>class</i> is the class of
 *  <i>obj</i>, or if <i>class</i> is one of the superclasses of
 *  <i>obj</i> or modules included in <i>obj</i>.
 *
 *     module M;    end
 *     class A
 *       include M
 *     end
 *     class B < A; end
 *     class C < B; end
 *     b = B.new
 *     b.instance_of? A   #=> false
 *     b.instance_of? B   #=> true
 *     b.instance_of? C   #=> false
 *     b.instance_of? M   #=> false
 *     b.kind_of? A       #=> true
 *     b.kind_of? B       #=> true
 *     b.kind_of? C       #=> false
 *     b.kind_of? M       #=> true
 */

VALUE
rb_obj_is_kind_of(obj, c)
    VALUE obj, c;
{
    VALUE cl = CLASS_OF(obj);

    switch (TYPE(c)) {
      case T_MODULE:
      case T_CLASS:
      case T_ICLASS:
        break;

      default:
        rb_raise(rb_eTypeError, "class or module required");
    }

    while (cl) {
        if (cl == c || RCLASS(cl)->m_tbl == RCLASS(c)->m_tbl)
            return Qtrue;
        cl = RCLASS(cl)->super;
    }
    return Qfalse;
}


singleton_method_added (Object)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


singleton_method_removed (Object)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


singleton_method_undefined (Object)

/*
 * Not documented
 */

static VALUE
rb_obj_dummy()
{
    return Qnil;
}


display (Object)

/*
 *  call-seq:
 *     obj.display(port=$>)    => nil
 *
 *  Prints <i>obj</i> on the given port (default <code>$></code>).
 *  Equivalent to:
 *
 *     def display(port=$>)
 *       port.write self
 *     end
 *
 *  For example:
 *
 *     1.display
 *     "cat".display
 *     [ 4, 5, 6 ].display
 *     puts
 *
 *  <em>produces:</em>
 *
 *     1cat456
 */

static VALUE
rb_obj_display(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE out;

    if (rb_scan_args(argc, argv, "01", &out) == 0) {
        out = rb_stdout;
    }

    rb_io_write(out, self);

    return Qnil;
}


hash (Object)

/*
 *  call-seq:
 *     obj.hash    => fixnum
 *
 *  Generates a <code>Fixnum</code> hash value for this object. This
 *  function must have the property that <code>a.eql?(b)</code> implies
 *  <code>a.hash == b.hash</code>. The hash value is used by class
 *  <code>Hash</code>. Any hash value that exceeds the capacity of a
 *  <code>Fixnum</code> will be truncated before being used.
 */

VALUE
rb_obj_id(VALUE obj)
{
    /*
     *                32-bit VALUE space
     *          MSB ------------------------ LSB
     *  false   00000000000000000000000000000000
     *  true    00000000000000000000000000000010
     *  nil     00000000000000000000000000000100
     *  undef   00000000000000000000000000000110
     *  symbol  ssssssssssssssssssssssss00001110
     *  object  oooooooooooooooooooooooooooooo00        = 0 (mod sizeof(RVALUE))
     *  fixnum  fffffffffffffffffffffffffffffff1
     *
     *                    object_id space
     *                                       LSB
     *  false   00000000000000000000000000000000
     *  true    00000000000000000000000000000010
     *  nil     00000000000000000000000000000100
     *  undef   00000000000000000000000000000110
     *  symbol   000SSSSSSSSSSSSSSSSSSSSSSSSSSS0        S...S % A = 4 (S...S = s...s * A + 4)
     *  object   oooooooooooooooooooooooooooooo0        o...o % A = 0
     *  fixnum  fffffffffffffffffffffffffffffff1        bignum if required
     *
     *  where A = sizeof(RVALUE)/4
     *
     *  sizeof(RVALUE) is
     *  20 if 32-bit, double is 4-byte aligned
     *  24 if 32-bit, double is 8-byte aligned
     *  40 if 64-bit
     */
    if (TYPE(obj) == T_SYMBOL) {
        return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
    }
    if (SPECIAL_CONST_P(obj)) {
        return LONG2NUM((long)obj);
    }
    return (VALUE)((long)obj|FIXNUM_FLAG);
}


__id__ (Object)

/*
 *  call-seq:
 *     obj.hash    => fixnum
 *
 *  Generates a <code>Fixnum</code> hash value for this object. This
 *  function must have the property that <code>a.eql?(b)</code> implies
 *  <code>a.hash == b.hash</code>. The hash value is used by class
 *  <code>Hash</code>. Any hash value that exceeds the capacity of a
 *  <code>Fixnum</code> will be truncated before being used.
 */

VALUE
rb_obj_id(VALUE obj)
{
    /*
     *                32-bit VALUE space
     *          MSB ------------------------ LSB
     *  false   00000000000000000000000000000000
     *  true    00000000000000000000000000000010
     *  nil     00000000000000000000000000000100
     *  undef   00000000000000000000000000000110
     *  symbol  ssssssssssssssssssssssss00001110
     *  object  oooooooooooooooooooooooooooooo00        = 0 (mod sizeof(RVALUE))
     *  fixnum  fffffffffffffffffffffffffffffff1
     *
     *                    object_id space
     *                                       LSB
     *  false   00000000000000000000000000000000
     *  true    00000000000000000000000000000010
     *  nil     00000000000000000000000000000100
     *  undef   00000000000000000000000000000110
     *  symbol   000SSSSSSSSSSSSSSSSSSSSSSSSSSS0        S...S % A = 4 (S...S = s...s * A + 4)
     *  object   oooooooooooooooooooooooooooooo0        o...o % A = 0
     *  fixnum  fffffffffffffffffffffffffffffff1        bignum if required
     *
     *  where A = sizeof(RVALUE)/4
     *
     *  sizeof(RVALUE) is
     *  20 if 32-bit, double is 4-byte aligned
     *  24 if 32-bit, double is 8-byte aligned
     *  40 if 64-bit
     */
    if (TYPE(obj) == T_SYMBOL) {
        return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
    }
    if (SPECIAL_CONST_P(obj)) {
        return LONG2NUM((long)obj);
    }
    return (VALUE)((long)obj|FIXNUM_FLAG);
}


object_id (Object)

/*
 *  call-seq:
 *     obj.hash    => fixnum
 *
 *  Generates a <code>Fixnum</code> hash value for this object. This
 *  function must have the property that <code>a.eql?(b)</code> implies
 *  <code>a.hash == b.hash</code>. The hash value is used by class
 *  <code>Hash</code>. Any hash value that exceeds the capacity of a
 *  <code>Fixnum</code> will be truncated before being used.
 */

VALUE
rb_obj_id(VALUE obj)
{
    /*
     *                32-bit VALUE space
     *          MSB ------------------------ LSB
     *  false   00000000000000000000000000000000
     *  true    00000000000000000000000000000010
     *  nil     00000000000000000000000000000100
     *  undef   00000000000000000000000000000110
     *  symbol  ssssssssssssssssssssssss00001110
     *  object  oooooooooooooooooooooooooooooo00        = 0 (mod sizeof(RVALUE))
     *  fixnum  fffffffffffffffffffffffffffffff1
     *
     *                    object_id space
     *                                       LSB
     *  false   00000000000000000000000000000000
     *  true    00000000000000000000000000000010
     *  nil     00000000000000000000000000000100
     *  undef   00000000000000000000000000000110
     *  symbol   000SSSSSSSSSSSSSSSSSSSSSSSSSSS0        S...S % A = 4 (S...S = s...s * A + 4)
     *  object   oooooooooooooooooooooooooooooo0        o...o % A = 0
     *  fixnum  fffffffffffffffffffffffffffffff1        bignum if required
     *
     *  where A = sizeof(RVALUE)/4
     *
     *  sizeof(RVALUE) is
     *  20 if 32-bit, double is 4-byte aligned
     *  24 if 32-bit, double is 8-byte aligned
     *  40 if 64-bit
     */
    if (TYPE(obj) == T_SYMBOL) {
        return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
    }
    if (SPECIAL_CONST_P(obj)) {
        return LONG2NUM((long)obj);
    }
    return (VALUE)((long)obj|FIXNUM_FLAG);
}


dclone (Object)

# File lib/rexml/xpath_parser.rb, line 8
  def dclone
    clone
  end


instance_variable_get (Object)

# File lib/soap/soap.rb, line 123
    def instance_variable_get(ivarname)
      instance_eval(ivarname)
    end


instance_variable_set (Object)

# File lib/soap/soap.rb, line 127
    def instance_variable_set(ivarname, value)
      instance_eval("#{ivarname} = value")
    end


to_yaml_style (Object)

# File lib/yaml/rubytypes.rb, line 12
    def to_yaml_style; end


to_yaml_properties (Object)

# File lib/yaml/rubytypes.rb, line 13
    def to_yaml_properties; instance_variables.sort; end


to_yaml (Object)

# File lib/yaml/rubytypes.rb, line 14
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            out.map( taguri, to_yaml_style ) do |map|
                                to_yaml_properties.each do |m|
                    map.add( m[1..-1], instance_variable_get( m ) )
                end
            end
        end
        end


to_enum (Object)

/*
 *  call-seq:
 *    obj.to_enum(method = :each, *args)
 *    obj.enum_for(method = :each, *args)
 *
 *  Returns Enumerable::Enumerator.new(self, method, *args).
 *
 *  e.g.:
 *     str = "xyz"
 *
 *     enum = str.enum_for(:each_byte)
 *     a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
 *
 *     # protects an array from being modified
 *     a = [1, 2, 3]
 *     some_method(a.to_enum)
 *
 */
static VALUE
obj_to_enum(obj, enum_args)
    VALUE obj, enum_args;
{
    rb_ary_unshift(enum_args, obj);

    return rb_apply(rb_cEnumerator, id_new, enum_args);
}


enum_for (Object)

/*
 *  call-seq:
 *    obj.to_enum(method = :each, *args)
 *    obj.enum_for(method = :each, *args)
 *
 *  Returns Enumerable::Enumerator.new(self, method, *args).
 *
 *  e.g.:
 *     str = "xyz"
 *
 *     enum = str.enum_for(:each_byte)
 *     a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
 *
 *     # protects an array from being modified
 *     a = [1, 2, 3]
 *     some_method(a.to_enum)
 *
 */
static VALUE
obj_to_enum(obj, enum_args)
    VALUE obj, enum_args;
{
    rb_ary_unshift(enum_args, obj);

    return rb_apply(rb_cEnumerator, id_new, enum_args);
}


each_object (ObjectSpace)

/*
 *  call-seq:
 *     ObjectSpace.each_object([module]) {|obj| ... } => fixnum
 *
 *  Calls the block once for each living, nonimmediate object in this
 *  Ruby process. If <i>module</i> is specified, calls the block
 *  for only those classes or modules that match (or are a subclass of)
 *  <i>module</i>. Returns the number of objects found. Immediate
 *  objects (<code>Fixnum</code>s, <code>Symbol</code>s
 *  <code>true</code>, <code>false</code>, and <code>nil</code>) are
 *  never returned. In the example below, <code>each_object</code>
 *  returns both the numbers we defined and several constants defined in
 *  the <code>Math</code> module.
 *
 *     a = 102.7
 *     b = 95       # Won't be returned
 *     c = 12345678987654321
 *     count = ObjectSpace.each_object(Numeric) {|x| p x }
 *     puts "Total count: #{count}"
 *
 *  <em>produces:</em>
 *
 *     12345678987654321
 *     102.7
 *     2.71828182845905
 *     3.14159265358979
 *     2.22044604925031e-16
 *     1.7976931348623157e+308
 *     2.2250738585072e-308
 *     Total count: 7
 *
 */

static VALUE
os_each_obj(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE of;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &of) == 0) {
        return os_live_obj();
    }
    else {
        return os_obj_of(of);
    }
}


garbage_collect (ObjectSpace)

/*
 *  call-seq:
 *     GC.start                     => nil
 *     gc.garbage_collect           => nil
 *     ObjectSpace.garbage_collect  => nil
 *
 *  Initiates garbage collection, unless manually disabled.
 *
 */

VALUE
rb_gc_start()
{
    rb_gc();
    return Qnil;
}


add_finalizer (ObjectSpace)

/* deprecated
 */

static VALUE
add_final(os, block)
    VALUE os, block;
{
    rb_warn("ObjectSpace::add_finalizer is deprecated; use define_finalizer");
    if (!rb_respond_to(block, rb_intern("call"))) {
        rb_raise(rb_eArgError, "wrong type argument %s (should be callable)",
                 rb_obj_classname(block));
    }
    rb_ary_push(finalizers, block);
    return block;
}


remove_finalizer (ObjectSpace)

/*
 * deprecated
 */
static VALUE
rm_final(os, block)
    VALUE os, block;
{
    rb_warn("ObjectSpace::remove_finalizer is deprecated; use undefine_finalizer");
    rb_ary_delete(finalizers, block);
    return block;
}


finalizers (ObjectSpace)

/*
 * deprecated
 */
static VALUE
finals()
{
    rb_warn("ObjectSpace::finalizers is deprecated");
    return finalizers;
}


call_finalizer (ObjectSpace)

/*
 * deprecated
 */

static VALUE
call_final(os, obj)
    VALUE os, obj;
{
    rb_warn("ObjectSpace::call_finalizer is deprecated; use define_finalizer");
    need_call_final = 1;
    FL_SET(obj, FL_FINALIZE);
    return obj;
}


define_finalizer (ObjectSpace)

/*
 *  call-seq:
 *     ObjectSpace.define_finalizer(obj, aProc=proc())
 *
 *  Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
 *  was destroyed.
 *
 */

static VALUE
define_final(argc, argv, os)
    int argc;
    VALUE *argv;
    VALUE os;
{
    VALUE obj, block, table;

    rb_scan_args(argc, argv, "11", &obj, &block);
    if (argc == 1) {
        block = rb_block_proc();
    }
    else if (!rb_respond_to(block, rb_intern("call"))) {
        rb_raise(rb_eArgError, "wrong type argument %s (should be callable)",
                 rb_obj_classname(block));
    }
    need_call_final = 1;
    FL_SET(obj, FL_FINALIZE);

    block = rb_ary_new3(2, INT2FIX(ruby_safe_level), block);

    if (!finalizer_table) {
        finalizer_table = st_init_numtable();
    }
    if (st_lookup(finalizer_table, obj, &table)) {
        rb_ary_push(table, block);
    }
    else {
        st_add_direct(finalizer_table, obj, rb_ary_new3(1, block));
    }
    return block;
}


undefine_finalizer (ObjectSpace)

/*
 *  call-seq:
 *     ObjectSpace.undefine_finalizer(obj)
 *
 *  Removes all finalizers for <i>obj</i>.
 *
 */

static VALUE
undefine_final(os, obj)
    VALUE os, obj;
{
    if (finalizer_table) {
        st_delete(finalizer_table, (st_data_t*)&obj, 0);
    }
    return obj;
}


_id2ref (ObjectSpace)

/*
 *  call-seq:
 *     ObjectSpace._id2ref(object_id) -> an_object
 *
 *  Converts an object id to a reference to the object. May not be
 *  called on an object id passed as a parameter to a finalizer.
 *
 *     s = "I am a string"                    #=> "I am a string"
 *     r = ObjectSpace._id2ref(s.object_id)   #=> "I am a string"
 *     r == s                                 #=> true
 *
 */

static VALUE
id2ref(obj, objid)
    VALUE obj, objid;
{
    unsigned long ptr, p0;

    rb_secure(4);
    p0 = ptr = NUM2ULONG(objid);
    if (ptr == Qtrue) return Qtrue;
    if (ptr == Qfalse) return Qfalse;
    if (ptr == Qnil) return Qnil;
    if (FIXNUM_P(ptr)) return (VALUE)ptr;
    ptr = objid ^ FIXNUM_FLAG;  /* unset FIXNUM_FLAG */

    if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
        ID symid = ptr / sizeof(RVALUE);
        if (rb_id2name(symid) == 0)
            rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
        return ID2SYM(symid);
    }

    if (!is_pointer_to_heap((void *)ptr)|| BUILTIN_TYPE(ptr) >= T_BLKTAG) {
        rb_raise(rb_eRangeError, "0x%lx is not id value", p0);
    }
    if (BUILTIN_TYPE(ptr) == 0 || RBASIC(ptr)->klass == 0) {
        rb_raise(rb_eRangeError, "0x%lx is recycled object", p0);
    }
    return (VALUE)ptr;
}


add_observer (Observable)

# File lib/observer.rb, line 123
  def add_observer(observer)
    @observer_peers = [] unless defined? @observer_peers
    unless observer.respond_to? :update
      raise NoMethodError, "observer needs to respond to `update'"
    end
    @observer_peers.push observer
  end


delete_observer (Observable)

# File lib/observer.rb, line 135
  def delete_observer(observer)
    @observer_peers.delete observer if defined? @observer_peers
  end


delete_observers (Observable)

# File lib/observer.rb, line 142
  def delete_observers
    @observer_peers.clear if defined? @observer_peers
  end


count_observers (Observable)

# File lib/observer.rb, line 149
  def count_observers
    if defined? @observer_peers
      @observer_peers.size
    else
      0
    end
  end


changed (Observable)

# File lib/observer.rb, line 161
  def changed(state=true)
    @observer_state = state
  end


changed? (Observable)

# File lib/observer.rb, line 168
  def changed?
    if defined? @observer_state and @observer_state
      true
    else
      false
    end
  end


notify_observers (Observable)

# File lib/observer.rb, line 181
  def notify_observers(*arg)
    if defined? @observer_state and @observer_state
      if defined? @observer_peers
        for i in @observer_peers.dup
          i.update(*arg)
        end
      end
      @observer_state = false
    end
  end


new (OLEProperty)

# File ext/win32ole/lib/win32ole/property.rb, line 4
  def initialize(obj, dispid, gettypes, settypes)
    @obj = obj
    @dispid = dispid
    @gettypes = gettypes
    @settypes = settypes
  end


[] (OLEProperty)

# File ext/win32ole/lib/win32ole/property.rb, line 10
  def [](*args)
    @obj._getproperty(@dispid, args, @gettypes)
  end


[]= (OLEProperty)

# File ext/win32ole/lib/win32ole/property.rb, line 13
  def []=(*args)
    @obj._setproperty(@dispid, args, @settypes)
  end


popen3 (Open3)

# File lib/open3.rb, line 46
  def popen3(*cmd)
    pw = IO::pipe   # pipe[0] for read, pipe[1] for write
    pr = IO::pipe
    pe = IO::pipe

    pid = fork{
      # child
      fork{
        # grandchild
        pw[1].close
        STDIN.reopen(pw[0])
        pw[0].close

        pr[0].close
        STDOUT.reopen(pr[1])
        pr[1].close

        pe[0].close
        STDERR.reopen(pe[1])
        pe[1].close

        exec(*cmd)
      }
      exit!(0)
    }

    pw[0].close
    pr[1].close
    pe[1].close
    Process.waitpid(pid)
    pi = [pw[1], pr[0], pe[0]]
    pw[1].sync = true
    if defined? yield
      begin
        return yield(*pi)
      ensure
        pi.each{|p| p.close unless p.closed?}
      end
    end
    pi
  end


new (OpenStruct)

# File lib/ostruct.rb, line 46
  def initialize(hash=nil)
    @table = {}
    if hash
      for k,v in hash
        @table[k.to_sym] = v
        new_ostruct_member(k)
      end
    end
  end


initialize_copy (OpenStruct)

# File lib/ostruct.rb, line 57
  def initialize_copy(orig)
    super
    @table = @table.dup
  end


marshal_dump (OpenStruct)

# File lib/ostruct.rb, line 62
  def marshal_dump
    @table
  end


marshal_load (OpenStruct)

# File lib/ostruct.rb, line 65
  def marshal_load(x)
    @table = x
    @table.each_key{|key| new_ostruct_member(key)}
  end


new_ostruct_member (OpenStruct)

# File lib/ostruct.rb, line 70
  def new_ostruct_member(name)
    name = name.to_sym
    unless self.respond_to?(name)
      meta = class << self; self; end
      meta.send(:define_method, name) { @table[name] }
      meta.send(:define_method, "#{name}=""#{name}=") { |x| @table[name] = x }
    end
  end


delete_field (OpenStruct)

# File lib/ostruct.rb, line 102
  def delete_field(name)
    @table.delete name.to_sym
  end


inspect (OpenStruct)

# File lib/ostruct.rb, line 111
  def inspect
    str = "#<#{self.class}"

    Thread.current[InspectKey] ||= []
    if Thread.current[InspectKey].include?(self) then
      str << " ..."
    else
      first = true
      for k,v in @table
        str << "," unless first
        first = false

        Thread.current[InspectKey] << v
        begin
          str << " #{k}=#{v.inspect}"
        ensure
          Thread.current[InspectKey].pop
        end
      end
    end

    str << ">"
  end


== (OpenStruct)

# File lib/ostruct.rb, line 142
  def ==(other)
    return false unless(other.kind_of?(OpenStruct))
    return @table == other.table
  end


new (OpenURI::HTTPError)

# File lib/open-uri.rb, line 283
    def initialize(message, io)
      super(message)
      @io = io
    end


last_modified (OpenURI::Meta)

# File lib/open-uri.rb, line 350
    def last_modified
      if v = @meta['last-modified']
        Time.httpdate(v)
      else
        nil
      end
    end


content_type (OpenURI::Meta)

# File lib/open-uri.rb, line 383
    def content_type
      type, *parameters = content_type_parse
      type || 'application/octet-stream'
    end


charset (OpenURI::Meta)

# File lib/open-uri.rb, line 398
    def charset
      type, *parameters = content_type_parse
      if pair = parameters.assoc('charset')
        pair.last.downcase
      elsif block_given?
        yield
      elsif type && %r{\Atext/} =~ type &&
            @base_uri && /\Ahttp\z/i =~ @base_uri.scheme
        "iso-8859-1" # RFC2616 3.7.1
      else
        nil
      end
    end


content_encoding (OpenURI::Meta)

# File lib/open-uri.rb, line 415
    def content_encoding
      v = @meta['content-encoding']
      if v && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ v
        v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
      else
        []
      end
    end


open (OpenURI::OpenRead)

# File lib/open-uri.rb, line 518
    def open(*rest, &block)
      OpenURI.open_uri(self, *rest, &block)
    end


read (OpenURI::OpenRead)

# File lib/open-uri.rb, line 526
    def read(options={})
      self.open(options) {|f|
        str = f.read
        Meta.init str, f
        str
      }
    end


complete (OptionParser::Completion)

# File lib/optparse.rb, line 221
    def complete(key, icase = false, pat = nil)
      pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'),
                         icase)
      canon, sw, k, v, cn = nil
      candidates = []
      each do |k, *v|
        (if Regexp === k
           kn = nil
           k === key
         else
           kn = defined?(k.id2name) ? k.id2name : k
           pat === kn
         end) or next
        v << k if v.empty?
        candidates << [k, v, kn]
      end
      candidates = candidates.sort_by {|k, v, kn| kn.size}
      if candidates.size == 1
        canon, sw, * = candidates[0]
      elsif candidates.size > 1
        canon, sw, cn = candidates.shift
        candidates.each do |k, v, kn|
          next if sw == v
          if String === cn and String === kn
            if cn.rindex(kn, 0)
              canon, sw, cn = k, v, kn
              next
            elsif kn.rindex(cn, 0)
              next
            end
          end
          throw :ambiguous, key
        end
      end
      if canon
        block_given? or return key, *sw
        yield(key, *sw)
      end
    end


convert (OptionParser::Completion)

# File lib/optparse.rb, line 261
    def convert(opt = nil, val = nil, *)
      val
    end


parse (OptionParser::NoArgument)

# File lib/optparse.rb, line 428
      def parse(arg, argv)
        yield(NeedlessArgument, arg) if arg
        conv_arg(arg)
      end


incompatible_argument_styles (OptionParser::NoArgument)

# File lib/optparse.rb, line 433
      def self.incompatible_argument_styles(*)
      end


pattern (OptionParser::NoArgument)

# File lib/optparse.rb, line 436
      def self.pattern
        Object
      end


parse (OptionParser::OptionalArgument)

# File lib/optparse.rb, line 466
      def parse(arg, argv, &error)
        if arg
          conv_arg(*parse_arg(arg, &error))
        else
          conv_arg(arg)
        end
      end


parse (OptionParser::PlacedArgument)

# File lib/optparse.rb, line 483
      def parse(arg, argv, &error)
        if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
          return nil, block, nil
        end
        opt = (val = parse_arg(val, &error))[1]
        val = conv_arg(*val)
        if opt and !arg
          argv.shift
        else
          val[0] = nil
        end
        val
      end


parse (OptionParser::RequiredArgument)

# File lib/optparse.rb, line 449
      def parse(arg, argv)
        unless arg
          raise MissingArgument if argv.empty?
          arg = argv.shift
        end
        conv_arg(*parse_arg(arg) {|*exc| raise(*exc)})
      end


guess (OptionParser::Switch)

# File lib/optparse.rb, line 288
    def self.guess(arg)
      case arg
      when ""
        t = self
      when /\A=?\[/
        t = Switch::OptionalArgument
      when /\A\s+\[/
        t = Switch::PlacedArgument
      else
        t = Switch::RequiredArgument
      end
      self >= t or incompatible_argument_styles(arg, t)
      t
    end


incompatible_argument_styles (OptionParser::Switch)

# File lib/optparse.rb, line 303
    def self.incompatible_argument_styles(arg, t)
      raise ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}"
    end


pattern (OptionParser::Switch)

# File lib/optparse.rb, line 307
    def self.pattern
      NilClass
    end


new (OptionParser::Switch)

# File lib/optparse.rb, line 311
    def initialize(pattern = nil, conv = nil,
                   short = nil, long = nil, arg = nil,
                   desc = ([] if short or long), block = Proc.new)
      raise if Array === pattern
      @pattern, @conv, @short, @long, @arg, @desc, @block =
        pattern, conv, short, long, arg, desc, block
    end


summarize (OptionParser::Switch)

# File lib/optparse.rb, line 370
    def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
      sopts, lopts, s = [], [], nil
      @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
      @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
      return if sopts.empty? and lopts.empty? # completely hidden

      left = [sopts.join(', ')]
      right = desc.dup

      while s = lopts.shift
        l = left[-1].length + s.length
        l += arg.length if left.size == 1 && arg
        l < max or left << ''
        left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
      end

      left[0] << arg if arg
      mlen = left.collect {|s| s.length}.max.to_i
      while mlen > width and l = left.shift
        mlen = left.collect {|s| s.length}.max.to_i if l.length == mlen
        yield(indent + l)
      end

      while begin l = left.shift; r = right.shift; l or r end
        l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
        yield(indent + l)
      end


switch_name (OptionParser)

# File lib/optparse.rb, line 416
    def switch_name
      (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
    end


options (Options::OptionList)

# File lib/rdoc/options.rb, line 243
    def OptionList.options
      OPTION_LIST.map do |long, short, arg,|
        [ long,
          short,
          arg ? GetoptLong::REQUIRED_ARGUMENT : GetoptLong::NO_ARGUMENT
        ]
      end
    end


strip_output (Options::OptionList)

# File lib/rdoc/options.rb, line 253
    def OptionList.strip_output(text)
      text =~ /^\s+/
      leading_spaces = $&
      text.gsub!(/^#{leading_spaces}/, '')
      $stdout.puts text
    end


error (Options::OptionList)

# File lib/rdoc/options.rb, line 263
    def OptionList.error(msg)
      $stderr.puts
      $stderr.puts msg
      $stderr.puts "\nFor help on options, try 'rdoc --help'\n\n"
      exit 1
    end


usage (Options::OptionList)

# File lib/rdoc/options.rb, line 272
    def OptionList.usage(generator_names)

      puts
      puts(VERSION_STRING)
      puts

      name = File.basename($0)
      OptionList.strip_output("Usage:\n\n\#{name} [options]  [names...]\n\nFiles are parsed, and the information they contain\ncollected, before any output is produced. This allows cross\nreferences between all files to be resolved. If a name is a\ndirectory, it is traversed. If no names are specified, all\nRuby files in the current directory (and subdirectories) are\nprocessed.\n\nOptions:\n\n")

      OPTION_LIST.each do |long, short, arg, desc|
        opt = sprintf("%20s", "#{long}, #{short}")
        oparg = sprintf("%-7s", arg)
        print "#{opt} #{oparg}"
        desc = desc.split("\n")
        if arg.nil? || arg.length < 7
          puts desc.shift
        else
          puts
        end
        desc.each do |line|
          puts(" "*28 + line)
        end
        puts
      end

      puts "\nAvailable output formatters: " +
        generator_names.sort.join(', ') + "\n\n"

      puts "For information on where the output goes, use\n\n"
      puts "   rdoc --help-output\n\n"

      exit 0
    end


help_output (Options::OptionList)

# File lib/rdoc/options.rb, line 321
    def OptionList.help_output
      OptionList.strip_output("How RDoc generates output depends on the output formatter being\nused, and on the options you give.\n\n- HTML output is normally produced into a number of separate files\n(one per class, module, and file, along with various indices).\nThese files will appear in the directory given by the --op\noption (doc/ by default).\n\n- XML output by default is written to standard output. If a\n--opname option is given, the output will instead be written\nto a file with that name in the output directory.\n\n- .chm files (Windows help files) are written in the --op directory.\nIf an --opname parameter is present, that name is used, otherwise\nthe file will be called rdoc.chm.\n\nFor information on other RDoc options, use \"rdoc --help\".\n")
      exit 0
    end


parse (Options)

# File lib/rdoc/options.rb, line 349
  def parse(argv, generators)
    old_argv = ARGV.dup
    begin
      ARGV.replace(argv)
      @op_dir = "doc"
      @op_name = nil
      @show_all = false
      @main_page = nil
      @marge     = false
      @exclude   = []
      @quiet = false
      @generator_name = 'html'
      @generator = generators[@generator_name]
      @rdoc_include = []
      @title = nil
      @template = nil
      @diagram = false
      @fileboxes = false
      @show_hash = false
      @image_format = 'png'
      @inline_source = false
      @all_one_file  = false
      @tab_width = 8
      @include_line_numbers = false
      @extra_accessor_flags = {}
      @promiscuous = false
      @force_update = false

      @css = nil
      @webcvs = nil

      @charset = case $KCODE
                 when /^S/i
                   'Shift_JIS'
                 when /^E/i
                   'EUC-JP'
                 else
                   'iso-8859-1'
                 end

      accessors = []

      go = GetoptLong.new(*OptionList.options)
      go.quiet = true

      go.each do |opt, arg|
        case opt
        when "--all"           then @show_all      = true
        when "--charset"       then @charset       = arg
        when "--debug"         then $DEBUG         = true
        when "--exclude"       then @exclude       << Regexp.new(arg)
        when "--inline-source" then @inline_source = true
        when "--line-numbers"  then @include_line_numbers = true
        when "--main"          then @main_page     = arg
        when "--merge"         then @merge         = true
        when "--one-file"      then @all_one_file  = @inline_source = true
        when "--op"            then @op_dir        = arg
        when "--opname"        then @op_name       = arg
        when "--promiscuous"   then @promiscuous   = true
        when "--quiet"         then @quiet         = true
        when "--show-hash"     then @show_hash     = true
        when "--style"         then @css           = arg
        when "--template"      then @template      = arg
        when "--title"         then @title         = arg
        when "--webcvs"        then @webcvs        = arg

        when "--accessor"
          arg.split(/,/).each do |accessor|
            if accessor =~ /^(\w+)(=(.*))?$/
              accessors << $1
              @extra_accessor_flags[$1] = $3
            end
          end

        when "--diagram"
          check_diagram
          @diagram = true

        when "--fileboxes"
          @fileboxes = true if @diagram

        when "--fmt"
          @generator_name = arg.downcase
          setup_generator(generators)

        when "--help"
          OptionList.usage(generators.keys)

        when "--help-output"
          OptionList.help_output

        when "--image-format"
          if ['gif', 'png', 'jpeg', 'jpg'].include?(arg)
            @image_format = arg
          else
            raise GetoptLong::InvalidOption.new("unknown image format: #{arg}")
          end

        when "--include"
          @rdoc_include.concat arg.split(/\s*,\s*/)

        when "--ri", "--ri-site", "--ri-system"
          @generator_name = "ri"
          @op_dir = case opt
                    when "--ri" then RI::Paths::HOMEDIR
                    when "--ri-site" then RI::Paths::SITEDIR
                    when "--ri-system" then RI::Paths::SYSDIR
                    else fail opt
                    end
          setup_generator(generators)

        when "--tab-width"
          begin
            @tab_width     = Integer(arg)
          rescue
            $stderr.puts "Invalid tab width: '#{arg}'"
            exit 1
          end

        when "--extension"
          new, old = arg.split(/=/, 2)
          OptionList.error("Invalid parameter to '-E'") unless new && old
          unless RDoc::ParserFactory.alias_extension(old, new)
            OptionList.error("Unknown extension .#{old} to -E")
          end

        when "--force-update"
          @force_update = true

        when "--version"
          puts VERSION_STRING
          exit
        end

      end

      @files = ARGV.dup

      @rdoc_include << "." if @rdoc_include.empty?

      if @exclude.empty?
        @exclude = nil
      else
        @exclude = Regexp.new(@exclude.join("|"))
      end

      check_files

      # If no template was specified, use the default
      # template for the output formatter

      @template ||= @generator_name

      # Generate a regexp from the accessors
      unless accessors.empty?
        re = '^(' + accessors.map{|a| Regexp.quote(a)}.join('|') + ')$'
        @extra_accessors = Regexp.new(re)
      end

    rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => error
      OptionList.error(error.message)

    ensure
      ARGV.replace(old_argv)
    end
  end


title (Options)

# File lib/rdoc/options.rb, line 517
  def title
    @title ||= "RDoc Documentation"
  end


title= (Options)

# File lib/rdoc/options.rb, line 524
  def title=(string)
    @title ||= string
  end


parsedate (ParseDate)

# File lib/parsedate.rb, line 46
  def parsedate(str, comp=false)
    Date._parse(str, comp).
      values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)
  end


new (ParseError)

# File lib/optparse.rb, line 1591
    def initialize(*args)
      @args = args
      @reason = nil
    end


recover (ParseError)

# File lib/optparse.rb, line 1602
    def recover(argv)
      argv[0, 0] = @args
      argv
    end


set_option (ParseError)

# File lib/optparse.rb, line 1607
    def set_option(opt, eq)
      if eq
        @args[0] = opt
      else
        @args.unshift(opt)
      end
      self
    end


reason (ParseError)

# File lib/optparse.rb, line 1619
    def reason
      @reason || self.class::Reason
    end


inspect (ParseError)

# File lib/optparse.rb, line 1623
    def inspect
      "#<#{self.class.to_s}: #{args.join(' ')}>"
    end


message (ParseError)

# File lib/optparse.rb, line 1630
    def message
      reason + ': ' + args.join(' ')
    end


new (Pathname)

# File lib/pathname.rb, line 203
  def initialize(path)
    path = path.__send__(TO_PATH) if path.respond_to? TO_PATH
    @path = path.dup

    if /\0/ =~ @path
      raise ArgumentError, "pathname contains \\0: #{@path.inspect}"
    end

    self.taint if @path.tainted?
  end


freeze (Pathname)

# File lib/pathname.rb, line 214
  def freeze() super; @path.freeze; self end


taint (Pathname)

# File lib/pathname.rb, line 215
  def taint() super; @path.taint; self end


untaint (Pathname)

# File lib/pathname.rb, line 216
  def untaint() super; @path.untaint; self end


== (Pathname)

# File lib/pathname.rb, line 223
  def ==(other)
    return false unless Pathname === other
    other.to_s == @path
  end


<=> (Pathname)

# File lib/pathname.rb, line 231
  def <=>(other)
    return nil unless Pathname === other
    @path.tr('/', "\0") <=> other.to_s.tr('/', "\0")
  end


to_s (Pathname)

# File lib/pathname.rb, line 241
  def to_s
    @path.dup
  end


sub (Pathname)

# File lib/pathname.rb, line 253
  def sub(pattern, *rest, &block)
    self.class.new(@path.sub(pattern, *rest, &block))
  end


cleanpath (Pathname)

# File lib/pathname.rb, line 306
  def cleanpath(consider_symlink=false)
    if consider_symlink
      cleanpath_conservative
    else
      cleanpath_aggressive
    end
  end


realpath (Pathname)

# File lib/pathname.rb, line 446
  def realpath
    path = @path
    prefix, names = split_names(path)
    if prefix == ''
      prefix, names2 = split_names(Dir.pwd)
      names = names2 + names
    end
    prefix, *names = realpath_rec(prefix, names, {})
    self.class.new(prepend_prefix(prefix, File.join(*names)))
  end


parent (Pathname)

# File lib/pathname.rb, line 460
  def parent
    self + '..'
  end


mountpoint? (Pathname)

# File lib/pathname.rb, line 465
  def mountpoint?
    begin
      stat1 = self.lstat
      stat2 = self.parent.lstat
      stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
        stat1.dev != stat2.dev
    rescue Errno::ENOENT
      false
    end
  end


root? (Pathname)

# File lib/pathname.rb, line 483
  def root?
    !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path)
  end


absolute? (Pathname)

# File lib/pathname.rb, line 489
  def absolute?
    !relative?
  end


relative? (Pathname)

# File lib/pathname.rb, line 494
  def relative?
    path = @path
    while r = chop_basename(path)
      path, basename = r
    end
    path == ''
  end


each_filename (Pathname)

# File lib/pathname.rb, line 508
  def each_filename # :yield: filename
    prefix, names = split_names(@path)
    names.each {|filename| yield filename }
    nil
  end


descend (Pathname)

# File lib/pathname.rb, line 534
  def descend
    vs = []
    ascend {|v| vs << v }
    vs.reverse_each {|v| yield v }
    nil
  end


ascend (Pathname)

# File lib/pathname.rb, line 561
  def ascend
    path = @path
    yield self
    while r = chop_basename(path)
      path, name = r
      break if path.empty?
      yield self.class.new(del_trailing_separator(path))
    end
  end


+ (Pathname)

# File lib/pathname.rb, line 581
  def +(other)
    other = Pathname.new(other) unless Pathname === other
    Pathname.new(plus(@path, other.to_s))
  end


join (Pathname)

# File lib/pathname.rb, line 634
  def join(*args)
    args.unshift self
    result = args.pop
    result = Pathname.new(result) unless Pathname === result
    return result if result.absolute?
    args.reverse_each {|arg|
      arg = Pathname.new(arg) unless Pathname === arg
      result = arg + result
      return result if result.absolute?
    }
    result
  end


children (Pathname)

# File lib/pathname.rb, line 668
  def children(with_directory=true)
    with_directory = false if @path == '.'
    result = []
    Dir.foreach(@path) {|e|
      next if e == '.' || e == '..'
      if with_directory
        result << self.class.new(File.join(@path, e))
      else
        result << self.class.new(e)
      end
    }
    result
  end


relative_path_from (Pathname)

# File lib/pathname.rb, line 693
  def relative_path_from(base_directory)
    dest_directory = self.cleanpath.to_s
    base_directory = base_directory.cleanpath.to_s
    dest_prefix = dest_directory
    dest_names = []
    while r = chop_basename(dest_prefix)
      dest_prefix, basename = r
      dest_names.unshift basename if basename != '.'
    end
    base_prefix = base_directory
    base_names = []
    while r = chop_basename(base_prefix)
      base_prefix, basename = r
      base_names.unshift basename if basename != '.'
    end
    if dest_prefix != base_prefix
      raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
    end
    while !dest_names.empty? &&
          !base_names.empty? &&
          dest_names.first == base_names.first
      dest_names.shift
      base_names.shift
    end
    if base_names.include? '..'
      raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
    end
    base_names.fill('..')
    relpath_names = base_names + dest_names
    if relpath_names.empty?
      Pathname.new('.')
    else
      Pathname.new(File.join(*relpath_names))
    end
  end


each_line (Pathname)

# File lib/pathname.rb, line 737
  def each_line(*args, &block) # :yield: line
    IO.foreach(@path, *args, &block)
  end


foreachline (Pathname)

# File lib/pathname.rb, line 742
  def foreachline(*args, &block)
    warn "Pathname#foreachline is obsoleted.  Use Pathname#each_line."
    each_line(*args, &block)
  end


read (Pathname)

# File lib/pathname.rb, line 749
  def read(*args) IO.read(@path, *args) end


readlines (Pathname)

# File lib/pathname.rb, line 752
  def readlines(*args) IO.readlines(@path, *args) end


sysopen (Pathname)

# File lib/pathname.rb, line 755
  def sysopen(*args) IO.sysopen(@path, *args) end


atime (Pathname)

# File lib/pathname.rb, line 762
  def atime() File.atime(@path) end


ctime (Pathname)

# File lib/pathname.rb, line 765
  def ctime() File.ctime(@path) end


mtime (Pathname)

# File lib/pathname.rb, line 768
  def mtime() File.mtime(@path) end


chmod (Pathname)

# File lib/pathname.rb, line 771
  def chmod(mode) File.chmod(mode, @path) end


lchmod (Pathname)

# File lib/pathname.rb, line 774
  def lchmod(mode) File.lchmod(mode, @path) end


chown (Pathname)

# File lib/pathname.rb, line 777
  def chown(owner, group) File.chown(owner, group, @path) end


lchown (Pathname)

# File lib/pathname.rb, line 780
  def lchown(owner, group) File.lchown(owner, group, @path) end


fnmatch (Pathname)

# File lib/pathname.rb, line 784
  def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end


fnmatch? (Pathname)

# File lib/pathname.rb, line 787
  def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end


ftype (Pathname)

# File lib/pathname.rb, line 791
  def ftype() File.ftype(@path) end


make_link (Pathname)

# File lib/pathname.rb, line 794
  def make_link(old) File.link(old, @path) end


open (Pathname)

# File lib/pathname.rb, line 797
  def open(*args, &block) # :yield: file
    File.open(@path, *args, &block)
  end


readlink (Pathname)

# File lib/pathname.rb, line 802
  def readlink() self.class.new(File.readlink(@path)) end


rename (Pathname)

# File lib/pathname.rb, line 805
  def rename(to) File.rename(@path, to) end


stat (Pathname)

# File lib/pathname.rb, line 808
  def stat() File.stat(@path) end


lstat (Pathname)

# File lib/pathname.rb, line 811
  def lstat() File.lstat(@path) end


make_symlink (Pathname)

# File lib/pathname.rb, line 814
  def make_symlink(old) File.symlink(old, @path) end


truncate (Pathname)

# File lib/pathname.rb, line 817
  def truncate(length) File.truncate(@path, length) end


utime (Pathname)

# File lib/pathname.rb, line 820
  def utime(atime, mtime) File.utime(atime, mtime, @path) end


basename (Pathname)

# File lib/pathname.rb, line 823
  def basename(*args) self.class.new(File.basename(@path, *args)) end


dirname (Pathname)

# File lib/pathname.rb, line 826
  def dirname() self.class.new(File.dirname(@path)) end


extname (Pathname)

# File lib/pathname.rb, line 829
  def extname() File.extname(@path) end


expand_path (Pathname)

# File lib/pathname.rb, line 832
  def expand_path(*args) self.class.new(File.expand_path(@path, *args)) end


split (Pathname)

# File lib/pathname.rb, line 836
  def split() File.split(@path).map {|f| self.class.new(f) } end


link (Pathname)

# File lib/pathname.rb, line 840
  def link(old)
    warn 'Pathname#link is obsoleted.  Use Pathname#make_link.'
    File.link(old, @path)
  end


symlink (Pathname)

# File lib/pathname.rb, line 847
  def symlink(old)
    warn 'Pathname#symlink is obsoleted.  Use Pathname#make_symlink.'
    File.symlink(old, @path)
  end


blockdev? (Pathname)

# File lib/pathname.rb, line 857
  def blockdev?() FileTest.blockdev?(@path) end


chardev? (Pathname)

# File lib/pathname.rb, line 860
  def chardev?() FileTest.chardev?(@path) end


executable? (Pathname)

# File lib/pathname.rb, line 863
  def executable?() FileTest.executable?(@path) end


executable_real? (Pathname)

# File lib/pathname.rb, line 866
  def executable_real?() FileTest.executable_real?(@path) end


exist? (Pathname)

# File lib/pathname.rb, line 869
  def exist?() FileTest.exist?(@path) end


grpowned? (Pathname)

# File lib/pathname.rb, line 872
  def grpowned?() FileTest.grpowned?(@path) end


directory? (Pathname)

# File lib/pathname.rb, line 875
  def directory?() FileTest.directory?(@path) end


file? (Pathname)

# File lib/pathname.rb, line 878
  def file?() FileTest.file?(@path) end


pipe? (Pathname)

# File lib/pathname.rb, line 881
  def pipe?() FileTest.pipe?(@path) end


socket? (Pathname)

# File lib/pathname.rb, line 884
  def socket?() FileTest.socket?(@path) end


owned? (Pathname)

# File lib/pathname.rb, line 887
  def owned?() FileTest.owned?(@path) end


readable? (Pathname)

# File lib/pathname.rb, line 890
  def readable?() FileTest.readable?(@path) end


world_readable? (Pathname)

# File lib/pathname.rb, line 893
  def world_readable?() FileTest.world_readable?(@path) end


readable_real? (Pathname)

# File lib/pathname.rb, line 896
  def readable_real?() FileTest.readable_real?(@path) end


setuid? (Pathname)

# File lib/pathname.rb, line 899
  def setuid?() FileTest.setuid?(@path) end


setgid? (Pathname)

# File lib/pathname.rb, line 902
  def setgid?() FileTest.setgid?(@path) end


size (Pathname)

# File lib/pathname.rb, line 905
  def size() FileTest.size(@path) end


size? (Pathname)

# File lib/pathname.rb, line 908
  def size?() FileTest.size?(@path) end


sticky? (Pathname)

# File lib/pathname.rb, line 911
  def sticky?() FileTest.sticky?(@path) end


symlink? (Pathname)

# File lib/pathname.rb, line 914
  def symlink?() FileTest.symlink?(@path) end


writable? (Pathname)

# File lib/pathname.rb, line 917
  def writable?() FileTest.writable?(@path) end


world_writable? (Pathname)

# File lib/pathname.rb, line 920
  def world_writable?() FileTest.world_writable?(@path) end


writable_real? (Pathname)

# File lib/pathname.rb, line 923
  def writable_real?() FileTest.writable_real?(@path) end


zero? (Pathname)

# File lib/pathname.rb, line 926
  def zero?() FileTest.zero?(@path) end


glob (Pathname)

# File lib/pathname.rb, line 932
  def Pathname.glob(*args) # :yield: p
    if block_given?
      Dir.glob(*args) {|f| yield self.new(f) }
    else
      Dir.glob(*args).map {|f| self.new(f) }
    end
  end


getwd (Pathname)

# File lib/pathname.rb, line 941
  def Pathname.getwd() self.new(Dir.getwd) end


chdir (Pathname)

# File lib/pathname.rb, line 945
  def chdir(&block)
    warn "Pathname#chdir is obsoleted.  Use Dir.chdir."
    Dir.chdir(@path, &block)
  end


chroot (Pathname)

# File lib/pathname.rb, line 951
  def chroot
    warn "Pathname#chroot is obsoleted.  Use Dir.chroot."
    Dir.chroot(@path)
  end


entries (Pathname)

# File lib/pathname.rb, line 958
  def entries() Dir.entries(@path).map {|f| self.class.new(f) } end


each_entry (Pathname)

# File lib/pathname.rb, line 964
  def each_entry(&block) # :yield: p
    Dir.foreach(@path) {|f| yield self.class.new(f) }
  end


dir_foreach (Pathname)

# File lib/pathname.rb, line 969
  def dir_foreach(*args, &block)
    warn "Pathname#dir_foreach is obsoleted.  Use Pathname#each_entry."
    each_entry(*args, &block)
  end


mkdir (Pathname)

# File lib/pathname.rb, line 975
  def mkdir(*args) Dir.mkdir(@path, *args) end


rmdir (Pathname)

# File lib/pathname.rb, line 978
  def rmdir() Dir.rmdir(@path) end


opendir (Pathname)

# File lib/pathname.rb, line 981
  def opendir(&block) # :yield: dir
    Dir.open(@path, &block)
  end


find (Pathname)

# File lib/pathname.rb, line 998
  def find(&block) # :yield: p
    require 'find'
    if @path == '.'
      Find.find(@path) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) }
    else
      Find.find(@path) {|f| yield self.class.new(f) }
    end
  end


mkpath (Pathname)

# File lib/pathname.rb, line 1012
  def mkpath
    require 'fileutils'
    FileUtils.mkpath(@path)
    nil
  end


rmtree (Pathname)

# File lib/pathname.rb, line 1019
  def rmtree
    # The name "rmtree" is borrowed from File::Path of Perl.
    # File::Path provides "mkpath" and "rmtree".
    require 'fileutils'
    FileUtils.rm_r(@path)
    nil
  end


unlink (Pathname)

# File lib/pathname.rb, line 1032
  def unlink()
    begin
      Dir.unlink @path
    rescue Errno::ENOTDIR
      File.unlink @path
    end
  end


foreach (Pathname)

# File lib/pathname.rb, line 1042
  def foreach(*args, &block)
    warn "Pathname#foreach is obsoleted.  Use each_line or each_entry."
    if FileTest.directory? @path
      # For polymorphism between Dir.foreach and IO.foreach,
      # Pathname#foreach doesn't yield Pathname object.
      Dir.foreach(@path, *args, &block)
    else
      IO.foreach(@path, *args, &block)
    end
  end


pingecho (Ping)

# File lib/ping.rb, line 44
  def pingecho(host, timeout=5, service="echo")
    begin
      timeout(timeout) do
        s = TCPSocket.new(host, service)
        s.close
      end
    rescue Errno::ECONNREFUSED
      return true
    rescue Timeout::Error, StandardError
      return false
    end
    return true
  end


pretty_print (PP::ObjectMixin)

# File lib/pp.rb, line 257
    def pretty_print(q)
      if /\(Kernel\)#/ !~ method(:inspect).inspect
        q.text self.inspect
      elsif /\(Kernel\)#/ !~ method(:to_s).inspect && instance_variables.empty?
        q.text self.to_s
      else
        q.pp_object(self)
      end
    end


pretty_print_cycle (PP::ObjectMixin)

# File lib/pp.rb, line 269
    def pretty_print_cycle(q)
      q.object_address_group(self) {
        q.breakable
        q.text '...'
      }
    end


pretty_print_instance_variables (PP::ObjectMixin)

# File lib/pp.rb, line 280
    def pretty_print_instance_variables
      instance_variables.sort
    end


pretty_print_inspect (PP::ObjectMixin)

# File lib/pp.rb, line 291
    def pretty_print_inspect
      if /\(PP::ObjectMixin\)#/ =~ method(:pretty_print).inspect
        raise "pretty_print is not overridden for #{self.class}"
      end
      PP.singleline_pp(self, '')
    end


guard_inspect_key (PP::PPMethods)

# File lib/pp.rb, line 110
    def guard_inspect_key
      if Thread.current[InspectKey] == nil
        Thread.current[InspectKey] = []
      end

      save = Thread.current[InspectKey]

      begin
        Thread.current[InspectKey] = []
        yield
      ensure
        Thread.current[InspectKey] = save
      end
    end


pp (PP::PPMethods)

# File lib/pp.rb, line 130
    def pp(obj)
      id = obj.__id__

      if Thread.current[InspectKey].include? id
        group {obj.pretty_print_cycle self}
        return
      end

      begin
        Thread.current[InspectKey] << id
        group {obj.pretty_print self}
      ensure
        Thread.current[InspectKey].pop unless PP.sharing_detection
      end
    end


object_group (PP::PPMethods)

# File lib/pp.rb, line 149
    def object_group(obj, &block) # :yield:
      group(1, '#<' + obj.class.name, '>', &block)
    end


object_address_group (PP::PPMethods)

# File lib/pp.rb, line 153
    def object_address_group(obj, &block)
      id = "%x" % (obj.__id__ * 2)
      id.sub!(/\Af(?=[[:xdigit:]]{2}+\z)/, '') if id.sub!(/\A\.\./, '')
      group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
    end


comma_breakable (PP::PPMethods)

# File lib/pp.rb, line 163
    def comma_breakable
      text ','
      breakable
    end


seplist (PP::PPMethods)

# File lib/pp.rb, line 192
    def seplist(list, sep=nil, iter_method=:each) # :yield: element
      sep ||= lambda { comma_breakable }
      first = true
      list.__send__(iter_method) {|*v|
        if first
          first = false
        else
          sep.call
        end
        yield(*v)
      }
    end


pp_object (PP::PPMethods)

# File lib/pp.rb, line 205
    def pp_object(obj)
      object_address_group(obj) {
        seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
          breakable
          v = v.to_s if Symbol === v
          text v
          text '='
          group(1) {
            breakable ''
            pp(obj.instance_eval(v))
          }
        }
      }
    end


pp_hash (PP::PPMethods)

# File lib/pp.rb, line 220
    def pp_hash(obj)
      group(1, '{', '}') {
        seplist(obj, nil, :each_pair) {|k, v|
          group {
            pp k
            text '=>'
            group(1) {
              breakable ''
              pp v
            }
          }
        }
      }
    end


pp (PP)

# File lib/pp.rb, line 75
  def PP.pp(obj, out=$>, width=79)
    q = PP.new(out, width)
    q.guard_inspect_key {q.pp obj}
    q.flush
    #$pp = q
    out << "\n"
  end


singleline_pp (PP)

# File lib/pp.rb, line 87
  def PP.singleline_pp(obj, out=$>)
    q = SingleLine.new(out)
    q.guard_inspect_key {q.pp obj}
    q.flush
    out
  end


included (Precision)

/*
 * call_seq:
 *   included
 *
 * When the +Precision+ module is mixed-in to a class, this +included+
 * method is used to add our default +induced_from+ implementation
 * to the host class.
 */

static VALUE
prec_included(module, include)
    VALUE module, include;
{
    switch (TYPE(include)) {
      case T_CLASS:
      case T_MODULE:
       break;
      default:
       Check_Type(include, T_CLASS);
       break;
    }
    rb_define_singleton_method(include, "induced_from", prec_induced_from, 1);
    return module;
}


prec (Precision)

/*
 *  call-seq:
 *   num.prec(klass)   => a_klass
 *
 *  Converts _self_ into an instance of _klass_. By default,
 *  +prec+ invokes
 *
 *     klass.induced_from(num)
 *
 *  and returns its value. So, if <code>klass.induced_from</code>
 *  doesn't return an instance of _klass_, it will be necessary
 *  to reimplement +prec+.
 */

static VALUE
prec_prec(x, klass)
    VALUE x, klass;
{
    return rb_funcall(klass, prc_if, 1, x);
}


prec_i (Precision)

/*
 *  call-seq:
 *    num.prec_i  =>  Integer
 *
 *  Returns an +Integer+ converted from _num_. It is equivalent
 *  to <code>prec(Integer)</code>.
 */

static VALUE
prec_prec_i(x)
    VALUE x;
{
    VALUE klass = rb_cInteger;

    return rb_funcall(x, prc_pr, 1, klass);
}


prec_f (Precision)

/*
 *  call-seq:
 *    num.prec_f  =>  Float
 *
 *  Returns a +Float+ converted from _num_. It is equivalent
 *  to <code>prec(Float)</code>.
 */

static VALUE
prec_prec_f(x)
    VALUE x;
{
    VALUE klass = rb_cFloat;

    return rb_funcall(x, prc_pr, 1, klass);
}


new (PrettyPrint::Breakable)

# File lib/prettyprint.rb, line 262
    def initialize(sep, width, q)
      @obj = sep
      @width = width
      @pp = q
      @indent = q.indent
      @group = q.current_group
      @group.breakables.push self
    end


output (PrettyPrint::Breakable)

# File lib/prettyprint.rb, line 272
    def output(out, output_width)
      @group.breakables.shift
      if @group.break?
        out << @pp.newline
        out << @pp.genspace.call(@indent)
        @indent
      else
        @pp.group_queue.delete @group if @group.breakables.empty?
        out << @obj
        output_width + @width
      end
    end


new (PrettyPrint::Group)

# File lib/prettyprint.rb, line 287
    def initialize(depth)
      @depth = depth
      @breakables = []
      @break = false
    end


break (PrettyPrint::Group)

# File lib/prettyprint.rb, line 294
    def break
      @break = true
    end


break? (PrettyPrint::Group)

# File lib/prettyprint.rb, line 298
    def break?
      @break
    end


first? (PrettyPrint::Group)

# File lib/prettyprint.rb, line 302
    def first?
      if defined? @first
        false
      else
        @first = false
        true
      end
    end


new (PrettyPrint::GroupQueue)

# File lib/prettyprint.rb, line 313
    def initialize(*groups)
      @queue = []
      groups.each {|g| enq g}
    end


enq (PrettyPrint::GroupQueue)

# File lib/prettyprint.rb, line 318
    def enq(group)
      depth = group.depth
      @queue << [] until depth < @queue.length
      @queue[depth] << group
    end


deq (PrettyPrint::GroupQueue)

# File lib/prettyprint.rb, line 324
    def deq
      @queue.each {|gs|
        (gs.length-1).downto(0) {|i|
          unless gs[i].breakables.empty?
            group = gs.slice!(i, 1).first
            group.break
            return group
          end
        }
        gs.each {|group| group.break}
        gs.clear
      }
      return nil
    end


delete (PrettyPrint::GroupQueue)

# File lib/prettyprint.rb, line 339
    def delete(group)
      @queue[group.depth].delete(group)
    end


new (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 345
    def initialize(output, maxwidth=nil, newline=nil)
      @output = output
      @first = [true]
    end


text (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 350
    def text(obj, width=nil)
      @output << obj
    end


breakable (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 354
    def breakable(sep=' ', width=nil)
      @output << sep
    end


nest (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 358
    def nest(indent)
      yield
    end


group (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 362
    def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil)
      @first.push true
      @output << open_obj
      yield
      @output << close_obj
      @first.pop
    end


flush (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 370
    def flush
    end


first? (PrettyPrint::SingleLine)

# File lib/prettyprint.rb, line 373
    def first?
      result = @first[-1]
      @first[-1] = false
      result
    end


new (PrettyPrint::Text)

# File lib/prettyprint.rb, line 244
    def initialize
      @objs = []
      @width = 0
    end


output (PrettyPrint::Text)

# File lib/prettyprint.rb, line 250
    def output(out, output_width)
      @objs.each {|obj| out << obj}
      output_width + @width
    end


add (PrettyPrint::Text)

# File lib/prettyprint.rb, line 255
    def add(obj, width)
      @objs << obj
      @width += width
    end


format (PrettyPrint)

# File lib/prettyprint.rb, line 43
  def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n})
    q = PrettyPrint.new(output, maxwidth, newline, &genspace)
    yield q
    q.flush
    output
  end


singleline_format (PrettyPrint)

# File lib/prettyprint.rb, line 57
  def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil)
    q = SingleLine.new(output)
    yield q
    output
  end


new (PrettyPrint)

# File lib/prettyprint.rb, line 80
  def initialize(output='', maxwidth=79, newline="\n", &genspace)
    @output = output
    @maxwidth = maxwidth
    @newline = newline
    @genspace = genspace || lambda {|n| ' ' * n}

    @output_width = 0
    @buffer_width = 0
    @buffer = []

    root_group = Group.new(0)
    @group_stack = [root_group]
    @group_queue = GroupQueue.new(root_group)
    @indent = 0
  end


current_group (PrettyPrint)

# File lib/prettyprint.rb, line 98
  def current_group
    @group_stack.last
  end


first? (PrettyPrint)

# File lib/prettyprint.rb, line 119
  def first?
    warn "PrettyPrint#first? is obsoleted at 1.8.2."
    current_group.first?
  end


break_outmost_groups (PrettyPrint)

# File lib/prettyprint.rb, line 124
  def break_outmost_groups
    while @maxwidth < @output_width + @buffer_width
      return unless group = @group_queue.deq
      until group.breakables.empty?
        data = @buffer.shift
        @output_width = data.output(@output, @output_width)
        @buffer_width -= data.width
      end
      while !@buffer.empty? && Text === @buffer.first
        text = @buffer.shift
        @output_width = text.output(@output, @output_width)
        @buffer_width -= text.width
      end
    end
  end


text (PrettyPrint)

# File lib/prettyprint.rb, line 144
  def text(obj, width=obj.length)
    if @buffer.empty?
      @output << obj
      @output_width += width
    else
      text = @buffer.last
      unless Text === text
        text = Text.new
        @buffer << text
      end
      text.add(obj, width)
      @buffer_width += width
      break_outmost_groups
    end
  end


fill_breakable (PrettyPrint)

# File lib/prettyprint.rb, line 160
  def fill_breakable(sep=' ', width=sep.length)
    group { breakable sep, width }
  end


breakable (PrettyPrint)

# File lib/prettyprint.rb, line 172
  def breakable(sep=' ', width=sep.length)
    group = @group_stack.last
    if group.break?
      flush
      @output << @newline
      @output << @genspace.call(@indent)
      @output_width = @indent
      @buffer_width = 0
    else
      @buffer << Breakable.new(sep, width, self)
      @buffer_width += width
      break_outmost_groups
    end
  end


group (PrettyPrint)

# File lib/prettyprint.rb, line 197
  def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length)
    text open_obj, open_width
    group_sub {
      nest(indent) {
        yield
      }
    }
    text close_obj, close_width
  end


group_sub (PrettyPrint)

# File lib/prettyprint.rb, line 207
  def group_sub
    group = Group.new(@group_stack.last.depth + 1)
    @group_stack.push group
    @group_queue.enq group
    begin
      yield
    ensure
      @group_stack.pop
      if group.breakables.empty?
        @group_queue.delete group
      end
    end
  end


nest (PrettyPrint)

# File lib/prettyprint.rb, line 224
  def nest(indent)
    @indent += indent
    begin
      yield
    ensure
      @indent -= indent
    end
  end


flush (PrettyPrint)

# File lib/prettyprint.rb, line 235
  def flush
    @buffer.each {|data|
      @output_width = data.output(@output, @output_width)
    }
    @buffer.clear
    @buffer_width = 0
  end


new (Prime)

# File lib/mathn.rb, line 72
  def initialize
    @seed = 1
    @primes = []
    @counts = []
  end


succ (Prime)

# File lib/mathn.rb, line 78
  def succ
    i = -1
    size = @primes.size
    while i < size
      if i == -1
        @seed += 1
        i += 1
      else
        while @seed > @counts[i]
          @counts[i] += @primes[i]
        end
        if @seed != @counts[i]
          i += 1
        else
          i = -1
        end
      end
    end
    @primes.push @seed
    @counts.push @seed + @seed
    return @seed
  end


each (Prime)

# File lib/mathn.rb, line 102
  def each
    loop do
      yield succ
    end
  end


new (Proc)

/*
 *  call-seq:
 *     Proc.new {|...| block } => a_proc
 *     Proc.new                => a_proc
 *
 *  Creates a new <code>Proc</code> object, bound to the current
 *  context. <code>Proc::new</code> may be called without a block only
 *  within a method with an attached block, in which case that block is
 *  converted to the <code>Proc</code> object.
 *
 *     def proc_from
 *       Proc.new
 *     end
 *     proc = proc_from { "hello" }
 *     proc.call   #=> "hello"
 */

static VALUE
proc_s_new(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE block = proc_alloc(klass, Qfalse);

    rb_obj_call_init(block, argc, argv);
    return block;
}


clone (Proc)

/*
 * MISSING: documentation
 */

static VALUE
proc_clone(self)
    VALUE self;
{
    struct BLOCK *orig, *data;
    VALUE bind;

    Data_Get_Struct(self, struct BLOCK, orig);
    bind = Data_Make_Struct(rb_obj_class(self),struct BLOCK,blk_mark,blk_free,data);
    CLONESETUP(bind, self);
    blk_dup(data, orig);

    return bind;
}


dup (Proc)

/*
 * MISSING: documentation
 */

static VALUE
proc_dup(self)
    VALUE self;
{
    struct BLOCK *orig, *data;
    VALUE bind;

    Data_Get_Struct(self, struct BLOCK, orig);
    bind = Data_Make_Struct(rb_obj_class(self),struct BLOCK,blk_mark,blk_free,data);
    blk_dup(data, orig);

    return bind;
}


call (Proc)

/*
 *  call-seq:
 *     prc.call(params,...)   => obj
 *     prc[params,...]        => obj
 *
 *  Invokes the block, setting the block's parameters to the values in
 *  <i>params</i> using something close to method calling semantics.
 *  Generates a warning if multiple values are passed to a proc that
 *  expects just one (previously this silently converted the parameters
 *  to an array).
 *
 *  For procs created using <code>Kernel.proc</code>, generates an
 *  error if the wrong number of parameters
 *  are passed to a proc with multiple parameters. For procs created using
 *  <code>Proc.new</code>, extra parameters are silently discarded.
 *
 *  Returns the value of the last expression evaluated in the block. See
 *  also <code>Proc#yield</code>.
 *
 *     a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
 *     a_proc.call(9, 1, 2, 3)   #=> [9, 18, 27]
 *     a_proc[9, 1, 2, 3]        #=> [9, 18, 27]
 *     a_proc = Proc.new {|a,b| a}
 *     a_proc.call(1,2,3)
 *
 *  <em>produces:</em>
 *
 *     prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
 *      from prog.rb:4:in `call'
 *      from prog.rb:5
 */

static VALUE
proc_call(proc, args)
    VALUE proc, args;           /* OK */
{
    return proc_invoke(proc, args, Qundef, 0);
}


arity (Proc)

/*
 *  call-seq:
 *     prc.arity -> fixnum
 *
 *  Returns the number of arguments that would not be ignored. If the block
 *  is declared to take no arguments, returns 0. If the block is known
 *  to take exactly n arguments, returns n. If the block has optional
 *  arguments, return -n-1, where n is the number of mandatory
 *  arguments. A <code>proc</code> with no argument declarations
 *  is the same a block declaring <code>||</code> as its arguments.
 *
 *     Proc.new {}.arity          #=>  0
 *     Proc.new {||}.arity        #=>  0
 *     Proc.new {|a|}.arity       #=>  1
 *     Proc.new {|a,b|}.arity     #=>  2
 *     Proc.new {|a,b,c|}.arity   #=>  3
 *     Proc.new {|*a|}.arity      #=> -1
 *     Proc.new {|a,*b|}.arity    #=> -2
 */

static VALUE
proc_arity(proc)
    VALUE proc;
{
    struct BLOCK *data;
    NODE *list;
    int n;

    Data_Get_Struct(proc, struct BLOCK, data);
    if (data->var == 0) {
        if (data->body && nd_type(data->body) == NODE_IFUNC &&
            data->body->nd_cfnc == bmcall) {
            return method_arity(data->body->nd_tval);
        }
        return INT2FIX(-1);
    }
    if (data->var == (NODE*)1) return INT2FIX(0);
    if (data->var == (NODE*)2) return INT2FIX(0);
    switch (nd_type(data->var)) {
      default:
        return INT2FIX(1);
      case NODE_MASGN:
        list = data->var->nd_head;
        n = 0;
        while (list) {
            n++;
            list = list->nd_next;
        }
        if (data->var->nd_args) return INT2FIX(-n-1);
        return INT2FIX(n);
    }
}


[] (Proc)

/*
 *  call-seq:
 *     prc.call(params,...)   => obj
 *     prc[params,...]        => obj
 *
 *  Invokes the block, setting the block's parameters to the values in
 *  <i>params</i> using something close to method calling semantics.
 *  Generates a warning if multiple values are passed to a proc that
 *  expects just one (previously this silently converted the parameters
 *  to an array).
 *
 *  For procs created using <code>Kernel.proc</code>, generates an
 *  error if the wrong number of parameters
 *  are passed to a proc with multiple parameters. For procs created using
 *  <code>Proc.new</code>, extra parameters are silently discarded.
 *
 *  Returns the value of the last expression evaluated in the block. See
 *  also <code>Proc#yield</code>.
 *
 *     a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
 *     a_proc.call(9, 1, 2, 3)   #=> [9, 18, 27]
 *     a_proc[9, 1, 2, 3]        #=> [9, 18, 27]
 *     a_proc = Proc.new {|a,b| a}
 *     a_proc.call(1,2,3)
 *
 *  <em>produces:</em>
 *
 *     prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
 *      from prog.rb:4:in `call'
 *      from prog.rb:5
 */

static VALUE
proc_call(proc, args)
    VALUE proc, args;           /* OK */
{
    return proc_invoke(proc, args, Qundef, 0);
}


== (Proc)

/*
 * call-seq:
 *   prc == other_proc   =>  true or false
 *
 * Return <code>true</code> if <i>prc</i> is the same object as
 * <i>other_proc</i>, or if they are both procs with the same body.
 */

static VALUE
proc_eq(self, other)
    VALUE self, other;
{
    struct BLOCK *data, *data2;

    if (self == other) return Qtrue;
    if (TYPE(other) != T_DATA) return Qfalse;
    if (RDATA(other)->dmark != (RUBY_DATA_FUNC)blk_mark) return Qfalse;
    if (CLASS_OF(self) != CLASS_OF(other)) return Qfalse;
    Data_Get_Struct(self, struct BLOCK, data);
    Data_Get_Struct(other, struct BLOCK, data2);
    if (data->body != data2->body) return Qfalse;
    if (data->var != data2->var) return Qfalse;
    if (data->scope != data2->scope) return Qfalse;
    if (data->dyna_vars != data2->dyna_vars) return Qfalse;
    if (data->flags != data2->flags) return Qfalse;

    return Qtrue;
}


to_s (Proc)

/*
 * call-seq:
 *   prc.to_s   => string
 *
 * Shows the unique identifier for this proc, along with
 * an indication of where the proc was defined.
 */

static VALUE
proc_to_s(self)
    VALUE self;
{
    struct BLOCK *data;
    NODE *node;
    char *cname = rb_obj_classname(self);
    const int w = (sizeof(VALUE) * CHAR_BIT) / 4;
    long len = strlen(cname)+6+w; /* 6:tags 16:addr */
    VALUE str;

    Data_Get_Struct(self, struct BLOCK, data);
    if ((node = data->frame.node) || (node = data->body)) {
        len += strlen(node->nd_file) + 2 + (SIZEOF_LONG*CHAR_BIT-NODE_LSHIFT)/3;
        str = rb_str_new(0, len);
        snprintf(RSTRING(str)->ptr, len+1,
                 "#<%s:0x%.*lx@%s:%d>", cname, w, (VALUE)data->body,
                 node->nd_file, nd_line(node));
    }
    else {
        str = rb_str_new(0, len);
        snprintf(RSTRING(str)->ptr, len+1,
                 "#<%s:0x%.*lx>", cname, w, (VALUE)data->body);
    }
    RSTRING(str)->len = strlen(RSTRING(str)->ptr);
    if (OBJ_TAINTED(self)) OBJ_TAINT(str);

    return str;
}


to_proc (Proc)

/*
 *  call-seq:
 *     prc.to_proc -> prc
 *
 *  Part of the protocol for converting objects to <code>Proc</code>
 *  objects. Instances of class <code>Proc</code> simply return
 *  themselves.
 */

static VALUE
proc_to_self(self)
    VALUE self;
{
    return self;
}


binding (Proc)

/*
 *  call-seq:
 *     prc.binding    => binding
 *
 *  Returns the binding associated with <i>prc</i>. Note that
 *  <code>Kernel#eval</code> accepts either a <code>Proc</code> or a
 *  <code>Binding</code> object as its second parameter.
 *
 *     def fred(param)
 *       proc {}
 *     end
 *
 *     b = fred(99)
 *     eval("param", b.binding)   #=> 99
 *     eval("param", b)           #=> 99
 */

static VALUE
proc_binding(proc)
    VALUE proc;
{
    struct BLOCK *orig, *data;
    VALUE bind;

    Data_Get_Struct(proc, struct BLOCK, orig);
    bind = Data_Make_Struct(rb_cBinding,struct BLOCK,blk_mark,blk_free,data);
    MEMCPY(data, orig, struct BLOCK, 1);
    frame_dup(&data->frame);

    if (data->iter) {
        blk_copy_prev(data);
    }
    else {
        data->prev = 0;
    }

    return bind;
}


rid (Process::GID)

/*
 *  call-seq:
 *     Process.gid           => fixnum
 *     Process::GID.rid      => fixnum
 *     Process::Sys.getgid   => fixnum
 *
 *  Returns the (real) group ID for this process.
 *
 *     Process.gid   #=> 500
 */

static VALUE
proc_getgid(obj)
    VALUE obj;
{
    int gid = getgid();
    return INT2FIX(gid);
}


eid (Process::GID)

/*
 *  call-seq:
 *     Process.egid          => fixnum
 *     Process::GID.eid      => fixnum
 *     Process::Sys.geteid   => fixnum
 *
 *  Returns the effective group ID for this process. Not available on
 *  all platforms.
 *
 *     Process.egid   #=> 500
 */

static VALUE
proc_getegid(obj)
    VALUE obj;
{
    int egid = getegid();

    return INT2FIX(egid);
}


change_privilege (Process::GID)

/*
 *  call-seq:
 *     Process::GID.change_privilege(integer)   => fixnum
 *
 *  Change the current process's real and effective group ID to that
 *  specified by _integer_. Returns the new group ID. Not
 *  available on all platforms.
 *
 *     [Process.gid, Process.egid]          #=> [0, 0]
 *     Process::GID.change_privilege(33)    #=> 33
 *     [Process.gid, Process.egid]          #=> [33, 33]
 */

static VALUE
p_gid_change_privilege(obj, id)
    VALUE obj, id;
{
    int gid;

    check_gid_switch();

    gid = NUM2INT(id);

    if (geteuid() == 0) { /* root-user */
#if defined(HAVE_SETRESGID)
        if (setresgid(gid, gid, gid) < 0) rb_sys_fail(0);
        SAVED_GROUP_ID = gid;
#elif defined HAVE_SETGID
        if (setgid(gid) < 0) rb_sys_fail(0);
        SAVED_GROUP_ID = gid;
#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
        if (getgid() == gid) {
            if (SAVED_GROUP_ID == gid) {
                if (setregid(-1, gid) < 0) rb_sys_fail(0);
            } else {
                if (gid == 0) { /* (r,e,s) == (root, y, x) */
                    if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0);
                    if (setregid(SAVED_GROUP_ID, 0) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = 0; /* (r,e,s) == (x, root, root) */
                    if (setregid(gid, gid) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = gid;
                } else { /* (r,e,s) == (z, y, x) */
                    if (setregid(0, 0) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = 0;
                    if (setregid(gid, gid) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = gid;
                }
            }
        } else {
            if (setregid(gid, gid) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
        }
#elif defined(HAVE_SETRGID) && defined (HAVE_SETEGID)
        if (getgid() == gid) {
            if (SAVED_GROUP_ID == gid) {
                if (setegid(gid) < 0) rb_sys_fail(0);
            } else {
                if (gid == 0) {
                    if (setegid(gid) < 0) rb_sys_fail(0);
                    if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = 0;
                    if (setrgid(0) < 0) rb_sys_fail(0);
                } else {
                    if (setrgid(0) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = 0;
                    if (setegid(gid) < 0) rb_sys_fail(0);
                    if (setrgid(gid) < 0) rb_sys_fail(0);
                    SAVED_GROUP_ID = gid;
                }
            }
        } else {
            if (setegid(gid) < 0) rb_sys_fail(0);
            if (setrgid(gid) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
        }
#else
        rb_notimplement();
#endif
    } else { /* unprivileged user */
#if defined(HAVE_SETRESGID)
        if (setresgid((getgid() == gid)? -1: gid,
                      (getegid() == gid)? -1: gid,
                      (SAVED_GROUP_ID == gid)? -1: gid) < 0) rb_sys_fail(0);
        SAVED_GROUP_ID = gid;
#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
        if (SAVED_GROUP_ID == gid) {
            if (setregid((getgid() == gid)? -1: gid,
                         (getegid() == gid)? -1: gid) < 0) rb_sys_fail(0);
        } else if (getgid() != gid) {
            if (setregid(gid, (getegid() == gid)? -1: gid) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
        } else if (/* getgid() == gid && */ getegid() != gid) {
            if (setregid(getegid(), gid) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
            if (setregid(gid, -1) < 0) rb_sys_fail(0);
        } else { /* getgid() == gid && getegid() == gid */
            if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0);
            if (setregid(SAVED_GROUP_ID, gid) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
            if (setregid(gid, -1) < 0) rb_sys_fail(0);
        }
#elif defined(HAVE_SETRGID) && defined(HAVE_SETEGID)
        if (SAVED_GROUP_ID == gid) {
            if (getegid() != gid && setegid(gid) < 0) rb_sys_fail(0);
            if (getgid() != gid && setrgid(gid) < 0) rb_sys_fail(0);
        } else if (/* SAVED_GROUP_ID != gid && */ getegid() == gid) {
            if (getgid() != gid) {
                if (setrgid(gid) < 0) rb_sys_fail(0);
                SAVED_GROUP_ID = gid;
            } else {
                if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
                SAVED_GROUP_ID = gid;
                if (setrgid(gid) < 0) rb_sys_fail(0);
            }
        } else if (/* getegid() != gid && */ getgid() == gid) {
            if (setegid(gid) < 0) rb_sys_fail(0);
            if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
            if (setrgid(gid) < 0) rb_sys_fail(0);
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#elif defined HAVE_44BSD_SETGID
        if (getgid() == gid) {
            /* (r,e,s)==(gid,?,?) ==> (gid,gid,gid) */
            if (setgid(gid) < 0) rb_sys_fail(0);
            SAVED_GROUP_ID = gid;
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#elif defined HAVE_SETEGID
        if (getgid() == gid && SAVED_GROUP_ID == gid) {
            if (setegid(gid) < 0) rb_sys_fail(0);
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#elif defined HAVE_SETGID
        if (getgid() == gid && SAVED_GROUP_ID == gid) {
            if (setgid(gid) < 0) rb_sys_fail(0);
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#else
        rb_notimplement();
#endif
    }
    return INT2FIX(gid);
}


grant_privilege (Process::GID)

/*
 *  call-seq:
 *     Process::GID.grant_privilege(integer)    => fixnum
 *     Process::GID.eid = integer               => fixnum
 *
 *  Set the effective group ID, and if possible, the saved group ID of
 *  the process to the given _integer_. Returns the new
 *  effective group ID. Not available on all platforms.
 *
 *     [Process.gid, Process.egid]          #=> [0, 0]
 *     Process::GID.grant_privilege(31)     #=> 33
 *     [Process.gid, Process.egid]          #=> [0, 33]
 */

static VALUE
p_gid_grant_privilege(obj, id)
    VALUE obj, id;
{
    return rb_setegid_core(NUM2INT(id));
}


re_exchange (Process::GID)

/*
 *  call-seq:
 *     Process::GID.re_exchange   => fixnum
 *
 *  Exchange real and effective group IDs and return the new effective
 *  group ID. Not available on all platforms.
 *
 *     [Process.gid, Process.egid]   #=> [0, 33]
 *     Process::GID.re_exchange      #=> 0
 *     [Process.gid, Process.egid]   #=> [33, 0]
 */

static VALUE
p_gid_exchange(obj)
    VALUE obj;
{
    int gid, egid;

    check_gid_switch();

    gid = getgid();
    egid = getegid();

#if defined(HAVE_SETRESGID) &&  !defined(__CHECKER__)
    if (setresgid(egid, gid, gid) < 0) rb_sys_fail(0);
    SAVED_GROUP_ID = gid;
#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
    if (setregid(egid,gid) < 0) rb_sys_fail(0);
    SAVED_GROUP_ID = gid;
#else
    rb_notimplement();
#endif
    return INT2FIX(gid);
}


re_exchangeable? (Process::GID)

/*
 *  call-seq:
 *     Process::GID.re_exchangeable?   => true or false
 *
 *  Returns +true+ if the real and effective group IDs of a
 *  process may be exchanged on the current platform.
 *
 */

static VALUE
p_gid_exchangeable()
{
#if defined(HAVE_SETRESGID) &&  !defined(__CHECKER__)
    return Qtrue;
#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
    return Qtrue;
#else
    return Qfalse;
#endif
}


sid_available? (Process::GID)

/*
 *  call-seq:
 *     Process::GID.sid_available?   => true or false
 *
 *  Returns +true+ if the current platform has saved group
 *  ID functionality.
 *
 */

static VALUE
p_gid_have_saved_id()
{
#if defined(HAVE_SETRESGID) || defined(HAVE_SETEGID) || defined(_POSIX_SAVED_IDS)
    return Qtrue;
#else
    return Qfalse;
#endif
}


switch (Process::GID)

/*
 *  call-seq:
 *     Process::GID.switch              => fixnum
 *     Process::GID.switch {|| block}   => object
 *
 *  Switch the effective and real group IDs of the current process. If
 *  a <em>block</em> is given, the group IDs will be switched back
 *  after the block is executed. Returns the new effective group ID if
 *  called without a block, and the return value of the block if one
 *  is given.
 *
 */

static VALUE
p_gid_switch(obj)
    VALUE obj;
{
    int gid, egid;

    check_gid_switch();

    gid = getgid();
    egid = getegid();

    if (gid != egid) {
        proc_setegid(obj, INT2FIX(gid));
        if (rb_block_given_p()) {
            under_gid_switch = 1;
            return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, SAVED_GROUP_ID);
        } else {
            return INT2FIX(egid);
        }
    } else if (egid != SAVED_GROUP_ID) {
        proc_setegid(obj, INT2FIX(SAVED_GROUP_ID));
        if (rb_block_given_p()) {
            under_gid_switch = 1;
            return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, egid);
        } else {
            return INT2FIX(gid);
        }
    } else {
        errno = EPERM;
        rb_sys_fail(0);
    }
#else
static VALUE
p_gid_sw_ensure(obj)
    VALUE obj;
{
    under_gid_switch = 0;
    return p_gid_exchange(obj);
}


== (Process::Status)

/*
 *  call-seq:
 *     stat == other   => true or false
 *
 *  Returns +true+ if the integer value of _stat_
 *  equals <em>other</em>.
 */

static VALUE
pst_equal(st1, st2)
    VALUE st1, st2;
{
    if (st1 == st2) return Qtrue;
    return rb_equal(pst_to_i(st1), st2);
}


& (Process::Status)

/*
 *  call-seq:
 *     stat & num   => fixnum
 *
 *  Logical AND of the bits in _stat_ with <em>num</em>.
 *
 *     fork { exit 0x37 }
 *     Process.wait
 *     sprintf('%04x', $?.to_i)       #=> "3700"
 *     sprintf('%04x', $? & 0x1e00)   #=> "1600"
 */

static VALUE
pst_bitand(st1, st2)
    VALUE st1, st2;
{
    int status = NUM2INT(st1) & NUM2INT(st2);

    return INT2NUM(status);
}


>> (Process::Status)

/*
 *  call-seq:
 *     stat >> num   => fixnum
 *
 *  Shift the bits in _stat_ right <em>num</em> places.
 *
 *     fork { exit 99 }   #=> 26563
 *     Process.wait       #=> 26563
 *     $?.to_i            #=> 25344
 *     $? >> 8            #=> 99
 */

static VALUE
pst_rshift(st1, st2)
    VALUE st1, st2;
{
    int status = NUM2INT(st1) >> NUM2INT(st2);

    return INT2NUM(status);
}


to_i (Process::Status)

/*
 *  call-seq:
 *     stat.to_i     => fixnum
 *     stat.to_int   => fixnum
 *
 *  Returns the bits in _stat_ as a <code>Fixnum</code>. Poking
 *  around in these bits is platform dependent.
 *
 *     fork { exit 0xab }         #=> 26566
 *     Process.wait               #=> 26566
 *     sprintf('%04x', $?.to_i)   #=> "ab00"
 */

static VALUE
pst_to_i(st)
    VALUE st;
{
    return rb_iv_get(st, "status");
}


to_int (Process::Status)

/*
 *  call-seq:
 *     stat.to_i     => fixnum
 *     stat.to_int   => fixnum
 *
 *  Returns the bits in _stat_ as a <code>Fixnum</code>. Poking
 *  around in these bits is platform dependent.
 *
 *     fork { exit 0xab }         #=> 26566
 *     Process.wait               #=> 26566
 *     sprintf('%04x', $?.to_i)   #=> "ab00"
 */

static VALUE
pst_to_i(st)
    VALUE st;
{
    return rb_iv_get(st, "status");
}


to_s (Process::Status)

/*
 *  call-seq:
 *     stat.to_s   => string
 *
 *  Equivalent to _stat_<code>.to_i.to_s</code>.
 */

static VALUE
pst_to_s(st)
    VALUE st;
{
    return rb_fix2str(pst_to_i(st), 10);
}


inspect (Process::Status)

/*
 *  call-seq:
 *     stat.inspect   => string
 *
 *  Override the inspection method.
 */

static VALUE
pst_inspect(st)
    VALUE st;
{
    VALUE pid;
    int status;
    VALUE str;
    char buf[256];

    pid = pst_pid(st);
    status = NUM2INT(st);

    snprintf(buf, sizeof(buf), "#<%s: pid=%ld", rb_class2name(CLASS_OF(st)), NUM2LONG(pid));
    str = rb_str_new2(buf);
    if (WIFSTOPPED(status)) {
        int stopsig = WSTOPSIG(status);
        const char *signame = ruby_signal_name(stopsig);
        if (signame) {
            snprintf(buf, sizeof(buf), ",stopped(SIG%s=%d)", signame, stopsig);
        }
        else {
            snprintf(buf, sizeof(buf), ",stopped(%d)", stopsig);
        }
        rb_str_cat2(str, buf);
    }
    if (WIFSIGNALED(status)) {
        int termsig = WTERMSIG(status);
        const char *signame = ruby_signal_name(termsig);
        if (signame) {
            snprintf(buf, sizeof(buf), ",signaled(SIG%s=%d)", signame, termsig);
        }
        else {
            snprintf(buf, sizeof(buf), ",signaled(%d)", termsig);
        }
        rb_str_cat2(str, buf);
    }
    if (WIFEXITED(status)) {
        snprintf(buf, sizeof(buf), ",exited(%d)", WEXITSTATUS(status));
        rb_str_cat2(str, buf);
    }
#ifdef WCOREDUMP
    if (WCOREDUMP(status)) {
        rb_str_cat2(str, ",coredumped");
    }
#endif
    rb_str_cat2(str, ">");
    return str;
}


pid (Process::Status)

/*
 *  call-seq:
 *     stat.pid   => fixnum
 *
 *  Returns the process ID that this status object represents.
 *
 *     fork { exit }   #=> 26569
 *     Process.wait    #=> 26569
 *     $?.pid          #=> 26569
 */

static VALUE
pst_pid(st)
    VALUE st;
{
    return rb_iv_get(st, "pid");
}


stopped? (Process::Status)

/*
 *  call-seq:
 *     stat.stopped?   => true or false
 *
 *  Returns +true+ if this process is stopped. This is only
 *  returned if the corresponding <code>wait</code> call had the
 *  <code>WUNTRACED</code> flag set.
 */

static VALUE
pst_wifstopped(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (WIFSTOPPED(status))
        return Qtrue;
    else
        return Qfalse;
}


stopsig (Process::Status)

/*
 *  call-seq:
 *     stat.stopsig   => fixnum or nil
 *
 *  Returns the number of the signal that caused _stat_ to stop
 *  (or +nil+ if self is not stopped).
 */

static VALUE
pst_wstopsig(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (WIFSTOPPED(status))
        return INT2NUM(WSTOPSIG(status));
    return Qnil;
}


signaled? (Process::Status)

/*
 *  call-seq:
 *     stat.signaled?   => true or false
 *
 *  Returns +true+ if _stat_ terminated because of
 *  an uncaught signal.
 */

static VALUE
pst_wifsignaled(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (WIFSIGNALED(status))
        return Qtrue;
    else
        return Qfalse;
}


termsig (Process::Status)

/*
 *  call-seq:
 *     stat.termsig   => fixnum or nil
 *
 *  Returns the number of the signal that caused _stat_ to
 *  terminate (or +nil+ if self was not terminated by an
 *  uncaught signal).
 */

static VALUE
pst_wtermsig(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (WIFSIGNALED(status))
        return INT2NUM(WTERMSIG(status));
    return Qnil;
}


exited? (Process::Status)

/*
 *  call-seq:
 *     stat.exited?   => true or false
 *
 *  Returns +true+ if _stat_ exited normally (for
 *  example using an <code>exit()</code> call or finishing the
 *  program).
 */

static VALUE
pst_wifexited(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (WIFEXITED(status))
        return Qtrue;
    else
        return Qfalse;
}


exitstatus (Process::Status)

/*
 *  call-seq:
 *     stat.exitstatus   => fixnum or nil
 *
 *  Returns the least significant eight bits of the return code of
 *  _stat_. Only available if <code>exited?</code> is
 *  +true+.
 *
 *     fork { }           #=> 26572
 *     Process.wait       #=> 26572
 *     $?.exited?         #=> true
 *     $?.exitstatus      #=> 0
 *
 *     fork { exit 99 }   #=> 26573
 *     Process.wait       #=> 26573
 *     $?.exited?         #=> true
 *     $?.exitstatus      #=> 99
 */

static VALUE
pst_wexitstatus(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (WIFEXITED(status))
        return INT2NUM(WEXITSTATUS(status));
    return Qnil;
}


success? (Process::Status)

/*
 *  call-seq:
 *     stat.success?   => true, false or nil
 *
 *  Returns +true+ if _stat_ is successful, +false+ if not.
 *  Returns +nil+ if <code>exited?</code> is not +true+.
 */

static VALUE
pst_success_p(st)
    VALUE st;
{
    int status = NUM2INT(st);

    if (!WIFEXITED(status))
        return Qnil;
    return WEXITSTATUS(status) == EXIT_SUCCESS ? Qtrue : Qfalse;
}


coredump? (Process::Status)

/*
 *  call-seq:
 *     stat.coredump?   => true or false
 *
 *  Returns +true+ if _stat_ generated a coredump
 *  when it terminated. Not available on all platforms.
 */

static VALUE
pst_wcoredump(st)
    VALUE st;
{
#ifdef WCOREDUMP
    int status = NUM2INT(st);

    if (WCOREDUMP(status))
        return Qtrue;
    else
        return Qfalse;
#else
    return Qfalse;
#endif
}


getuid (Process::Sys)

/*
 *  call-seq:
 *     Process.uid           => fixnum
 *     Process::UID.rid      => fixnum
 *     Process::Sys.getuid   => fixnum
 *
 *  Returns the (real) user ID of this process.
 *
 *     Process.uid   #=> 501
 */

static VALUE
proc_getuid(obj)
    VALUE obj;
{
    int uid = getuid();
    return INT2FIX(uid);
}


geteuid (Process::Sys)

/*
 *  call-seq:
 *     Process.euid           => fixnum
 *     Process::UID.eid       => fixnum
 *     Process::Sys.geteuid   => fixnum
 *
 *  Returns the effective user ID for this process.
 *
 *     Process.euid   #=> 501
 */

static VALUE
proc_geteuid(obj)
    VALUE obj;
{
    int euid = geteuid();
    return INT2FIX(euid);
}


getgid (Process::Sys)

/*
 *  call-seq:
 *     Process.gid           => fixnum
 *     Process::GID.rid      => fixnum
 *     Process::Sys.getgid   => fixnum
 *
 *  Returns the (real) group ID for this process.
 *
 *     Process.gid   #=> 500
 */

static VALUE
proc_getgid(obj)
    VALUE obj;
{
    int gid = getgid();
    return INT2FIX(gid);
}


getegid (Process::Sys)

/*
 *  call-seq:
 *     Process.egid          => fixnum
 *     Process::GID.eid      => fixnum
 *     Process::Sys.geteid   => fixnum
 *
 *  Returns the effective group ID for this process. Not available on
 *  all platforms.
 *
 *     Process.egid   #=> 500
 */

static VALUE
proc_getegid(obj)
    VALUE obj;
{
    int egid = getegid();

    return INT2FIX(egid);
}


setuid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setuid(integer)   => nil
 *
 *  Set the user ID of the current process to _integer_. Not
 *  available on all platforms.
 *
 */

static VALUE
p_sys_setuid(obj, id)
    VALUE obj, id;
{
#if defined HAVE_SETUID
    check_uid_switch();
    if (setuid(NUM2INT(id)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setgid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setgid(integer)   => nil
 *
 *  Set the group ID of the current process to _integer_. Not
 *  available on all platforms.
 *
 */

static VALUE
p_sys_setgid(obj, id)
    VALUE obj, id;
{
#if defined HAVE_SETGID
    check_gid_switch();
    if (setgid(NUM2INT(id)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setruid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setruid(integer)   => nil
 *
 *  Set the real user ID of the calling process to _integer_.
 *  Not available on all platforms.
 *
 */

static VALUE
p_sys_setruid(obj, id)
    VALUE obj, id;
{
#if defined HAVE_SETRUID
    check_uid_switch();
    if (setruid(NUM2INT(id)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setrgid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setrgid(integer)   => nil
 *
 *  Set the real group ID of the calling process to _integer_.
 *  Not available on all platforms.
 *
 */

static VALUE
p_sys_setrgid(obj, id)
    VALUE obj, id;
{
#if defined HAVE_SETRGID
    check_gid_switch();
    if (setrgid(NUM2INT(id)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


seteuid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.seteuid(integer)   => nil
 *
 *  Set the effective user ID of the calling process to
 *  _integer_.  Not available on all platforms.
 *
 */

static VALUE
p_sys_seteuid(obj, id)
    VALUE obj, id;
{
#if defined HAVE_SETEUID
    check_uid_switch();
    if (seteuid(NUM2INT(id)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setegid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setegid(integer)   => nil
 *
 *  Set the effective group ID of the calling process to
 *  _integer_.  Not available on all platforms.
 *
 */

static VALUE
p_sys_setegid(obj, id)
    VALUE obj, id;
{
#if defined HAVE_SETEGID
    check_gid_switch();
    if (setegid(NUM2INT(id)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setreuid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setreuid(rid, eid)   => nil
 *
 *  Sets the (integer) real and/or effective user IDs of the current
 *  process to _rid_ and _eid_, respectively. A value of
 *  <code>-1</code> for either means to leave that ID unchanged. Not
 *  available on all platforms.
 *
 */

static VALUE
p_sys_setreuid(obj, rid, eid)
    VALUE obj, rid, eid;
{
#if defined HAVE_SETREUID
    check_uid_switch();
    if (setreuid(NUM2INT(rid),NUM2INT(eid)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setregid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setregid(rid, eid)   => nil
 *
 *  Sets the (integer) real and/or effective group IDs of the current
 *  process to <em>rid</em> and <em>eid</em>, respectively. A value of
 *  <code>-1</code> for either means to leave that ID unchanged. Not
 *  available on all platforms.
 *
 */

static VALUE
p_sys_setregid(obj, rid, eid)
    VALUE obj, rid, eid;
{
#if defined HAVE_SETREGID
    check_gid_switch();
    if (setregid(NUM2INT(rid),NUM2INT(eid)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setresuid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setresuid(rid, eid, sid)   => nil
 *
 *  Sets the (integer) real, effective, and saved user IDs of the
 *  current process to _rid_, _eid_, and _sid_ respectively. A
 *  value of <code>-1</code> for any value means to
 *  leave that ID unchanged. Not available on all platforms.
 *
 */

static VALUE
p_sys_setresuid(obj, rid, eid, sid)
    VALUE obj, rid, eid, sid;
{
#if defined HAVE_SETRESUID
    check_uid_switch();
    if (setresuid(NUM2INT(rid),NUM2INT(eid),NUM2INT(sid)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


setresgid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.setresgid(rid, eid, sid)   => nil
 *
 *  Sets the (integer) real, effective, and saved user IDs of the
 *  current process to <em>rid</em>, <em>eid</em>, and <em>sid</em>
 *  respectively. A value of <code>-1</code> for any value means to
 *  leave that ID unchanged. Not available on all platforms.
 *
 */

static VALUE
p_sys_setresgid(obj, rid, eid, sid)
    VALUE obj, rid, eid, sid;
{
#if defined HAVE_SETRESGID
    check_gid_switch();
    if (setresgid(NUM2INT(rid),NUM2INT(eid),NUM2INT(sid)) != 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return Qnil;
}


issetugid (Process::Sys)

/*
 *  call-seq:
 *     Process::Sys.issetugid   => true or false
 *
 *  Returns +true+ if the process was created as a result
 *  of an execve(2) system call which had either of the setuid or
 *  setgid bits set (and extra privileges were given as a result) or
 *  if it has changed any of its real, effective or saved user or
 *  group IDs since it began execution.
 *
 */

static VALUE
p_sys_issetugid(obj)
    VALUE obj;
{
#if defined HAVE_ISSETUGID
    rb_secure(2);
    if (issetugid()) {
        return Qtrue;
    } else {
        return Qfalse;
    }
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}


rid (Process::UID)

/*
 *  call-seq:
 *     Process.uid           => fixnum
 *     Process::UID.rid      => fixnum
 *     Process::Sys.getuid   => fixnum
 *
 *  Returns the (real) user ID of this process.
 *
 *     Process.uid   #=> 501
 */

static VALUE
proc_getuid(obj)
    VALUE obj;
{
    int uid = getuid();
    return INT2FIX(uid);
}


eid (Process::UID)

/*
 *  call-seq:
 *     Process.euid           => fixnum
 *     Process::UID.eid       => fixnum
 *     Process::Sys.geteuid   => fixnum
 *
 *  Returns the effective user ID for this process.
 *
 *     Process.euid   #=> 501
 */

static VALUE
proc_geteuid(obj)
    VALUE obj;
{
    int euid = geteuid();
    return INT2FIX(euid);
}


change_privilege (Process::UID)

/*
 *  call-seq:
 *     Process::UID.change_privilege(integer)   => fixnum
 *
 *  Change the current process's real and effective user ID to that
 *  specified by _integer_. Returns the new user ID. Not
 *  available on all platforms.
 *
 *     [Process.uid, Process.euid]          #=> [0, 0]
 *     Process::UID.change_privilege(31)    #=> 31
 *     [Process.uid, Process.euid]          #=> [31, 31]
 */

static VALUE
p_uid_change_privilege(obj, id)
    VALUE obj, id;
{
    int uid;

    check_uid_switch();

    uid = NUM2INT(id);

    if (geteuid() == 0) { /* root-user */
#if defined(HAVE_SETRESUID)
        if (setresuid(uid, uid, uid) < 0) rb_sys_fail(0);
        SAVED_USER_ID = uid;
#elif defined(HAVE_SETUID)
        if (setuid(uid) < 0) rb_sys_fail(0);
        SAVED_USER_ID = uid;
#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
        if (getuid() == uid) {
            if (SAVED_USER_ID == uid) {
                if (setreuid(-1, uid) < 0) rb_sys_fail(0);
            } else {
                if (uid == 0) { /* (r,e,s) == (root, root, x) */
                    if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0);
                    if (setreuid(SAVED_USER_ID, 0) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = 0; /* (r,e,s) == (x, root, root) */
                    if (setreuid(uid, uid) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = uid;
                } else {
                    if (setreuid(0, -1) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = 0;
                    if (setreuid(uid, uid) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = uid;
                }
            }
        } else {
            if (setreuid(uid, uid) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
        }
#elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID)
        if (getuid() == uid) {
            if (SAVED_USER_ID == uid) {
                if (seteuid(uid) < 0) rb_sys_fail(0);
            } else {
                if (uid == 0) {
                    if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = 0;
                    if (setruid(0) < 0) rb_sys_fail(0);
                } else {
                    if (setruid(0) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = 0;
                    if (seteuid(uid) < 0) rb_sys_fail(0);
                    if (setruid(uid) < 0) rb_sys_fail(0);
                    SAVED_USER_ID = uid;
                }
            }
        } else {
            if (seteuid(uid) < 0) rb_sys_fail(0);
            if (setruid(uid) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
        }
#else
        rb_notimplement();
#endif
    } else { /* unprivileged user */
#if defined(HAVE_SETRESUID)
        if (setresuid((getuid() == uid)? -1: uid,
                      (geteuid() == uid)? -1: uid,
                      (SAVED_USER_ID == uid)? -1: uid) < 0) rb_sys_fail(0);
        SAVED_USER_ID = uid;
#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
        if (SAVED_USER_ID == uid) {
            if (setreuid((getuid() == uid)? -1: uid,
                         (geteuid() == uid)? -1: uid) < 0) rb_sys_fail(0);
        } else if (getuid() != uid) {
            if (setreuid(uid, (geteuid() == uid)? -1: uid) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
        } else if (/* getuid() == uid && */ geteuid() != uid) {
            if (setreuid(geteuid(), uid) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
            if (setreuid(uid, -1) < 0) rb_sys_fail(0);
        } else { /* getuid() == uid && geteuid() == uid */
            if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0);
            if (setreuid(SAVED_USER_ID, uid) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
            if (setreuid(uid, -1) < 0) rb_sys_fail(0);
        }
#elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID)
        if (SAVED_USER_ID == uid) {
            if (geteuid() != uid && seteuid(uid) < 0) rb_sys_fail(0);
            if (getuid() != uid && setruid(uid) < 0) rb_sys_fail(0);
        } else if (/* SAVED_USER_ID != uid && */ geteuid() == uid) {
            if (getuid() != uid) {
                if (setruid(uid) < 0) rb_sys_fail(0);
                SAVED_USER_ID = uid;
            } else {
                if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
                SAVED_USER_ID = uid;
                if (setruid(uid) < 0) rb_sys_fail(0);
            }
        } else if (/* geteuid() != uid && */ getuid() == uid) {
            if (seteuid(uid) < 0) rb_sys_fail(0);
            if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
            if (setruid(uid) < 0) rb_sys_fail(0);
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#elif defined HAVE_44BSD_SETUID
        if (getuid() == uid) {
            /* (r,e,s)==(uid,?,?) ==> (uid,uid,uid) */
            if (setuid(uid) < 0) rb_sys_fail(0);
            SAVED_USER_ID = uid;
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#elif defined HAVE_SETEUID
        if (getuid() == uid && SAVED_USER_ID == uid) {
            if (seteuid(uid) < 0) rb_sys_fail(0);
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#elif defined HAVE_SETUID
        if (getuid() == uid && SAVED_USER_ID == uid) {
            if (setuid(uid) < 0) rb_sys_fail(0);
        } else {
            errno = EPERM;
            rb_sys_fail(0);
        }
#else
        rb_notimplement();
#endif
    }
    return INT2FIX(uid);
}


grant_privilege (Process::UID)

/*
 *  call-seq:
 *     Process::UID.grant_privilege(integer)   => fixnum
 *     Process::UID.eid= integer               => fixnum
 *
 *  Set the effective user ID, and if possible, the saved user ID of
 *  the process to the given _integer_. Returns the new
 *  effective user ID. Not available on all platforms.
 *
 *     [Process.uid, Process.euid]          #=> [0, 0]
 *     Process::UID.grant_privilege(31)     #=> 31
 *     [Process.uid, Process.euid]          #=> [0, 31]
 */

static VALUE
p_uid_grant_privilege(obj, id)
    VALUE obj, id;
{
    return rb_seteuid_core(NUM2INT(id));
}


re_exchange (Process::UID)

/*
 *  call-seq:
 *     Process::UID.re_exchange   => fixnum
 *
 *  Exchange real and effective user IDs and return the new effective
 *  user ID. Not available on all platforms.
 *
 *     [Process.uid, Process.euid]   #=> [0, 31]
 *     Process::UID.re_exchange      #=> 0
 *     [Process.uid, Process.euid]   #=> [31, 0]
 */

static VALUE
p_uid_exchange(obj)
    VALUE obj;
{
    int uid, euid;

    check_uid_switch();

    uid = getuid();
    euid = geteuid();

#if defined(HAVE_SETRESUID) &&  !defined(__CHECKER__)
    if (setresuid(euid, uid, uid) < 0) rb_sys_fail(0);
    SAVED_USER_ID = uid;
#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
    if (setreuid(euid,uid) < 0) rb_sys_fail(0);
    SAVED_USER_ID = uid;
#else
    rb_notimplement();
#endif
    return INT2FIX(uid);
}


re_exchangeable? (Process::UID)

/*
 *  call-seq:
 *     Process::UID.re_exchangeable?   => true or false
 *
 *  Returns +true+ if the real and effective user IDs of a
 *  process may be exchanged on the current platform.
 *
 */

static VALUE
p_uid_exchangeable()
{
#if defined(HAVE_SETRESUID) &&  !defined(__CHECKER__)
    return Qtrue;
#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
    return Qtrue;
#else
    return Qfalse;
#endif
}


sid_available? (Process::UID)

/*
 *  call-seq:
 *     Process::UID.sid_available?   => true or false
 *
 *  Returns +true+ if the current platform has saved user
 *  ID functionality.
 *
 */

static VALUE
p_uid_have_saved_id()
{
#if defined(HAVE_SETRESUID) || defined(HAVE_SETEUID) || defined(_POSIX_SAVED_IDS)
    return Qtrue;
#else
    return Qfalse;
#endif
}


switch (Process::UID)

/*
 *  call-seq:
 *     Process::UID.switch              => fixnum
 *     Process::UID.switch {|| block}   => object
 *
 *  Switch the effective and real user IDs of the current process. If
 *  a <em>block</em> is given, the user IDs will be switched back
 *  after the block is executed. Returns the new effective user ID if
 *  called without a block, and the return value of the block if one
 *  is given.
 *
 */

static VALUE
p_uid_switch(obj)
    VALUE obj;
{
    int uid, euid;

    check_uid_switch();

    uid = getuid();
    euid = geteuid();

    if (uid != euid) {
        proc_seteuid(obj, INT2FIX(uid));
        if (rb_block_given_p()) {
            under_uid_switch = 1;
            return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, SAVED_USER_ID);
        } else {
            return INT2FIX(euid);
        }
    } else if (euid != SAVED_USER_ID) {
        proc_seteuid(obj, INT2FIX(SAVED_USER_ID));
        if (rb_block_given_p()) {
            under_uid_switch = 1;
            return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, euid);
        } else {
            return INT2FIX(uid);
        }
    } else {
        errno = EPERM;
        rb_sys_fail(0);
    }

#else
static VALUE
p_uid_sw_ensure(obj)
    VALUE obj;
{
    under_uid_switch = 0;
    return p_uid_exchange(obj);
}


fork (Process)

/*
 *  call-seq:
 *     Kernel.fork  [{ block }]   => fixnum or nil
 *     Process.fork [{ block }]   => fixnum or nil
 *
 *  Creates a subprocess. If a block is specified, that block is run
 *  in the subprocess, and the subprocess terminates with a status of
 *  zero. Otherwise, the +fork+ call returns twice, once in
 *  the parent, returning the process ID of the child, and once in
 *  the child, returning _nil_. The child process can exit using
 *  <code>Kernel.exit!</code> to avoid running any
 *  <code>at_exit</code> functions. The parent process should
 *  use <code>Process.wait</code> to collect the termination statuses
 *  of its children or use <code>Process.detach</code> to register
 *  disinterest in their status; otherwise, the operating system
 *  may accumulate zombie processes.
 *
 *  The thread calling fork is the only thread in the created child process.
 *  fork doesn't copy other threads.
 */

static VALUE
rb_f_fork(obj)
    VALUE obj;
{
#if !defined(__human68k__) && !defined(_WIN32) && !defined(__MACOS__) && !defined(__EMX__) && !defined(__VMS)
    int pid;

    rb_secure(2);

#ifndef __VMS
    fflush(stdout);
    fflush(stderr);
#endif

    switch (pid = fork()) {
      case 0:
#ifdef linux
        after_exec();
#endif
        rb_thread_atfork();
        if (rb_block_given_p()) {
            int status;

            rb_protect(rb_yield, Qundef, &status);
            ruby_stop(status);
        }
        return Qnil;

      case -1:
        rb_sys_fail("fork(2)");
        return Qnil;

      default:
        return INT2FIX(pid);
    }
#else
    rb_notimplement();
#endif
}


exit! (Process)

/*
 *  call-seq:
 *     Process.exit!(fixnum=-1)
 *
 *  Exits the process immediately. No exit handlers are
 *  run. <em>fixnum</em> is returned to the underlying system as the
 *  exit status.
 *
 *     Process.exit!(0)
 */

static VALUE
rb_f_exit_bang(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE status;
    int istatus;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &status) == 1) {
        switch (status) {
          case Qtrue:
            istatus = EXIT_SUCCESS;
            break;
          case Qfalse:
            istatus = EXIT_FAILURE;
            break;
          default:
            istatus = NUM2INT(status);
            break;
        }
    }
    else {
        istatus = EXIT_FAILURE;
    }
    _exit(istatus);

    return Qnil;                /* not reached */
}


exit (Process)

/*
 *  call-seq:
 *     exit(integer=0)
 *     Kernel::exit(integer=0)
 *     Process::exit(integer=0)
 *
 *  Initiates the termination of the Ruby script by raising the
 *  <code>SystemExit</code> exception. This exception may be caught. The
 *  optional parameter is used to return a status code to the invoking
 *  environment.
 *
 *     begin
 *       exit
 *       puts "never get here"
 *     rescue SystemExit
 *       puts "rescued a SystemExit exception"
 *     end
 *     puts "after begin block"
 *
 *  <em>produces:</em>
 *
 *     rescued a SystemExit exception
 *     after begin block
 *
 *  Just prior to termination, Ruby executes any <code>at_exit</code> functions
 *  (see Kernel::at_exit) and runs any object finalizers (see
 *  ObjectSpace::define_finalizer).
 *
 *     at_exit { puts "at_exit function" }
 *     ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
 *     exit
 *
 *  <em>produces:</em>
 *
 *     at_exit function
 *     in finalizer
 */

VALUE
rb_f_exit(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE status;
    int istatus;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &status) == 1) {
    switch (status) {
      case Qtrue:
        istatus = EXIT_SUCCESS;
        break;
      case Qfalse:
        istatus = EXIT_FAILURE;
        break;
      default:
        istatus = NUM2INT(status);
#if EXIT_SUCCESS != 0
        if (istatus == 0) istatus = EXIT_SUCCESS;
#endif
        break;
    }
    }
    else {
    istatus = EXIT_SUCCESS;
    }
    rb_exit(istatus);
    return Qnil;		/* not reached */
}


abort (Process)

/*
 *  call-seq:
 *     abort
 *     Kernel::abort
 *     Process::abort
 *
 *  Terminate execution immediately, effectively by calling
 *  <code>Kernel.exit(1)</code>. If _msg_ is given, it is written
 *  to STDERR prior to terminating.
 */

VALUE
rb_f_abort(argc, argv)
    int argc;
    VALUE *argv;
{
    rb_secure(4);
    if (argc == 0) {
    if (!NIL_P(ruby_errinfo)) {
        error_print();
    }
    rb_exit(EXIT_FAILURE);
    }
    else {
    VALUE mesg;

    rb_scan_args(argc, argv, "1", &mesg);
    StringValue(mesg);
    rb_io_puts(1, &mesg, rb_stderr);
    terminate_process(EXIT_FAILURE, mesg);
    }
    return Qnil;		/* not reached */
}


kill (Process)

/*
 *  call-seq:
 *     Process.kill(signal, pid, ...)    => fixnum
 *
 *  Sends the given signal to the specified process id(s), or to the
 *  current process if _pid_ is zero. _signal_ may be an
 *  integer signal number or a POSIX signal name (either with or without
 *  a +SIG+ prefix). If _signal_ is negative (or starts
 *  with a minus sign), kills process groups instead of
 *  processes. Not all signals are available on all platforms.
 *
 *     pid = fork do
 *        Signal.trap("HUP") { puts "Ouch!"; exit }
 *        # ... do some work ...
 *     end
 *     # ...
 *     Process.kill("HUP", pid)
 *     Process.wait
 *
 *  <em>produces:</em>
 *
 *     Ouch!
 */

VALUE
rb_f_kill(argc, argv)
    int argc;
    VALUE *argv;
{
    int negative = 0;
    int sig;
    int i;
    char *s;

    rb_secure(2);
    if (argc < 2)
    rb_raise(rb_eArgError, "wrong number of arguments -- kill(sig, pid...)");
    switch (TYPE(argv[0])) {
      case T_FIXNUM:
    sig = FIX2INT(argv[0]);
    break;

      case T_SYMBOL:
    s = rb_id2name(SYM2ID(argv[0]));
    if (!s) rb_raise(rb_eArgError, "bad signal");
    goto str_signal;

      case T_STRING:
    s = RSTRING(argv[0])->ptr;
    if (s[0] == '-') {
        negative++;
        s++;
    }
      str_signal:
    if (strncmp("SIG", s, 3) == 0)
        s += 3;
    if((sig = signm2signo(s)) == 0)
        rb_raise(rb_eArgError, "unsupported name `SIG%s'", s);

    if (negative)
        sig = -sig;
    break;

      default:
        {
        VALUE str;

        str = rb_check_string_type(argv[0]);
        if (!NIL_P(str)) {
        s = RSTRING(str)->ptr;
        goto str_signal;
        }
        rb_raise(rb_eArgError, "bad signal type %s",
             rb_obj_classname(argv[0]));
    }
    break;
    }

    if (sig < 0) {
    sig = -sig;
    for (i=1; i<argc; i++) {
        int pid = NUM2INT(argv[i]);
#ifdef HAS_KILLPG
        if (killpg(pid, sig) < 0)
#else
        if (kill(-pid, sig) < 0)
#endif
        rb_sys_fail(0);
    }
    }
    else {
    for (i=1; i<argc; i++) {
        Check_Type(argv[i], T_FIXNUM);
        if (kill(FIX2INT(argv[i]), sig) < 0)
        rb_sys_fail(0);
    }
    }
    return INT2FIX(i-1);
}


wait (Process)

/*
 *  call-seq:
 *     Process.wait()                     => fixnum
 *     Process.wait(pid=-1, flags=0)      => fixnum
 *     Process.waitpid(pid=-1, flags=0)   => fixnum
 *
 *  Waits for a child process to exit, returns its process id, and
 *  sets <code>$?</code> to a <code>Process::Status</code> object
 *  containing information on that process. Which child it waits on
 *  depends on the value of _pid_:
 *
 *  > 0::   Waits for the child whose process ID equals _pid_.
 *
 *  0::     Waits for any child whose process group ID equals that of the
 *          calling process.
 *
 *  -1::    Waits for any child process (the default if no _pid_ is
 *          given).
 *
 *  < -1::  Waits for any child whose process group ID equals the absolute
 *          value of _pid_.
 *
 *  The _flags_ argument may be a logical or of the flag values
 *  <code>Process::WNOHANG</code> (do not block if no child available)
 *  or <code>Process::WUNTRACED</code> (return stopped children that
 *  haven't been reported). Not all flags are available on all
 *  platforms, but a flag value of zero will work on all platforms.
 *
 *  Calling this method raises a <code>SystemError</code> if there are
 *  no child processes. Not available on all platforms.
 *
 *     include Process
 *     fork { exit 99 }                 #=> 27429
 *     wait                             #=> 27429
 *     $?.exitstatus                    #=> 99
 *
 *     pid = fork { sleep 3 }           #=> 27440
 *     Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
 *     waitpid(pid, Process::WNOHANG)   #=> nil
 *     Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
 *     waitpid(pid, 0)                  #=> 27440
 *     Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003
 */

static VALUE
proc_wait(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE vpid, vflags;
    int pid, flags, status;

    rb_secure(2);
    flags = 0;
    rb_scan_args(argc, argv, "02", &vpid, &vflags);
    if (argc == 0) {
        pid = -1;
    }
    else {
        pid = NUM2INT(vpid);
        if (argc == 2 && !NIL_P(vflags)) {
            flags = NUM2UINT(vflags);
        }
    }
    if ((pid = rb_waitpid(pid, &status, flags)) < 0)
        rb_sys_fail(0);
    if (pid == 0) {
        return rb_last_status = Qnil;
    }
    return INT2FIX(pid);
}


wait2 (Process)

/*
 *  call-seq:
 *     Process.wait2(pid=-1, flags=0)      => [pid, status]
 *     Process.waitpid2(pid=-1, flags=0)   => [pid, status]
 *
 *  Waits for a child process to exit (see Process::waitpid for exact
 *  semantics) and returns an array containing the process id and the
 *  exit status (a <code>Process::Status</code> object) of that
 *  child. Raises a <code>SystemError</code> if there are no child
 *  processes.
 *
 *     Process.fork { exit 99 }   #=> 27437
 *     pid, status = Process.wait2
 *     pid                        #=> 27437
 *     status.exitstatus          #=> 99
 */

static VALUE
proc_wait2(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE pid = proc_wait(argc, argv);
    if (NIL_P(pid)) return Qnil;
    return rb_assoc_new(pid, rb_last_status);
}


waitpid (Process)

/*
 *  call-seq:
 *     Process.wait()                     => fixnum
 *     Process.wait(pid=-1, flags=0)      => fixnum
 *     Process.waitpid(pid=-1, flags=0)   => fixnum
 *
 *  Waits for a child process to exit, returns its process id, and
 *  sets <code>$?</code> to a <code>Process::Status</code> object
 *  containing information on that process. Which child it waits on
 *  depends on the value of _pid_:
 *
 *  > 0::   Waits for the child whose process ID equals _pid_.
 *
 *  0::     Waits for any child whose process group ID equals that of the
 *          calling process.
 *
 *  -1::    Waits for any child process (the default if no _pid_ is
 *          given).
 *
 *  < -1::  Waits for any child whose process group ID equals the absolute
 *          value of _pid_.
 *
 *  The _flags_ argument may be a logical or of the flag values
 *  <code>Process::WNOHANG</code> (do not block if no child available)
 *  or <code>Process::WUNTRACED</code> (return stopped children that
 *  haven't been reported). Not all flags are available on all
 *  platforms, but a flag value of zero will work on all platforms.
 *
 *  Calling this method raises a <code>SystemError</code> if there are
 *  no child processes. Not available on all platforms.
 *
 *     include Process
 *     fork { exit 99 }                 #=> 27429
 *     wait                             #=> 27429
 *     $?.exitstatus                    #=> 99
 *
 *     pid = fork { sleep 3 }           #=> 27440
 *     Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
 *     waitpid(pid, Process::WNOHANG)   #=> nil
 *     Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
 *     waitpid(pid, 0)                  #=> 27440
 *     Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003
 */

static VALUE
proc_wait(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE vpid, vflags;
    int pid, flags, status;

    rb_secure(2);
    flags = 0;
    rb_scan_args(argc, argv, "02", &vpid, &vflags);
    if (argc == 0) {
        pid = -1;
    }
    else {
        pid = NUM2INT(vpid);
        if (argc == 2 && !NIL_P(vflags)) {
            flags = NUM2UINT(vflags);
        }
    }
    if ((pid = rb_waitpid(pid, &status, flags)) < 0)
        rb_sys_fail(0);
    if (pid == 0) {
        return rb_last_status = Qnil;
    }
    return INT2FIX(pid);
}


waitpid2 (Process)

/*
 *  call-seq:
 *     Process.wait2(pid=-1, flags=0)      => [pid, status]
 *     Process.waitpid2(pid=-1, flags=0)   => [pid, status]
 *
 *  Waits for a child process to exit (see Process::waitpid for exact
 *  semantics) and returns an array containing the process id and the
 *  exit status (a <code>Process::Status</code> object) of that
 *  child. Raises a <code>SystemError</code> if there are no child
 *  processes.
 *
 *     Process.fork { exit 99 }   #=> 27437
 *     pid, status = Process.wait2
 *     pid                        #=> 27437
 *     status.exitstatus          #=> 99
 */

static VALUE
proc_wait2(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE pid = proc_wait(argc, argv);
    if (NIL_P(pid)) return Qnil;
    return rb_assoc_new(pid, rb_last_status);
}


waitall (Process)

/*
 *  call-seq:
 *     Process.waitall   => [ [pid1,status1], ...]
 *
 *  Waits for all children, returning an array of
 *  _pid_/_status_ pairs (where _status_ is a
 *  <code>Process::Status</code> object).
 *
 *     fork { sleep 0.2; exit 2 }   #=> 27432
 *     fork { sleep 0.1; exit 1 }   #=> 27433
 *     fork {            exit 0 }   #=> 27434
 *     p Process.waitall
 *
 *  <em>produces</em>:
 *
 *     [[27434, #<Process::Status: pid=27434,exited(0)>],
 *      [27433, #<Process::Status: pid=27433,exited(1)>],
 *      [27432, #<Process::Status: pid=27432,exited(2)>]]
 */

static VALUE
proc_waitall()
{
    VALUE result;
    int pid, status;

    rb_secure(2);
    result = rb_ary_new();
#ifdef NO_WAITPID
    if (pid_tbl) {
        st_foreach(pid_tbl, waitall_each, result);
    }

    for (pid = -1;;) {
        pid = wait(&status);
        if (pid == -1) {
            if (errno == ECHILD)
                break;
            if (errno == EINTR) {
                rb_thread_schedule();
                continue;
            }
            rb_sys_fail(0);
        }
        last_status_set(status, pid);
        rb_ary_push(result, rb_assoc_new(INT2NUM(pid), rb_last_status));
    }
#else
    rb_last_status = Qnil;
    for (pid = -1;;) {
        pid = rb_waitpid(-1, &status, 0);
        if (pid == -1) {
            if (errno == ECHILD)
                break;
            rb_sys_fail(0);
        }
        rb_ary_push(result, rb_assoc_new(INT2NUM(pid), rb_last_status));
    }
#endif
    return result;
}


detach (Process)

/*
 *  call-seq:
 *     Process.detach(pid)   => thread
 *
 *  Some operating systems retain the status of terminated child
 *  processes until the parent collects that status (normally using
 *  some variant of <code>wait()</code>. If the parent never collects
 *  this status, the child stays around as a <em>zombie</em> process.
 *  <code>Process::detach</code> prevents this by setting up a
 *  separate Ruby thread whose sole job is to reap the status of the
 *  process _pid_ when it terminates. Use <code>detach</code>
 *  only when you do not intent to explicitly wait for the child to
 *  terminate.  <code>detach</code> only checks the status
 *  periodically (currently once each second).
 *
 *  In this first example, we don't reap the first child process, so
 *  it appears as a zombie in the process status display.
 *
 *     p1 = fork { sleep 0.1 }
 *     p2 = fork { sleep 0.2 }
 *     Process.waitpid(p2)
 *     sleep 2
 *     system("ps -ho pid,state -p #{p1}")
 *
 *  <em>produces:</em>
 *
 *     27389 Z
 *
 *  In the next example, <code>Process::detach</code> is used to reap
 *  the child automatically.
 *
 *     p1 = fork { sleep 0.1 }
 *     p2 = fork { sleep 0.2 }
 *     Process.detach(p1)
 *     Process.waitpid(p2)
 *     sleep 2
 *     system("ps -ho pid,state -p #{p1}")
 *
 *  <em>(produces no output)</em>
 */

static VALUE
proc_detach(VALUE obj, VALUE pid)
{
    rb_secure(2);
    return rb_detach_process(NUM2INT(pid));
}


pid (Process)

/*
 *  call-seq:
 *     Process.pid   => fixnum
 *
 *  Returns the process id of this process. Not available on all
 *  platforms.
 *
 *     Process.pid   #=> 27415
 */

static VALUE
get_pid()
{
    rb_secure(2);
    return INT2FIX(getpid());
}


ppid (Process)

/*
 *  call-seq:
 *     Process.ppid   => fixnum
 *
 *  Returns the process id of the parent of this process. Always
 *  returns 0 on NT. Not available on all platforms.
 *
 *     puts "I am #{Process.pid}"
 *     Process.fork { puts "Dad is #{Process.ppid}" }
 *
 *  <em>produces:</em>
 *
 *     I am 27417
 *     Dad is 27417
 */

static VALUE
get_ppid()
{
    rb_secure(2);
#ifdef _WIN32
    return INT2FIX(0);
#else
    return INT2FIX(getppid());
#endif
}


setpgrp (Process)

/*
 *  call-seq:
 *     Process.setpgrp   => 0
 *
 *  Equivalent to <code>setpgid(0,0)</code>. Not available on all
 *  platforms.
 */

static VALUE
proc_setpgrp()
{
    rb_secure(2);
  /* check for posix setpgid() first; this matches the posix */
  /* getpgrp() above.  It appears that configure will set SETPGRP_VOID */
  /* even though setpgrp(0,0) would be prefered. The posix call avoids */
  /* this confusion. */
#ifdef HAVE_SETPGID
    if (setpgid(0,0) < 0) rb_sys_fail(0);
#elif defined(HAVE_SETPGRP) && defined(SETPGRP_VOID)
    if (setpgrp() < 0) rb_sys_fail(0);
#else
    rb_notimplement();
#endif
    return INT2FIX(0);
}


getpgid (Process)

/*
 *  call-seq:
 *     Process.getpgid(pid)   => integer
 *
 *  Returns the process group ID for the given process id. Not
 *  available on all platforms.
 *
 *     Process.getpgid(Process.ppid())   #=> 25527
 */

static VALUE
proc_getpgid(obj, pid)
    VALUE obj, pid;
{
#if defined(HAVE_GETPGID) && !defined(__CHECKER__)
    int i;

    rb_secure(2);
    i = getpgid(NUM2INT(pid));
    if (i < 0) rb_sys_fail(0);
    return INT2NUM(i);
#else
    rb_notimplement();
#endif
}


setpgid (Process)

/*
 *  call-seq:
 *     Process.setpgid(pid, integer)   => 0
 *
 *  Sets the process group ID of _pid_ (0 indicates this
 *  process) to <em>integer</em>. Not available on all platforms.
 */

static VALUE
proc_setpgid(obj, pid, pgrp)
    VALUE obj, pid, pgrp;
{
#ifdef HAVE_SETPGID
    int ipid, ipgrp;

    rb_secure(2);
    ipid = NUM2INT(pid);
    ipgrp = NUM2INT(pgrp);

    if (setpgid(ipid, ipgrp) < 0) rb_sys_fail(0);
    return INT2FIX(0);
#else
    rb_notimplement();
#endif
}


setsid (Process)

/*
 *  call-seq:
 *     Process.setsid   => fixnum
 *
 *  Establishes this process as a new session and process group
 *  leader, with no controlling tty. Returns the session id. Not
 *  available on all platforms.
 *
 *     Process.setsid   #=> 27422
 */

static VALUE
proc_setsid()
{
#if defined(HAVE_SETSID)
    int pid;

    rb_secure(2);
    pid = setsid();
    if (pid < 0) rb_sys_fail(0);
    return INT2FIX(pid);
#elif defined(HAVE_SETPGRP) && defined(TIOCNOTTY)
  rb_pid_t pid;
  int ret;

  rb_secure(2);
  pid = getpid();
#if defined(SETPGRP_VOID)
  ret = setpgrp();
  /* If `pid_t setpgrp(void)' is equivalent to setsid(),
     `ret' will be the same value as `pid', and following open() will fail.
     In Linux, `int setpgrp(void)' is equivalent to setpgid(0, 0). */
#else
  ret = setpgrp(0, pid);
#endif
  if (ret == -1) rb_sys_fail(0);

  if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
    ioctl(fd, TIOCNOTTY, NULL);
    close(fd);
  }
  return INT2FIX(pid);
#else
    rb_notimplement();
#endif
}


getpriority (Process)

/*
 *  call-seq:
 *     Process.getpriority(kind, integer)   => fixnum
 *
 *  Gets the scheduling priority for specified process, process group,
 *  or user. <em>kind</em> indicates the kind of entity to find: one
 *  of <code>Process::PRIO_PGRP</code>,
 *  <code>Process::PRIO_USER</code>, or
 *  <code>Process::PRIO_PROCESS</code>. _integer_ is an id
 *  indicating the particular process, process group, or user (an id
 *  of 0 means _current_). Lower priorities are more favorable
 *  for scheduling. Not available on all platforms.
 *
 *     Process.getpriority(Process::PRIO_USER, 0)      #=> 19
 *     Process.getpriority(Process::PRIO_PROCESS, 0)   #=> 19
 */

static VALUE
proc_getpriority(obj, which, who)
    VALUE obj, which, who;
{
#ifdef HAVE_GETPRIORITY
    int prio, iwhich, iwho;

    rb_secure(2);
    iwhich = NUM2INT(which);
    iwho   = NUM2INT(who);

    errno = 0;
    prio = getpriority(iwhich, iwho);
    if (errno) rb_sys_fail(0);
    return INT2FIX(prio);
#else
    rb_notimplement();
#endif
}


setpriority (Process)

/*
 *  call-seq:
 *     Process.setpriority(kind, integer, priority)   => 0
 *
 *  See <code>Process#getpriority</code>.
 *
 *     Process.setpriority(Process::PRIO_USER, 0, 19)      #=> 0
 *     Process.setpriority(Process::PRIO_PROCESS, 0, 19)   #=> 0
 *     Process.getpriority(Process::PRIO_USER, 0)          #=> 19
 *     Process.getpriority(Process::PRIO_PROCESS, 0)       #=> 19
 */

static VALUE
proc_setpriority(obj, which, who, prio)
    VALUE obj, which, who, prio;
{
#ifdef HAVE_GETPRIORITY
    int iwhich, iwho, iprio;

    rb_secure(2);
    iwhich = NUM2INT(which);
    iwho   = NUM2INT(who);
    iprio  = NUM2INT(prio);

    if (setpriority(iwhich, iwho, iprio) < 0)
        rb_sys_fail(0);
    return INT2FIX(0);
#else
    rb_notimplement();
#endif
}


getrlimit (Process)

/*
 *  call-seq:
 *     Process.getrlimit(resource)   => [cur_limit, max_limit]
 *
 *  Gets the resource limit of the process.
 *  _cur_limit_ means current (soft) limit and
 *  _max_limit_ means maximum (hard) limit.
 *
 *  _resource_ indicates the kind of resource to limit:
 *  such as <code>Process::RLIMIT_CORE</code>,
 *  <code>Process::RLIMIT_CPU</code>, etc.
 *  See Process.setrlimit for details.
 *
 *  _cur_limit_ and _max_limit_ may be <code>Process::RLIM_INFINITY</code>,
 *  <code>Process::RLIM_SAVED_MAX</code> or
 *  <code>Process::RLIM_SAVED_CUR</code>.
 *  See Process.setrlimit and the system getrlimit(2) manual for details.
 */

static VALUE
proc_getrlimit(VALUE obj, VALUE resource)
{
#if defined(HAVE_GETRLIMIT) && defined(RLIM2NUM)
    struct rlimit rlim;

    rb_secure(2);

    if (getrlimit(NUM2INT(resource), &rlim) < 0) {
        rb_sys_fail("getrlimit");
    }
    return rb_assoc_new(RLIM2NUM(rlim.rlim_cur), RLIM2NUM(rlim.rlim_max));
#else
    rb_notimplement();
#endif
}


setrlimit (Process)

/*
 *  call-seq:
 *     Process.setrlimit(resource, cur_limit, max_limit)        => nil
 *     Process.setrlimit(resource, cur_limit)                   => nil
 *
 *  Sets the resource limit of the process.
 *  _cur_limit_ means current (soft) limit and
 *  _max_limit_ means maximum (hard) limit.
 *
 *  If _max_limit_ is not given, _cur_limit_ is used.
 *
 *  _resource_ indicates the kind of resource to limit.
 *  The list of resources are OS dependent.
 *  Ruby may support following resources.
 *
 *  [Process::RLIMIT_CORE] core size (bytes) (SUSv3)
 *  [Process::RLIMIT_CPU] CPU time (seconds) (SUSv3)
 *  [Process::RLIMIT_DATA] data segment (bytes) (SUSv3)
 *  [Process::RLIMIT_FSIZE] file size (bytes) (SUSv3)
 *  [Process::RLIMIT_NOFILE] file descriptors (number) (SUSv3)
 *  [Process::RLIMIT_STACK] stack size (bytes) (SUSv3)
 *  [Process::RLIMIT_AS] total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD but 4.4BSD-Lite)
 *  [Process::RLIMIT_MEMLOCK] total size for mlock(2) (bytes) (4.4BSD, GNU/Linux)
 *  [Process::RLIMIT_NPROC] number of processes for the user (number) (4.4BSD, GNU/Linux)
 *  [Process::RLIMIT_RSS] resident memory size (bytes) (4.2BSD, GNU/Linux)
 *  [Process::RLIMIT_SBSIZE] all socket buffers (bytes) (NetBSD, FreeBSD)
 *
 *  Other <code>Process::RLIMIT_???</code> constants may be defined.
 *
 *  _cur_limit_ and _max_limit_ may be <code>Process::RLIM_INFINITY</code>,
 *  which means that the resource is not limited.
 *  They may be <code>Process::RLIM_SAVED_MAX</code> or
 *  <code>Process::RLIM_SAVED_CUR</code> too.
 *  See system setrlimit(2) manual for details.
 *
 */

static VALUE
proc_setrlimit(int argc, VALUE *argv, VALUE obj)
{
#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
    VALUE resource, rlim_cur, rlim_max;
    struct rlimit rlim;

    rb_secure(2);

    rb_scan_args(argc, argv, "21", &resource, &rlim_cur, &rlim_max);
    if (rlim_max == Qnil)
        rlim_max = rlim_cur;

    rlim.rlim_cur = NUM2RLIM(rlim_cur);
    rlim.rlim_max = NUM2RLIM(rlim_max);

    if (setrlimit(NUM2INT(resource), &rlim) < 0) {
        rb_sys_fail("setrlimit");
    }
    return Qnil;
#else
    rb_notimplement();
#endif
}


uid (Process)

/*
 *  call-seq:
 *     Process.uid           => fixnum
 *     Process::UID.rid      => fixnum
 *     Process::Sys.getuid   => fixnum
 *
 *  Returns the (real) user ID of this process.
 *
 *     Process.uid   #=> 501
 */

static VALUE
proc_getuid(obj)
    VALUE obj;
{
    int uid = getuid();
    return INT2FIX(uid);
}


uid= (Process)

/*
 *  call-seq:
 *     Process.uid= integer   => numeric
 *
 *  Sets the (integer) user ID for this process. Not available on all
 *  platforms.
 */

static VALUE
proc_setuid(obj, id)
    VALUE obj, id;
{
    int uid = NUM2INT(id);

    check_uid_switch();
#if defined(HAVE_SETRESUID) &&  !defined(__CHECKER__)
    if (setresuid(uid, -1, -1) < 0) rb_sys_fail(0);
#elif defined HAVE_SETREUID
    if (setreuid(uid, -1) < 0) rb_sys_fail(0);
#elif defined HAVE_SETRUID
    if (setruid(uid) < 0) rb_sys_fail(0);
#elif defined HAVE_SETUID
    {
        if (geteuid() == uid) {
            if (setuid(uid) < 0) rb_sys_fail(0);
        }
        else {
            rb_notimplement();
        }
    }
#else
    rb_notimplement();
#endif
    return INT2FIX(uid);
}


gid (Process)

/*
 *  call-seq:
 *     Process.gid           => fixnum
 *     Process::GID.rid      => fixnum
 *     Process::Sys.getgid   => fixnum
 *
 *  Returns the (real) group ID for this process.
 *
 *     Process.gid   #=> 500
 */

static VALUE
proc_getgid(obj)
    VALUE obj;
{
    int gid = getgid();
    return INT2FIX(gid);
}


gid= (Process)

/*
 *  call-seq:
 *     Process.gid= fixnum   => fixnum
 *
 *  Sets the group ID for this process.
 */

static VALUE
proc_setgid(obj, id)
    VALUE obj, id;
{
    int gid = NUM2INT(id);

    check_gid_switch();
#if defined(HAVE_SETRESGID) && !defined(__CHECKER__)
    if (setresgid(gid, -1, -1) < 0) rb_sys_fail(0);
#elif defined HAVE_SETREGID
    if (setregid(gid, -1) < 0) rb_sys_fail(0);
#elif defined HAVE_SETRGID
    if (setrgid(gid) < 0) rb_sys_fail(0);
#elif defined HAVE_SETGID
    {
        if (getegid() == gid) {
            if (setgid(gid) < 0) rb_sys_fail(0);
        }
        else {
            rb_notimplement();
        }
    }
#else
    rb_notimplement();
#endif
    return INT2FIX(gid);
}


euid (Process)

/*
 *  call-seq:
 *     Process.euid           => fixnum
 *     Process::UID.eid       => fixnum
 *     Process::Sys.geteuid   => fixnum
 *
 *  Returns the effective user ID for this process.
 *
 *     Process.euid   #=> 501
 */

static VALUE
proc_geteuid(obj)
    VALUE obj;
{
    int euid = geteuid();
    return INT2FIX(euid);
}


euid= (Process)

/*
 *  call-seq:
 *     Process.euid= integer
 *
 *  Sets the effective user ID for this process. Not available on all
 *  platforms.
 */

static VALUE
proc_seteuid(obj, euid)
    VALUE obj, euid;
{
    check_uid_switch();
#if defined(HAVE_SETRESUID) && !defined(__CHECKER__)
    if (setresuid(-1, NUM2INT(euid), -1) < 0) rb_sys_fail(0);
#elif defined HAVE_SETREUID
    if (setreuid(-1, NUM2INT(euid)) < 0) rb_sys_fail(0);
#elif defined HAVE_SETEUID
    if (seteuid(NUM2INT(euid)) < 0) rb_sys_fail(0);
#elif defined HAVE_SETUID
    euid = NUM2INT(euid);
    if (euid == getuid()) {
        if (setuid(euid) < 0) rb_sys_fail(0);
    }
    else {
        rb_notimplement();
    }
#else
    rb_notimplement();
#endif
    return euid;
}


egid (Process)

/*
 *  call-seq:
 *     Process.egid          => fixnum
 *     Process::GID.eid      => fixnum
 *     Process::Sys.geteid   => fixnum
 *
 *  Returns the effective group ID for this process. Not available on
 *  all platforms.
 *
 *     Process.egid   #=> 500
 */

static VALUE
proc_getegid(obj)
    VALUE obj;
{
    int egid = getegid();

    return INT2FIX(egid);
}


egid= (Process)

/*
 *  call-seq:
 *     Process.egid = fixnum   => fixnum
 *
 *  Sets the effective group ID for this process. Not available on all
 *  platforms.
 */

static VALUE
proc_setegid(obj, egid)
    VALUE obj, egid;
{
    check_gid_switch();

#if defined(HAVE_SETRESGID) && !defined(__CHECKER__)
    if (setresgid(-1, NUM2INT(egid), -1) < 0) rb_sys_fail(0);
#elif defined HAVE_SETREGID
    if (setregid(-1, NUM2INT(egid)) < 0) rb_sys_fail(0);
#elif defined HAVE_SETEGID
    if (setegid(NUM2INT(egid)) < 0) rb_sys_fail(0);
#elif defined HAVE_SETGID
    egid = NUM2INT(egid);
    if (egid == getgid()) {
        if (setgid(egid) < 0) rb_sys_fail(0);
    }
    else {
        rb_notimplement();
    }
#else
    rb_notimplement();
#endif
    return egid;
}


initgroups (Process)

/*
 *  call-seq:
 *     Process.initgroups(username, gid)   => array
 *
 *  Initializes the supplemental group access list by reading the
 *  system group database and using all groups of which the given user
 *  is a member. The group with the specified <em>gid</em> is also
 *  added to the list. Returns the resulting <code>Array</code> of the
 *  gids of all the groups in the supplementary group access list. Not
 *  available on all platforms.
 *
 *     Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
 *     Process.initgroups( "mgranger", 30 )   #=> [30, 6, 10, 11]
 *     Process.groups   #=> [30, 6, 10, 11]
 *
 */

static VALUE
proc_initgroups(obj, uname, base_grp)
    VALUE obj, uname, base_grp;
{
#ifdef HAVE_INITGROUPS
    if (initgroups(StringValuePtr(uname), (rb_gid_t)NUM2INT(base_grp)) != 0) {
        rb_sys_fail(0);
    }
    return proc_getgroups(obj);
#else
    rb_notimplement();
    return Qnil;
#endif
}


groups (Process)

/*
 *  call-seq:
 *     Process.groups   => array
 *
 *  Get an <code>Array</code> of the gids of groups in the
 *  supplemental group access list for this process.
 *
 *     Process.groups   #=> [27, 6, 10, 11]
 *
 */

static VALUE
proc_getgroups(VALUE obj)
{
#ifdef HAVE_GETGROUPS
    VALUE ary;
    size_t ngroups;
    rb_gid_t *groups;
    int i;

    groups = ALLOCA_N(rb_gid_t, maxgroups);

    ngroups = getgroups(maxgroups, groups);
    if (ngroups == -1)
        rb_sys_fail(0);

    ary = rb_ary_new();
    for (i = 0; i < ngroups; i++)
        rb_ary_push(ary, INT2NUM(groups[i]));

    return ary;
#else
    rb_notimplement();
    return Qnil;
#endif
}


groups= (Process)

/*
 *  call-seq:
 *     Process.groups= array   => array
 *
 *  Set the supplemental group access list to the given
 *  <code>Array</code> of group IDs.
 *
 *     Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
 *     Process.groups = [27, 6, 10, 11]   #=> [27, 6, 10, 11]
 *     Process.groups   #=> [27, 6, 10, 11]
 *
 */

static VALUE
proc_setgroups(VALUE obj, VALUE ary)
{
#ifdef HAVE_SETGROUPS
    size_t ngroups;
    rb_gid_t *groups;
    int i;
    struct group *gr;

    Check_Type(ary, T_ARRAY);

    ngroups = RARRAY(ary)->len;
    if (ngroups > maxgroups)
        rb_raise(rb_eArgError, "too many groups, %d max", maxgroups);

    groups = ALLOCA_N(rb_gid_t, ngroups);

    for (i = 0; i < ngroups && i < RARRAY(ary)->len; i++) {
        VALUE g = RARRAY(ary)->ptr[i];

        if (FIXNUM_P(g)) {
            groups[i] = FIX2INT(g);
        }
        else {
            VALUE tmp = rb_check_string_type(g);

            if (NIL_P(tmp)) {
                groups[i] = NUM2INT(g);
            }
            else {
                gr = getgrnam(RSTRING(tmp)->ptr);
                if (gr == NULL)
                    rb_raise(rb_eArgError,
                             "can't find group for %s", RSTRING(tmp)->ptr);
                groups[i] = gr->gr_gid;
            }
        }
    }

    i = setgroups(ngroups, groups);
    if (i == -1)
        rb_sys_fail(0);

    return proc_getgroups(obj);
#else
    rb_notimplement();
    return Qnil;
#endif
}


maxgroups (Process)

/*
 *  call-seq:
 *     Process.maxgroups   => fixnum
 *
 *  Returns the maximum number of gids allowed in the supplemental
 *  group access list.
 *
 *     Process.maxgroups   #=> 32
 */

static VALUE
proc_getmaxgroups(obj)
    VALUE obj;
{
    return INT2FIX(maxgroups);
}


maxgroups= (Process)

/*
 *  call-seq:
 *     Process.maxgroups= fixnum   => fixnum
 *
 *  Sets the maximum number of gids allowed in the supplemental group
 *  access list.
 */

static VALUE
proc_setmaxgroups(VALUE obj, VALUE val)
{
    size_t  ngroups = FIX2INT(val);

    if (ngroups > 4096)
        ngroups = 4096;

    maxgroups = ngroups;

    return INT2FIX(maxgroups);
}


times (Process)

/*
 *  call-seq:
 *     Process.times   => aStructTms
 *
 *  Returns a <code>Tms</code> structure (see <code>Struct::Tms</code>
 *  on page 388) that contains user and system CPU times for this
 *  process.
 *
 *     t = Process.times
 *     [ t.utime, t.stime ]   #=> [0.0, 0.02]
 */

VALUE
rb_proc_times(obj)
    VALUE obj;
{
#if defined(HAVE_TIMES) && !defined(__CHECKER__)
    const double hertz =
#ifdef HAVE__SC_CLK_TCK
        (double)sysconf(_SC_CLK_TCK);
#else
#ifndef HZ
# ifdef CLK_TCK
#   define HZ CLK_TCK
# else
#   define HZ 60
# endif
#endif /* HZ */
        HZ;
#endif
    struct tms buf;
    volatile VALUE utime, stime, cutime, sctime;

    times(&buf);
    return rb_struct_new(S_Tms,
                         utime = rb_float_new(buf.tms_utime / hertz),
                         stime = rb_float_new(buf.tms_stime / hertz),
                         cutime = rb_float_new(buf.tms_cutime / hertz),
                         sctime = rb_float_new(buf.tms_cstime / hertz));
#else
    rb_notimplement();
#endif
}


new (PStore)

# File lib/pstore.rb, line 94
  def initialize(file)
    dir = File::dirname(file)
    unless File::directory? dir
      raise PStore::Error, format("directory %s does not exist", dir)
    end
    if File::exist? file and not File::readable? file
      raise PStore::Error, format("file %s not readable", file)
    end
    @transaction = false
    @filename = file
    @abort = false
  end


[] (PStore)

# File lib/pstore.rb, line 128
  def [](name)
    in_transaction
    @table[name]
  end


fetch (PStore)

# File lib/pstore.rb, line 142
  def fetch(name, default=PStore::Error)
    in_transaction
    unless @table.key? name
      if default==PStore::Error
        raise PStore::Error, format("undefined root name `%s'", name)
      else
        return default
      end
    end
    @table[name]
  end


[]= (PStore)

# File lib/pstore.rb, line 173
  def []=(name, value)
    in_transaction_wr()
    @table[name] = value
  end


delete (PStore)

# File lib/pstore.rb, line 183
  def delete(name)
    in_transaction_wr()
    @table.delete name
  end


roots (PStore)

# File lib/pstore.rb, line 194
  def roots
    in_transaction
    @table.keys
  end


root? (PStore)

# File lib/pstore.rb, line 204
  def root?(name)
    in_transaction
    @table.key? name
  end


path (PStore)

# File lib/pstore.rb, line 209
  def path
    @filename
  end


commit (PStore)

# File lib/pstore.rb, line 235
  def commit
    in_transaction
    @abort = false
    throw :pstore_abort_transaction
  end


abort (PStore)

# File lib/pstore.rb, line 261
  def abort
    in_transaction
    @abort = true
    throw :pstore_abort_transaction
  end


transaction (PStore)

# File lib/pstore.rb, line 284
  def transaction(read_only=false)  # :yields:  pstore
    raise PStore::Error, "nested transaction" if @transaction
    begin
      @rdonly = read_only
      @abort = false
      @transaction = true
      value = nil
      new_file = @filename + ".new"

      content = nil
      unless read_only
        file = File.open(@filename, RDWR_ACCESS)
        file.flock(File::LOCK_EX)
        commit_new(file) if FileTest.exist?(new_file)
        content = file.read()
      else
        begin
          file = File.open(@filename, RD_ACCESS)
          file.flock(File::LOCK_SH)
          content = (File.open(new_file, RD_ACCESS) {|n| n.read} rescue file.read())
        rescue Errno::ENOENT
          content = ""
        end
      end

      if content != ""
        @table = load(content)
        if !read_only
          size = content.size
          md5 = Digest::MD5.digest(content)
        end
      else
        @table = {}
      end
      content = nil             # unreference huge data

      begin
        catch(:pstore_abort_transaction) do
          value = yield(self)
        end
      rescue Exception
        @abort = true
        raise
      ensure
        if !read_only and !@abort
          tmp_file = @filename + ".tmp"
          content = dump(@table)
          if !md5 || size != content.size || md5 != Digest::MD5.digest(content)
            File.open(tmp_file, WR_ACCESS) {|t| t.write(content)}
            File.rename(tmp_file, new_file)
            commit_new(file)
          end
          content = nil         # unreference huge data
        end
      end
    ensure
      @table = nil
      @transaction = false
      file.close if file
    end
    value
  end


new (Queue)

# File lib/thread.rb, line 266
  def initialize
    @que = []
    @waiting = []
    @que.taint          # enable tainted comunication
    @waiting.taint
    self.taint
  end


push (Queue)

# File lib/thread.rb, line 277
  def push(obj)
    Thread.critical = true
    @que.push obj
    begin
      t = @waiting.shift
      t.wakeup if t
    rescue ThreadError
      retry
    ensure
      Thread.critical = false
    end
    begin
      t.run if t
    rescue ThreadError
    end
  end


pop (Queue)

# File lib/thread.rb, line 309
  def pop(non_block=false)
    while (Thread.critical = true; @que.empty?)
      raise ThreadError, "queue empty" if non_block
      @waiting.push Thread.current
      Thread.stop
    end
    @que.shift
  ensure
    Thread.critical = false
  end


empty? (Queue)

# File lib/thread.rb, line 333
  def empty?
    @que.empty?
  end


clear (Queue)

# File lib/thread.rb, line 340
  def clear
    @que.clear
  end


length (Queue)

# File lib/thread.rb, line 347
  def length
    @que.length
  end


num_waiting (Queue)

# File lib/thread.rb, line 359
  def num_waiting
    @waiting.size
  end


racc_runtime_type (Racc::Parser)

# File lib/racc/parser.rb, line 62
    def Parser.racc_runtime_type
      Racc_Runtime_Type
    end


new (Range)

/*
 *  call-seq:
 *     Range.new(start, end, exclusive=false)    => range
 *
 *  Constructs a range using the given <i>start</i> and <i>end</i>. If the third
 *  parameter is omitted or is <code>false</code>, the <i>range</i> will include
 *  the end object; otherwise, it will be excluded.
 */

static VALUE
range_initialize(argc, argv, range)
    int argc;
    VALUE *argv;
    VALUE range;
{
    VALUE beg, end, flags;

    rb_scan_args(argc, argv, "21", &beg, &end, &flags);
    /* Ranges are immutable, so that they should be initialized only once. */
    if (rb_ivar_defined(range, id_beg)) {
        rb_name_error(rb_intern("initialize"), "`initialize' called twice");
    }
    range_init(range, beg, end, RTEST(flags));
    return Qnil;
}


== (Range)

/*
 *  call-seq:
 *     rng == obj    => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> is a Range, has equivalent
 *  beginning and end items (by comparing them with <code>==</code>), and has
 *  the same #exclude_end? setting as <i>rng</t>.
 *
 *    (0..2) == (0..2)            #=> true
 *    (0..2) == Range.new(0,2)    #=> true
 *    (0..2) == (0...2)           #=> false
 *
 */

static VALUE
range_eq(range, obj)
    VALUE range, obj;
{
    if (range == obj) return Qtrue;
    if (!rb_obj_is_instance_of(obj, rb_obj_class(range)))
        return Qfalse;

    if (!rb_equal(rb_ivar_get(range, id_beg), rb_ivar_get(obj, id_beg)))
        return Qfalse;
    if (!rb_equal(rb_ivar_get(range, id_end), rb_ivar_get(obj, id_end)))
        return Qfalse;

    if (EXCL(range) != EXCL(obj)) return Qfalse;

    return Qtrue;
}


=== (Range)

/*
 *  call-seq:
 *     rng === obj       =>  true or false
 *     rng.member?(val)  =>  true or false
 *     rng.include?(val) =>  true or false
 *
 *  Returns <code>true</code> if <i>obj</i> is an element of
 *  <i>rng</i>, <code>false</code> otherwise. Conveniently,
 *  <code>===</code> is the comparison operator used by
 *  <code>case</code> statements.
 *
 *     case 79
 *     when 1..50   then   print "low\n"
 *     when 51..75  then   print "medium\n"
 *     when 76..100 then   print "high\n"
 *     end
 *
 *  <em>produces:</em>
 *
 *     high
 */

static VALUE
range_include(range, val)
    VALUE range, val;
{
    VALUE beg, end;

    beg = rb_ivar_get(range, id_beg);
    end = rb_ivar_get(range, id_end);
    if (r_le(beg, val)) {
        if (EXCL(range)) {
            if (r_lt(val, end)) return Qtrue;
        }
        else {
            if (r_le(val, end)) return Qtrue;
        }
    }
    return Qfalse;
}


eql? (Range)

/*
 *  call-seq:
 *     rng.eql?(obj)    => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> is a Range, has equivalent
 *  beginning and end items (by comparing them with #eql?), and has the same
 *  #exclude_end? setting as <i>rng</i>.
 *
 *    (0..2) == (0..2)            #=> true
 *    (0..2) == Range.new(0,2)    #=> true
 *    (0..2) == (0...2)           #=> false
 *
 */

static VALUE
range_eql(range, obj)
    VALUE range, obj;
{
    if (range == obj) return Qtrue;
    if (!rb_obj_is_instance_of(obj, rb_obj_class(range)))
        return Qfalse;

    if (!rb_eql(rb_ivar_get(range, id_beg), rb_ivar_get(obj, id_beg)))
        return Qfalse;
    if (!rb_eql(rb_ivar_get(range, id_end), rb_ivar_get(obj, id_end)))
        return Qfalse;

    if (EXCL(range) != EXCL(obj)) return Qfalse;

    return Qtrue;
}


hash (Range)

/*
 * call-seq:
 *   rng.hash    => fixnum
 *
 * Generate a hash value such that two ranges with the same start and
 * end points, and the same value for the "exclude end" flag, generate
 * the same hash value.
 */

static VALUE
range_hash(range)
    VALUE range;
{
    long hash = EXCL(range);
    VALUE v;

    v = rb_hash(rb_ivar_get(range, id_beg));
    hash ^= v << 1;
    v = rb_hash(rb_ivar_get(range, id_end));
    hash ^= v << 9;
    hash ^= EXCL(range) << 24;

    return LONG2FIX(hash);
}


each (Range)

/*
 *  call-seq:
 *     rng.each {| i | block } => rng
 *
 *  Iterates over the elements <i>rng</i>, passing each in turn to the
 *  block. You can only iterate if the start object of the range
 *  supports the +succ+ method (which means that you can't iterate over
 *  ranges of +Float+ objects).
 *
 *     (10..15).each do |n|
 *        print n, ' '
 *     end
 *
 *  <em>produces:</em>
 *
 *     10 11 12 13 14 15
 */

static VALUE
range_each(range)
    VALUE range;
{
    VALUE beg, end;

    beg = rb_ivar_get(range, id_beg);
    end = rb_ivar_get(range, id_end);

    if (!rb_respond_to(beg, id_succ)) {
        rb_raise(rb_eTypeError, "can't iterate from %s",
                 rb_obj_classname(beg));
    }
    if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
        long lim = FIX2LONG(end);
        long i;

        if (!EXCL(range)) lim += 1;
        for (i=FIX2LONG(beg); i<lim; i++) {
            rb_yield(LONG2NUM(i));
        }
    }
    else if (TYPE(beg) == T_STRING) {
        VALUE args[5];
        long iter[2];

        args[0] = beg; args[1] = end; args[2] = range;
        iter[0] = 1; iter[1] = 1;
        rb_iterate((VALUE(*)_((VALUE)))str_step, (VALUE)args, step_i,
                   (VALUE)iter);
    }
    else {
        range_each_func(range, each_i, beg, end, NULL);
    }
    return range;
}


step (Range)

/*
 *  call-seq:
 *     rng.step(n=1) {| obj | block }    => rng
 *
 *  Iterates over <i>rng</i>, passing each <i>n</i>th element to the block. If
 *  the range contains numbers or strings, natural ordering is used.  Otherwise
 *  <code>step</code> invokes <code>succ</code> to iterate through range
 *  elements. The following code uses class <code>Xs</code>, which is defined
 *  in the class-level documentation.
 *
 *     range = Xs.new(1)..Xs.new(10)
 *     range.step(2) {|x| puts x}
 *     range.step(3) {|x| puts x}
 *
 *  <em>produces:</em>
 *
 *      1 x
 *      3 xxx
 *      5 xxxxx
 *      7 xxxxxxx
 *      9 xxxxxxxxx
 *      1 x
 *      4 xxxx
 *      7 xxxxxxx
 *     10 xxxxxxxxxx
 */

static VALUE
range_step(argc, argv, range)
    int argc;
    VALUE *argv;
    VALUE range;
{
    VALUE b, e, step;
    long unit;

    b = rb_ivar_get(range, id_beg);
    e = rb_ivar_get(range, id_end);
    if (rb_scan_args(argc, argv, "01", &step) == 0) {
        step = INT2FIX(1);
    }

    unit = NUM2LONG(step);
    if (unit < 0) {
        rb_raise(rb_eArgError, "step can't be negative");
    }
    if (FIXNUM_P(b) && FIXNUM_P(e)) { /* fixnums are special */
        long end = FIX2LONG(e);
        long i;

        if (unit == 0) rb_raise(rb_eArgError, "step can't be 0");
        if (!EXCL(range)) end += 1;
        i = FIX2LONG(b);
        while (i < end) {
            rb_yield(LONG2NUM(i));
            if (i + unit < i) break;
            i += unit;
        }
    }
    else {
        VALUE tmp = rb_check_string_type(b);

        if (!NIL_P(tmp)) {
            VALUE args[5];
            long iter[2];

            b = tmp;
            if (unit == 0) rb_raise(rb_eArgError, "step can't be 0");
            args[0] = b; args[1] = e; args[2] = range;
            iter[0] = 1; iter[1] = unit;
            rb_iterate((VALUE(*)_((VALUE)))str_step, (VALUE)args, step_i,
                        (VALUE)iter);
        }
        else if (rb_obj_is_kind_of(b, rb_cNumeric)) {
            ID c = rb_intern(EXCL(range) ? "<" : "<=");

            if (rb_equal(step, INT2FIX(0))) rb_raise(rb_eArgError, "step can't be 0");
            while (RTEST(rb_funcall(b, c, 1, e))) {
                rb_yield(b);
                b = rb_funcall(b, '+', 1, step);
            }
        }
        else {
            long args[2];

            if (unit == 0) rb_raise(rb_eArgError, "step can't be 0");
            if (!rb_respond_to(b, id_succ)) {
                rb_raise(rb_eTypeError, "can't iterate from %s",
                         rb_obj_classname(b));
            }

            args[0] = 1;
            args[1] = unit;
            range_each_func(range, step_i, b, e, args);
        }
    }
    return range;
}


first (Range)

/*
 *  call-seq:
 *     rng.first    => obj
 *     rng.begin    => obj
 *
 *  Returns the first object in <i>rng</i>.
 */

static VALUE
range_first(range)
    VALUE range;
{
    return rb_ivar_get(range, id_beg);
}


last (Range)

/*
 *  call-seq:
 *     rng.end    => obj
 *     rng.last   => obj
 *
 *  Returns the object that defines the end of <i>rng</i>.
 *
 *     (1..10).end    #=> 10
 *     (1...10).end   #=> 10
 */

static VALUE
range_last(range)
    VALUE range;
{
    return rb_ivar_get(range, id_end);
}


begin (Range)

/*
 *  call-seq:
 *     rng.first    => obj
 *     rng.begin    => obj
 *
 *  Returns the first object in <i>rng</i>.
 */

static VALUE
range_first(range)
    VALUE range;
{
    return rb_ivar_get(range, id_beg);
}


end (Range)

/*
 *  call-seq:
 *     rng.end    => obj
 *     rng.last   => obj
 *
 *  Returns the object that defines the end of <i>rng</i>.
 *
 *     (1..10).end    #=> 10
 *     (1...10).end   #=> 10
 */

static VALUE
range_last(range)
    VALUE range;
{
    return rb_ivar_get(range, id_end);
}


to_s (Range)

/*
 * call-seq:
 *   rng.to_s   => string
 *
 * Convert this range object to a printable form.
 */

static VALUE
range_to_s(range)
    VALUE range;
{
    VALUE str, str2;

    str = rb_obj_as_string(rb_ivar_get(range, id_beg));
    str2 = rb_obj_as_string(rb_ivar_get(range, id_end));
    str = rb_str_dup(str);
    rb_str_cat(str, "...", EXCL(range)?3:2);
    rb_str_append(str, str2);
    OBJ_INFECT(str, str2);

    return str;
}


inspect (Range)

/*
 * call-seq:
 *   rng.inspect  => string
 *
 * Convert this range object to a printable form (using
 * <code>inspect</code> to convert the start and end
 * objects).
 */

static VALUE
range_inspect(range)
    VALUE range;
{
    VALUE str, str2;

    str = rb_inspect(rb_ivar_get(range, id_beg));
    str2 = rb_inspect(rb_ivar_get(range, id_end));
    str = rb_str_dup(str);
    rb_str_cat(str, "...", EXCL(range)?3:2);
    rb_str_append(str, str2);
    OBJ_INFECT(str, str2);

    return str;
}


exclude_end? (Range)

/*
 *  call-seq:
 *     rng.exclude_end?    => true or false
 *
 *  Returns <code>true</code> if <i>rng</i> excludes its end value.
 */

static VALUE
range_exclude_end_p(range)
    VALUE range;
{
    return EXCL(range) ? Qtrue : Qfalse;
}


member? (Range)

/*
 *  call-seq:
 *     rng === obj       =>  true or false
 *     rng.member?(val)  =>  true or false
 *     rng.include?(val) =>  true or false
 *
 *  Returns <code>true</code> if <i>obj</i> is an element of
 *  <i>rng</i>, <code>false</code> otherwise. Conveniently,
 *  <code>===</code> is the comparison operator used by
 *  <code>case</code> statements.
 *
 *     case 79
 *     when 1..50   then   print "low\n"
 *     when 51..75  then   print "medium\n"
 *     when 76..100 then   print "high\n"
 *     end
 *
 *  <em>produces:</em>
 *
 *     high
 */

static VALUE
range_include(range, val)
    VALUE range, val;
{
    VALUE beg, end;

    beg = rb_ivar_get(range, id_beg);
    end = rb_ivar_get(range, id_end);
    if (r_le(beg, val)) {
        if (EXCL(range)) {
            if (r_lt(val, end)) return Qtrue;
        }
        else {
            if (r_le(val, end)) return Qtrue;
        }
    }
    return Qfalse;
}


include? (Range)

/*
 *  call-seq:
 *     rng === obj       =>  true or false
 *     rng.member?(val)  =>  true or false
 *     rng.include?(val) =>  true or false
 *
 *  Returns <code>true</code> if <i>obj</i> is an element of
 *  <i>rng</i>, <code>false</code> otherwise. Conveniently,
 *  <code>===</code> is the comparison operator used by
 *  <code>case</code> statements.
 *
 *     case 79
 *     when 1..50   then   print "low\n"
 *     when 51..75  then   print "medium\n"
 *     when 76..100 then   print "high\n"
 *     end
 *
 *  <em>produces:</em>
 *
 *     high
 */

static VALUE
range_include(range, val)
    VALUE range, val;
{
    VALUE beg, end;

    beg = rb_ivar_get(range, id_beg);
    end = rb_ivar_get(range, id_end);
    if (r_le(beg, val)) {
        if (EXCL(range)) {
            if (r_lt(val, end)) return Qtrue;
        }
        else {
            if (r_le(val, end)) return Qtrue;
        }
    }
    return Qfalse;
}


pretty_print (Range)

# File lib/pp.rb, line 351
  def pretty_print(q)
    q.pp self.begin
    q.breakable ''
    q.text(self.exclude_end? ? '...' : '..')
    q.breakable ''
    q.pp self.end
  end


yaml_new (Range)

# File lib/yaml/rubytypes.rb, line 201
    def Range.yaml_new( klass, tag, val )
        inr = %r'(\w+|[+-]?\d+(?:\.\d+)?(?:e[+-]\d+)?|"(?:[^\\"]|\\.)*")'
        opts = {}
        if String === val and val =~ /^#{inr}(\.{2,3})#{inr}$/o
            r1, rdots, r2 = $1, $2, $3
            opts = {
                'begin' => YAML.load( "--- #{r1}" ),
                'end' => YAML.load( "--- #{r2}" ),
                'excl' => rdots.length == 3
            }
            val = {}
        elsif Hash === val
            opts['begin'] = val.delete('begin')
            opts['end'] = val.delete('end')
            opts['excl'] = val.delete('excl')
        end
        if Hash === opts
            r = YAML::object_maker( klass, {} )
            # Thank you, NaHi
            Range.instance_method(:initialize).
                  bind(r).
                  call( opts['begin'], opts['end'], opts['excl'] )
            val.each { |k,v| r.instance_variable_set( k, v ) }
            r
        else
            raise YAML::TypeError, "Invalid Range: " + val.inspect
        end
    end


to_yaml (Range)

# File lib/yaml/rubytypes.rb, line 229
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            # if self.begin.is_complex_yaml? or self.begin.respond_to? :to_str or
            #   self.end.is_complex_yaml? or self.end.respond_to? :to_str or
            #   not to_yaml_properties.empty?
                out.map( taguri, to_yaml_style ) do |map|
                    map.add( 'begin', self.begin )
                    map.add( 'end', self.end )
                    map.add( 'excl', self.exclude_end? )
                    to_yaml_properties.each do |m|
                        map.add( m, instance_variable_get( m ) )
                    end
                end
            # else
            #     out.scalar( taguri ) do |sc|
            #         sc.embed( self.begin )
            #         sc.concat( self.exclude_end? ? "..." : ".." )
            #         sc.embed( self.end )
            #     end
            # end
        end
        end


inspect (Rational)

# File lib/mathn.rb, line 120
  def inspect
    format "%s/%s", numerator.inspect, denominator.inspect
  end


** (Rational)

# File lib/mathn.rb, line 126
  def ** (other)
    if other.kind_of?(Rational)
      other2 = other
      if self < 0
        return Complex.new!(self, 0) ** other
      elsif other == 0
        return Rational(1,1)
      elsif self == 0
        return Rational(0,1)
      elsif self == 1
        return Rational(1,1)
      end

      npd = numerator.prime_division
      dpd = denominator.prime_division
      if other < 0
        other = -other
        npd, dpd = dpd, npd
      end

      for elm in npd
        elm[1] = elm[1] * other
        if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
         return Float(self) ** other2
        end
        elm[1] = elm[1].to_i
      end

      for elm in dpd
        elm[1] = elm[1] * other
        if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
         return Float(self) ** other2
        end
        elm[1] = elm[1].to_i
      end

      num = Integer.from_prime_division(npd)
      den = Integer.from_prime_division(dpd)

      Rational(num,den)

    elsif other.kind_of?(Integer)
      if other > 0
        num = numerator ** other
        den = denominator ** other
      elsif other < 0
        num = denominator ** -other
        den = numerator ** -other
      elsif other == 0
        num = 1
        den = 1
      end
      Rational.new!(num, den)
    elsif other.kind_of?(Float)
      Float(self) ** other
    else
      x , y = other.coerce(self)
      x ** y
    end
  end


power2 (Rational)

# File lib/mathn.rb, line 187
  def power2(other)
    if other.kind_of?(Rational)
      if self < 0
        return Complex(self, 0) ** other
      elsif other == 0
        return Rational(1,1)
      elsif self == 0
        return Rational(0,1)
      elsif self == 1
        return Rational(1,1)
      end

      dem = nil
      x = self.denominator.to_f.to_i
      neard = self.denominator.to_f ** (1.0/other.denominator.to_f)
      loop do
        if (neard**other.denominator == self.denominator)
          dem = neaed
          break
        end
      end
      nearn = self.numerator.to_f ** (1.0/other.denominator.to_f)
      Rational(num,den)

    elsif other.kind_of?(Integer)
      if other > 0
        num = numerator ** other
        den = denominator ** other
      elsif other < 0
        num = denominator ** -other
        den = numerator ** -other
      elsif other == 0
        num = 1
        den = 1
      end
      Rational.new!(num, den)
    elsif other.kind_of?(Float)
      Float(self) ** other
    else
      x , y = other.coerce(self)
      x ** y
    end
  end


reduce (Rational)

# File lib/rational.rb, line 71
  def Rational.reduce(num, den = 1)
    raise ZeroDivisionError, "denominator is zero" if den == 0

    if den < 0
      num = -num
      den = -den
    end
    gcd = num.gcd(den)
    num = num.div(gcd)
    den = den.div(gcd)
    if den == 1 && defined?(Unify)
      num
    else
      new!(num, den)
    end
  end


new! (Rational)

# File lib/rational.rb, line 93
  def Rational.new!(num, den = 1)
    new(num, den)
  end


new (Rational)

# File lib/rational.rb, line 102
  def initialize(num, den)
    if den < 0
      num = -num
      den = -den
    end
    if num.kind_of?(Integer) and den.kind_of?(Integer)
      @numerator = num
      @denominator = den
    else
      @numerator = num.to_i
      @denominator = den.to_i
    end
  end


+ (Rational)

# File lib/rational.rb, line 124
  def + (a)
    if a.kind_of?(Rational)
      num = @numerator * a.denominator
      num_a = a.numerator * @denominator
      Rational(num + num_a, @denominator * a.denominator)
    elsif a.kind_of?(Integer)
      self + Rational.new!(a, 1)
    elsif a.kind_of?(Float)
      Float(self) + a
    else
      x, y = a.coerce(self)
      x + y
    end
  end


- (Rational)

# File lib/rational.rb, line 148
  def - (a)
    if a.kind_of?(Rational)
      num = @numerator * a.denominator
      num_a = a.numerator * @denominator
      Rational(num - num_a, @denominator*a.denominator)
    elsif a.kind_of?(Integer)
      self - Rational.new!(a, 1)
    elsif a.kind_of?(Float)
      Float(self) - a
    else
      x, y = a.coerce(self)
      x - y
    end
  end


* (Rational)

# File lib/rational.rb, line 173
  def * (a)
    if a.kind_of?(Rational)
      num = @numerator * a.numerator
      den = @denominator * a.denominator
      Rational(num, den)
    elsif a.kind_of?(Integer)
      self * Rational.new!(a, 1)
    elsif a.kind_of?(Float)
      Float(self) * a
    else
      x, y = a.coerce(self)
      x * y
    end
  end


/ (Rational)

# File lib/rational.rb, line 195
  def / (a)
    if a.kind_of?(Rational)
      num = @numerator * a.denominator
      den = @denominator * a.numerator
      Rational(num, den)
    elsif a.kind_of?(Integer)
      raise ZeroDivisionError, "division by zero" if a == 0
      self / Rational.new!(a, 1)
    elsif a.kind_of?(Float)
      Float(self) / a
    else
      x, y = a.coerce(self)
      x / y
    end
  end


** (Rational)

# File lib/rational.rb, line 220
  def ** (other)
    if other.kind_of?(Rational)
      Float(self) ** other
    elsif other.kind_of?(Integer)
      if other > 0
        num = @numerator ** other
        den = @denominator ** other
      elsif other < 0
        num = @denominator ** -other
        den = @numerator ** -other
      elsif other == 0
        num = 1
        den = 1
      end
      Rational.new!(num, den)
    elsif other.kind_of?(Float)
      Float(self) ** other
    else
      x, y = other.coerce(self)
      x ** y
    end
  end


% (Rational)

# File lib/rational.rb, line 253
  def % (other)
    value = (self / other).to_i
    return self - other * value
  end


divmod (Rational)

# File lib/rational.rb, line 265
  def divmod(other)
    value = (self / other).to_i
    return value, self - other * value
  end


abs (Rational)

# File lib/rational.rb, line 273
  def abs
    if @numerator > 0
      Rational.new!(@numerator, @denominator)
    else
      Rational.new!(-@numerator, @denominator)
    end
  end


== (Rational)

# File lib/rational.rb, line 290
  def == (other)
    if other.kind_of?(Rational)
      @numerator == other.numerator and @denominator == other.denominator
    elsif other.kind_of?(Integer)
      self == Rational.new!(other, 1)
    elsif other.kind_of?(Float)
      Float(self) == other
    else
      other == self
    end
  end


<=> (Rational)

# File lib/rational.rb, line 305
  def <=> (other)
    if other.kind_of?(Rational)
      num = @numerator * other.denominator
      num_a = other.numerator * @denominator
      v = num - num_a
      if v > 0
        return 1
      elsif v < 0
        return  -1
      else
        return 0
      end
    elsif other.kind_of?(Integer)
      return self <=> Rational.new!(other, 1)
    elsif other.kind_of?(Float)
      return Float(self) <=> other
    elsif defined? other.coerce
      x, y = other.coerce(self)
      return x <=> y
    else
      return nil
    end
  end


coerce (Rational)

# File lib/rational.rb, line 329
  def coerce(other)
    if other.kind_of?(Float)
      return other, self.to_f
    elsif other.kind_of?(Integer)
      return Rational.new!(other, 1), self
    else
      super
    end
  end


to_i (Rational)

# File lib/rational.rb, line 350
  def to_i
    Integer(@numerator.div(@denominator))
  end


to_f (Rational)

# File lib/rational.rb, line 357
  def to_f
    @numerator.to_f/@denominator.to_f
  end


to_s (Rational)

# File lib/rational.rb, line 368
  def to_s
    if @denominator == 1
      @numerator.to_s
    else
      @numerator.to_s+"/"+@denominator.to_s
    end
  end


to_r (Rational)

# File lib/rational.rb, line 379
  def to_r
    self
  end


inspect (Rational)

# File lib/rational.rb, line 388
  def inspect
    sprintf("Rational(%s, %s)", @numerator.inspect, @denominator.inspect)
  end


hash (Rational)

# File lib/rational.rb, line 395
  def hash
    @numerator.hash ^ @denominator.hash
  end


new (RDoc::Alias)

# File lib/rdoc/code_objects.rb, line 693
    def initialize(text, old_name, new_name, comment)
      super()
      @text = text
      @old_name = old_name
      @new_name = new_name
      self.comment = comment
    end


to_s (RDoc::Alias)

# File lib/rdoc/code_objects.rb, line 701
    def to_s
      "alias: #{self.old_name} ->  #{self.new_name}\n#{self.comment}"
    end


new (RDoc::AnyMethod)

# File lib/rdoc/code_objects.rb, line 636
    def initialize(text, name)
      super()
      @text = text
      @name = name
      @token_stream  = nil
      @visibility    = :public
      @dont_rename_initialize = false
      @block_params  = nil
      @aliases       = []
      @is_alias_for  = nil
      @comment = ""
      @call_seq = nil
    end


<=> (RDoc::AnyMethod)

# File lib/rdoc/code_objects.rb, line 650
    def <=>(other)
      @name <=> other.name
    end


to_s (RDoc::AnyMethod)

# File lib/rdoc/code_objects.rb, line 654
    def to_s
      res = self.class.name + ": " + @name + " (" + @text + ")\n"
      res << @comment.to_s
      res
    end


param_seq (RDoc::AnyMethod)

# File lib/rdoc/code_objects.rb, line 660
    def param_seq
      p = params.gsub(/\s*\#.*/, '')
      p = p.tr("\n", " ").squeeze(" ")
      p = "(" + p + ")" unless p[0] == ?(

      if (block = block_params)
        # If this method has explicit block parameters, remove any
        # explicit &block
$stderr.puts p
        p.sub!(/,?\s*&\w+/)
$stderr.puts p

        block.gsub!(/\s*\#.*/, '')
        block = block.tr("\n", " ").squeeze(" ")
        if block[0] == ?(
          block.sub!(/^\(/, '').sub!(/\)/, '')
        end
        p << " {|#{block}| ...}"
      end
      p
    end


add_alias (RDoc::AnyMethod)

# File lib/rdoc/code_objects.rb, line 682
    def add_alias(method)
      @aliases << method
    end


new (RDoc::Attr)

# File lib/rdoc/code_objects.rb, line 722
    def initialize(text, name, rw, comment)
      super()
      @text = text
      @name = name
      @rw = rw
      @visibility = :public
      self.comment = comment
    end


to_s (RDoc::Attr)

# File lib/rdoc/code_objects.rb, line 731
    def to_s
      "attr: #{self.name} #{self.rw}\n#{self.comment}"
    end


<=> (RDoc::Attr)

# File lib/rdoc/code_objects.rb, line 735
    def <=>(other)
      self.name <=> other.name
    end


new (RDoc::C_Parser)

# File lib/rdoc/parsers/parse_c.rb, line 177
    def initialize(top_level, file_name, body, options, stats)
      @known_classes = KNOWN_CLASSES.dup
      @body = handle_tab_width(handle_ifdefs_in(body))
      @options = options
      @stats   = stats
      @top_level = top_level
      @classes = Hash.new
      @file_dir = File.dirname(file_name)
      @progress = $stderr unless options.quiet
    end


scan (RDoc::C_Parser)

# File lib/rdoc/parsers/parse_c.rb, line 190
    def scan
      remove_commented_out_lines
      do_classes
      do_constants
      do_methods
      do_includes
      do_aliases
      @top_level
    end


new (RDoc::ClassModule)

# File lib/rdoc/code_objects.rb, line 556
    def initialize(name, superclass = nil)
      @name       = name
      @diagram    = nil
      @superclass = superclass
      @comment    = ""
      super()
    end


full_name (RDoc::ClassModule)

# File lib/rdoc/code_objects.rb, line 565
    def full_name
      if @parent && @parent.full_name
        @parent.full_name + "::" + @name
      else
        @name
      end
    end


http_url (RDoc::ClassModule)

# File lib/rdoc/code_objects.rb, line 573
    def http_url(prefix)
      path = full_name.split("::")
      File.join(prefix, *path) + ".html"
    end


is_module? (RDoc::ClassModule)

# File lib/rdoc/code_objects.rb, line 579
    def is_module?
      false
    end


to_s (RDoc::ClassModule)

# File lib/rdoc/code_objects.rb, line 584
    def to_s
      res = self.class.name + ": " + @name
      res << @comment.to_s
      res << super
      res
    end


find_class_named (RDoc::ClassModule)

# File lib/rdoc/code_objects.rb, line 591
    def find_class_named(name)
      return self if full_name == name
      @classes.each_value {|c| return c if c.find_class_named(name) }
      nil
    end


document_self= (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 34
    def document_self=(val)
      @document_self = val
      if !val
        remove_methods_etc
      end
    end


start_doc (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 43
    def start_doc
      @document_self = true
      @document_children = true
    end


stop_doc (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 48
    def stop_doc
      @document_self = false
      @document_children = false
    end


document_children= (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 57
    def document_children=(val)
      @document_children = val
      if !val
        remove_classes_and_modules
      end
    end


remove_classes_and_modules (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 69
    def remove_classes_and_modules
    end


remove_methods_etc (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 72
    def remove_methods_etc
    end


new (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 75
    def initialize
      @document_self = true
      @document_children = true
      @force_documentation = false
      @done_documenting = false
    end


comment= (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 87
    def comment=(comment)
      @comment = comment unless comment.empty?
    end


attr_overridable (RDoc::CodeObject)

# File lib/rdoc/code_objects.rb, line 97
    def CodeObject.attr_overridable(name, *aliases)
      @overridables ||= {}

      attr_accessor name

      aliases.unshift name
      aliases.each do |directive_name|
        @overridables[directive_name.to_s] = name
      end
    end


new (RDoc::Constant)

# File lib/rdoc/code_objects.rb, line 710
    def initialize(name, value, comment)
      super()
      @name = name
      @value = value
      self.comment = comment
    end


new (RDoc::Context::Section)

# File lib/rdoc/code_objects.rb, line 125
      def initialize(title, comment)
        @title = title
        @@sequence.succ!
        @sequence = @@sequence.dup
        set_comment(comment)
      end


new (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 163
    def initialize
      super()

      @in_files    = []

      @name    ||= "unknown"
      @comment ||= ""
      @parent  = nil
      @visibility = :public

      @current_section = Section.new(nil, nil)
      @sections = [ @current_section ]

      initialize_methods_etc
      initialize_classes_and_modules
    end


classes (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 181
    def classes
      @classes.values
    end


modules (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 186
    def modules
      @modules.values
    end


ongoing_visibility= (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 191
    def ongoing_visibility=(vis)
      @visibility = vis
    end


set_visibility_for (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 198
    def set_visibility_for(methods, vis, singleton=false)
      count = 0
      @method_list.each do |m|
        if methods.include?(m.name) && m.singleton == singleton
          m.visibility = vis
          count += 1
        end
      end

      return if count == methods.size || singleton

      # perhaps we need to look at attributes

      @attributes.each do |a|
        if methods.include?(a.name)
          a.visibility = vis
          count += 1
        end
      end
    end


record_location (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 220
    def record_location(toplevel)
      @in_files << toplevel unless @in_files.include?(toplevel)
    end


defined_in? (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 225
    def defined_in?(file)
      @in_files.include?(file)
    end


add_class (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 229
    def add_class(class_type, name, superclass)
      add_class_or_module(@classes, class_type, name, superclass)
    end


add_module (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 233
    def add_module(class_type, name)
      add_class_or_module(@modules, class_type, name, nil)
    end


add_method (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 237
    def add_method(a_method)
      puts "Adding #@visibility method #{a_method.name} to #@name" if $DEBUG
      a_method.visibility = @visibility
      add_to(@method_list, a_method)
    end


add_attribute (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 243
    def add_attribute(an_attribute)
      add_to(@attributes, an_attribute)
    end


add_alias (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 247
    def add_alias(an_alias)
      meth = find_instance_method_named(an_alias.old_name)
      if meth
        new_meth = AnyMethod.new(an_alias.text, an_alias.new_name)
        new_meth.is_alias_for = meth
        new_meth.singleton    = meth.singleton
        new_meth.params       = meth.params
        new_meth.comment = "Alias for \##{meth.name}"
        meth.add_alias(new_meth)
        add_method(new_meth)
      else
        add_to(@aliases, an_alias)
      end
    end


add_include (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 262
    def add_include(an_include)
      add_to(@includes, an_include)
    end


add_constant (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 266
    def add_constant(const)
      add_to(@constants, const)
    end


add_require (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 271
    def add_require(a_require)
      if self.kind_of? TopLevel
        add_to(@requires, a_require)
      else
        parent.add_require(a_require)
      end
    end


add_class_or_module (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 279
    def add_class_or_module(collection, class_type, name, superclass=nil)
      cls = collection[name]
      if cls
        puts "Reusing class/module #{name}" if $DEBUG
      else
        cls = class_type.new(name, superclass)
        puts "Adding class/module #{name} to #@name" if $DEBUG
#        collection[name] = cls if @document_self  && !@done_documenting
        collection[name] = cls if !@done_documenting
        cls.parent = self
        cls.section = @current_section
      end
      cls
    end


add_to (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 294
    def add_to(array, thing)
      array <<  thing if @document_self  && !@done_documenting
      thing.parent = self
      thing.section = @current_section
    end


remove_methods_etc (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 304
    def remove_methods_etc
      initialize_methods_etc
    end


initialize_methods_etc (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 308
    def initialize_methods_etc
      @method_list = []
      @attributes  = []
      @aliases     = []
      @requires    = []
      @includes    = []
      @constants   = []
    end


remove_classes_and_modules (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 318
    def remove_classes_and_modules
      initialize_classes_and_modules
    end


initialize_classes_and_modules (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 322
    def initialize_classes_and_modules
      @classes     = {}
      @modules     = {}
    end


find_module_named (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 328
    def find_module_named(name)
      return self if self.name == name
      res = @modules[name] || @classes[name]
      return res if res
      find_enclosing_module_named(name)
    end


find_enclosing_module_named (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 336
    def find_enclosing_module_named(name)
      parent && parent.find_module_named(name)
    end


each_classmodule (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 343
    def each_classmodule
      @modules.each_value {|m| yield m}
      @classes.each_value {|c| yield c}
    end


each_method (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 348
    def each_method
      @method_list.each {|m| yield m}
    end


each_attribute (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 352
    def each_attribute
      @attributes.each {|a| yield a}
    end


each_constant (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 356
    def each_constant
      @constants.each {|c| yield c}
    end


toplevel (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 362
    def toplevel
      return @toplevel if defined? @toplevel
      @toplevel = self
      @toplevel = @toplevel.parent until TopLevel === @toplevel
      @toplevel
    end


<=> (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 370
    def <=>(other)
      name <=> other.name
    end


find_symbol (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 377
    def find_symbol(symbol, method=nil)
      result = nil
      case symbol
      when /^::(.*)/
        result = toplevel.find_symbol($1)
      when /::/
        modules = symbol.split(/::/)
        unless modules.empty?
          module_name = modules.shift
          result = find_module_named(module_name)
          if result
            modules.each do |module_name|
              result = result.find_module_named(module_name)
              break unless result
            end
          end
        end
      else
        # if a method is specified, then we're definitely looking for
        # a module, otherwise it could be any symbol
        if method
          result = find_module_named(symbol)
        else
          result = find_local_symbol(symbol)
          if result.nil?
            if symbol =~ /^[A-Z]/
              result = parent
              while result && result.name != symbol
                result = result.parent
              end
            end
          end
        end
      end
      if result && method
        if !result.respond_to?(:find_local_symbol)
          p result.name
          p method
          fail
        end
        result = result.find_local_symbol(method)
      end
      result
    end


find_local_symbol (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 422
    def find_local_symbol(symbol)
      res = find_method_named(symbol) ||
            find_constant_named(symbol) ||
            find_attribute_named(symbol) ||
            find_module_named(symbol)
    end


set_current_section (RDoc::Context)

# File lib/rdoc/code_objects.rb, line 431
    def set_current_section(title, comment)
      @current_section = Section.new(title, comment)
      @sections << @current_section
    end


new (RDoc::Diagram)

# File lib/rdoc/diagram.rb, line 36
    def initialize(info, options)
      @info = info
      @options = options
      @counter = 0
      File.makedirs(DOT_PATH)
      @diagram_cache = {}
    end


draw (RDoc::Diagram)

# File lib/rdoc/diagram.rb, line 48
    def draw
      unless @options.quiet
        $stderr.print "Diagrams: "
        $stderr.flush
      end

      @info.each_with_index do |i, file_count|
        @done_modules = {}
        @local_names = find_names(i)
        @global_names = []
        @global_graph = graph = DOT::DOTDigraph.new('name' => 'TopLevel',
                                    'fontname' => FONT,
                                    'fontsize' => '8',
                                    'bgcolor'  => 'lightcyan1',
                                    'compound' => 'true')

        # it's a little hack %) i'm too lazy to create a separate class
        # for default node
        graph << DOT::DOTNode.new('name' => 'node',
                                  'fontname' => FONT,
                                  'color' => 'black',
                                  'fontsize' => 8)

        i.modules.each do |mod|
          draw_module(mod, graph, true, i.file_relative_name)
        end
        add_classes(i, graph, i.file_relative_name)

        i.diagram = convert_to_png("f_#{file_count}", graph)

        # now go through and document each top level class and
        # module independently
        i.modules.each_with_index do |mod, count|
          @done_modules = {}
          @local_names = find_names(mod)
          @global_names = []

          @global_graph = graph = DOT::DOTDigraph.new('name' => 'TopLevel',
                                      'fontname' => FONT,
                                      'fontsize' => '8',
                                      'bgcolor'  => 'lightcyan1',
                                      'compound' => 'true')

          graph << DOT::DOTNode.new('name' => 'node',
                                    'fontname' => FONT,
                                    'color' => 'black',
                                    'fontsize' => 8)
          draw_module(mod, graph, true)
          mod.diagram = convert_to_png("m_#{file_count}_#{count}",
                                       graph)
        end
      end
      $stderr.puts unless @options.quiet
    end


new (RDoc::Fortran95parser::Fortran95Definition)

# File lib/rdoc/parsers/parse_f95.rb, line 1673
      def initialize(varname, types, inivalue, arraysuffix, comment,
                     nodoc=false)
        @varname = varname
        @types = types
        @inivalue = inivalue
        @arraysuffix = arraysuffix
        @comment = comment
        @nodoc = nodoc
      end


to_s (RDoc::Fortran95parser::Fortran95Definition)

# File lib/rdoc/parsers/parse_f95.rb, line 1683
      def to_s
        return "<Fortran95Definition:\nvarname=\#{@varname}, types=\#{types},\ninivalue=\#{@inivalue}, arraysuffix=\#{@arraysuffix}, nodoc=\#{@nodoc},\ncomment=\n\#{@comment}\n>\n"
      end


include_attr? (RDoc::Fortran95parser::Fortran95Definition)

# File lib/rdoc/parsers/parse_f95.rb, line 1698
      def include_attr?(attr)
        return if !attr
        @types.split(",").each{ |type|
          return true if type.strip.chomp.upcase == attr.strip.chomp.upcase
        }
        return nil
      end


new (RDoc::Fortran95parser)

# File lib/rdoc/parsers/parse_f95.rb, line 195
    def initialize(top_level, file_name, body, options, stats)
      @body = body
      @stats = stats
      @file_name  = file_name
      @options = options
      @top_level = top_level
      @progress = $stderr unless options.quiet
    end


scan (RDoc::Fortran95parser)

# File lib/rdoc/parsers/parse_f95.rb, line 205
    def scan

      # remove private comment
      remaining_code = remove_private_comments(@body)

      # continuation lines are united to one line
      remaining_code = united_to_one_line(remaining_code)

      # semicolons are replaced to line feed
      remaining_code = semicolon_to_linefeed(remaining_code)

      # collect comment for file entity
      whole_comment, remaining_code = collect_first_comment(remaining_code)
      @top_level.comment = whole_comment

      # String "remaining_code" is converted to Array "remaining_lines"
      remaining_lines = remaining_code.split("\n")

      # "module" or "program" parts are parsed (new)
      #
      level_depth = 0
      block_searching_flag = nil
      block_searching_lines = []
      pre_comment = []
      module_program_trailing = ""
      module_program_name = ""
      other_block_level_depth = 0
      other_block_searching_flag = nil
      remaining_lines.collect!{|line|
        if !block_searching_flag && !other_block_searching_flag
          if line =~ /^\s*?module\s+(\w+)\s*?(!.*?)?$/i
            block_searching_flag = :module
            block_searching_lines << line
            module_program_name = $1
            module_program_trailing = find_comments($2)
            next false
          elsif line =~ /^\s*?program\s+(\w+)\s*?(!.*?)?$/i ||
                 line =~ /^\s*?\w/ && !block_start?(line)
            block_searching_flag = :program
            block_searching_lines << line
            module_program_name = $1 || ""
            module_program_trailing = find_comments($2)
            next false

          elsif block_start?(line)
            other_block_searching_flag = true
            next line

          elsif line =~ /^\s*?!\s?(.*)/
            pre_comment << line
            next line
          else
            pre_comment = []
            next line
          end
        elsif other_block_searching_flag
          other_block_level_depth += 1 if block_start?(line)
          other_block_level_depth -= 1 if block_end?(line)
          if other_block_level_depth < 0
            other_block_level_depth = 0
            other_block_searching_flag = nil
          end
          next line
        end

        block_searching_lines << line
        level_depth += 1 if block_start?(line)
        level_depth -= 1 if block_end?(line)
        if level_depth >= 0
          next false
        end

        # "module_program_code" is formatted.
        # ":nodoc:" flag is checked.
        #
        module_program_code = block_searching_lines.join("\n")
        module_program_code = remove_empty_head_lines(module_program_code)
        if module_program_trailing =~ /^:nodoc:/
          # next loop to search next block
          level_depth = 0
          block_searching_flag = false
          block_searching_lines = []
          pre_comment = []
          next false
        end

        # NormalClass is created, and added to @top_level
        #
        if block_searching_flag == :module
          module_name = module_program_name
          module_code = module_program_code
          module_trailing = module_program_trailing
          progress "m"
          @stats.num_modules += 1
          f9x_module = @top_level.add_module NormalClass, module_name
          f9x_module.record_location @top_level

          f9x_comment = COMMENTS_ARE_UPPER ?
            find_comments(pre_comment.join("\n"))  + "\n" + module_trailing :
              module_trailing + "\n" + find_comments(module_code.sub(/^.*$\n/i, ''))
          f9x_module.comment = f9x_comment
          parse_program_or_module(f9x_module, module_code)

          TopLevel.all_files.each do |name, toplevel|
            if toplevel.include_includes?(module_name, @options.ignore_case)
              if !toplevel.include_requires?(@file_name, @options.ignore_case)
                toplevel.add_require(Require.new(@file_name, ""))
              end
            end
            toplevel.each_classmodule{|m|
              if m.include_includes?(module_name, @options.ignore_case)
                if !m.include_requires?(@file_name, @options.ignore_case)
                  m.add_require(Require.new(@file_name, ""))
                end
              end
            }
          end
        elsif block_searching_flag == :program
          program_name = module_program_name
          program_code = module_program_code
          program_trailing = module_program_trailing
          progress "p"
          program_comment = COMMENTS_ARE_UPPER ?
            find_comments(pre_comment.join("\n")) + "\n" + program_trailing :
              program_trailing + "\n" + find_comments(program_code.sub(/^.*$\n/i, ''))
          program_comment = "\n\n= <i>Program</i> <tt>#{program_name}</tt>\n\n" \
                            + program_comment
          @top_level.comment << program_comment
          parse_program_or_module(@top_level, program_code, :private)
        end

        # next loop to search next block
        level_depth = 0
        block_searching_flag = false
        block_searching_lines = []
        pre_comment = []
        next false
      }

      remaining_lines.delete_if{ |line|
        line == false
      }

      # External subprograms and functions are parsed
      #
      parse_program_or_module(@top_level, remaining_lines.join("\n"),
                              :public, true)

      @top_level
    end


new (RDoc::Include)

# File lib/rdoc/code_objects.rb, line 757
    def initialize(name, comment)
      super()
      @name = name
      self.comment = comment
    end


is_module? (RDoc::NormalModule)

# File lib/rdoc/code_objects.rb, line 612
    def is_module?
      true
    end


write_extra_pages (RDoc::Page)

# File lib/rdoc/generators/template/html/hefss.rb, line 413
def write_extra_pages
  template = TemplatePage.new(BLANK)
  File.open("blank.html", "w") { |f| template.write_html_on(f, {}) }
end


write_extra_pages (RDoc::Page)

# File lib/rdoc/generators/template/html/kilmer.rb, line 430
def write_extra_pages
  template = TemplatePage.new(BLANK)
  File.open("blank.html", "w") { |f| template.write_html_on(f, {}) }
end


parse_files_matching (RDoc::ParserFactory)

# File lib/rdoc/parsers/parserfactory.rb, line 56
    def parse_files_matching(regexp)
      @@parsers.unshift Parsers.new(regexp, self)
    end


can_parse (RDoc::ParserFactory)

# File lib/rdoc/parsers/parserfactory.rb, line 62
    def ParserFactory.can_parse(file_name)
      @@parsers.find {|p| p.regexp.match(file_name) }
    end


alias_extension (RDoc::ParserFactory)

# File lib/rdoc/parsers/parserfactory.rb, line 70
    def ParserFactory.alias_extension(old_ext, new_ext)
      parser = ParserFactory.can_parse("xxx.#{old_ext}")
      return false unless parser
      @@parsers.unshift Parsers.new(Regexp.new("\\.#{new_ext}$"), parser.parser)
      true
    end


parser_for (RDoc::ParserFactory)

# File lib/rdoc/parsers/parserfactory.rb, line 80
    def ParserFactory.parser_for(top_level, file_name, body, options, stats)
      # If no extension, look for shebang
      if file_name !~ /\.\w+$/ && body =~ %r{\A#!(.+)}
        shebang = $1
        case shebang
        when %r{env\s+ruby}, %r{/ruby}
          file_name = "dummy.rb"
        end
      end
      parser_description = can_parse(file_name)
      if parser_description
        parser = parser_description.parser
      else
        parser = SimpleParser
      end

      parser.new(top_level, file_name, body, options, stats)
    end


document (RDoc::RDoc)

# File lib/rdoc/rdoc.rb, line 249
    def document(argv)

      TopLevel::reset

      @stats = Stats.new

      options = Options.instance
      options.parse(argv, GENERATORS)

      @last_created = nil
      unless options.all_one_file
        @last_created = setup_output_dir(options.op_dir, options.force_update)
      end
      start_time = Time.now

      file_info = parse_files(options)

      if file_info.empty?
        $stderr.puts "\nNo newer files." unless options.quiet
      else
        gen = options.generator

        $stderr.puts "\nGenerating #{gen.key.upcase}..." unless options.quiet

        require gen.file_name

        gen_class = Generators.const_get(gen.class_name)
        gen = gen_class.for(options)

        pwd = Dir.pwd

        Dir.chdir(options.op_dir)  unless options.all_one_file

        begin
          Diagram.new(file_info, options).draw if options.diagram
          gen.generate(file_info)
          update_output_dir(".", start_time)
        ensure
          Dir.chdir(pwd)
        end
      end

      unless options.quiet
        puts
        @stats.print
      end
    end


new (RDoc::Require)

# File lib/rdoc/code_objects.rb, line 745
    def initialize(name, comment)
      super()
      @name = name.gsub(/'|"/, "") #'
      self.comment = comment
    end


new (RDoc::RubyParser)

# File lib/rdoc/parsers/parse_rb.rb, line 1387
    def initialize(top_level, file_name, content, options, stats)
      @options = options
      @stats   = stats
      @size = 0
      @token_listeners = nil
      @input_file_name = file_name
      @scanner = RubyLex.new(content)
      @scanner.exception_on_syntax_error = false
      @top_level = top_level
      @progress = $stderr unless options.quiet
    end


scan (RDoc::RubyParser)

# File lib/rdoc/parsers/parse_rb.rb, line 1399
    def scan
      @tokens = []
      @unget_read = []
      @read = []
      catch(:eof) do
        catch(:enddoc) do
          begin
            parse_toplevel_statements(@top_level)
          rescue Exception => e
            $stderr.puts "\n\n"
            $stderr.puts "RDoc failure in #@input_file_name at or around " +
                         "line #{@scanner.line_no} column #{@scanner.char_no}"
            $stderr.puts
            $stderr.puts "Before reporting this, could you check that the file"
            $stderr.puts "you're documenting compiles cleanly--RDoc is not a"
            $stderr.puts "full Ruby parser, and gets confused easily if fed"
            $stderr.puts "invalid programs."
            $stderr.puts
            $stderr.puts "The internal error was:\n\n"

            e.set_backtrace(e.backtrace[0,4])
            raise
          end
        end
      end
      @top_level
    end


new (RDoc::SimpleParser)

# File lib/rdoc/parsers/parse_simple.rb, line 15
    def initialize(top_level, file_name, body, options, stats)

      preprocess = SM::PreProcess.new(file_name, options.rdoc_include)

      preprocess.handle(body) do |directive, param|
        $stderr.puts "Unrecognized directive '#{directive}' in #{file_name}"
      end

      @body = body
      @options = options
      @top_level = top_level
    end


scan (RDoc::SimpleParser)

# File lib/rdoc/parsers/parse_simple.rb, line 31
    def scan
      #    @body.gsub(/^(\s\n)+/, '')
      @top_level.comment = remove_private_comments(@body)
      @top_level
    end


remove_private_comments (RDoc::SimpleParser)

# File lib/rdoc/parsers/parse_simple.rb, line 37
    def remove_private_comments(comment)
      comment.gsub(/^--.*?^\+\+/m, '').sub(/^--.*/m, '')
    end


new (RDoc::Stats)

# File lib/rdoc/rdoc.rb, line 37
    def initialize
      @num_files = @num_classes = @num_modules = @num_methods = 0
      @start = Time.now
    end


print (RDoc::Stats)

# File lib/rdoc/rdoc.rb, line 41
    def print
      puts "Files:   #@num_files"
      puts "Classes: #@num_classes"
      puts "Modules: #@num_modules"
      puts "Methods: #@num_methods"
      puts "Elapsed: " + sprintf("%0.3fs", Time.now - @start)
    end


new (RDoc::Token)

# File lib/rdoc/parsers/parse_f95.rb, line 158
    def initialize(line_no, char_no)
      @line_no = line_no
      @char_no = char_no
      @text    = NO_TEXT
    end


set_text (RDoc::Token)

# File lib/rdoc/parsers/parse_f95.rb, line 165
    def set_text(text)
      @text = text
      self
    end


reset (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 472
    def TopLevel::reset
      @@all_classes = {}
      @@all_modules = {}
    end


new (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 477
    def initialize(file_name)
      super()
      @name = "TopLevel"
      @file_relative_name = file_name
      @file_absolute_name = file_name
      @file_stat          = File.stat(file_name)
      @diagram            = nil
    end


full_name (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 486
    def full_name
      nil
    end


add_class_or_module (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 496
    def add_class_or_module(collection, class_type, name, superclass)
      cls = collection[name]
      if cls
        puts "Reusing class/module #{name}" if $DEBUG
      else
        if class_type == NormalModule
          all = @@all_modules
        else
          all = @@all_classes
        end
        cls = all[name]
        if !cls
          cls = class_type.new(name, superclass)
          all[name] = cls  unless @done_documenting
        end
        puts "Adding class/module #{name} to #@name" if $DEBUG
        collection[name] = cls unless @done_documenting
        cls.parent = self
      end
      cls
    end


all_classes_and_modules (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 518
    def TopLevel.all_classes_and_modules
      @@all_classes.values + @@all_modules.values
    end


find_class_named (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 522
    def TopLevel.find_class_named(name)
     @@all_classes.each_value do |c|
        res = c.find_class_named(name)
        return res if res
      end
      nil
    end


find_local_symbol (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 530
    def find_local_symbol(symbol)
      find_class_or_module_named(symbol) || super
    end


find_class_or_module_named (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 534
    def find_class_or_module_named(symbol)
      @@all_classes.each_value {|c| return c if c.name == symbol}
      @@all_modules.each_value {|m| return m if m.name == symbol}
      nil
    end


find_module_named (RDoc::TopLevel)

# File lib/rdoc/code_objects.rb, line 541
    def find_module_named(name)
      find_class_or_module_named(name) || find_enclosing_module_named(name)
    end


usage (RDoc)

# File lib/rdoc/usage.rb, line 81
  def RDoc.usage(*args)
    exit_code = 0

    if args.size > 0
      status = args[0]
      if status.respond_to?(:to_int)
        exit_code = status.to_int
        args.shift
      end
    end

    # display the usage and exit with the given code
    usage_no_exit(*args)
    exit(exit_code)
  end


usage_no_exit (RDoc)

# File lib/rdoc/usage.rb, line 98
  def RDoc.usage_no_exit(*args)
    main_program_file = caller[-1].sub(/:\d+$/, '')
    comment = File.open(main_program_file) do |file|
      find_comment(file)
    end

    comment = comment.gsub(/^\s*#/, '')

    markup = SM::SimpleMarkup.new
    flow_convertor = SM::ToFlow.new

    flow = markup.convert(comment, flow_convertor)

    format = "plain"

    unless args.empty?
      flow = extract_sections(flow, args)
    end

    options = RI::Options.instance
    if args = ENV["RI"]
      options.parse(args.split)
    end
    formatter = options.formatter.new(options, "")
    formatter.display_flow(flow)
  end


new (RegAnd)

# File lib/eregex.rb, line 15
  def initialize(re1, re2)
    @re1 = re1
    @re2 = re2
  end


=~ (RegAnd)

# File lib/eregex.rb, line 20
  def =~ (str)
    @re1 =~ str and @re2 =~ str
  end


quote (Regexp)

/*
 *  call-seq:
 *     Regexp.escape(str)   => a_str
 *     Regexp.quote(str)    => a_str
 *
 *  Escapes any characters that would have special meaning in a regular
 *  expression. Returns a new escaped string, or self if no characters are
 *  escaped.  For any string,
 *  <code>Regexp.escape(<i>str</i>)=~<i>str</i></code> will be true.
 *
 *     Regexp.escape('\\*?{}.')   #=> \\\\\*\?\{\}\.
 */

static VALUE
rb_reg_s_quote(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str, kcode;
    int kcode_saved = reg_kcode;

    rb_scan_args(argc, argv, "11", &str, &kcode);
    if (!NIL_P(kcode)) {
        rb_set_kcode(StringValuePtr(kcode));
        curr_kcode = reg_kcode;
        reg_kcode = kcode_saved;
    }
    StringValue(str);
    str = rb_reg_quote(str);
    rb_kcode_reset_option();
    return str;
}


escape (Regexp)

/*
 *  call-seq:
 *     Regexp.escape(str)   => a_str
 *     Regexp.quote(str)    => a_str
 *
 *  Escapes any characters that would have special meaning in a regular
 *  expression. Returns a new escaped string, or self if no characters are
 *  escaped.  For any string,
 *  <code>Regexp.escape(<i>str</i>)=~<i>str</i></code> will be true.
 *
 *     Regexp.escape('\\*?{}.')   #=> \\\\\*\?\{\}\.
 */

static VALUE
rb_reg_s_quote(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE str, kcode;
    int kcode_saved = reg_kcode;

    rb_scan_args(argc, argv, "11", &str, &kcode);
    if (!NIL_P(kcode)) {
        rb_set_kcode(StringValuePtr(kcode));
        curr_kcode = reg_kcode;
        reg_kcode = kcode_saved;
    }
    StringValue(str);
    str = rb_reg_quote(str);
    rb_kcode_reset_option();
    return str;
}


union (Regexp)

/*
 *  call-seq:
 *     Regexp.union([pattern]*)   => new_str
 *
 *  Return a <code>Regexp</code> object that is the union of the given
 *  <em>pattern</em>s, i.e., will match any of its parts. The <em>pattern</em>s
 *  can be Regexp objects, in which case their options will be preserved, or
 *  Strings. If no arguments are given, returns <code>/(?!)/</code>.
 *
 *     Regexp.union                         #=> /(?!)/
 *     Regexp.union("penzance")             #=> /penzance/
 *     Regexp.union("skiing", "sledding")   #=> /skiing|sledding/
 *     Regexp.union(/dogs/, /cats/i)        #=> /(?-mix:dogs)|(?i-mx:cats)/
 */
static VALUE
rb_reg_s_union(argc, argv)
    int argc;
    VALUE *argv;
{
    if (argc == 0) {
        VALUE args[1];
        args[0] = rb_str_new2("(?!)");
        return rb_class_new_instance(1, args, rb_cRegexp);
    }
    else if (argc == 1) {
        VALUE v;
        v = rb_check_convert_type(argv[0], T_REGEXP, "Regexp", "to_regexp");
        if (!NIL_P(v))
            return v;
        else {
            VALUE args[1];
            args[0] = rb_reg_s_quote(argc, argv);
            return rb_class_new_instance(1, args, rb_cRegexp);
        }
    }
    else {
        int i, kcode = -1;
        VALUE kcode_re = Qnil;
        VALUE source = rb_str_buf_new(0);
        VALUE args[3];
        for (i = 0; i < argc; i++) {
            volatile VALUE v;
            if (0 < i)
                rb_str_buf_cat2(source, "|");
            v = rb_check_convert_type(argv[i], T_REGEXP, "Regexp", "to_regexp");
            if (!NIL_P(v)) {
                if (FL_TEST(v, KCODE_FIXED)) {
                    if (kcode == -1) {
                        kcode_re = v;
                        kcode = RBASIC(v)->flags & KCODE_MASK;
                    }
                    else if ((RBASIC(v)->flags & KCODE_MASK) != kcode) {
                        volatile VALUE str1, str2;
                        str1 = rb_inspect(kcode_re);
                        str2 = rb_inspect(v);
                        rb_raise(rb_eArgError, "mixed kcode: %s and %s",
                            RSTRING(str1)->ptr, RSTRING(str2)->ptr);
                    }
                }
                v = rb_reg_to_s(v);
            }
            else {
                args[0] = argv[i];
                v = rb_reg_s_quote(1, args);
            }
            rb_str_buf_append(source, v);
        }
        args[0] = source;
        args[1] = Qnil;
        switch (kcode) {
          case -1:
            args[2] = Qnil;
            break;
          case KCODE_NONE:
            args[2] = rb_str_new2("n");
            break;
          case KCODE_EUC:
            args[2] = rb_str_new2("e");
            break;
          case KCODE_SJIS:
            args[2] = rb_str_new2("s");
            break;
          case KCODE_UTF8:
            args[2] = rb_str_new2("u");
            break;
        }
        return rb_class_new_instance(3, args, rb_cRegexp);
    }
}


last_match (Regexp)

/*
 *  call-seq:
 *     Regexp.last_match           => matchdata
 *     Regexp.last_match(fixnum)   => str
 *
 *  The first form returns the <code>MatchData</code> object generated by the
 *  last successful pattern match. Equivalent to reading the global variable
 *  <code>$~</code>. The second form returns the nth field in this
 *  <code>MatchData</code> object.
 *
 *     /c(.)t/ =~ 'cat'       #=> 0
 *     Regexp.last_match      #=> #<MatchData:0x401b3d30>
 *     Regexp.last_match(0)   #=> "cat"
 *     Regexp.last_match(1)   #=> "a"
 *     Regexp.last_match(2)   #=> nil
 */

static VALUE
rb_reg_s_last_match(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE nth;

    if (rb_scan_args(argc, argv, "01", &nth) == 1) {
        return rb_reg_nth_match(NUM2INT(nth), rb_backref_get());
    }
    return match_getter();
}


new (Regexp)

/*
 *  call-seq:
 *     Regexp.new(string [, options [, lang]])       => regexp
 *     Regexp.new(regexp)                            => regexp
 *     Regexp.compile(string [, options [, lang]])   => regexp
 *     Regexp.compile(regexp)                        => regexp
 *
 *  Constructs a new regular expression from <i>pattern</i>, which can be either
 *  a <code>String</code> or a <code>Regexp</code> (in which case that regexp's
 *  options are propagated, and new options may not be specified (a change as of
 *  Ruby 1.8). If <i>options</i> is a <code>Fixnum</code>, it should be one or
 *  more of the constants <code>Regexp::EXTENDED</code>,
 *  <code>Regexp::IGNORECASE</code>, and <code>Regexp::MULTILINE</code>,
 *  <em>or</em>-ed together. Otherwise, if <i>options</i> is not
 *  <code>nil</code>, the regexp will be case insensitive. The <i>lang</i>
 *  parameter enables multibyte support for the regexp: `n', `N' = none, `e',
 *  `E' = EUC, `s', `S' = SJIS, `u', `U' = UTF-8.
 *
 *     r1 = Regexp.new('^a-z+:\\s+\w+')           #=> /^a-z+:\s+\w+/
 *     r2 = Regexp.new('cat', true)               #=> /cat/i
 *     r3 = Regexp.new('dog', Regexp::EXTENDED)   #=> /dog/x
 *     r4 = Regexp.new(r2)                        #=> /cat/i
 */

static VALUE
rb_reg_initialize_m(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    const char *s;
    long len;
    int flags = 0;

    if (argc == 0 || argc > 3) {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    if (TYPE(argv[0]) == T_REGEXP) {
        if (argc > 1) {
            rb_warn("flags%s ignored", (argc == 3) ? " and encoding": "");
        }
        rb_reg_check(argv[0]);
        flags = RREGEXP(argv[0])->ptr->options & 0xf;
        if (FL_TEST(argv[0], KCODE_FIXED)) {
            switch (RBASIC(argv[0])->flags & KCODE_MASK) {
              case KCODE_NONE:
                flags |= 16;
                break;
              case KCODE_EUC:
                flags |= 32;
                break;
              case KCODE_SJIS:
                flags |= 48;
                break;
              case KCODE_UTF8:
                flags |= 64;
                break;
              default:
                break;
            }
        }
        s = RREGEXP(argv[0])->str;
        len = RREGEXP(argv[0])->len;
    }
    else {
        if (argc >= 2) {
            if (FIXNUM_P(argv[1])) flags = FIX2INT(argv[1]);
            else if (RTEST(argv[1])) flags = RE_OPTION_IGNORECASE;
        }
        if (argc == 3 && !NIL_P(argv[2])) {
            char *kcode = StringValuePtr(argv[2]);

            flags &= ~0x70;
            switch (kcode[0]) {
              case 'n': case 'N':
                flags |= 16;
                break;
              case 'e': case 'E':
                flags |= 32;
                break;
              case 's': case 'S':
                flags |= 48;
                break;
              case 'u': case 'U':
                flags |= 64;
                break;
              default:
                break;
            }
        }
        s = StringValuePtr(argv[0]);
        len = RSTRING(argv[0])->len;
    }
    rb_reg_initialize(self, s, len, flags);
    return self;
}


hash (Regexp)

/*
 * call-seq:
 *   rxp.hash   => fixnum
 *
 * Produce a hash based on the text and options of this regular expression.
 */

static VALUE
rb_reg_hash(re)
    VALUE re;
{
    int hashval, len;
    char *p;

    rb_reg_check(re);
    hashval = RREGEXP(re)->ptr->options;
    len = RREGEXP(re)->len;
    p  = RREGEXP(re)->str;
    while (len--) {
        hashval = hashval * 33 + *p++;
    }
    hashval = hashval + (hashval>>5);

    return INT2FIX(hashval);
}


eql? (Regexp)

/*
 *  call-seq:
 *     rxp == other_rxp      => true or false
 *     rxp.eql?(other_rxp)   => true or false
 *
 *  Equality---Two regexps are equal if their patterns are identical, they have
 *  the same character set code, and their <code>casefold?</code> values are the
 *  same.
 *
 *     /abc/  == /abc/x   #=> false
 *     /abc/  == /abc/i   #=> false
 *     /abc/u == /abc/n   #=> false
 */

static VALUE
rb_reg_equal(re1, re2)
    VALUE re1, re2;
{
    if (re1 == re2) return Qtrue;
    if (TYPE(re2) != T_REGEXP) return Qfalse;
    rb_reg_check(re1); rb_reg_check(re2);
    if (RREGEXP(re1)->len != RREGEXP(re2)->len) return Qfalse;
    if (memcmp(RREGEXP(re1)->str, RREGEXP(re2)->str, RREGEXP(re1)->len) == 0 &&
        rb_reg_cur_kcode(re1) == rb_reg_cur_kcode(re2) &&
        RREGEXP(re1)->ptr->options == RREGEXP(re2)->ptr->options) {
        return Qtrue;
    }
    return Qfalse;
}


== (Regexp)

/*
 *  call-seq:
 *     rxp == other_rxp      => true or false
 *     rxp.eql?(other_rxp)   => true or false
 *
 *  Equality---Two regexps are equal if their patterns are identical, they have
 *  the same character set code, and their <code>casefold?</code> values are the
 *  same.
 *
 *     /abc/  == /abc/x   #=> false
 *     /abc/  == /abc/i   #=> false
 *     /abc/u == /abc/n   #=> false
 */

static VALUE
rb_reg_equal(re1, re2)
    VALUE re1, re2;
{
    if (re1 == re2) return Qtrue;
    if (TYPE(re2) != T_REGEXP) return Qfalse;
    rb_reg_check(re1); rb_reg_check(re2);
    if (RREGEXP(re1)->len != RREGEXP(re2)->len) return Qfalse;
    if (memcmp(RREGEXP(re1)->str, RREGEXP(re2)->str, RREGEXP(re1)->len) == 0 &&
        rb_reg_cur_kcode(re1) == rb_reg_cur_kcode(re2) &&
        RREGEXP(re1)->ptr->options == RREGEXP(re2)->ptr->options) {
        return Qtrue;
    }
    return Qfalse;
}


=~ (Regexp)

/*
 *  call-seq:
 *     rxp.match(str)   => matchdata or nil
 *
 *  Returns a <code>MatchData</code> object describing the match, or
 *  <code>nil</code> if there was no match. This is equivalent to retrieving the
 *  value of the special variable <code>$~</code> following a normal match.
 *
 *     /(.)(.)(.)/.match("abc")[2]   #=> "b"
 */

VALUE
rb_reg_match(re, str)
    VALUE re, str;
{
    long start;

    if (NIL_P(str)) {
        rb_backref_set(Qnil);
        return Qnil;
    }
    StringValue(str);
    start = rb_reg_search(re, str, 0, 0);
    if (start < 0) {
        return Qnil;
    }
    return LONG2FIX(start);
}


=== (Regexp)

/*
 *  call-seq:
 *     rxp === str   => true or false
 *
 *  Case Equality---Synonym for <code>Regexp#=~</code> used in case statements.
 *
 *     a = "HELLO"
 *     case a
 *     when /^[a-z]*$/; print "Lower case\n"
 *     when /^[A-Z]*$/; print "Upper case\n"
 *     else;            print "Mixed case\n"
 *     end
 *
 *  <em>produces:</em>
 *
 *     Upper case
 */

VALUE
rb_reg_eqq(re, str)
    VALUE re, str;
{
    long start;

    if (TYPE(str) != T_STRING) {
        str = rb_check_string_type(str);
        if (NIL_P(str)) {
            rb_backref_set(Qnil);
            return Qfalse;
        }
    }
    StringValue(str);
    start = rb_reg_search(re, str, 0, 0);
    if (start < 0) {
        return Qfalse;
    }
    return Qtrue;
}


~ (Regexp)

/*
 *  call-seq:
 *     ~ rxp   => integer or nil
 *
 *  Match---Matches <i>rxp</i> against the contents of <code>$_</code>.
 *  Equivalent to <code><i>rxp</i> =~ $_</code>.
 *
 *     $_ = "input data"
 *     ~ /at/   #=> 7
 */

VALUE
rb_reg_match2(re)
    VALUE re;
{
    long start;
    VALUE line = rb_lastline_get();

    if (TYPE(line) != T_STRING) {
        rb_backref_set(Qnil);
        return Qnil;
    }

    start = rb_reg_search(re, line, 0, 0);
    if (start < 0) {
        return Qnil;
    }
    return LONG2FIX(start);
}


match (Regexp)

/*
 *  call-seq:
 *     rxp.match(str)   => matchdata or nil
 *
 *  Returns a <code>MatchData</code> object describing the match, or
 *  <code>nil</code> if there was no match. This is equivalent to retrieving the
 *  value of the special variable <code>$~</code> following a normal match.
 *
 *     /(.)(.)(.)/.match("abc")[2]   #=> "b"
 */

static VALUE
rb_reg_match_m(re, str)
    VALUE re, str;
{
    VALUE result = rb_reg_match(re, str);

    if (NIL_P(result)) return Qnil;
    result = rb_backref_get();
    rb_match_busy(result);
    return result;
}


to_s (Regexp)

/*
 *  call-seq:
 *     rxp.to_s   => str
 *
 *  Returns a string containing the regular expression and its options (using the
 *  <code>(?xxx:yyy)</code> notation. This string can be fed back in to
 *  <code>Regexp::new</code> to a regular expression with the same semantics as
 *  the original. (However, <code>Regexp#==</code> may not return true when
 *  comparing the two, as the source of the regular expression itself may
 *  differ, as the example shows).  <code>Regexp#inspect</code> produces a
 *  generally more readable version of <i>rxp</i>.
 *
 *     r1 = /ab+c/ix         #=> /ab+c/ix
 *     s1 = r1.to_s          #=> "(?ix-m:ab+c)"
 *     r2 = Regexp.new(s1)   #=> /(?ix-m:ab+c)/
 *     r1 == r2              #=> false
 *     r1.source             #=> "ab+c"
 *     r2.source             #=> "(?ix-m:ab+c)"
 */

static VALUE
rb_reg_to_s(re)
    VALUE re;
{
    int options;
    const int embeddable = RE_OPTION_MULTILINE|RE_OPTION_IGNORECASE|RE_OPTION_EXTENDED;
    long len;
    const char* ptr;
    VALUE str = rb_str_buf_new2("(?");

    rb_reg_check(re);

    options = RREGEXP(re)->ptr->options;
    ptr = RREGEXP(re)->str;
    len = RREGEXP(re)->len;
  again:
    if (len >= 4 && ptr[0] == '(' && ptr[1] == '?') {
        int err = 1;
        ptr += 2;
        if ((len -= 2) > 0) {
            do {
                if (*ptr == 'm') {
                    options |= RE_OPTION_MULTILINE;
                }
                else if (*ptr == 'i') {
                    options |= RE_OPTION_IGNORECASE;
                }
                else if (*ptr == 'x') {
                    options |= RE_OPTION_EXTENDED;
                }
                else break;
                ++ptr;
            } while (--len > 0);
        }
        if (len > 1 && *ptr == '-') {
            ++ptr;
            --len;
            do {
                if (*ptr == 'm') {
                    options &= ~RE_OPTION_MULTILINE;
                }
                else if (*ptr == 'i') {
                    options &= ~RE_OPTION_IGNORECASE;
                }
                else if (*ptr == 'x') {
                    options &= ~RE_OPTION_EXTENDED;
                }
                else break;
                ++ptr;
            } while (--len > 0);
        }
        if (*ptr == ')') {
            --len;
            ++ptr;
            goto again;
        }
        if (*ptr == ':' && ptr[len-1] == ')') {
            Regexp *rp;
            rb_kcode_set_option(re);
            rp = ALLOC(Regexp);
            MEMZERO((char *)rp, Regexp, 1);
            err = re_compile_pattern(++ptr, len -= 2, rp) != 0;
            rb_kcode_reset_option();
            re_free_pattern(rp);
        }
        if (err) {
            options = RREGEXP(re)->ptr->options;
            ptr = RREGEXP(re)->str;
            len = RREGEXP(re)->len;
        }
    }

    if (options & RE_OPTION_MULTILINE) rb_str_buf_cat2(str, "m");
    if (options & RE_OPTION_IGNORECASE) rb_str_buf_cat2(str, "i");
    if (options & RE_OPTION_EXTENDED) rb_str_buf_cat2(str, "x");

    if ((options & embeddable) != embeddable) {
        rb_str_buf_cat2(str, "-");
        if (!(options & RE_OPTION_MULTILINE)) rb_str_buf_cat2(str, "m");
        if (!(options & RE_OPTION_IGNORECASE)) rb_str_buf_cat2(str, "i");
        if (!(options & RE_OPTION_EXTENDED)) rb_str_buf_cat2(str, "x");
    }

    rb_str_buf_cat2(str, ":");
    rb_reg_expr_str(str, ptr, len);
    rb_str_buf_cat2(str, ")");

    OBJ_INFECT(str, re);
    return str;
}


inspect (Regexp)

/*
 * call-seq:
 *    rxp.inspect   => string
 *
 * Produce a nicely formatted string-version of _rxp_. Perhaps surprisingly,
 * <code>#inspect</code> actually produces the more natural version of
 * the string than <code>#to_s</code>.
 *
 *     /ab+c/ix.to_s         #=> /ab+c/ix
*/

static VALUE
rb_reg_inspect(re)
    VALUE re;
{
    rb_reg_check(re);
    return rb_reg_desc(RREGEXP(re)->str, RREGEXP(re)->len, re);
}


source (Regexp)

/*
 *  call-seq:
 *     rxp.source   => str
 *
 *  Returns the original string of the pattern.
 *
 *     /ab+c/ix.source   #=> "ab+c"
 */

static VALUE
rb_reg_source(re)
    VALUE re;
{
    VALUE str;

    rb_reg_check(re);
    str = rb_str_new(RREGEXP(re)->str,RREGEXP(re)->len);
    if (OBJ_TAINTED(re)) OBJ_TAINT(str);
    return str;
}


casefold? (Regexp)

/*
 *  call-seq:
 *     rxp.casefold?   => true or false
 *
 *  Returns the value of the case-insensitive flag.
 */

static VALUE
rb_reg_casefold_p(re)
    VALUE re;
{
    rb_reg_check(re);
    if (RREGEXP(re)->ptr->options & RE_OPTION_IGNORECASE) return Qtrue;
    return Qfalse;
}


options (Regexp)

/*
 *  call-seq:
 *     rxp.options   => fixnum
 *
 *  Returns the set of bits corresponding to the options used when creating this
 *  Regexp (see <code>Regexp::new</code> for details. Note that additional bits
 *  may be set in the returned options: these are used internally by the regular
 *  expression code. These extra bits are ignored if the options are passed to
 *  <code>Regexp::new</code>.
 *
 *     Regexp::IGNORECASE                  #=> 1
 *     Regexp::EXTENDED                    #=> 2
 *     Regexp::MULTILINE                   #=> 4
 *
 *     /cat/.options                       #=> 128
 *     /cat/ix.options                     #=> 131
 *     Regexp.new('cat', true).options     #=> 129
 *     Regexp.new('cat', 0, 's').options   #=> 384
 *
 *     r = /cat/ix
 *     Regexp.new(r.source, r.options)     #=> /cat/ix
 */

static VALUE
rb_reg_options_m(re)
    VALUE re;
{
    int options = rb_reg_options(re);
    return INT2NUM(options);
}


kcode (Regexp)

/*
 *  call-seq:
 *     rxp.kcode   => str
 *
 *  Returns the character set code for the regexp.
 */

static VALUE
rb_reg_kcode_m(re)
    VALUE re;
{
    char *kcode;

    if (FL_TEST(re, KCODE_FIXED)) {
        switch (RBASIC(re)->flags & KCODE_MASK) {
          case KCODE_NONE:
            kcode = "none"; break;
          case KCODE_EUC:
            kcode = "euc"; break;
          case KCODE_SJIS:
            kcode = "sjis"; break;
          case KCODE_UTF8:
            kcode = "utf8"; break;
          default:
            rb_bug("unknown kcode - should not happen");
            break;
        }
        return rb_str_new2(kcode);
    }
    return Qnil;
}


| (Regexp)

# File lib/eregex.rb, line 26
  def |(other)
    RegOr.new(self, other)
  end


& (Regexp)

# File lib/eregex.rb, line 29
  def &(other)
    RegAnd.new(self, other)
  end


yaml_new (Regexp)

# File lib/yaml/rubytypes.rb, line 255
    def Regexp.yaml_new( klass, tag, val )
        if String === val and val =~ /^\/(.*)\/([mix]*)$/
            val = { 'regexp' => $1, 'mods' => $2 }
        end
        if Hash === val
            mods = nil
            unless val['mods'].to_s.empty?
                mods = 0x00
                mods |= Regexp::EXTENDED if val['mods'].include?( 'x' )
                mods |= Regexp::IGNORECASE if val['mods'].include?( 'i' )
                mods |= Regexp::MULTILINE if val['mods'].include?( 'm' )
            end
            val.delete( 'mods' )
            r = YAML::object_maker( klass, {} )
            Regexp.instance_method(:initialize).
                  bind(r).
                  call( val.delete( 'regexp' ), mods )
            val.each { |k,v| r.instance_variable_set( k, v ) }
            r
        else
            raise YAML::TypeError, "Invalid Regular expression: " + val.inspect
        end
    end


to_yaml (Regexp)

# File lib/yaml/rubytypes.rb, line 278
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            if to_yaml_properties.empty?
                out.scalar( taguri, self.inspect, :plain )
            else
                out.map( taguri, to_yaml_style ) do |map|
                    src = self.inspect
                    if src =~ /\A\/(.*)\/([a-z]*)\Z/
                        map.add( 'regexp', $1 )
                        map.add( 'mods', $2 )
                    else
                                raise YAML::TypeError, "Invalid Regular expression: " + src
                    end
                    to_yaml_properties.each do |m|
                        map.add( m, instance_variable_get( m ) )
                    end
                end
            end
        end
        end


new (RegOr)

# File lib/eregex.rb, line 4
  def initialize(re1, re2)
    @re1 = re1
    @re2 = re2
  end


=~ (RegOr)

# File lib/eregex.rb, line 9
  def =~ (str)
    @re1 =~ str or @re2 =~ str
  end


new (Resolv::DNS::Config)

# File lib/resolv.rb, line 717
      def initialize(config_info=nil)
        @mutex = Mutex.new
        @config_info = config_info
        @initialized = nil
      end


parse_resolv_conf (Resolv::DNS::Config)

# File lib/resolv.rb, line 723
      def Config.parse_resolv_conf(filename)
        nameserver = []
        search = nil
        ndots = 1
        open(filename) {|f|
          f.each {|line|
            line.sub!(/[#;].*/, '')
            keyword, *args = line.split(/\s+/)
            args.each { |arg|
              arg.untaint
            }
            next unless keyword
            case keyword
            when 'nameserver'
              nameserver += args
            when 'domain'
              next if args.empty?
              search = [args[0]]
            when 'search'
              next if args.empty?
              search = args
            when 'options'
              args.each {|arg|
                case arg
                when /\Andots:(\d+)\z/
                  ndots = $1.to_i
                end
              }
            end
          }
        }
        return { :nameserver => nameserver, :search => search, :ndots => ndots }
      end


default_config_hash (Resolv::DNS::Config)

# File lib/resolv.rb, line 757
      def Config.default_config_hash(filename="/etc/resolv.conf")
        if File.exist? filename
          config_hash = Config.parse_resolv_conf(filename)
        else
          if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
            search, nameserver = Win32::Resolv.get_resolv_info
            config_hash = {}
            config_hash[:nameserver] = nameserver if nameserver
            config_hash[:search] = [search].flatten if search
          end
        end
        config_hash
      end


lazy_initialize (Resolv::DNS::Config)

# File lib/resolv.rb, line 771
      def lazy_initialize
        @mutex.synchronize {
          unless @initialized
            @nameserver = []
            @search = nil
            @ndots = 1
            case @config_info
            when nil
              config_hash = Config.default_config_hash
            when String
              config_hash = Config.parse_resolv_conf(@config_info)
            when Hash
              config_hash = @config_info.dup
              if String === config_hash[:nameserver]
                config_hash[:nameserver] = [config_hash[:nameserver]]
              end
              if String === config_hash[:search]
                config_hash[:search] = [config_hash[:search]]
              end
            else
              raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}")
            end
            @nameserver = config_hash[:nameserver] if config_hash.include? :nameserver
            @search = config_hash[:search] if config_hash.include? :search
            @ndots = config_hash[:ndots] if config_hash.include? :ndots

            @nameserver = ['0.0.0.0'] if @nameserver.empty?
            if @search
              @search = @search.map {|arg| Label.split(arg) }
            else
              hostname = Socket.gethostname
              if /\./ =~ hostname
                @search = [Label.split($')]
              else
                @search = [[]]
              end
            end

            if !@nameserver.kind_of?(Array) ||
               !@nameserver.all? {|ns| String === ns }
              raise ArgumentError.new("invalid nameserver config: #{@nameserver.inspect}")
            end

            if !@search.kind_of?(Array) ||
               !@search.all? {|ls| ls.all? {|l| Label::Str === l } }
              raise ArgumentError.new("invalid search config: #{@search.inspect}")
            end

            if !@ndots.kind_of?(Integer)
              raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}")
            end

            @initialized = true
          end
        }
        self
      end


single? (Resolv::DNS::Config)

# File lib/resolv.rb, line 829
      def single?
        lazy_initialize
        if @nameserver.length == 1
          return @nameserver[0]
        else
          return nil
        end
      end


generate_candidates (Resolv::DNS::Config)

# File lib/resolv.rb, line 838
      def generate_candidates(name)
        candidates = nil
        name = Name.create(name)
        if name.absolute?
          candidates = [name]
        else
          if @ndots <= name.length - 1
            candidates = [Name.new(name.to_a)]
          else
            candidates = []
          end
          candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
        end
        return candidates
      end


generate_timeouts (Resolv::DNS::Config)

# File lib/resolv.rb, line 856
      def generate_timeouts
        ts = [InitialTimeout]
        ts << ts[-1] * 2 / @nameserver.length
        ts << ts[-1] * 2
        ts << ts[-1] * 2
        return ts
      end


resolv (Resolv::DNS::Config)

# File lib/resolv.rb, line 864
      def resolv(name)
        candidates = generate_candidates(name)
        timeouts = generate_timeouts
        begin
          candidates.each {|candidate|
            begin
              timeouts.each {|tout|
                @nameserver.each {|nameserver|
                  begin
                    yield candidate, tout, nameserver
                  rescue ResolvTimeout
                  end
                }
              }
              raise ResolvError.new("DNS resolv timeout: #{name}")
            rescue NXDomain
            end
          }
        rescue ResolvError
        end
      end


new (Resolv::DNS::Label::Str)

# File lib/resolv.rb, line 936
        def initialize(string)
          @string = string
          @downcase = string.downcase
        end


to_s (Resolv::DNS::Label::Str)

# File lib/resolv.rb, line 942
        def to_s
          return @string
        end


inspect (Resolv::DNS::Label::Str)

# File lib/resolv.rb, line 946
        def inspect
          return "#<#{self.class} #{self.to_s}>"
        end


== (Resolv::DNS::Label::Str)

# File lib/resolv.rb, line 950
        def ==(other)
          return @downcase == other.downcase
        end


eql? (Resolv::DNS::Label::Str)

# File lib/resolv.rb, line 954
        def eql?(other)
          return self == other
        end


hash (Resolv::DNS::Label::Str)

# File lib/resolv.rb, line 958
        def hash
          return @downcase.hash
        end


split (Resolv::DNS::Label)

# File lib/resolv.rb, line 929
      def self.split(arg)
        labels = []
        arg.scan(/[^\.]+/) {labels << Str.new($&)}
        return labels
      end


new (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1251
        def initialize(data)
          @data = data
          @index = 0
          @limit = data.length
          yield self
        end


get_length16 (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1258
        def get_length16
          len, = self.get_unpack('n')
          save_limit = @limit
          @limit = @index + len
          d = yield(len)
          if @index < @limit
            raise DecodeError.new("junk exists")
          elsif @limit < @index
            raise DecodeError.new("limit exceeded")
          end
          @limit = save_limit
          return d
        end


get_bytes (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1272
        def get_bytes(len = @limit - @index)
          d = @data[@index, len]
          @index += len
          return d
        end


get_unpack (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1278
        def get_unpack(template)
          len = 0
          template.each_byte {|byte|
            case byte
            when ?c, ?C
              len += 1
            when ?n
              len += 2
            when ?N
              len += 4
            else
              raise StandardError.new("unsupported template: '#{byte.chr}' in '#{template}'")
            end
          }
          raise DecodeError.new("limit exceeded") if @limit < @index + len
          arr = @data.unpack("@#{@index}#{template}")
          @index += len
          return arr
        end


get_string (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1298
        def get_string
          len = @data[@index]
          raise DecodeError.new("limit exceeded") if @limit < @index + 1 + len
          d = @data[@index + 1, len]
          @index += 1 + len
          return d
        end


get_string_list (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1306
        def get_string_list
          strings = []
          while @index < @limit
            strings << self.get_string
          end
          strings
        end


get_name (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1314
        def get_name
          return Name.new(self.get_labels)
        end


get_labels (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1318
        def get_labels(limit=nil)
          limit = @index if !limit || @index < limit
          d = []
          while true
            case @data[@index]
            when 0
              @index += 1
              return d
            when 192..255
              idx = self.get_unpack('n')[0] & 0x3fff
              if limit <= idx
                raise DecodeError.new("non-backward name pointer")
              end
              save_index = @index
              @index = idx
              d += self.get_labels(limit)
              @index = save_index
              return d
            else
              d << self.get_label
            end
          end
          return d
        end


get_label (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1343
        def get_label
          return Label::Str.new(self.get_string)
        end


get_question (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1347
        def get_question
          name = self.get_name
          type, klass = self.get_unpack("nn")
          return name, Resource.get_class(type, klass)
        end


get_rr (Resolv::DNS::Message::MessageDecoder)

# File lib/resolv.rb, line 1353
        def get_rr
          name = self.get_name
          type, klass, ttl = self.get_unpack('nnN')
          typeclass = Resource.get_class(type, klass)
          return name, ttl, self.get_length16 {typeclass.decode_rdata(self)}
        end


new (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1156
        def initialize
          @data = ''
          @names = {}
          yield self
        end


to_s (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1162
        def to_s
          return @data
        end


put_bytes (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1166
        def put_bytes(d)
          @data << d
        end


put_pack (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1170
        def put_pack(template, *d)
          @data << d.pack(template)
        end


put_length16 (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1174
        def put_length16
          length_index = @data.length
          @data << "\0\0"
          data_start = @data.length
          yield
          data_end = @data.length
          @data[length_index, 2] = [data_end - data_start].pack("n")
        end


put_string (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1183
        def put_string(d)
          self.put_pack("C", d.length)
          @data << d
        end


put_string_list (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1188
        def put_string_list(ds)
          ds.each {|d|
            self.put_string(d)
          }
        end


put_name (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1194
        def put_name(d)
          put_labels(d.to_a)
        end


put_labels (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1198
        def put_labels(d)
          d.each_index {|i|
            domain = d[i..-1]
            if idx = @names[domain]
              self.put_pack("n", 0xc000 | idx)
              return
            else
              @names[domain] = @data.length
              self.put_label(d[i])
            end
          }
          @data << "\0"
        end


put_label (Resolv::DNS::Message::MessageEncoder)

# File lib/resolv.rb, line 1212
        def put_label(d)
          self.put_string(d.string)
        end


new (Resolv::DNS::Message)

# File lib/resolv.rb, line 1045
      def initialize(id = (@@identifier += 1) & 0xffff)
        @id = id
        @qr = 0
        @opcode = 0
        @aa = 0
        @tc = 0
        @rd = 0 # recursion desired
        @ra = 0 # recursion available
        @rcode = 0
        @question = []
        @answer = []
        @authority = []
        @additional = []
      end


== (Resolv::DNS::Message)

# File lib/resolv.rb, line 1063
      def ==(other)
        return @id == other.id &&
               @qr == other.qr &&
               @opcode == other.opcode &&
               @aa == other.aa &&
               @tc == other.tc &&
               @rd == other.rd &&
               @ra == other.ra &&
               @rcode == other.rcode &&
               @question == other.question &&
               @answer == other.answer &&
               @authority == other.authority &&
               @additional == other.additional
      end


add_question (Resolv::DNS::Message)

# File lib/resolv.rb, line 1078
      def add_question(name, typeclass)
        @question << [Name.create(name), typeclass]
      end


each_question (Resolv::DNS::Message)

# File lib/resolv.rb, line 1082
      def each_question
        @question.each {|name, typeclass|
          yield name, typeclass
        }
      end


add_answer (Resolv::DNS::Message)

# File lib/resolv.rb, line 1088
      def add_answer(name, ttl, data)
        @answer << [Name.create(name), ttl, data]
      end


each_answer (Resolv::DNS::Message)

# File lib/resolv.rb, line 1092
      def each_answer
        @answer.each {|name, ttl, data|
          yield name, ttl, data
        }
      end


add_authority (Resolv::DNS::Message)

# File lib/resolv.rb, line 1098
      def add_authority(name, ttl, data)
        @authority << [Name.create(name), ttl, data]
      end


each_authority (Resolv::DNS::Message)

# File lib/resolv.rb, line 1102
      def each_authority
        @authority.each {|name, ttl, data|
          yield name, ttl, data
        }
      end


add_additional (Resolv::DNS::Message)

# File lib/resolv.rb, line 1108
      def add_additional(name, ttl, data)
        @additional << [Name.create(name), ttl, data]
      end


each_additional (Resolv::DNS::Message)

# File lib/resolv.rb, line 1112
      def each_additional
        @additional.each {|name, ttl, data|
          yield name, ttl, data
        }
      end


each_resource (Resolv::DNS::Message)

# File lib/resolv.rb, line 1118
      def each_resource
        each_answer {|name, ttl, data| yield name, ttl, data}
        each_authority {|name, ttl, data| yield name, ttl, data}
        each_additional {|name, ttl, data| yield name, ttl, data}
      end


encode (Resolv::DNS::Message)

# File lib/resolv.rb, line 1124
      def encode
        return MessageEncoder.new {|msg|
          msg.put_pack('nnnnnn',
            @id,
            (@qr & 1) << 15 |
            (@opcode & 15) << 11 |
            (@aa & 1) << 10 |
            (@tc & 1) << 9 |
            (@rd & 1) << 8 |
            (@ra & 1) << 7 |
            (@rcode & 15),
            @question.length,
            @answer.length,
            @authority.length,
            @additional.length)
          @question.each {|q|
            name, typeclass = q
            msg.put_name(name)
            msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
          }
          [@answer, @authority, @additional].each {|rr|
            rr.each {|r|
              name, ttl, data = r
              msg.put_name(name)
              msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
              msg.put_length16 {data.encode_rdata(msg)}
            }
          }
        }.to_s
      end


decode (Resolv::DNS::Message)

# File lib/resolv.rb, line 1217
      def Message.decode(m)
        o = Message.new(0)
        MessageDecoder.new(m) {|msg|
          id, flag, qdcount, ancount, nscount, arcount =
            msg.get_unpack('nnnnnn')
          o.id = id
          o.qr = (flag >> 15) & 1
          o.opcode = (flag >> 11) & 15
          o.aa = (flag >> 10) & 1
          o.tc = (flag >> 9) & 1
          o.rd = (flag >> 8) & 1
          o.ra = (flag >> 7) & 1
          o.rcode = flag & 15
          (1..qdcount).each {
            name, typeclass = msg.get_question
            o.add_question(name, typeclass)
          }
          (1..ancount).each {
            name, ttl, data = msg.get_rr
            o.add_answer(name, ttl, data)
          }
          (1..nscount).each {
            name, ttl, data = msg.get_rr
            o.add_authority(name, ttl, data)
          }
          (1..arcount).each {
            name, ttl, data = msg.get_rr
            o.add_additional(name, ttl, data)
          }
        }
        return o
      end


create (Resolv::DNS::Name)

# File lib/resolv.rb, line 965
      def self.create(arg)
        case arg
        when Name
          return arg
        when String
          return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
        else
          raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
        end
      end


new (Resolv::DNS::Name)

# File lib/resolv.rb, line 976
      def initialize(labels, absolute=true)
        @labels = labels
        @absolute = absolute
      end


inspect (Resolv::DNS::Name)

# File lib/resolv.rb, line 981
      def inspect
        "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
      end


absolute? (Resolv::DNS::Name)

# File lib/resolv.rb, line 985
      def absolute?
        return @absolute
      end


== (Resolv::DNS::Name)

# File lib/resolv.rb, line 989
      def ==(other)
        return false unless Name === other
        return @labels == other.to_a && @absolute == other.absolute?
      end


subdomain_of? (Resolv::DNS::Name)

# File lib/resolv.rb, line 1005
      def subdomain_of?(other)
        raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
        return false if @absolute != other.absolute?
        other_len = other.length
        return false if @labels.length <= other_len
        return @labels[-other_len, other_len] == other.to_a
      end


hash (Resolv::DNS::Name)

# File lib/resolv.rb, line 1013
      def hash
        return @labels.hash ^ @absolute.hash
      end


to_a (Resolv::DNS::Name)

# File lib/resolv.rb, line 1017
      def to_a
        return @labels
      end


length (Resolv::DNS::Name)

# File lib/resolv.rb, line 1021
      def length
        return @labels.length
      end


[] (Resolv::DNS::Name)

# File lib/resolv.rb, line 1025
      def [](i)
        return @labels[i]
      end


to_s (Resolv::DNS::Name)

# File lib/resolv.rb, line 1037
      def to_s
        return @labels.join('.')
      end


encode_rdata (Resolv::DNS::Query)

# File lib/resolv.rb, line 1363
      def encode_rdata(msg)
        raise EncodeError.new("#{self.class} is query.")
      end


decode_rdata (Resolv::DNS::Query)

# File lib/resolv.rb, line 1367
      def self.decode_rdata(msg)
        raise DecodeError.new("#{self.class} is query.")
      end


send (Resolv::DNS::Requester::ConnectedUDP::Sender)

# File lib/resolv.rb, line 658
          def send
            @sock.send(@msg, 0)
          end


new (Resolv::DNS::Requester::ConnectedUDP)

# File lib/resolv.rb, line 620
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          @sock = UDPSocket.new(host.index(':') ? Socket::AF_INET6 : Socket::AF_INET)
          @sock.connect(host, port)
          @sock.fcntl(Fcntl::F_SETFD, 1) if defined? Fcntl::F_SETFD
          @id = -1
          @thread = Thread.new {
            DNSThreadGroup.add Thread.current
            loop {
              reply = @sock.recv(UDPSize)
              msg = begin
                Message.decode(reply)
              rescue DecodeError
                STDERR.print("DNS message decoding error: #{reply.inspect}")
                next
              end
              if s = @senders[msg.id]
                s.recv msg
              else
                #STDERR.print("non-handled DNS message: #{msg.inspect}")
              end
            }
          }
        end


sender (Resolv::DNS::Requester::ConnectedUDP)

# File lib/resolv.rb, line 647
        def sender(msg, data, queue, host=@host, port=@port)
          unless host == @host && port == @port
            raise RequestError.new("host/port don't match: #{host}:#{port}")
          end
          id = Thread.exclusive { @id = (@id + 1) & 0xffff }
          request = msg.encode
          request[0,2] = [id].pack('n')
          return @senders[id] = Sender.new(request, data, @sock, queue)
        end


new (Resolv::DNS::Requester::Sender)

# File lib/resolv.rb, line 556
        def initialize(msg, data, sock, queue)
          @msg = msg
          @data = data
          @sock = sock
          @queue = queue
        end


recv (Resolv::DNS::Requester::Sender)

# File lib/resolv.rb, line 564
        def recv(msg)
          @queue.push([msg, @data])
        end


send (Resolv::DNS::Requester::TCP::Sender)

# File lib/resolv.rb, line 705
          def send
            @sock.print(@msg)
            @sock.flush
          end


new (Resolv::DNS::Requester::TCP)

# File lib/resolv.rb, line 665
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          @sock = TCPSocket.new
          @sock.connect(host, port)
          @sock.fcntl(Fcntl::F_SETFD, 1) if defined? Fcntl::F_SETFD
          @id = -1
          @senders = {}
          @thread = Thread.new {
            DNSThreadGroup.add Thread.current
            loop {
              len = @sock.read(2).unpack('n')
              reply = @sock.read(len)
              msg = begin
                Message.decode(reply)
              rescue DecodeError
                STDERR.print("DNS message decoding error: #{reply.inspect}")
                next
              end
              if s = @senders[msg.id]
                s.push msg
              else
                #STDERR.print("non-handled DNS message: #{msg.inspect}")
              end
            }
          }
        end


sender (Resolv::DNS::Requester::TCP)

# File lib/resolv.rb, line 694
        def sender(msg, data, queue, host=@host, port=@port)
          unless host == @host && port == @port
            raise RequestError.new("host/port don't match: #{host}:#{port}")
          end
          id = Thread.exclusive { @id = (@id + 1) & 0xffff }
          request = msg.encode
          request[0,2] = [request.length, id].pack('nn')
          return @senders[id] = Sender.new(request, data, @sock, queue)
        end


new (Resolv::DNS::Requester::UnconnectedUDP::Sender)

# File lib/resolv.rb, line 607
          def initialize(msg, data, sock, host, port, queue)
            super(msg, data, sock, queue)
            @host = host
            @port = port
          end


send (Resolv::DNS::Requester::UnconnectedUDP::Sender)

# File lib/resolv.rb, line 613
          def send
            @sock.send(@msg, 0, @host, @port)
          end


new (Resolv::DNS::Requester::UnconnectedUDP)

# File lib/resolv.rb, line 570
        def initialize
          super()
          @sock = UDPSocket.new
          @sock.fcntl(Fcntl::F_SETFD, 1) if defined? Fcntl::F_SETFD
          @id = {}
          @id.default = -1
          @thread = Thread.new {
            DNSThreadGroup.add Thread.current
            loop {
              reply, from = @sock.recvfrom(UDPSize)
              msg = begin
                Message.decode(reply)
              rescue DecodeError
                STDERR.print("DNS message decoding error: #{reply.inspect}\n")
                next
              end
              if s = @senders[[[from[3],from[1]],msg.id]]
                s.recv msg
              else
                #STDERR.print("non-handled DNS message: #{msg.inspect} from #{from.inspect}\n")
              end
            }
          }
        end


sender (Resolv::DNS::Requester::UnconnectedUDP)

# File lib/resolv.rb, line 595
        def sender(msg, data, queue, host, port=Port)
          service = [host, port]
          id = Thread.exclusive {
            @id[service] = (@id[service] + 1) & 0xffff
          }
          request = msg.encode
          request[0,2] = [id].pack('n')
          return @senders[[service, id]] =
            Sender.new(request, data, @sock, host, port, queue)
        end


new (Resolv::DNS::Requester)

# File lib/resolv.rb, line 528
      def initialize
        @senders = {}
      end


close (Resolv::DNS::Requester)

# File lib/resolv.rb, line 532
      def close
        thread, sock, @thread, @sock = @thread, @sock
        begin
          if thread
            thread.kill
            thread.join
          end
        ensure
          sock.close if sock
        end
      end


delete (Resolv::DNS::Requester)

# File lib/resolv.rb, line 544
      def delete(arg)
        case arg
        when Sender
          @senders.delete_if {|k, s| s == arg }
        when Queue
          @senders.delete_if {|k, s| s.queue == arg }
        else
          raise ArgumentError.new("neither Sender or Queue: #{arg}")
        end
      end


new (Resolv::DNS::Resource::DomainName)

# File lib/resolv.rb, line 1432
        def initialize(name)
          @name = name
        end


encode_rdata (Resolv::DNS::Resource::DomainName)

# File lib/resolv.rb, line 1437
        def encode_rdata(msg)
          msg.put_name(@name)
        end


decode_rdata (Resolv::DNS::Resource::DomainName)

# File lib/resolv.rb, line 1441
        def self.decode_rdata(msg)
          return self.new(msg.get_name)
        end


new (Resolv::DNS::Resource::Generic)

# File lib/resolv.rb, line 1408
        def initialize(data)
          @data = data
        end


encode_rdata (Resolv::DNS::Resource::Generic)

# File lib/resolv.rb, line 1413
        def encode_rdata(msg)
          msg.put_bytes(data)
        end


decode_rdata (Resolv::DNS::Resource::Generic)

# File lib/resolv.rb, line 1417
        def self.decode_rdata(msg)
          return self.new(msg.get_bytes)
        end


create (Resolv::DNS::Resource::Generic)

# File lib/resolv.rb, line 1421
        def self.create(type_value, class_value)
          c = Class.new(Generic)
          c.const_set(:TypeValue, type_value)
          c.const_set(:ClassValue, class_value)
          Generic.const_set("Type#{type_value}_Class#{class_value}", c)
          ClassHash[[type_value, class_value]] = c
          return c
        end


new (Resolv::DNS::Resource::HINFO)

# File lib/resolv.rb, line 1493
        def initialize(cpu, os)
          @cpu = cpu
          @os = os
        end


encode_rdata (Resolv::DNS::Resource::HINFO)

# File lib/resolv.rb, line 1499
        def encode_rdata(msg)
          msg.put_string(@cpu)
          msg.put_string(@os)
        end


decode_rdata (Resolv::DNS::Resource::HINFO)

# File lib/resolv.rb, line 1504
        def self.decode_rdata(msg)
          cpu = msg.get_string
          os = msg.get_string
          return self.new(cpu, os)
        end


new (Resolv::DNS::Resource::IN::A)

# File lib/resolv.rb, line 1598
          def initialize(address)
            @address = IPv4.create(address)
          end


encode_rdata (Resolv::DNS::Resource::IN::A)

# File lib/resolv.rb, line 1603
          def encode_rdata(msg)
            msg.put_bytes(@address.address)
          end


decode_rdata (Resolv::DNS::Resource::IN::A)

# File lib/resolv.rb, line 1607
          def self.decode_rdata(msg)
            return self.new(IPv4.new(msg.get_bytes(4)))
          end


new (Resolv::DNS::Resource::IN::AAAA)

# File lib/resolv.rb, line 1639
          def initialize(address)
            @address = IPv6.create(address)
          end


encode_rdata (Resolv::DNS::Resource::IN::AAAA)

# File lib/resolv.rb, line 1644
          def encode_rdata(msg)
            msg.put_bytes(@address.address)
          end


decode_rdata (Resolv::DNS::Resource::IN::AAAA)

# File lib/resolv.rb, line 1648
          def self.decode_rdata(msg)
            return self.new(IPv6.new(msg.get_bytes(16)))
          end


new (Resolv::DNS::Resource::IN::SRV)

# File lib/resolv.rb, line 1685
          def initialize(priority, weight, port, target)
            @priority = priority.to_int
            @weight = weight.to_int
            @port = port.to_int
            @target = Name.create(target)
          end


encode_rdata (Resolv::DNS::Resource::IN::SRV)

# File lib/resolv.rb, line 1694
          def encode_rdata(msg)
            msg.put_pack("n", @priority)
            msg.put_pack("n", @weight)
            msg.put_pack("n", @port)
            msg.put_name(@target)
          end


decode_rdata (Resolv::DNS::Resource::IN::SRV)

# File lib/resolv.rb, line 1701
          def self.decode_rdata(msg)
            priority, = msg.get_unpack("n")
            weight,   = msg.get_unpack("n")
            port,     = msg.get_unpack("n")
            target    = msg.get_name
            return self.new(priority, weight, port, target)
          end


new (Resolv::DNS::Resource::IN::WKS)

# File lib/resolv.rb, line 1615
          def initialize(address, protocol, bitmap)
            @address = IPv4.create(address)
            @protocol = protocol
            @bitmap = bitmap
          end


encode_rdata (Resolv::DNS::Resource::IN::WKS)

# File lib/resolv.rb, line 1622
          def encode_rdata(msg)
            msg.put_bytes(@address.address)
            msg.put_pack("n", @protocol)
            msg.put_bytes(@bitmap)
          end


decode_rdata (Resolv::DNS::Resource::IN::WKS)

# File lib/resolv.rb, line 1628
          def self.decode_rdata(msg)
            address = IPv4.new(msg.get_bytes(4))
            protocol, = msg.get_unpack("n")
            bitmap = msg.get_bytes
            return self.new(address, protocol, bitmap)
          end


new (Resolv::DNS::Resource::MINFO)

# File lib/resolv.rb, line 1514
        def initialize(rmailbx, emailbx)
          @rmailbx = rmailbx
          @emailbx = emailbx
        end


encode_rdata (Resolv::DNS::Resource::MINFO)

# File lib/resolv.rb, line 1520
        def encode_rdata(msg)
          msg.put_name(@rmailbx)
          msg.put_name(@emailbx)
        end


decode_rdata (Resolv::DNS::Resource::MINFO)

# File lib/resolv.rb, line 1525
        def self.decode_rdata(msg)
          rmailbx = msg.get_string
          emailbx = msg.get_string
          return self.new(rmailbx, emailbx)
        end


new (Resolv::DNS::Resource::MX)

# File lib/resolv.rb, line 1535
        def initialize(preference, exchange)
          @preference = preference
          @exchange = exchange
        end


encode_rdata (Resolv::DNS::Resource::MX)

# File lib/resolv.rb, line 1541
        def encode_rdata(msg)
          msg.put_pack('n', @preference)
          msg.put_name(@exchange)
        end


decode_rdata (Resolv::DNS::Resource::MX)

# File lib/resolv.rb, line 1546
        def self.decode_rdata(msg)
          preference, = msg.get_unpack('n')
          exchange = msg.get_name
          return self.new(preference, exchange)
        end


new (Resolv::DNS::Resource::SOA)

# File lib/resolv.rb, line 1460
        def initialize(mname, rname, serial, refresh, retry_, expire, minimum)
          @mname = mname
          @rname = rname
          @serial = serial
          @refresh = refresh
          @retry = retry_
          @expire = expire
          @minimum = minimum
        end


encode_rdata (Resolv::DNS::Resource::SOA)

# File lib/resolv.rb, line 1471
        def encode_rdata(msg)
          msg.put_name(@mname)
          msg.put_name(@rname)
          msg.put_pack('NNNNN', @serial, @refresh, @retry, @expire, @minimum)
        end


decode_rdata (Resolv::DNS::Resource::SOA)

# File lib/resolv.rb, line 1477
        def self.decode_rdata(msg)
          mname = msg.get_name
          rname = msg.get_name
          serial, refresh, retry_, expire, minimum = msg.get_unpack('NNNNN')
          return self.new(
            mname, rname, serial, refresh, retry_, expire, minimum)
        end


new (Resolv::DNS::Resource::TXT)

# File lib/resolv.rb, line 1556
        def initialize(first_string, *rest_strings)
          @strings = [first_string, *rest_strings]
        end


data (Resolv::DNS::Resource::TXT)

# File lib/resolv.rb, line 1561
        def data
          @strings[0]
        end


encode_rdata (Resolv::DNS::Resource::TXT)

# File lib/resolv.rb, line 1565
        def encode_rdata(msg)
          msg.put_string_list(@strings)
        end


decode_rdata (Resolv::DNS::Resource::TXT)

# File lib/resolv.rb, line 1569
        def self.decode_rdata(msg)
          strings = msg.get_string_list
          return self.new(*strings)
        end


encode_rdata (Resolv::DNS::Resource)

# File lib/resolv.rb, line 1375
      def encode_rdata(msg)
        raise NotImplementedError.new
      end


decode_rdata (Resolv::DNS::Resource)

# File lib/resolv.rb, line 1379
      def self.decode_rdata(msg)
        raise NotImplementedError.new
      end


== (Resolv::DNS::Resource)

# File lib/resolv.rb, line 1383
      def ==(other)
        return self.class == other.class &&
          self.instance_variables == other.instance_variables &&
          self.instance_variables.collect {|name| self.instance_eval name} ==
            other.instance_variables.collect {|name| other.instance_eval name}
      end


eql? (Resolv::DNS::Resource)

# File lib/resolv.rb, line 1390
      def eql?(other)
        return self == other
      end


hash (Resolv::DNS::Resource)

# File lib/resolv.rb, line 1394
      def hash
        h = 0
        self.instance_variables.each {|name|
          h ^= self.instance_eval("#{name}.hash")
        }
        return h
      end


get_class (Resolv::DNS::Resource)

# File lib/resolv.rb, line 1402
      def self.get_class(type_value, class_value)
        return ClassHash[[type_value, class_value]] ||
               Generic.create(type_value, class_value)
      end


open (Resolv::DNS)

# File lib/resolv.rb, line 371
    def self.open(*args)
      dns = new(*args)
      return dns unless block_given?
      begin
        yield dns
      ensure
        dns.close
      end
    end


new (Resolv::DNS)

# File lib/resolv.rb, line 381
    def initialize(config_info=nil)
      @mutex = Mutex.new
      @config = Config.new(config_info)
      @initialized = nil
    end


lazy_initialize (Resolv::DNS)

# File lib/resolv.rb, line 387
    def lazy_initialize
      @mutex.synchronize {
        unless @initialized
          @config.lazy_initialize

          if nameserver = @config.single?
            @requester = Requester::ConnectedUDP.new(nameserver)
          else
            @requester = Requester::UnconnectedUDP.new
          end

          @initialized = true
        end
      }
      self
    end


close (Resolv::DNS)

# File lib/resolv.rb, line 404
    def close
      @mutex.synchronize {
        if @initialized
          @requester.close if @requester
          @requester = nil
          @initialized = false
        end
      }
    end


getaddress (Resolv::DNS)

# File lib/resolv.rb, line 414
    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("DNS result has no information for #{name}")
    end


getaddresses (Resolv::DNS)

# File lib/resolv.rb, line 419
    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end


each_address (Resolv::DNS)

# File lib/resolv.rb, line 425
    def each_address(name)
      each_resource(name, Resource::IN::A) {|resource| yield resource.address}
    end


getname (Resolv::DNS)

# File lib/resolv.rb, line 429
    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("DNS result has no information for #{address}")
    end


getnames (Resolv::DNS)

# File lib/resolv.rb, line 434
    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end


each_name (Resolv::DNS)

# File lib/resolv.rb, line 440
    def each_name(address)
      case address
      when Name
        ptr = address
      when IPv4::Regex
        ptr = IPv4.create(address).to_name
      when IPv6::Regex
        ptr = IPv6.create(address).to_name
      else
        raise ResolvError.new("cannot interpret as address: #{address}")
      end
      each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
    end


getresource (Resolv::DNS)

# File lib/resolv.rb, line 454
    def getresource(name, typeclass)
      each_resource(name, typeclass) {|resource| return resource}
      raise ResolvError.new("DNS result has no information for #{name}")
    end


getresources (Resolv::DNS)

# File lib/resolv.rb, line 459
    def getresources(name, typeclass)
      ret = []
      each_resource(name, typeclass) {|resource| ret << resource}
      return ret
    end


each_resource (Resolv::DNS)

# File lib/resolv.rb, line 465
    def each_resource(name, typeclass, &proc)
      lazy_initialize
      q = Queue.new
      senders = {}
      begin
        @config.resolv(name) {|candidate, tout, nameserver|
          msg = Message.new
          msg.rd = 1
          msg.add_question(candidate, typeclass)
          unless sender = senders[[candidate, nameserver]]
            sender = senders[[candidate, nameserver]] =
              @requester.sender(msg, candidate, q, nameserver)
          end
          sender.send
          reply = reply_name = nil
          timeout(tout, ResolvTimeout) { reply, reply_name = q.pop }
          case reply.rcode
          when RCode::NoError
            extract_resources(reply, reply_name, typeclass, &proc)
            return
          when RCode::NXDomain
            raise Config::NXDomain.new(reply_name.to_s)
          else
            raise Config::OtherResolvError.new(reply_name.to_s)
          end
        }
      ensure
        @requester.delete(q)
      end
    end


extract_resources (Resolv::DNS)

# File lib/resolv.rb, line 496
    def extract_resources(msg, name, typeclass)
      if typeclass < Resource::ANY
        n0 = Name.create(name)
        msg.each_answer {|n, ttl, data|
          yield data if n0 == n
        }
      end
      yielded = false
      n0 = Name.create(name)
      msg.each_answer {|n, ttl, data|
        if n0 == n
          case data
          when typeclass
            yield data
            yielded = true
          when Resource::CNAME
            n0 = data.name
          end
        end
      }
      return if yielded
      msg.each_answer {|n, ttl, data|
        if n0 == n
          case data
          when typeclass
            yield data
          end
        end
      }
    end


new (Resolv::Hosts)

# File lib/resolv.rb, line 288
    def initialize(filename = DefaultFileName)
      @filename = filename
      @mutex = Mutex.new
      @initialized = nil
    end


lazy_initialize (Resolv::Hosts)

# File lib/resolv.rb, line 294
    def lazy_initialize
      @mutex.synchronize {
        unless @initialized
          @name2addr = {}
          @addr2name = {}
          open(@filename) {|f|
            f.each {|line|
              line.sub!(/#.*/, '')
              addr, hostname, *aliases = line.split(/\s+/)
              next unless addr
              addr.untaint
              hostname.untaint
              @addr2name[addr] = [] unless @addr2name.include? addr
              @addr2name[addr] << hostname
              @addr2name[addr] += aliases
              @name2addr[hostname] = [] unless @name2addr.include? hostname
              @name2addr[hostname] << addr
              aliases.each {|n|
                n.untaint
                @name2addr[n] = [] unless @name2addr.include? n
                @name2addr[n] << addr
              }
            }
          }
          @name2addr.each {|name, arr| arr.reverse!}
          @initialized = true
        end
      }
      self
    end


getaddress (Resolv::Hosts)

# File lib/resolv.rb, line 325
    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("#{@filename} has no name: #{name}")
    end


getaddresses (Resolv::Hosts)

# File lib/resolv.rb, line 330
    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end


each_address (Resolv::Hosts)

# File lib/resolv.rb, line 336
    def each_address(name, &proc)
      lazy_initialize
      if @name2addr.include?(name)
        @name2addr[name].each(&proc)
      end
    end


getname (Resolv::Hosts)

# File lib/resolv.rb, line 343
    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("#{@filename} has no address: #{address}")
    end


getnames (Resolv::Hosts)

# File lib/resolv.rb, line 348
    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end


each_name (Resolv::Hosts)

# File lib/resolv.rb, line 354
    def each_name(address, &proc)
      lazy_initialize
      if @addr2name.include?(address)
        @addr2name[address].each(&proc)
      end
    end


create (Resolv::IPv4)

# File lib/resolv.rb, line 1717
    def self.create(arg)
      case arg
      when IPv4
        return arg
      when Regex
        if (0..255) === (a = $1.to_i) &&
           (0..255) === (b = $2.to_i) &&
           (0..255) === (c = $3.to_i) &&
           (0..255) === (d = $4.to_i)
          return self.new([a, b, c, d].pack("CCCC"))
        else
          raise ArgumentError.new("IPv4 address with invalid value: " + arg)
        end
      else
        raise ArgumentError.new("cannot interpret as IPv4 address: #{arg.inspect}")
      end
    end


new (Resolv::IPv4)

# File lib/resolv.rb, line 1735
    def initialize(address)
      unless address.kind_of?(String) && address.length == 4
        raise ArgumentError.new('IPv4 address must be 4 bytes')
      end
      @address = address
    end


to_s (Resolv::IPv4)

# File lib/resolv.rb, line 1743
    def to_s
      return sprintf("%d.%d.%d.%d", *@address.unpack("CCCC"))
    end


inspect (Resolv::IPv4)

# File lib/resolv.rb, line 1747
    def inspect
      return "#<#{self.class} #{self.to_s}>"
    end


to_name (Resolv::IPv4)

# File lib/resolv.rb, line 1751
    def to_name
      return DNS::Name.create(
        '%d.%d.%d.%d.in-addr.arpa.' % @address.unpack('CCCC').reverse)
    end


== (Resolv::IPv4)

# File lib/resolv.rb, line 1756
    def ==(other)
      return @address == other.address
    end


eql? (Resolv::IPv4)

# File lib/resolv.rb, line 1760
    def eql?(other)
      return self == other
    end


hash (Resolv::IPv4)

# File lib/resolv.rb, line 1764
    def hash
      return @address.hash
    end


create (Resolv::IPv6)

# File lib/resolv.rb, line 1797
    def self.create(arg)
      case arg
      when IPv6
        return arg
      when String
        address = ''
        if Regex_8Hex =~ arg
          arg.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
        elsif Regex_CompressedHex =~ arg
          prefix = $1
          suffix = $2
          a1 = ''
          a2 = ''
          prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
          suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
          omitlen = 16 - a1.length - a2.length
          address << a1 << "\0" * omitlen << a2
        elsif Regex_6Hex4Dec =~ arg
          prefix, a, b, c, d = $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i
          if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
            prefix.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
            address << [a, b, c, d].pack('CCCC')
          else
            raise ArgumentError.new("not numeric IPv6 address: " + arg)
          end
        elsif Regex_CompressedHex4Dec =~ arg
          prefix, suffix, a, b, c, d = $1, $2, $3.to_i, $4.to_i, $5.to_i, $6.to_i
          if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
            a1 = ''
            a2 = ''
            prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
            suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
            omitlen = 12 - a1.length - a2.length
            address << a1 << "\0" * omitlen << a2 << [a, b, c, d].pack('CCCC')
          else
            raise ArgumentError.new("not numeric IPv6 address: " + arg)
          end
        else
          raise ArgumentError.new("not numeric IPv6 address: " + arg)
        end
        return IPv6.new(address)
      else
        raise ArgumentError.new("cannot interpret as IPv6 address: #{arg.inspect}")
      end
    end


new (Resolv::IPv6)

# File lib/resolv.rb, line 1843
    def initialize(address)
      unless address.kind_of?(String) && address.length == 16
        raise ArgumentError.new('IPv6 address must be 16 bytes')
      end
      @address = address
    end


to_s (Resolv::IPv6)

# File lib/resolv.rb, line 1851
    def to_s
      address = sprintf("%X:%X:%X:%X:%X:%X:%X:%X", *@address.unpack("nnnnnnnn"))
      unless address.sub!(/(^|:)0(:0)+(:|$)/, '::')
        address.sub!(/(^|:)0(:|$)/, '::')
      end
      return address
    end


inspect (Resolv::IPv6)

# File lib/resolv.rb, line 1859
    def inspect
      return "#<#{self.class} #{self.to_s}>"
    end


to_name (Resolv::IPv6)

# File lib/resolv.rb, line 1863
    def to_name
      # ip6.arpa should be searched too. [RFC3152]
      return DNS::Name.new(
        @address.unpack("H32")[0].split(//).reverse + ['ip6', 'int'])
    end


== (Resolv::IPv6)

# File lib/resolv.rb, line 1869
    def ==(other)
      return @address == other.address
    end


eql? (Resolv::IPv6)

# File lib/resolv.rb, line 1873
    def eql?(other)
      return self == other
    end


hash (Resolv::IPv6)

# File lib/resolv.rb, line 1877
    def hash
      return @address.hash
    end


getaddress (Resolv)

# File lib/resolv.rb, line 198
  def self.getaddress(name)
    DefaultResolver.getaddress(name)
  end


getaddresses (Resolv)

# File lib/resolv.rb, line 202
  def self.getaddresses(name)
    DefaultResolver.getaddresses(name)
  end


each_address (Resolv)

# File lib/resolv.rb, line 206
  def self.each_address(name, &block)
    DefaultResolver.each_address(name, &block)
  end


getname (Resolv)

# File lib/resolv.rb, line 210
  def self.getname(address)
    DefaultResolver.getname(address)
  end


getnames (Resolv)

# File lib/resolv.rb, line 214
  def self.getnames(address)
    DefaultResolver.getnames(address)
  end


each_name (Resolv)

# File lib/resolv.rb, line 218
  def self.each_name(address, &proc)
    DefaultResolver.each_name(address, &proc)
  end


new (Resolv)

# File lib/resolv.rb, line 222
  def initialize(resolvers=[Hosts.new, DNS.new])
    @resolvers = resolvers
  end


getaddress (Resolv)

# File lib/resolv.rb, line 226
  def getaddress(name)
    each_address(name) {|address| return address}
    raise ResolvError.new("no address for #{name}")
  end


getaddresses (Resolv)

# File lib/resolv.rb, line 231
  def getaddresses(name)
    ret = []
    each_address(name) {|address| ret << address}
    return ret
  end


each_address (Resolv)

# File lib/resolv.rb, line 237
  def each_address(name)
    if AddressRegex =~ name
      yield name
      return
    end
    yielded = false
    @resolvers.each {|r|
      r.each_address(name) {|address|
        yield address.to_s
        yielded = true
      }
      return if yielded
    }
  end


getname (Resolv)

# File lib/resolv.rb, line 252
  def getname(address)
    each_name(address) {|name| return name}
    raise ResolvError.new("no name for #{address}")
  end


getnames (Resolv)

# File lib/resolv.rb, line 257
  def getnames(address)
    ret = []
    each_name(address) {|name| ret << name}
    return ret
  end


each_name (Resolv)

# File lib/resolv.rb, line 263
  def each_name(address)
    yielded = false
    @resolvers.each {|r|
      r.each_name(address) {|name|
        yield name.to_s
        yielded = true
      }
      return if yielded
    }
  end


new (REXML::AttlistDecl)

# File lib/rexml/attlistdecl.rb, line 28
                def initialize(source)
                        super()
                        if (source.kind_of? Array)
                                @element_name, @pairs, @contents = *source
                        end
                end


[] (REXML::AttlistDecl)

# File lib/rexml/attlistdecl.rb, line 37
                def [](key)
                        @pairs[key]
                end


include? (REXML::AttlistDecl)

# File lib/rexml/attlistdecl.rb, line 43
                def include?(key)
                        @pairs.keys.include? key
                end


each (REXML::AttlistDecl)

# File lib/rexml/attlistdecl.rb, line 49
                def each(&block)
                        @pairs.each(&block)
                end


write (REXML::AttlistDecl)

# File lib/rexml/attlistdecl.rb, line 54
                def write out, indent=-1
                        out << @contents
                end


node_type (REXML::AttlistDecl)

# File lib/rexml/attlistdecl.rb, line 58
                def node_type
                        :attlistdecl
                end


new (REXML::Attribute)

# File lib/rexml/attribute.rb, line 42
                def initialize( first, second=nil, parent=nil )
                        @normalized = @unnormalized = @element = nil
                        if first.kind_of? Attribute
                                self.name = first.expanded_name
                                @unnormalized = first.value
                                if second.kind_of? Element
                                        @element = second
                                else
                                        @element = first.element
                                end
                        elsif first.kind_of? String
                                @element = parent
                                self.name = first
                                @normalized = second.to_s
                        else
                                raise "illegal argument #{first.class.name} to Attribute constructor"
                        end
                end


prefix (REXML::Attribute)

# File lib/rexml/attribute.rb, line 70
                def prefix
                        pf = super
                        if pf == ""
                                pf = @element.prefix if @element
                        end
                        pf
                end


namespace (REXML::Attribute)

# File lib/rexml/attribute.rb, line 83
                def namespace arg=nil
                        arg = prefix if arg.nil?
                        @element.namespace arg
                end


== (REXML::Attribute)

# File lib/rexml/attribute.rb, line 90
                def ==( other )
                        other.kind_of?(Attribute) and other.name==name and other.value==value
                end


hash (REXML::Attribute)

# File lib/rexml/attribute.rb, line 95
                def hash
                        name.hash + value.hash
                end


to_string (REXML::Attribute)

# File lib/rexml/attribute.rb, line 105
                def to_string
                        if @element and @element.context and @element.context[:attribute_quote] == :quote
                                %Q^#@expanded_name="#{to_s().gsub(/"/, '&quote;')}"^
                        else
                                "#@expanded_name='#{to_s().gsub(/'/, '&apos;')}'"
                        end
                end


to_s (REXML::Attribute)

# File lib/rexml/attribute.rb, line 114
                def to_s
                        return @normalized if @normalized

                        doctype = nil
                        if @element
                                doc = @element.document
                                doctype = doc.doctype if doc
                        end

                        @normalized = Text::normalize( @unnormalized, doctype )
                        @unnormalized = nil
      @normalized
                end


value (REXML::Attribute)

# File lib/rexml/attribute.rb, line 130
                def value
                        return @unnormalized if @unnormalized
                        doctype = nil
                        if @element
                                doc = @element.document
                                doctype = doc.doctype if doc
                        end
                        @unnormalized = Text::unnormalize( @normalized, doctype )
                        @normalized = nil
      @unnormalized
                end


clone (REXML::Attribute)

# File lib/rexml/attribute.rb, line 143
                def clone
                        Attribute.new self
                end


element= (REXML::Attribute)

# File lib/rexml/attribute.rb, line 151
                def element=( element )
                        @element = element
                        self
                end


remove (REXML::Attribute)

# File lib/rexml/attribute.rb, line 159
                def remove
                        @element.attributes.delete self.name unless @element.nil?
                end


write (REXML::Attribute)

# File lib/rexml/attribute.rb, line 164
                def write( output, indent=-1 )
                        output << to_string
                end


node_type (REXML::Attribute)

# File lib/rexml/attribute.rb, line 168
    def node_type
      :attribute
    end


inspect (REXML::Attribute)

# File lib/rexml/attribute.rb, line 172
    def inspect
      rv = ""
      write( rv )
      rv
    end


xpath (REXML::Attribute)

# File lib/rexml/attribute.rb, line 178
    def xpath
      path = @element.xpath
      path += "/@#{self.expanded_name}"
      return path
    end


new (REXML::Attributes)

# File lib/rexml/element.rb, line 957
    def initialize element
      @element = element
    end


[] (REXML::Attributes)

# File lib/rexml/element.rb, line 972
    def [](name)
      attr = get_attribute(name)
      return attr.value unless attr.nil?
      return nil
    end


to_a (REXML::Attributes)

# File lib/rexml/element.rb, line 978
    def to_a
      values.flatten
    end


length (REXML::Attributes)

# File lib/rexml/element.rb, line 985
    def length
      c = 0
      each_attribute { c+=1 }
      c
    end


each_attribute (REXML::Attributes)

# File lib/rexml/element.rb, line 999
    def each_attribute # :yields: attribute
      each_value do |val|
        if val.kind_of? Attribute
          yield val
        else
          val.each_value { |atr| yield atr }
        end
      end
    end


each (REXML::Attributes)

# File lib/rexml/element.rb, line 1014
    def each
      each_attribute do |attr|
        yield attr.expanded_name, attr.value
      end
    end


get_attribute (REXML::Attributes)

# File lib/rexml/element.rb, line 1029
    def get_attribute( name )
      attr = fetch( name, nil )
      if attr.nil?
        return nil if name.nil?
        # Look for prefix
        name =~ Namespace::NAMESPLIT
        prefix, n = $1, $2
        if prefix
          attr = fetch( n, nil )
          # check prefix
          if attr == nil
          elsif attr.kind_of? Attribute
            return attr if prefix == attr.prefix
          else
            attr = attr[ prefix ]
            return attr
          end
        end
        element_document = @element.document
        if element_document and element_document.doctype
          expn = @element.expanded_name
          expn = element_document.doctype.name if expn.size == 0
          attr_val = element_document.doctype.attribute_of(expn, name)
          return Attribute.new( name, attr_val ) if attr_val
        end
        return nil
      end
      if attr.kind_of? Hash
        attr = attr[ @element.prefix ]
      end
      return attr
    end


[]= (REXML::Attributes)

# File lib/rexml/element.rb, line 1074
    def []=( name, value )
      if value.nil?             # Delete the named attribute
        attr = get_attribute(name)
        delete attr
        return
      end
      element_document = @element.document
      unless value.kind_of? Attribute
        if @element.document and @element.document.doctype
          value = Text::normalize( value, @element.document.doctype )
        else
          value = Text::normalize( value, nil )
        end
        value = Attribute.new(name, value)
      end
      value.element = @element
      old_attr = fetch(value.name, nil)
      if old_attr.nil?
        store(value.name, value)
      elsif old_attr.kind_of? Hash
        old_attr[value.prefix] = value
      elsif old_attr.prefix != value.prefix
        # Check for conflicting namespaces
        raise ParseException.new(
          "Namespace conflict in adding attribute \"#{value.name}\": "+
          "Prefix \"#{old_attr.prefix}\" = "+
          "\"#{@element.namespace(old_attr.prefix)}\" and prefix "+
          "\"#{value.prefix}\" = \"#{@element.namespace(value.prefix)}\"") if
          value.prefix != "xmlns" and old_attr.prefix != "xmlns" and
          @element.namespace( old_attr.prefix ) ==
            @element.namespace( value.prefix )
          store value.name, { old_attr.prefix   => old_attr,
            value.prefix                => value }
      else
        store value.name, value
      end
      return @element
    end


prefixes (REXML::Attributes)

# File lib/rexml/element.rb, line 1119
    def prefixes
      ns = []
      each_attribute do |attribute|
        ns << attribute.name if attribute.prefix == 'xmlns'
      end
      if @element.document and @element.document.doctype
        expn = @element.expanded_name
        expn = @element.document.doctype.name if expn.size == 0
        @element.document.doctype.attributes_of(expn).each {
          |attribute|
          ns << attribute.name if attribute.prefix == 'xmlns'
        }
      end
      ns
    end


namespaces (REXML::Attributes)

# File lib/rexml/element.rb, line 1135
    def namespaces
      namespaces = {}
      each_attribute do |attribute|
        namespaces[attribute.name] = attribute.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
      end
      if @element.document and @element.document.doctype
        expn = @element.expanded_name
        expn = @element.document.doctype.name if expn.size == 0
        @element.document.doctype.attributes_of(expn).each {
          |attribute|
          namespaces[attribute.name] = attribute.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
        }
      end
      namespaces
    end


delete (REXML::Attributes)

# File lib/rexml/element.rb, line 1161
    def delete( attribute )
      name = nil
      prefix = nil
      if attribute.kind_of? Attribute
        name = attribute.name
        prefix = attribute.prefix
      else
        attribute =~ Namespace::NAMESPLIT
        prefix, name = $1, $2
        prefix = '' unless prefix
      end
      old = fetch(name, nil)
      attr = nil
      if old.kind_of? Hash # the supplied attribute is one of many
        attr = old.delete(prefix)
        if old.size == 1
          repl = nil
          old.each_value{|v| repl = v}
          store name, repl
        end
      elsif old.nil?
        return @element
      else # the supplied attribute is a top-level one
        attr = old
        res = super(name)
      end
      @element
    end


add (REXML::Attributes)

# File lib/rexml/element.rb, line 1193
    def add( attribute )
      self[attribute.name] = attribute
    end


delete_all (REXML::Attributes)

# File lib/rexml/element.rb, line 1203
    def delete_all( name )
      rv = []
      each_attribute { |attribute|
        rv << attribute if attribute.expanded_name == name
      }
      rv.each{ |attr| attr.remove }
      return rv
    end


get_attribute_ns (REXML::Attributes)

# File lib/rexml/element.rb, line 1217
    def get_attribute_ns(namespace, name)
      each_attribute() { |attribute|
        if name == attribute.name &&
          namespace == attribute.namespace()
          return attribute
        end
      }
      nil
    end


new (REXML::CData)

# File lib/rexml/cdata.rb, line 15
                def initialize( first, whitespace=true, parent=nil )
                        super( first, whitespace, parent, true, true, ILLEGAL )
                end


clone (REXML::CData)

# File lib/rexml/cdata.rb, line 25
                def clone
                        CData.new self
                end


to_s (REXML::CData)

# File lib/rexml/cdata.rb, line 34
                def to_s
                        @string
                end


value (REXML::CData)

# File lib/rexml/cdata.rb, line 38
    def value
      @string
    end


write (REXML::CData)

# File lib/rexml/cdata.rb, line 59
                def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
      Kernel.warn( "#{self.class.name}.write is deprecated" )
                        indent( output, indent )
                        output << START
                        output << @string
                        output << STOP
                end


new (REXML::Child)

# File lib/rexml/child.rb, line 17
                def initialize( parent = nil )
                        @parent = nil
                        # Declare @parent, but don't define it.  The next line sets the
                        # parent.
                        parent.add( self ) if parent
                end


replace_with (REXML::Child)

# File lib/rexml/child.rb, line 28
                def replace_with( child )
                        @parent.replace_child( self, child )
                        self
                end


remove (REXML::Child)

# File lib/rexml/child.rb, line 36
                def remove
                        unless @parent.nil?
                                @parent.delete self
                        end
                        self
                end


parent= (REXML::Child)

# File lib/rexml/child.rb, line 51
                def parent=( other )
                        return @parent if @parent == other
                        @parent.delete self if defined? @parent and @parent
                        @parent = other
                end


next_sibling= (REXML::Child)

# File lib/rexml/child.rb, line 67
                def next_sibling=( other )
                  parent.insert_after self, other
                end


previous_sibling= (REXML::Child)

# File lib/rexml/child.rb, line 78
                def previous_sibling=(other)
                  parent.insert_before self, other
                end


document (REXML::Child)

# File lib/rexml/child.rb, line 84
                def document
                        return parent.document unless parent.nil?
                        nil
                end


bytes (REXML::Child)

# File lib/rexml/child.rb, line 90
                def bytes
                        encoding = document.encoding

                        to_s
                end


new (REXML::Comment)

# File lib/rexml/comment.rb, line 23
                def initialize( first, second = nil )
                        #puts "IN COMMENT CONSTRUCTOR; SECOND IS #{second.type}"
                        super(second)
                        if first.kind_of? String
                                @string = first
                        elsif first.kind_of? Comment
                                @string = first.string
                        end
                end


clone (REXML::Comment)

# File lib/rexml/comment.rb, line 33
                def clone
                        Comment.new self
                end


write (REXML::Comment)

# File lib/rexml/comment.rb, line 50
                def write( output, indent=-1, transitive=false, ie_hack=false )
      Kernel.warn("Comment.write is deprecated.  See REXML::Formatters")
                        indent( output, indent )
                        output << START
                        output << @string
                        output << STOP
                end


<=> (REXML::Comment)

# File lib/rexml/comment.rb, line 63
                def <=>(other)
                        other.to_s <=> @string
                end


== (REXML::Comment)

# File lib/rexml/comment.rb, line 70
                def ==( other )
                        other.kind_of? Comment and
                        (other <=> self) == 0
                end


node_type (REXML::Comment)

# File lib/rexml/comment.rb, line 75
    def node_type
      :comment
    end


new (REXML::Declaration)

# File lib/rexml/doctype.rb, line 205
    def initialize src
      super()
      @string = src
    end


to_s (REXML::Declaration)

# File lib/rexml/doctype.rb, line 210
    def to_s
      @string+'>'
    end


write (REXML::Declaration)

# File lib/rexml/doctype.rb, line 217
    def write( output, indent )
      output << to_s
    end


new (REXML::DocType)

# File lib/rexml/doctype.rb, line 41
    def initialize( first, parent=nil )
      @entities = DEFAULT_ENTITIES
      @long_name = @uri = nil
      if first.kind_of? String
        super()
        @name = first
        @external_id = parent
      elsif first.kind_of? DocType
        super( parent )
        @name = first.name
        @external_id = first.external_id
      elsif first.kind_of? Array
        super( parent )
        @name = first[0]
        @external_id = first[1]
        @long_name = first[2]
        @uri = first[3]
      elsif first.kind_of? Source
        super( parent )
        parser = Parsers::BaseParser.new( first )
        event = parser.pull
        if event[0] == :start_doctype
          @name, @external_id, @long_name, @uri, = event[1..-1]
        end
      else
        super()
      end
    end


node_type (REXML::DocType)

# File lib/rexml/doctype.rb, line 70
    def node_type
      :doctype
    end


attributes_of (REXML::DocType)

# File lib/rexml/doctype.rb, line 74
    def attributes_of element
      rv = []
      each do |child|
        child.each do |key,val|
          rv << Attribute.new(key,val)
        end if child.kind_of? AttlistDecl and child.element_name == element
      end
      rv
    end


attribute_of (REXML::DocType)

# File lib/rexml/doctype.rb, line 84
    def attribute_of element, attribute
      att_decl = find do |child|
        child.kind_of? AttlistDecl and
        child.element_name == element and
        child.include? attribute
      end
      return nil unless att_decl
      att_decl[attribute]
    end


clone (REXML::DocType)

# File lib/rexml/doctype.rb, line 94
    def clone
      DocType.new self
    end


write (REXML::DocType)

# File lib/rexml/doctype.rb, line 108
    def write( output, indent=0, transitive=false, ie_hack=false )
      f = REXML::Formatters::Default.new
      indent( output, indent )
      output << START
      output << ' '
      output << @name
      output << " #@external_id" if @external_id
      output << " #{@long_name.inspect}" if @long_name
      output << " #{@uri.inspect}" if @uri
      unless @children.empty?
        next_indent = indent + 1
        output << ' ['
        child = nil    # speed
        @children.each { |child|
          output << "\n"
          f.write( child, output )
        }
        output << "\n]"
      end
      output << STOP
    end


context (REXML::DocType)

# File lib/rexml/doctype.rb, line 130
    def context
      @parent.context
    end


entity (REXML::DocType)

# File lib/rexml/doctype.rb, line 134
    def entity( name )
      @entities[name].unnormalized if @entities[name]
    end


add (REXML::DocType)

# File lib/rexml/doctype.rb, line 138
    def add child
      super(child)
      @entities = DEFAULT_ENTITIES.clone if @entities == DEFAULT_ENTITIES
      @entities[ child.name ] = child if child.kind_of? Entity
    end


public (REXML::DocType)

# File lib/rexml/doctype.rb, line 148
    def public
      case @external_id
      when "SYSTEM"
        nil
      when "PUBLIC"
        strip_quotes(@long_name)
      end
    end


system (REXML::DocType)

# File lib/rexml/doctype.rb, line 160
    def system
      case @external_id
      when "SYSTEM"
        strip_quotes(@long_name)
      when "PUBLIC"
        @uri.kind_of?(String) ? strip_quotes(@uri) : nil
      end
    end


notations (REXML::DocType)

# File lib/rexml/doctype.rb, line 174
    def notations
      children().select {|node| node.kind_of?(REXML::NotationDecl)}
    end


notation (REXML::DocType)

# File lib/rexml/doctype.rb, line 182
    def notation(name)
      notations.find { |notation_decl|
        notation_decl.name == name
      }
    end


new (REXML::Document)

# File lib/rexml/document.rb, line 34
                def initialize( source = nil, context = {} )
                        super()
                        @context = context
                        return if source.nil?
                        if source.kind_of? Document
                                @context = source.context
                                super source
                        else
                                build(  source )
                        end
                end


node_type (REXML::Document)

# File lib/rexml/document.rb, line 46
    def node_type
      :document
    end


clone (REXML::Document)

# File lib/rexml/document.rb, line 51
                def clone
                        Document.new self
                end


expanded_name (REXML::Document)

# File lib/rexml/document.rb, line 56
                def expanded_name
                        ''
                        #d = doc_type
                        #d ? d.name : "UNDEFINED"
                end


add (REXML::Document)

# File lib/rexml/document.rb, line 66
                def add( child )
                        if child.kind_of? XMLDecl
                                @children.unshift child
        child.parent = self
                        elsif child.kind_of? DocType
        # Find first Element or DocType node and insert the decl right
        # before it.  If there is no such node, just insert the child at the
        # end.  If there is a child and it is an DocType, then replace it.
        insert_before_index = 0
        @children.find { |x|
          insert_before_index += 1
          x.kind_of?(Element) || x.kind_of?(DocType)
        }
        if @children[ insert_before_index ] # Not null = not end of list
          if @children[ insert_before_index ].kind_of DocType
            @children[ insert_before_index ] = child
          else
            @children[ index_before_index-1, 0 ] = child
          end
        else  # Insert at end of list
          @children[insert_before_index] = child
        end
                                child.parent = self
                        else
                                rv = super
                                raise "attempted adding second root element to document" if @elements.size > 1
                                rv
                        end
                end


add_element (REXML::Document)

# File lib/rexml/document.rb, line 97
                def add_element(arg=nil, arg2=nil)
                        rv = super
                        raise "attempted adding second root element to document" if @elements.size > 1
                        rv
                end


root (REXML::Document)

# File lib/rexml/document.rb, line 105
                def root
      elements[1]
      #self
      #@children.find { |item| item.kind_of? Element }
                end


doctype (REXML::Document)

# File lib/rexml/document.rb, line 113
                def doctype
                        @children.find { |item| item.kind_of? DocType }
                end


xml_decl (REXML::Document)

# File lib/rexml/document.rb, line 119
                def xml_decl
                        rv = @children[0]
      return rv if rv.kind_of? XMLDecl
      rv = @children.unshift(XMLDecl.default)[0]
                end


version (REXML::Document)

# File lib/rexml/document.rb, line 127
                def version
                        xml_decl().version
                end


encoding (REXML::Document)

# File lib/rexml/document.rb, line 133
                def encoding
                        xml_decl().encoding
                end


stand_alone? (REXML::Document)

# File lib/rexml/document.rb, line 139
                def stand_alone?
                        xml_decl().stand_alone?
                end


write (REXML::Document)

# File lib/rexml/document.rb, line 182
                def write( output=$stdout, indent=-1, trans=false, ie_hack=false )
      if xml_decl.encoding != "UTF-8" && !output.kind_of?(Output)
        output = Output.new( output, xml_decl.encoding )
      end
      formatter = if indent > -1
          if trans
            REXML::Formatters::Transitive.new( indent, ie_hack )
          else
            REXML::Formatters::Pretty.new( indent, ie_hack )
          end
        else
          REXML::Formatters::Default.new( ie_hack )
        end
      formatter.write( self, output )
                end


parse_stream (REXML::Document)

# File lib/rexml/document.rb, line 199
                def Document::parse_stream( source, listener )
                        Parsers::StreamParser.new( source, listener ).parse
                end


new (REXML::DTD::ElementDecl)

# File lib/rexml/dtd/elementdecl.rb, line 11
                        def initialize match
                                @name = match[1]
                                @rest = match[2]
                        end


new (REXML::DTD::EntityDecl)

# File lib/rexml/dtd/entitydecl.rb, line 13
                        def initialize src
                                super()
                                md = nil
                                if src.match( PUBLIC )
                                        md = src.match( PUBLIC, true )
                                        @middle = "PUBLIC"
                                        @content = "#{md[2]} #{md[4]}"
                                elsif src.match( SYSTEM )
                                        md = src.match( SYSTEM, true )
                                        @middle = "SYSTEM"
                                        @content = md[2]
                                elsif src.match( PLAIN )
                                        md = src.match( PLAIN, true )
                                        @middle = ""
                                        @content = md[2]
                                elsif src.match( PERCENT )
                                        md = src.match( PERCENT, true )
                                        @middle = ""
                                        @content = md[2]
                                end
                                raise ParseException.new("failed Entity match", src) if md.nil?
                                @name = md[1]
                        end


to_s (REXML::DTD::EntityDecl)

# File lib/rexml/dtd/entitydecl.rb, line 37
                        def to_s
                                rv = "<!ENTITY #@name "
                                rv << "#@middle " if @middle.size > 0
                                rv << @content
                                rv
                        end


write (REXML::DTD::EntityDecl)

# File lib/rexml/dtd/entitydecl.rb, line 44
                        def write( output, indent )
        indent( output, indent )
                                output << to_s
                        end


parse_source (REXML::DTD::EntityDecl)

# File lib/rexml/dtd/entitydecl.rb, line 49
                        def EntityDecl.parse_source source, listener
                                md = source.match( PATTERN_RE, true )
                                thing = md[0].squeeze(" \t\n\r")
                                listener.send inspect.downcase, thing
                        end


new (REXML::DTD::NotationDecl)

# File lib/rexml/dtd/notationdecl.rb, line 9
                        def initialize src
                                super()
                                if src.match( PUBLIC )
                                        md = src.match( PUBLIC, true )
                                elsif src.match( SYSTEM )
                                        md = src.match( SYSTEM, true )
                                else
                                        raise ParseException.new( "error parsing notation: no matching pattern", src )
                                end
                                @name = md[1]
                                @middle = md[2]
                                @rest = md[3]
                        end


to_s (REXML::DTD::NotationDecl)

# File lib/rexml/dtd/notationdecl.rb, line 23
                        def to_s
                                "<!NOTATION #@name #@middle #@rest>"
                        end


write (REXML::DTD::NotationDecl)

# File lib/rexml/dtd/notationdecl.rb, line 27
                        def write( output, indent )
        indent( output, indent )
                                output << to_s
                        end


parse_source (REXML::DTD::NotationDecl)

# File lib/rexml/dtd/notationdecl.rb, line 32
                        def NotationDecl.parse_source source, listener
                                md = source.match( PATTERN_RE, true )
                                thing = md[0].squeeze(" \t\n\r")
                                listener.send inspect.downcase, thing
                        end


parse (REXML::DTD::Parser)

# File lib/rexml/dtd/dtd.rb, line 11
                        def Parser.parse( input )
                                case input
                                when String
                                        parse_helper input
                                when File
                                        parse_helper input.read
                                end
                        end


parse_helper (REXML::DTD::Parser)

# File lib/rexml/dtd/dtd.rb, line 21
                        def Parser.parse_helper( input )
                                contents = Parent.new
                                while input.size > 0
                                        case input
                                        when ElementDecl.PATTERN_RE
                                                match = $&
                                                source = $'
                                                contents << ElementDecl.new( match )
                                        when AttlistDecl.PATTERN_RE
                                                matchdata = $~
                                                source = $'
                                                contents << AttlistDecl.new( matchdata )
                                        when EntityDecl.PATTERN_RE
                                                matchdata = $~
                                                source = $'
                                                contents << EntityDecl.new( matchdata )
                                        when Comment.PATTERN_RE
                                                matchdata = $~
                                                source = $'
                                                contents << Comment.new( matchdata )
                                        when NotationDecl.PATTERN_RE
                                                matchdata = $~
                                                source = $'
                                                contents << NotationDecl.new( matchdata )
                                        end
                                end
                                contents
                        end


new (REXML::Element)

# File lib/rexml/element.rb, line 58
    def initialize( arg = UNDEFINED, parent=nil, context=nil )
      super(parent)

      @elements = Elements.new(self)
      @attributes = Attributes.new(self)
      @context = context

      if arg.kind_of? String
        self.name = arg
      elsif arg.kind_of? Element
        self.name = arg.expanded_name
        arg.attributes.each_attribute{ |attribute|
          @attributes << Attribute.new( attribute )
        }
        @context = arg.context
      end
    end


inspect (REXML::Element)

# File lib/rexml/element.rb, line 76
    def inspect
      rv = "<#@expanded_name"

      @attributes.each_attribute do |attr|
        rv << " "
        attr.write( rv, 0 )
      end

      if children.size > 0
        rv << "> ... </>"
      else
        rv << "/>"
      end
    end


clone (REXML::Element)

# File lib/rexml/element.rb, line 96
    def clone
      self.class.new self
    end


root_node (REXML::Element)

# File lib/rexml/element.rb, line 119
    def root_node
      parent.nil? ? self : parent.root_node
    end


root (REXML::Element)

# File lib/rexml/element.rb, line 123
    def root
      return elements[1] if self.kind_of? Document
      return self if parent.kind_of? Document or parent.nil?
      return parent.root
    end


document (REXML::Element)

# File lib/rexml/element.rb, line 131
    def document
      rt = root
      rt.parent if rt
    end


whitespace (REXML::Element)

# File lib/rexml/element.rb, line 145
    def whitespace
      @whitespace = nil
      if @context
        if @context[:respect_whitespace]
          @whitespace = (@context[:respect_whitespace] == :all or
                         @context[:respect_whitespace].include? expanded_name)
        end
        @whitespace = false if (@context[:compress_whitespace] and
                                (@context[:compress_whitespace] == :all or
                                 @context[:compress_whitespace].include? expanded_name)
                               )
      end
      @whitespace = true unless @whitespace == false
      @whitespace
    end


ignore_whitespace_nodes (REXML::Element)

# File lib/rexml/element.rb, line 161
    def ignore_whitespace_nodes
      @ignore_whitespace_nodes = false
      if @context
        if @context[:ignore_whitespace_nodes]
          @ignore_whitespace_nodes =
            (@context[:ignore_whitespace_nodes] == :all or
             @context[:ignore_whitespace_nodes].include? expanded_name)
        end
      end
    end


raw (REXML::Element)

# File lib/rexml/element.rb, line 178
    def raw
      @raw = (@context and @context[:raw] and
              (@context[:raw] == :all or
               @context[:raw].include? expanded_name))
               @raw
    end


prefixes (REXML::Element)

# File lib/rexml/element.rb, line 195
    def prefixes
      prefixes = []
      prefixes = parent.prefixes if parent
      prefixes |= attributes.prefixes
      return prefixes
    end


namespaces (REXML::Element)

# File lib/rexml/element.rb, line 202
    def namespaces
      namespaces = {}
      namespaces = parent.namespaces if parent
      namespaces = namespaces.merge( attributes.namespaces )
      return namespaces
    end


namespace (REXML::Element)

# File lib/rexml/element.rb, line 222
    def namespace(prefix=nil)
      if prefix.nil?
        prefix = prefix()
      end
      if prefix == ''
        prefix = "xmlns"
      else
        prefix = "xmlns:#{prefix}" unless prefix[0,5] == 'xmlns'
      end
      ns = attributes[ prefix ]
      ns = parent.namespace(prefix) if ns.nil? and parent
      ns = '' if ns.nil? and prefix == 'xmlns'
      return ns
    end


add_namespace (REXML::Element)

# File lib/rexml/element.rb, line 250
    def add_namespace( prefix, uri=nil )
      unless uri
        @attributes["xmlns"] = prefix
      else
        prefix = "xmlns:#{prefix}" unless prefix =~ /^xmlns:/
        @attributes[ prefix ] = uri
      end
      self
    end


delete_namespace (REXML::Element)

# File lib/rexml/element.rb, line 270
    def delete_namespace namespace="xmlns"
      namespace = "xmlns:#{namespace}" unless namespace == 'xmlns'
      attribute = attributes.get_attribute(namespace)
      attribute.remove unless attribute.nil?
      self
    end


add_element (REXML::Element)

# File lib/rexml/element.rb, line 295
    def add_element element, attrs=nil
      raise "First argument must be either an element name, or an Element object" if element.nil?
      el = @elements.add(element)
      attrs.each do |key, value|
        el.attributes[key]=Attribute.new(key,value,self)
      end       if attrs.kind_of? Hash
      el
    end


delete_element (REXML::Element)

# File lib/rexml/element.rb, line 315
    def delete_element element
      @elements.delete element
    end


has_elements? (REXML::Element)

# File lib/rexml/element.rb, line 324
    def has_elements?
      !@elements.empty?
    end


each_element_with_attribute (REXML::Element)

# File lib/rexml/element.rb, line 350
    def each_element_with_attribute( key, value=nil, max=0, name=nil, &block ) # :yields: Element
      each_with_something( proc {|child|
        if value.nil?
          child.attributes[key] != nil
        else
          child.attributes[key]==value
        end
      }, max, name, &block )
    end


each_element_with_text (REXML::Element)

# File lib/rexml/element.rb, line 381
    def each_element_with_text( text=nil, max=0, name=nil, &block ) # :yields: Element
      each_with_something( proc {|child|
        if text.nil?
          child.has_text?
        else
          child.text == text
        end
      }, max, name, &block )
    end


each_element (REXML::Element)

# File lib/rexml/element.rb, line 392
    def each_element( xpath=nil, &block ) # :yields: Element
      @elements.each( xpath, &block )
    end


get_elements (REXML::Element)

# File lib/rexml/element.rb, line 400
    def get_elements( xpath )
      @elements.to_a( xpath )
    end


next_element (REXML::Element)

# File lib/rexml/element.rb, line 409
    def next_element
      element = next_sibling
      element = element.next_sibling until element.nil? or element.kind_of? Element
      return element
    end


previous_element (REXML::Element)

# File lib/rexml/element.rb, line 420
    def previous_element
      element = previous_sibling
      element = element.previous_sibling until element.nil? or element.kind_of? Element
      return element
    end


has_text? (REXML::Element)

# File lib/rexml/element.rb, line 432
    def has_text?
      not text().nil?
    end


text (REXML::Element)

# File lib/rexml/element.rb, line 450
    def text( path = nil )
      rv = get_text(path)
      return rv.value unless rv.nil?
      nil
    end


get_text (REXML::Element)

# File lib/rexml/element.rb, line 461
    def get_text path = nil
      rv = nil
      if path
        element = @elements[ path ]
        rv = element.get_text unless element.nil?
      else
        rv = @children.find { |node| node.kind_of? Text }
      end
      return rv
    end


text= (REXML::Element)

# File lib/rexml/element.rb, line 492
    def text=( text )
      if text.kind_of? String
        text = Text.new( text, whitespace(), nil, raw() )
      elsif text and !text.kind_of? Text
        text = Text.new( text.to_s, whitespace(), nil, raw() )
      end
      old_text = get_text
      if text.nil?
        old_text.remove unless old_text.nil?
      else
        if old_text.nil?
          self << text
        else
          old_text.replace_with( text )
        end
      end
      return self
    end


add_text (REXML::Element)

# File lib/rexml/element.rb, line 522
    def add_text( text )
      if text.kind_of? String
        if @children[-1].kind_of? Text
          @children[-1] << text
          return
        end
        text = Text.new( text, whitespace(), nil, raw() )
      end
      self << text unless text.nil?
      return self
    end


node_type (REXML::Element)

# File lib/rexml/element.rb, line 534
    def node_type
      :element
    end


xpath (REXML::Element)

# File lib/rexml/element.rb, line 538
    def xpath
      path_elements = []
      cur = self
      path_elements << __to_xpath_helper( self )
      while cur.parent
        cur = cur.parent
        path_elements << __to_xpath_helper( cur )
      end
      return path_elements.reverse.join( "/" )
    end


attribute (REXML::Element)

# File lib/rexml/element.rb, line 553
    def attribute( name, namespace=nil )
      prefix = nil
      prefix = namespaces.index(namespace) if namespace
      prefix = nil if prefix == 'xmlns'
      attributes.get_attribute( "#{prefix ? prefix + ':' : ''}#{name}" )
    end


has_attributes? (REXML::Element)

# File lib/rexml/element.rb, line 562
    def has_attributes?
      return !@attributes.empty?
    end


add_attribute (REXML::Element)

# File lib/rexml/element.rb, line 583
    def add_attribute( key, value=nil )
      if key.kind_of? Attribute
        @attributes << key
      else
        @attributes[key] = value
      end
    end


add_attributes (REXML::Element)

# File lib/rexml/element.rb, line 595
    def add_attributes hash
      if hash.kind_of? Hash
        hash.each_pair {|key, value| @attributes[key] = value }
      elsif hash.kind_of? Array
        hash.each { |value| @attributes[ value[0] ] = value[1] }
      end
    end


delete_attribute (REXML::Element)

# File lib/rexml/element.rb, line 616
    def delete_attribute(key)
      attr = @attributes.get_attribute(key)
      attr.remove unless attr.nil?
    end


cdatas (REXML::Element)

# File lib/rexml/element.rb, line 627
    def cdatas
      find_all { |child| child.kind_of? CData }.freeze
    end


comments (REXML::Element)

# File lib/rexml/element.rb, line 633
    def comments
      find_all { |child| child.kind_of? Comment }.freeze
    end


instructions (REXML::Element)

# File lib/rexml/element.rb, line 639
    def instructions
      find_all { |child| child.kind_of? Instruction }.freeze
    end


texts (REXML::Element)

# File lib/rexml/element.rb, line 645
    def texts
      find_all { |child| child.kind_of? Text }.freeze
    end


write (REXML::Element)

# File lib/rexml/element.rb, line 674
    def write(writer=$stdout, indent=-1, transitive=false, ie_hack=false)
      Kernel.warn("#{self.class.name}.write is deprecated.  See REXML::Formatters")
      formatter = if indent > -1
          if transitive
            REXML::Formatters::Transitive.new( indent, ie_hack )
          else
            REXML::Formatters::Pretty.new( indent, ie_hack )
          end
        else
          REXML::Formatters::Default.new( ie_hack )
        end
      formatter.write( self, output )
    end


new (REXML::ElementDecl)

# File lib/rexml/doctype.rb, line 224
    def initialize( src )
      super
    end


new (REXML::Elements)

# File lib/rexml/element.rb, line 727
    def initialize parent
      @element = parent
    end


[] (REXML::Elements)

# File lib/rexml/element.rb, line 752
    def []( index, name=nil)
      if index.kind_of? Integer
        raise "index (#{index}) must be >= 1" if index < 1
        name = literalize(name) if name
        num = 0
        child = nil
        @element.find { |child|
          child.kind_of? Element and
          (name.nil? ? true : child.has_name?( name )) and
          (num += 1) == index
        }
      else
        return XPath::first( @element, index )
        #{ |element|
        #       return element if element.kind_of? Element
        #}
        #return nil
      end
    end


[]= (REXML::Elements)

# File lib/rexml/element.rb, line 785
    def []=( index, element )
      previous = self[index]
      if previous.nil?
        @element.add element
      else
        previous.replace_with element
      end
      return previous
    end


empty? (REXML::Elements)

# File lib/rexml/element.rb, line 796
    def empty?
      @element.find{ |child| child.kind_of? Element}.nil?
    end


index (REXML::Elements)

# File lib/rexml/element.rb, line 803
    def index element
      rv = 0
      found = @element.find do |child|
        child.kind_of? Element and
        (rv += 1) and
        child == element
      end
      return rv if found == element
      return -1
    end


delete (REXML::Elements)

# File lib/rexml/element.rb, line 825
    def delete element
      if element.kind_of? Element
        @element.delete element
      else
        el = self[element]
        el.remove if el
      end
    end


delete_all (REXML::Elements)

# File lib/rexml/element.rb, line 840
    def delete_all( xpath )
      rv = []
      XPath::each( @element, xpath) {|element|
        rv << element if element.kind_of? Element
      }
      rv.each do |element|
        @element.delete element
        element.remove
      end
      return rv
    end


add (REXML::Elements)

# File lib/rexml/element.rb, line 861
    def add element=nil
      rv = nil
      if element.nil?
        Element.new("", self, @element.context)
      elsif not element.kind_of?(Element)
        Element.new(element, self, @element.context)
      else
        @element << element
        element.context = @element.context
        element
      end
    end


each (REXML::Elements)

# File lib/rexml/element.rb, line 890
    def each( xpath=nil, &block)
      XPath::each( @element, xpath ) {|e| yield e if e.kind_of? Element }
    end


collect (REXML::Elements)

# File lib/rexml/element.rb, line 894
    def collect( xpath=nil, &block )
      collection = []
      XPath::each( @element, xpath ) {|e|
        collection << yield(e)  if e.kind_of?(Element)
      }
      collection
    end


inject (REXML::Elements)

# File lib/rexml/element.rb, line 902
    def inject( xpath=nil, initial=nil, &block )
      first = true
      XPath::each( @element, xpath ) {|e|
        if (e.kind_of? Element)
          if (first and initial == nil)
            initial = e
            first = false
          else
            initial = yield( initial, e ) if e.kind_of? Element
          end
        end
      }
      initial
    end


size (REXML::Elements)

# File lib/rexml/element.rb, line 921
    def size
      count = 0
      @element.each {|child| count+=1 if child.kind_of? Element }
      count
    end


to_a (REXML::Elements)

# File lib/rexml/element.rb, line 934
    def to_a( xpath=nil )
      rv = XPath.match( @element, xpath )
      return rv.find_all{|e| e.kind_of? Element} if xpath
      rv
    end


register (REXML::Encoding)

# File lib/rexml/encoding.rb, line 5
    def self.register(enc, &block)
      @encoding_methods[enc] = block
    end


apply (REXML::Encoding)

# File lib/rexml/encoding.rb, line 8
    def self.apply(obj, enc)
      @encoding_methods[enc][obj]
    end


encoding_method (REXML::Encoding)

# File lib/rexml/encoding.rb, line 11
    def self.encoding_method(enc)
      @encoding_methods[enc]
    end


encoding= (REXML::Encoding)

# File lib/rexml/encoding.rb, line 23
    def encoding=( enc )
      old_verbosity = $VERBOSE
      begin
        $VERBOSE = false
        enc = enc.nil? ? nil : enc.upcase
        return false if defined? @encoding and enc == @encoding
        if enc and enc != UTF_8
          @encoding = enc
          raise ArgumentError, "Bad encoding name #@encoding" unless @encoding =~ /^[\w-]+$/
          @encoding.untaint
          begin
            require 'rexml/encodings/ICONV.rb'
            Encoding.apply(self, "ICONV")
          rescue LoadError, Exception
            begin
              enc_file = File.join( "rexml", "encodings", "#@encoding.rb" )
              require enc_file
              Encoding.apply(self, @encoding)
            rescue LoadError => err
              puts err.message
              raise ArgumentError, "No decoder found for encoding #@encoding.  Please install iconv."
            end
          end
        else
          @encoding = UTF_8
          require 'rexml/encodings/UTF-8.rb'
          Encoding.apply(self, @encoding)
        end
      ensure
        $VERBOSE = old_verbosity
      end
      true
    end


check_encoding (REXML::Encoding)

# File lib/rexml/encoding.rb, line 57
    def check_encoding str
      # We have to recognize UTF-16, LSB UTF-16, and UTF-8
      if str[0] == 0xfe && str[1] == 0xff
        str[0,2] = ""
        return UTF_16
      elsif str[0] == 0xff && str[1] == 0xfe
        str[0,2] = ""
        return UNILE
      end
      str =~ /^\s*<\?xml\s+version\s*=\s*(['"]).*?\1\s+encoding\s*=\s*(["'])(.*?)\2/um
      return $3.upcase if $3
      return UTF_8
    end


decode_eucjp (REXML::Encoding)

# File lib/rexml/encodings/EUC-JP.rb, line 6
      def decode_eucjp(str)
        Uconv::euctou8(str)
      end


encode_eucjp (REXML::Encoding)

# File lib/rexml/encodings/EUC-JP.rb, line 10
      def encode_eucjp content
        Uconv::u8toeuc(content)
      end


decode_eucjp (REXML::Encoding)

# File lib/rexml/encodings/EUC-JP.rb, line 19
      def decode_eucjp(str)
        NKF.nkf(EUCTOU8, str)
      end


encode_eucjp (REXML::Encoding)

# File lib/rexml/encodings/EUC-JP.rb, line 23
      def encode_eucjp content
        NKF.nkf(U8TOEUC, content)
      end


encode_cp1252 (REXML::Encoding)

# File lib/rexml/encodings/CP-1252.rb, line 14
    def encode_cp1252(content)
      array_utf8 = content.unpack('U*')
      array_enc = []
      array_utf8.each do |num|
        case num
          # shortcut first bunch basic characters
        when 0..0xFF; array_enc << num
          # characters added compared to iso-8859-1
        when 0x20AC; array_enc << 0x80 # 0xe2 0x82 0xac
        when 0x201A; array_enc << 0x82 # 0xe2 0x82 0x9a
        when 0x0192; array_enc << 0x83 # 0xc6 0x92
        when 0x201E; array_enc << 0x84 # 0xe2 0x82 0x9e
        when 0x2026; array_enc << 0x85 # 0xe2 0x80 0xa6
        when 0x2020; array_enc << 0x86 # 0xe2 0x80 0xa0
        when 0x2021; array_enc << 0x87 # 0xe2 0x80 0xa1
        when 0x02C6; array_enc << 0x88 # 0xcb 0x86
        when 0x2030; array_enc << 0x89 # 0xe2 0x80 0xb0
        when 0x0160; array_enc << 0x8A # 0xc5 0xa0
        when 0x2039; array_enc << 0x8B # 0xe2 0x80 0xb9
        when 0x0152; array_enc << 0x8C # 0xc5 0x92
        when 0x017D; array_enc << 0x8E # 0xc5 0xbd
        when 0x2018; array_enc << 0x91 # 0xe2 0x80 0x98
        when 0x2019; array_enc << 0x92 # 0xe2 0x80 0x99
        when 0x201C; array_enc << 0x93 # 0xe2 0x80 0x9c
        when 0x201D; array_enc << 0x94 # 0xe2 0x80 0x9d
        when 0x2022; array_enc << 0x95 # 0xe2 0x80 0xa2
        when 0x2013; array_enc << 0x96 # 0xe2 0x80 0x93
        when 0x2014; array_enc << 0x97 # 0xe2 0x80 0x94
        when 0x02DC; array_enc << 0x98 # 0xcb 0x9c
        when 0x2122; array_enc << 0x99 # 0xe2 0x84 0xa2
        when 0x0161; array_enc << 0x9A # 0xc5 0xa1
        when 0x203A; array_enc << 0x9B # 0xe2 0x80 0xba
        when 0x0152; array_enc << 0x9C # 0xc5 0x93
        when 0x017E; array_enc << 0x9E # 0xc5 0xbe
        when 0x0178; array_enc << 0x9F # 0xc5 0xb8
        else
          # all remaining basic characters can be used directly
          if num <= 0xFF
            array_enc << num
          else
            # Numeric entity (&#nnnn;); shard by  Stefan Scholl
            array_enc.concat "&\##{num};".unpack('C*')
          end
        end
      end
      array_enc.pack('C*')
    end


decode_cp1252 (REXML::Encoding)

# File lib/rexml/encodings/CP-1252.rb, line 63
    def decode_cp1252(str)
      array_latin9 = str.unpack('C*')
      array_enc = []
      array_latin9.each do |num|
        case num
          # characters that added compared to iso-8859-1
        when 0x80; array_enc << 0x20AC # 0xe2 0x82 0xac
        when 0x82; array_enc << 0x201A # 0xe2 0x82 0x9a
        when 0x83; array_enc << 0x0192 # 0xc6 0x92
        when 0x84; array_enc << 0x201E # 0xe2 0x82 0x9e
        when 0x85; array_enc << 0x2026 # 0xe2 0x80 0xa6
        when 0x86; array_enc << 0x2020 # 0xe2 0x80 0xa0
        when 0x87; array_enc << 0x2021 # 0xe2 0x80 0xa1
        when 0x88; array_enc << 0x02C6 # 0xcb 0x86
        when 0x89; array_enc << 0x2030 # 0xe2 0x80 0xb0
        when 0x8A; array_enc << 0x0160 # 0xc5 0xa0
        when 0x8B; array_enc << 0x2039 # 0xe2 0x80 0xb9
        when 0x8C; array_enc << 0x0152 # 0xc5 0x92
        when 0x8E; array_enc << 0x017D # 0xc5 0xbd
        when 0x91; array_enc << 0x2018 # 0xe2 0x80 0x98
        when 0x92; array_enc << 0x2019 # 0xe2 0x80 0x99
        when 0x93; array_enc << 0x201C # 0xe2 0x80 0x9c
        when 0x94; array_enc << 0x201D # 0xe2 0x80 0x9d
        when 0x95; array_enc << 0x2022 # 0xe2 0x80 0xa2
        when 0x96; array_enc << 0x2013 # 0xe2 0x80 0x93
        when 0x97; array_enc << 0x2014 # 0xe2 0x80 0x94
        when 0x98; array_enc << 0x02DC # 0xcb 0x9c
        when 0x99; array_enc << 0x2122 # 0xe2 0x84 0xa2
        when 0x9A; array_enc << 0x0161 # 0xc5 0xa1
        when 0x9B; array_enc << 0x203A # 0xe2 0x80 0xba
        when 0x9C; array_enc << 0x0152 # 0xc5 0x93
        when 0x9E; array_enc << 0x017E # 0xc5 0xbe
        when 0x9F; array_enc << 0x0178 # 0xc5 0xb8
        else
          array_enc << num
        end
      end
      array_enc.pack('U*')
    end


encode_utf8 (REXML::Encoding)

# File lib/rexml/encodings/UTF-8.rb, line 3
    def encode_utf8 content
      content
    end


decode_utf8 (REXML::Encoding)

# File lib/rexml/encodings/UTF-8.rb, line 7
    def decode_utf8(str)
      str
    end


encode_unile (REXML::Encoding)

# File lib/rexml/encodings/UNILE.rb, line 3
    def encode_unile content
      array_utf8 = content.unpack("U*")
      array_enc = []
      array_utf8.each do |num|
        if ((num>>16) > 0)
          array_enc << ??
          array_enc << 0
        else
          array_enc << (num & 0xFF)
          array_enc << (num >> 8)
        end
      end
      array_enc.pack('C*')
    end


decode_unile (REXML::Encoding)

# File lib/rexml/encodings/UNILE.rb, line 18
    def decode_unile(str)
      array_enc=str.unpack('C*')
      array_utf8 = []
      0.step(array_enc.size-1, 2){|i|
        array_utf8 << (array_enc.at(i) + array_enc.at(i+1)*0x100)
      }
      array_utf8.pack('U*')
    end


encode_ascii (REXML::Encoding)

# File lib/rexml/encodings/US-ASCII.rb, line 4
    def encode_ascii content
      array_utf8 = content.unpack('U*')
      array_enc = []
      array_utf8.each do |num|
        if num <= 0x7F
          array_enc << num
        else
          # Numeric entity (&#nnnn;); shard by  Stefan Scholl
          array_enc.concat "&\##{num};".unpack('C*')
        end
      end
      array_enc.pack('C*')
    end


decode_ascii (REXML::Encoding)

# File lib/rexml/encodings/US-ASCII.rb, line 19
    def decode_ascii(str)
      str.unpack('C*').pack('U*')
    end


to_iso_8859_15 (REXML::Encoding)

# File lib/rexml/encodings/ISO-8859-15.rb, line 12
    def to_iso_8859_15(content)
      array_utf8 = content.unpack('U*')
      array_enc = []
      array_utf8.each do |num|
        case num
          # shortcut first bunch basic characters
        when 0..0xA3; array_enc << num
          # characters removed compared to iso-8859-1
        when 0xA4; array_enc << '&#164;'
        when 0xA6; array_enc << '&#166;'
        when 0xA8; array_enc << '&#168;'
        when 0xB4; array_enc << '&#180;'
        when 0xB8; array_enc << '&#184;'
        when 0xBC; array_enc << '&#188;'
        when 0xBD; array_enc << '&#189;'
        when 0xBE; array_enc << '&#190;'
          # characters added compared to iso-8859-1
        when 0x20AC; array_enc << 0xA4 # 0xe2 0x82 0xac
        when 0x0160; array_enc << 0xA6 # 0xc5 0xa0
        when 0x0161; array_enc << 0xA8 # 0xc5 0xa1
        when 0x017D; array_enc << 0xB4 # 0xc5 0xbd
        when 0x017E; array_enc << 0xB8 # 0xc5 0xbe
        when 0x0152; array_enc << 0xBC # 0xc5 0x92
        when 0x0153; array_enc << 0xBD # 0xc5 0x93
        when 0x0178; array_enc << 0xBE # 0xc5 0xb8
        else
          # all remaining basic characters can be used directly
          if num <= 0xFF
            array_enc << num
          else
            # Numeric entity (&#nnnn;); shard by  Stefan Scholl
            array_enc.concat "&\##{num};".unpack('C*')
          end
        end
      end
      array_enc.pack('C*')
    end


from_iso_8859_15 (REXML::Encoding)

# File lib/rexml/encodings/ISO-8859-15.rb, line 51
    def from_iso_8859_15(str)
      array_latin9 = str.unpack('C*')
      array_enc = []
      array_latin9.each do |num|
        case num
          # characters that differ compared to iso-8859-1
        when 0xA4; array_enc << 0x20AC
        when 0xA6; array_enc << 0x0160
        when 0xA8; array_enc << 0x0161
        when 0xB4; array_enc << 0x017D
        when 0xB8; array_enc << 0x017E
        when 0xBC; array_enc << 0x0152
        when 0xBD; array_enc << 0x0153
        when 0xBE; array_enc << 0x0178
        else
          array_enc << num
        end
      end
      array_enc.pack('U*')
    end


decode_iconv (REXML::Encoding)

# File lib/rexml/encodings/ICONV.rb, line 6
    def decode_iconv(str)
      Iconv.conv(UTF_8, @encoding, str)
    end


encode_iconv (REXML::Encoding)

# File lib/rexml/encodings/ICONV.rb, line 10
    def encode_iconv(content)
      Iconv.conv(@encoding, UTF_8, content)
    end


decode_sjis (REXML::Encoding)

# File lib/rexml/encodings/SHIFT-JIS.rb, line 6
      def decode_sjis content
        Uconv::sjistou8(content)
      end


encode_sjis (REXML::Encoding)

# File lib/rexml/encodings/SHIFT-JIS.rb, line 10
      def encode_sjis(str)
        Uconv::u8tosjis(str)
      end


decode_sjis (REXML::Encoding)

# File lib/rexml/encodings/SHIFT-JIS.rb, line 19
      def decode_sjis(str)
        NKF.nkf(SJISTOU8, str)
      end


encode_sjis (REXML::Encoding)

# File lib/rexml/encodings/SHIFT-JIS.rb, line 23
      def encode_sjis content
        NKF.nkf(U8TOSJIS, content)
      end


encode_utf16 (REXML::Encoding)

# File lib/rexml/encodings/UTF-16.rb, line 3
    def encode_utf16 content
      array_utf8 = content.unpack("U*")
      array_enc = []
      array_utf8.each do |num|
        if ((num>>16) > 0)
          array_enc << 0
          array_enc << ??
        else
          array_enc << (num >> 8)
          array_enc << (num & 0xFF)
        end
      end
      array_enc.pack('C*')
    end


decode_utf16 (REXML::Encoding)

# File lib/rexml/encodings/UTF-16.rb, line 18
    def decode_utf16(str)
      str = str[2..-1] if /^\376\377/n =~ str
      array_enc=str.unpack('C*')
      array_utf8 = []
      0.step(array_enc.size-1, 2){|i|
        array_utf8 << (array_enc.at(i+1) + array_enc.at(i)*0x100)
      }
      array_utf8.pack('U*')
    end


new (REXML::Entity)

# File lib/rexml/entity.rb, line 35
                def initialize stream, value=nil, parent=nil, reference=false
                        super(parent)
                        @ndata = @pubid = @value = @external = nil
                        if stream.kind_of? Array
                                @name = stream[1]
                                if stream[-1] == '%'
                                        @reference = true
                                        stream.pop
                                else
                                        @reference = false
                                end
                                if stream[2] =~ /SYSTEM|PUBLIC/
                                        @external = stream[2]
                                        if @external == 'SYSTEM'
                                                @ref = stream[3]
                                                @ndata = stream[4] if stream.size == 5
                                        else
                                                @pubid = stream[3]
                                                @ref = stream[4]
                                        end
                                else
                                        @value = stream[2]
                                end
                        else
                                @reference = reference
                                @external = nil
                                @name = stream
                                @value = value
                        end
                end


matches? (REXML::Entity)

# File lib/rexml/entity.rb, line 68
                def Entity::matches? string
                        (ENTITYDECL =~ string) == 0
                end


unnormalized (REXML::Entity)

# File lib/rexml/entity.rb, line 75
                def unnormalized
                        v = value()
                        return nil if v.nil?
                        @unnormalized = Text::unnormalize(v, parent)
                        @unnormalized
                end


normalized (REXML::Entity)

# File lib/rexml/entity.rb, line 86
                def normalized
                        @value
                end


write (REXML::Entity)

# File lib/rexml/entity.rb, line 98
                def write out, indent=-1
                        out << '<!ENTITY '
                        out << '% ' if @reference
                        out << @name
                        out << ' '
                        if @external
                                out << @external << ' '
                                if @pubid
                                        q = @pubid.include?('"')?"'":'"'
                                        out << q << @pubid << q << ' '
                                end
                                q = @ref.include?('"')?"'":'"'
                                out << q << @ref << q
                                out << ' NDATA ' << @ndata if @ndata
                        else
                                q = @value.include?('"')?"'":'"'
                                out << q << @value << q
                        end
                        out << '>'
                end


to_s (REXML::Entity)

# File lib/rexml/entity.rb, line 120
                def to_s
                        rv = ''
                        write rv
                        rv
                end


value (REXML::Entity)

# File lib/rexml/entity.rb, line 135
                def value
                        if @value
                                matches = @value.scan(PEREFERENCE_RE)
                                rv = @value.clone
                                if @parent
                                        matches.each do |entity_reference|
                                                entity_value = @parent.entity( entity_reference[0] )
                                                rv.gsub!( /%#{entity_reference};/um, entity_value )
                                        end
                                end
                                return rv
                        end
                        nil
                end


new (REXML::ExternalEntity)

# File lib/rexml/doctype.rb, line 230
    def initialize( src )
      super()
      @entity = src
    end


to_s (REXML::ExternalEntity)

# File lib/rexml/doctype.rb, line 234
    def to_s
      @entity
    end


write (REXML::ExternalEntity)

# File lib/rexml/doctype.rb, line 237
    def write( output, indent )
      output << @entity
    end


new (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 10
      def initialize( ie_hack=false )
        @ie_hack = ie_hack
      end


write (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 21
      def write( node, output )
        case node

        when Document
          if node.xml_decl.encoding != "UTF-8" && !output.kind_of?(Output)
            output = Output.new( output, node.xml_decl.encoding )
          end
          write_document( node, output )

        when Element
          write_element( node, output )

        when Declaration, ElementDecl, NotationDecl, ExternalEntity, Entity,
             Attribute, AttlistDecl
          node.write( output,-1 )

        when Instruction
          write_instruction( node, output )

        when DocType, XMLDecl
          node.write( output )

        when Comment
          write_comment( node, output )

        when CData
          write_cdata( node, output )

        when Text
          write_text( node, output )

        else
          raise Exception.new("XML FORMATTING ERROR")

        end
      end


write_document (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 59
      def write_document( node, output )
        node.children.each { |child| write( child, output ) }
      end


write_element (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 63
      def write_element( node, output )
        output << "<#{node.expanded_name}"

        node.attributes.each_attribute do |attr|
          output << " "
          attr.write( output )
        end unless node.attributes.empty?

        if node.children.empty?
          output << " " if @ie_hack
          output << "/"
        else
          output << ">"
          node.children.each { |child|
            write( child, output )
          }
          output << "</#{node.expanded_name}"
        end
        output << ">"
      end


write_text (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 84
      def write_text( node, output )
        output << node.to_s()
      end


write_comment (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 88
      def write_comment( node, output )
        output << Comment::START
        output << node.to_s
        output << Comment::STOP
      end


write_cdata (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 94
      def write_cdata( node, output )
        output << CData::START
        output << node.to_s
        output << CData::STOP
      end


write_instruction (REXML::Formatters::Default)

# File lib/rexml/formatters/default.rb, line 100
      def write_instruction( node, output )
        output << Instruction::START.sub(/\\/u, '')
        output << node.target
        output << ' '
        output << node.content
        output << Instruction::STOP.sub(/\\/u, '')
      end


new (REXML::Formatters::Pretty)

# File lib/rexml/formatters/pretty.rb, line 29
      def initialize( indentation=2, ie_hack=false )
        @indentation = indentation
        @level = 0
        @ie_hack = ie_hack
        @width = 80
      end


write_element (REXML::Formatters::Pretty)

# File lib/rexml/formatters/pretty.rb, line 37
      def write_element(node, output)
        output << ' '*@level
        output << "<#{node.expanded_name}"

        node.attributes.each_attribute do |attr|
          output << " "
          attr.write( output )
        end unless node.attributes.empty?

        if node.children.empty?
          if @ie_hack
            output << " "
          end
          output << "/"
        else
          output << ">"
          # If compact and all children are text, and if the formatted output
          # is less than the specified width, then try to print everything on
          # one line
          skip = false
          if compact
            if node.children.inject(true) {|s,c| s & c.kind_of?(Text)}
              string = ""
              old_level = @level
              @level = 0
              node.children.each { |child| write( child, string ) }
              @level = old_level
              if string.length < @width
                output << string
                skip = true
              end
            end
          end
          unless skip
            output << "\n"
            @level += @indentation
            node.children.each { |child|
              next if child.kind_of?(Text) and child.to_s.strip.length == 0
              write( child, output )
              output << "\n"
            }
            @level -= @indentation
            output << ' '*@level
          end
          output << "</#{node.expanded_name}"
        end
        output << ">"
      end


write_text (REXML::Formatters::Pretty)

# File lib/rexml/formatters/pretty.rb, line 86
      def write_text( node, output )
        s = node.to_s()
        s.gsub!(/\s/,' ')
        s.squeeze!(" ")
        s = wrap(s, 80-@level)
        s = indent_text(s, @level, " ", true)
        output << (' '*@level + s)
      end


write_comment (REXML::Formatters::Pretty)

# File lib/rexml/formatters/pretty.rb, line 95
      def write_comment( node, output)
        output << ' ' * @level
        super
      end


write_cdata (REXML::Formatters::Pretty)

# File lib/rexml/formatters/pretty.rb, line 100
      def write_cdata( node, output)
        output << ' ' * @level
        super
      end


write_document (REXML::Formatters::Pretty)

# File lib/rexml/formatters/pretty.rb, line 105
      def write_document( node, output )
        # Ok, this is a bit odd.  All XML documents have an XML declaration,
        # but it may not write itself if the user didn't specifically add it,
        # either through the API or in the input document.  If it doesn't write
        # itself, then we don't need a carriage return... which makes this
        # logic more complex.
        node.children.each { |child|
          next if child == node.children[-1] and child.instance_of?(Text)
          unless child == node.children[0] or child.instance_of?(Text) or
            (child == node.children[1] and !node.children[0].writethis)
            output << "\n"
          end
          write( child, output )
        }
      end


new (REXML::Formatters::Transitive)

# File lib/rexml/formatters/transitive.rb, line 15
      def initialize( indentation=2 )
        @indentation = indentation
        @level = 0
      end


write_element (REXML::Formatters::Transitive)

# File lib/rexml/formatters/transitive.rb, line 21
      def write_element( node, output )
        output << "<#{node.expanded_name}"

        node.attributes.each_attribute do |attr|
          output << " "
          attr.write( output )
        end unless node.attributes.empty?

        output << "\n"
        output << ' '*@level
        if node.children.empty?
          output << "/"
        else
          output << ">"
          # If compact and all children are text, and if the formatted output
          # is less than the specified width, then try to print everything on
          # one line
          skip = false
          @level += @indentation
          node.children.each { |child|
            write( child, output )
          }
          @level -= @indentation
          output << "</#{node.expanded_name}"
          output << "\n"
          output << ' '*@level
        end
        output << ">"
      end


write_text (REXML::Formatters::Transitive)

# File lib/rexml/formatters/transitive.rb, line 51
      def write_text( node, output )
        output << node.to_s()
      end


namespace_context= (REXML::Functions)

# File lib/rexml/functions.rb, line 14
    def Functions::namespace_context=(x) ; @@namespace_context=x ; end


variables= (REXML::Functions)

# File lib/rexml/functions.rb, line 15
    def Functions::variables=(x) ; @@variables=x ; end


namespace_context (REXML::Functions)

# File lib/rexml/functions.rb, line 16
    def Functions::namespace_context ; @@namespace_context ; end


variables (REXML::Functions)

# File lib/rexml/functions.rb, line 17
    def Functions::variables ; @@variables ; end


context= (REXML::Functions)

# File lib/rexml/functions.rb, line 19
    def Functions::context=(value); @@context = value; end


text (REXML::Functions)

# File lib/rexml/functions.rb, line 21
    def Functions::text( )
      if @@context[:node].node_type == :element
        return @@context[:node].find_all{|n| n.node_type == :text}.collect{|n| n.value}
      elsif @@context[:node].node_type == :text
        return @@context[:node].value
      else
        return false
      end
    end


last (REXML::Functions)

# File lib/rexml/functions.rb, line 31
    def Functions::last( )
      @@context[:size]
    end


position (REXML::Functions)

# File lib/rexml/functions.rb, line 35
    def Functions::position( )
      @@context[:index]
    end


count (REXML::Functions)

# File lib/rexml/functions.rb, line 39
    def Functions::count( node_set )
      node_set.size
    end


id (REXML::Functions)

# File lib/rexml/functions.rb, line 45
    def Functions::id( object )
    end


local_name (REXML::Functions)

# File lib/rexml/functions.rb, line 49
    def Functions::local_name( node_set=nil )
      get_namespace( node_set ) do |node|
        return node.local_name
      end
    end


namespace_uri (REXML::Functions)

# File lib/rexml/functions.rb, line 55
    def Functions::namespace_uri( node_set=nil )
      get_namespace( node_set ) {|node| node.namespace}
    end


name (REXML::Functions)

# File lib/rexml/functions.rb, line 59
    def Functions::name( node_set=nil )
      get_namespace( node_set ) do |node|
        node.expanded_name
      end
    end


get_namespace (REXML::Functions)

# File lib/rexml/functions.rb, line 66
    def Functions::get_namespace( node_set = nil )
      if node_set == nil
        yield @@context[:node] if defined? @@context[:node].namespace
      else
        if node_set.respond_to? :each
          node_set.each { |node| yield node if defined? node.namespace }
        elsif node_set.respond_to? :namespace
          yield node_set
        end
      end
    end


string (REXML::Functions)

# File lib/rexml/functions.rb, line 113
    def Functions::string( object=nil )
      #object = @context unless object
      if object.instance_of? Array
        string( object[0] )
      elsif defined? object.node_type
        if object.node_type == :attribute
          object.value
        elsif object.node_type == :element || object.node_type == :document
          string_value(object)
        else
          object.to_s
        end
      elsif object.nil?
        return ""
      else
        object.to_s
      end
    end


string_value (REXML::Functions)

# File lib/rexml/functions.rb, line 132
    def Functions::string_value( o )
      rv = ""
      o.children.each { |e|
        if e.node_type == :text
          rv << e.to_s
        elsif e.node_type == :element
          rv << string_value( e )
        end
      }
      rv
    end


concat (REXML::Functions)

# File lib/rexml/functions.rb, line 145
    def Functions::concat( *objects )
      objects.join
    end


starts_with (REXML::Functions)

# File lib/rexml/functions.rb, line 150
    def Functions::starts_with( string, test )
      string(string).index(string(test)) == 0
    end


contains (REXML::Functions)

# File lib/rexml/functions.rb, line 155
    def Functions::contains( string, test )
      string(string).include?(string(test))
    end


substring_before (REXML::Functions)

# File lib/rexml/functions.rb, line 160
    def Functions::substring_before( string, test )
      ruby_string = string(string)
      ruby_index = ruby_string.index(string(test))
      if ruby_index.nil?
        ""
      else
        ruby_string[ 0...ruby_index ]
      end
    end


substring_after (REXML::Functions)

# File lib/rexml/functions.rb, line 171
    def Functions::substring_after( string, test )
      ruby_string = string(string)
      test_string = string(test)
      return $1 if ruby_string =~ /#{test}(.*)/
      ""
    end


substring (REXML::Functions)

# File lib/rexml/functions.rb, line 180
    def Functions::substring( string, start, length=nil )
      ruby_string = string(string)
      ruby_length = if length.nil?
                      ruby_string.length.to_f
                    else
                      number(length)
                    end
      ruby_start = number(start)

      # Handle the special cases
      return '' if (
        ruby_length.nan? or
        ruby_start.nan? or
        ruby_start.infinite?
      )

      infinite_length = ruby_length.infinite? == 1
      ruby_length = ruby_string.length if infinite_length

      # Now, get the bounds.  The XPath bounds are 1..length; the ruby bounds
      # are 0..length.  Therefore, we have to offset the bounds by one.
      ruby_start = ruby_start.round - 1
      ruby_length = ruby_length.round

      if ruby_start < 0
       ruby_length += ruby_start unless infinite_length
       ruby_start = 0
      end
      return '' if ruby_length <= 0
      ruby_string[ruby_start,ruby_length]
    end


string_length (REXML::Functions)

# File lib/rexml/functions.rb, line 213
    def Functions::string_length( string )
      string(string).length
    end


normalize_space (REXML::Functions)

# File lib/rexml/functions.rb, line 218
    def Functions::normalize_space( string=nil )
      string = string(@@context[:node]) if string.nil?
      if string.kind_of? Array
        string.collect{|x| string.to_s.strip.gsub(/\s+/um, ' ') if string}
      else
        string.to_s.strip.gsub(/\s+/um, ' ')
      end
    end


translate (REXML::Functions)

# File lib/rexml/functions.rb, line 228
    def Functions::translate( string, tr1, tr2 )
      from = string(tr1)
      to = string(tr2)

      # the map is our translation table.
      #
      # if a character occurs more than once in the
      # from string then we ignore the second &
      # subsequent mappings
      #
      # if a charactcer maps to nil then we delete it
      # in the output.  This happens if the from
      # string is longer than the to string
      #
      # there's nothing about - or ^ being special in
      # http://www.w3.org/TR/xpath#function-translate
      # so we don't build ranges or negated classes

      map = Hash.new
      0.upto(from.length - 1) { |pos|
        from_char = from[pos]
        unless map.has_key? from_char
          map[from_char] =
          if pos < to.length
            to[pos]
          else
            nil
          end
        end
      }

      string(string).unpack('U*').collect { |c|
        if map.has_key? c then map[c] else c end
      }.compact.pack('U*')
    end


boolean (REXML::Functions)

# File lib/rexml/functions.rb, line 265
    def Functions::boolean( object=nil )
      if object.kind_of? String
        if object =~ /\d+/u
          return object.to_f != 0
        else
          return object.size > 0
        end
      elsif object.kind_of? Array
        object = object.find{|x| x and true}
      end
      return object ? true : false
    end


not (REXML::Functions)

# File lib/rexml/functions.rb, line 279
    def Functions::not( object )
      not boolean( object )
    end


true (REXML::Functions)

# File lib/rexml/functions.rb, line 284
    def Functions::true( )
      true
    end


false (REXML::Functions)

# File lib/rexml/functions.rb, line 289
    def Functions::false(  )
      false
    end


lang (REXML::Functions)

# File lib/rexml/functions.rb, line 294
    def Functions::lang( language )
      lang = false
      node = @@context[:node]
      attr = nil
      until node.nil?
        if node.node_type == :element
          attr = node.attributes["xml:lang"]
          unless attr.nil?
            lang = compare_language(string(language), attr)
            break
          else
          end
        end
        node = node.parent
      end
      lang
    end


compare_language (REXML::Functions)

# File lib/rexml/functions.rb, line 312
    def Functions::compare_language lang1, lang2
      lang2.downcase.index(lang1.downcase) == 0
    end


number (REXML::Functions)

# File lib/rexml/functions.rb, line 329
    def Functions::number( object=nil )
      object = @@context[:node] unless object
      case object
      when true
        Float(1)
      when false
        Float(0)
      when Array
        number(string( object ))
      when Numeric
        object.to_f
      else
        str = string( object )
        # If XPath ever gets scientific notation...
        #if str =~ /^\s*-?(\d*\.?\d+|\d+\.)([Ee]\d*)?\s*$/
        if str =~ /^\s*-?(\d*\.?\d+|\d+\.)\s*$/
          str.to_f
        else
          (0.0 / 0.0)
        end
      end
    end


sum (REXML::Functions)

# File lib/rexml/functions.rb, line 352
    def Functions::sum( nodes )
      nodes = [nodes] unless nodes.kind_of? Array
      nodes.inject(0) { |r,n| r += number(string(n)) }
    end


floor (REXML::Functions)

# File lib/rexml/functions.rb, line 357
    def Functions::floor( number )
      number(number).floor
    end


ceiling (REXML::Functions)

# File lib/rexml/functions.rb, line 361
    def Functions::ceiling( number )
      number(number).ceil
    end


round (REXML::Functions)

# File lib/rexml/functions.rb, line 365
    def Functions::round( number )
      begin
        number(number).round
      rescue FloatDomainError
        number(number)
      end
    end


processing_instruction (REXML::Functions)

# File lib/rexml/functions.rb, line 373
    def Functions::processing_instruction( node )
      node.node_type == :processing_instruction
    end


method_missing (REXML::Functions)

# File lib/rexml/functions.rb, line 377
    def Functions::method_missing( id )
      puts "METHOD MISSING #{id.id2name}"
      XPath.match( @@context[:node], id.id2name )
    end


new (REXML::Instruction)

# File lib/rexml/instruction.rb, line 24
                def initialize(target, content=nil)
                        if target.kind_of? String
                                super()
                                @target = target
                                @content = content
                        elsif target.kind_of? Instruction
                                super(content)
                                @target = target.target
                                @content = target.content
                        end
                        @content.strip! if @content
                end


clone (REXML::Instruction)

# File lib/rexml/instruction.rb, line 37
                def clone
                        Instruction.new self
                end


write (REXML::Instruction)

# File lib/rexml/instruction.rb, line 44
                def write writer, indent=-1, transitive=false, ie_hack=false
      Kernel.warn( "#{self.class.name}.write is deprecated" )
                        indent(writer, indent)
                        writer << START.sub(/\\/u, '')
                        writer << @target
                        writer << ' '
                        writer << @content
                        writer << STOP.sub(/\\/u, '')
                end


== (REXML::Instruction)

# File lib/rexml/instruction.rb, line 56
                def ==( other )
                        other.kind_of? Instruction and
                        other.target == @target and
                        other.content == @content
                end


node_type (REXML::Instruction)

# File lib/rexml/instruction.rb, line 62
    def node_type
      :processing_instruction
    end


inspect (REXML::Instruction)

# File lib/rexml/instruction.rb, line 66
    def inspect
      "<?p-i #{target} ...?>"
    end


new (REXML::IOSource)

# File lib/rexml/source.rb, line 134
    def initialize(arg, block_size=500, encoding=nil)
      @er_source = @source = arg
      @to_utf = false

      # Determining the encoding is a deceptively difficult issue to resolve.
      # First, we check the first two bytes for UTF-16.  Then we
      # assume that the encoding is at least ASCII enough for the '>', and
      # we read until we get one of those.  This gives us the XML declaration,
      # if there is one.  If there isn't one, the file MUST be UTF-8, as per
      # the XML spec.  If there is one, we can determine the encoding from
      # it.
      @buffer = ""
      str = @source.read( 2 )
      if encoding
        self.encoding = encoding
      elsif 0xfe == str[0] && 0xff == str[1]
        @line_break = "\000>"
      elsif 0xff == str[0] && 0xfe == str[1]
        @line_break = ">\000"
      elsif 0xef == str[0] && 0xbb == str[1]
        str += @source.read(1)
        str = '' if (0xbf == str[2])
        @line_break = ">"
      else
        @line_break = ">"
      end
      super str+@source.readline( @line_break )
    end


scan (REXML::IOSource)

# File lib/rexml/source.rb, line 163
    def scan(pattern, cons=false)
      rv = super
      # You'll notice that this next section is very similar to the same
      # section in match(), but just a liiittle different.  This is
      # because it is a touch faster to do it this way with scan()
      # than the way match() does it; enough faster to warrent duplicating
      # some code
      if rv.size == 0
        until @buffer =~ pattern or @source.nil?
          begin
            # READLINE OPT
            #str = @source.read(@block_size)
            str = @source.readline(@line_break)
            str = decode(str) if @to_utf and str
            @buffer << str
          rescue Iconv::IllegalSequence
            raise
          rescue
            @source = nil
          end
        end
        rv = super
      end
      rv.taint
      rv
    end


read (REXML::IOSource)

# File lib/rexml/source.rb, line 190
    def read
      begin
        str = @source.readline(@line_break)
        str = decode(str) if @to_utf and str
        @buffer << str
      rescue Exception, NameError
        @source = nil
      end
    end


consume (REXML::IOSource)

# File lib/rexml/source.rb, line 200
    def consume( pattern )
      match( pattern, true )
    end


match (REXML::IOSource)

# File lib/rexml/source.rb, line 204
    def match( pattern, cons=false )
      rv = pattern.match(@buffer)
      @buffer = $' if cons and rv
      while !rv and @source
        begin
          str = @source.readline(@line_break)
          str = decode(str) if @to_utf and str
          @buffer << str
          rv = pattern.match(@buffer)
          @buffer = $' if cons and rv
        rescue
          @source = nil
        end
      end
      rv.taint
      rv
    end


empty? (REXML::IOSource)

# File lib/rexml/source.rb, line 222
    def empty?
      super and ( @source.nil? || @source.eof? )
    end


position (REXML::IOSource)

# File lib/rexml/source.rb, line 226
    def position
      @er_source.stat.pipe? ? 0 : @er_source.pos
    end


current_line (REXML::IOSource)

# File lib/rexml/source.rb, line 231
    def current_line
      begin
        pos = @er_source.pos        # The byte position in the source
        lineno = @er_source.lineno  # The XML < position in the source
        @er_source.rewind
        line = 0                    # The \r\n position in the source
        begin
          while @er_source.pos < pos
            @er_source.readline
            line += 1
          end
        rescue
        end
      rescue IOError
        pos = -1
        line = -1
      end
      [pos, lineno, line]
    end


new (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 21
                        def initialize node=nil
                                @node = node
                                if node.kind_of? String
                                        node = [ :text, node ]
                                elsif node.nil?
                                        node = [ :document, nil, nil ]
                                elsif node[0] == :start_element
                                        node[0] = :element
                                elsif node[0] == :start_doctype
                                        node[0] = :doctype
                                elsif node[0] == :start_document
                                        node[0] = :document
                                end
                        end


size (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 36
                        def size
                                if PARENTS.include? @node[0]
                                        @node[-1].size
                                else
                                        0
                                end
                        end


each (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 44
                        def each( &block )
                                size.times { |x| yield( at(x+4) ) }
                        end


name (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 48
                        def name
                                at(2)
                        end


name= (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 52
                        def name=( name_str, ns=nil )
                                pfx = ''
                                pfx = "#{prefix(ns)}:" if ns
                                _old_put(2, "#{pfx}#{name_str}")
                        end


parent= (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 58
                        def parent=( node )
                                _old_put(1,node)
                        end


local_name (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 62
                        def local_name
                                namesplit
                                @name
                        end


local_name= (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 67
                        def local_name=( name_str )
                                _old_put( 1, "#@prefix:#{name_str}" )
                        end


prefix (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 71
                        def prefix( namespace=nil )
                                prefix_of( self, namespace )
                        end


namespace (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 75
                        def namespace( prefix=prefix() )
                                namespace_of( self, prefix )
                        end


namespace= (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 79
                        def namespace=( namespace )
                                @prefix = prefix( namespace )
                                pfx = ''
                                pfx = "#@prefix:" if @prefix.size > 0
                                _old_put(1, "#{pfx}#@name")
                        end


[] (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 86
                        def []( reference, ns=nil )
                                if reference.kind_of? String
                                        pfx = ''
                                        pfx = "#{prefix(ns)}:" if ns
                                        at(3)["#{pfx}#{reference}"]
                                elsif reference.kind_of? Range
                                        _old_get( Range.new(4+reference.begin, reference.end, reference.exclude_end?) )
                                else
                                        _old_get( 4+reference )
                                end
                        end


=~ (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 98
                        def =~( path )
                                XPath.match( self, path )
                        end


[]= (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 103
                        def []=( reference, ns, value=nil )
                                if reference.kind_of? String
                                        value = ns unless value
                                        at( 3 )[reference] = value
                                elsif reference.kind_of? Range
                                        _old_put( Range.new(3+reference.begin, reference.end, reference.exclude_end?), ns )
                                else
                                        if value
                                                _old_put( 4+reference, ns, value )
                                        else
                                                _old_put( 4+reference, ns )
                                        end
                                end
                        end


<< (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 122
                        def << element
                                if node_type() == :text
                                        at(-1) << element
                                else
                                        newnode = Node.new( element )
                                        newnode.parent = self
                                        self.push( newnode )
                                end
                                at(-1)
                        end


node_type (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 133
                        def node_type
                                _old_get(0)
                        end


text= (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 137
                        def text=( foo )
                                replace = at(4).kind_of?(String)? 1 : 0
                                self._old_put(4,replace, normalizefoo)
                        end


root (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 142
                        def root
                                context = self
                                context = context.at(1) while context.at(1)
                        end


has_name? (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 147
                        def has_name?( name, namespace = '' )
                                at(3) == name and namespace() == namespace
                        end


children (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 151
                        def children
                                self
                        end


parent (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 155
                        def parent
                                at(1)
                        end


to_s (REXML::Light::Node)

# File lib/rexml/light/node.rb, line 159
                        def to_s

                        end


name= (REXML::Namespace)

# File lib/rexml/namespace.rb, line 14
                def name=( name )
                        @expanded_name = name
                        name =~ NAMESPLIT
                        if $1
                                @prefix = $1
                        else
                                @prefix = ""
                                @namespace = ""
                        end
                        @name = $2
                end


has_name? (REXML::Namespace)

# File lib/rexml/namespace.rb, line 27
                def has_name?( other, ns=nil )
                        if ns
                                return (namespace() == ns and name() == other)
                        elsif other.include? ":"
                                return fully_expanded_name == other
                        else
                                return name == other
                        end
                end


fully_expanded_name (REXML::Namespace)

# File lib/rexml/namespace.rb, line 41
                def fully_expanded_name
                        ns = prefix
                        return "#{ns}:#@name" if ns.size > 0
                        return @name
                end


next_sibling_node (REXML::Node)

# File lib/rexml/node.rb, line 10
                def next_sibling_node
                        return nil if @parent.nil?
                        @parent[ @parent.index(self) + 1 ]
                end


previous_sibling_node (REXML::Node)

# File lib/rexml/node.rb, line 16
                def previous_sibling_node
                        return nil if @parent.nil?
                        ind = @parent.index(self)
                        return nil if ind == 0
                        @parent[ ind - 1 ]
                end


to_s (REXML::Node)

# File lib/rexml/node.rb, line 26
                def to_s indent=nil
      unless indent.nil?
        Kernel.warn( "#{self.class.name}.to_s(indent) parameter is deprecated" )
        f = REXML::Formatters::Pretty.new( indent )
        f.write( self, rv, indent )
      else
        f = REXML::Formatters::Default.new
        f.write( self, rv = "" )
      end
      return rv
                end


indent (REXML::Node)

# File lib/rexml/node.rb, line 38
                def indent to, ind
                        if @parent and @parent.context and not @parent.context[:indentstyle].nil? then
                                indentstyle = @parent.context[:indentstyle]
                        else
                                indentstyle = '  '
                        end
                        to << indentstyle*ind unless ind<1
                end


parent? (REXML::Node)

# File lib/rexml/node.rb, line 47
                def parent?
                        false;
                end


each_recursive (REXML::Node)

# File lib/rexml/node.rb, line 53
                def each_recursive(&block) # :yields: node
                        self.elements.each {|node|
                                block.call(node)
                                node.each_recursive(&block)
                        }
                end


find_first_recursive (REXML::Node)

# File lib/rexml/node.rb, line 62
                def find_first_recursive(&block) # :yields: node
      each_recursive {|node|
        return node if block.call(node)
      }
      return nil
    end


index_in_parent (REXML::Node)

# File lib/rexml/node.rb, line 71
    def index_in_parent
      parent.index(self)+1
    end


new (REXML::NotationDecl)

# File lib/rexml/doctype.rb, line 244
    def initialize name, middle, pub, sys
      super(nil)
      @name = name
      @middle = middle
      @public = pub
      @system = sys
    end


to_s (REXML::NotationDecl)

# File lib/rexml/doctype.rb, line 252
    def to_s
      "<!NOTATION #@name #@middle#{
        @public ? ' ' + public.inspect : ''
      }#{
        @system ? ' ' +@system.inspect : ''
      }>"
    end


write (REXML::NotationDecl)

# File lib/rexml/doctype.rb, line 260
    def write( output, indent=-1 )
      output << to_s
    end


name (REXML::NotationDecl)

# File lib/rexml/doctype.rb, line 267
    def name
      @name
    end


new (REXML::Output)

# File lib/rexml/output.rb, line 9
                def initialize real_IO, encd="iso-8859-1"
                        @output = real_IO
                        self.encoding = encd

                        @to_utf = encd == UTF_8 ? false : true
                end


<< (REXML::Output)

# File lib/rexml/output.rb, line 16
                def <<( content )
                        @output << (@to_utf ? self.encode(content) : content)
                end


to_s (REXML::Output)

# File lib/rexml/output.rb, line 20
    def to_s
      "Output[#{encoding}]"
    end


new (REXML::Parent)

# File lib/rexml/parent.rb, line 12
    def initialize parent=nil
      super(parent)
      @children = []
    end


add (REXML::Parent)

# File lib/rexml/parent.rb, line 17
    def add( object )
      #puts "PARENT GOTS #{size} CHILDREN"
      object.parent = self
      @children << object
      #puts "PARENT NOW GOTS #{size} CHILDREN"
      object
    end


unshift (REXML::Parent)

# File lib/rexml/parent.rb, line 28
    def unshift( object )
      object.parent = self
      @children.unshift object
    end


delete (REXML::Parent)

# File lib/rexml/parent.rb, line 33
    def delete( object )
      found = false
      @children.delete_if {|c| c.equal?(object) and found = true }
      object.parent = nil if found
    end


each (REXML::Parent)

# File lib/rexml/parent.rb, line 39
    def each(&block)
      @children.each(&block)
    end


delete_if (REXML::Parent)

# File lib/rexml/parent.rb, line 43
    def delete_if( &block )
      @children.delete_if(&block)
    end


delete_at (REXML::Parent)

# File lib/rexml/parent.rb, line 47
    def delete_at( index )
      @children.delete_at index
    end


each_index (REXML::Parent)

# File lib/rexml/parent.rb, line 51
    def each_index( &block )
      @children.each_index(&block)
    end


[] (REXML::Parent)

# File lib/rexml/parent.rb, line 57
    def []( index )
      @children[index]
    end


[]= (REXML::Parent)

# File lib/rexml/parent.rb, line 70
    def []=( *args )
      args[-1].parent = self
      @children[*args[0..-2]] = args[-1]
    end


insert_before (REXML::Parent)

# File lib/rexml/parent.rb, line 82
    def insert_before( child1, child2 )
      if child1.kind_of? String
        child1 = XPath.first( self, child1 )
        child1.parent.insert_before child1, child2
      else
        ind = index(child1)
        child2.parent.delete(child2) if child2.parent
        @children[ind,0] = child2
        child2.parent = self
      end
      self
    end


insert_after (REXML::Parent)

# File lib/rexml/parent.rb, line 102
    def insert_after( child1, child2 )
      if child1.kind_of? String
        child1 = XPath.first( self, child1 )
        child1.parent.insert_after child1, child2
      else
        ind = index(child1)+1
        child2.parent.delete(child2) if child2.parent
        @children[ind,0] = child2
        child2.parent = self
      end
      self
    end


to_a (REXML::Parent)

# File lib/rexml/parent.rb, line 115
    def to_a
      @children.dup
    end


index (REXML::Parent)

# File lib/rexml/parent.rb, line 123
    def index( child )
      count = -1
      @children.find { |i| count += 1 ; i.hash == child.hash }
      count
    end


size (REXML::Parent)

# File lib/rexml/parent.rb, line 130
    def size
      @children.size
    end


replace_child (REXML::Parent)

# File lib/rexml/parent.rb, line 140
    def replace_child( to_replace, replacement )
      @children.map! {|c| c.equal?( to_replace ) ? replacement : c }
      to_replace.parent = nil
      replacement.parent = self
    end


deep_clone (REXML::Parent)

# File lib/rexml/parent.rb, line 148
    def deep_clone
      cl = clone()
      each do |child|
        if child.kind_of? Parent
          cl << child.deep_clone
        else
          cl << child.clone
        end
      end
      cl
    end


parent? (REXML::Parent)

# File lib/rexml/parent.rb, line 162
    def parent?
      true
    end


new (REXML::ParseException)

# File lib/rexml/parseexception.rb, line 5
    def initialize( message, source=nil, parser=nil, exception=nil )
      super(message)
      @source = source
      @parser = parser
      @continued_exception = exception
    end


to_s (REXML::ParseException)

# File lib/rexml/parseexception.rb, line 12
    def to_s
      # Quote the original exception, if there was one
      if @continued_exception
        err = @continued_exception.inspect
        err << "\n"
        err << @continued_exception.backtrace.join("\n")
        err << "\n...\n"
      else
        err = ""
      end

      # Get the stack trace and error message
      err << super

      # Add contextual information
      if @source
        err << "\nLine: #{line}\n"
        err << "Position: #{position}\n"
        err << "Last 80 unconsumed characters:\n"
        err << @source.buffer[0..80].gsub(/\n/, ' ')
      end

      err
    end


position (REXML::ParseException)

# File lib/rexml/parseexception.rb, line 37
    def position
      @source.current_line[0] if @source and defined? @source.current_line and
      @source.current_line
    end


line (REXML::ParseException)

# File lib/rexml/parseexception.rb, line 42
    def line
      @source.current_line[2] if @source and defined? @source.current_line and
      @source.current_line
    end


context (REXML::ParseException)

# File lib/rexml/parseexception.rb, line 47
    def context
      @source.current_line
    end


new (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 109
      def initialize( source )
        self.stream = source
      end


add_listener (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 113
      def add_listener( listener )
        if !defined?(@listeners) or !@listeners
          @listeners = []
          instance_eval "alias :_old_pull :pull\ndef pull\nevent = _old_pull\n@listeners.each do |listener|\nlistener.receive event\nend\nevent\nend\n"
        end
        @listeners << listener
      end


stream= (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 133
      def stream=( source )
        @source = SourceFactory.create_from( source )
        @closed = nil
        @document_status = nil
        @tags = []
        @stack = []
        @entities = []
        @nsstack = []
      end


position (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 143
      def position
        if @source.respond_to? :position
          @source.position
        else
          # FIXME
          0
        end
      end


empty? (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 153
      def empty?
        return (@source.empty? and @stack.empty?)
      end


has_next? (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 158
      def has_next?
        return !(@source.empty? and @stack.empty?)
      end


unshift (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 164
      def unshift token
        @stack.unshift(token)
      end


peek (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 174
      def peek depth=0
        raise %Q[Illegal argument "#{depth}"] if depth < -1
        temp = []
        if depth == -1
          temp.push(pull()) until empty?
        else
          while @stack.size+temp.size < depth+1
            temp.push(pull())
          end
        end
        @stack += temp if temp.size > 0
        @stack[depth]
      end


pull (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 189
      def pull
        if @closed
          x, @closed = @closed, nil
          return [ :end_element, x ]
        end
        return [ :end_document ] if empty?
        return @stack.shift if @stack.size > 0
        #STDERR.puts @source.encoding
        @source.read if @source.buffer.size<2
        #STDERR.puts "BUFFER = #{@source.buffer.inspect}"
        if @document_status == nil
          #@source.consume( /^\s*/um )
          word = @source.match( /^((?:\s+)|(?:<[^>]*>))/um )
          word = word[1] unless word.nil?
          #STDERR.puts "WORD = #{word.inspect}"
          case word
          when COMMENT_START
            return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
          when XMLDECL_START
            #STDERR.puts "XMLDECL"
            results = @source.match( XMLDECL_PATTERN, true )[1]
            version = VERSION.match( results )
            version = version[1] unless version.nil?
            encoding = ENCODING.match(results)
            encoding = encoding[1] unless encoding.nil?
            @source.encoding = encoding
            standalone = STANDALONE.match(results)
            standalone = standalone[1] unless standalone.nil?
            return [ :xmldecl, version, encoding, standalone ]
          when INSTRUCTION_START
            return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ]
          when DOCTYPE_START
            md = @source.match( DOCTYPE_PATTERN, true )
            @nsstack.unshift(curr_ns=Set.new)
            identity = md[1]
            close = md[2]
            identity =~ IDENTITY
            name = $1
            raise REXML::ParseException.new("DOCTYPE is missing a name") if name.nil?
            pub_sys = $2.nil? ? nil : $2.strip
            long_name = $4.nil? ? nil : $4.strip
            uri = $6.nil? ? nil : $6.strip
            args = [ :start_doctype, name, pub_sys, long_name, uri ]
            if close == ">"
              @document_status = :after_doctype
              @source.read if @source.buffer.size<2
              md = @source.match(/^\s*/um, true)
              @stack << [ :end_doctype ]
            else
              @document_status = :in_doctype
            end
            return args
          when /^\s+/
          else
            @document_status = :after_doctype
            @source.read if @source.buffer.size<2
            md = @source.match(/\s*/um, true)
          end
        end
        if @document_status == :in_doctype
          md = @source.match(/\s*(.*?>)/um)
          case md[1]
          when SYSTEMENTITY
            match = @source.match( SYSTEMENTITY, true )[1]
            return [ :externalentity, match ]

          when ELEMENTDECL_START
            return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ]

          when ENTITY_START
            match = @source.match( ENTITYDECL, true ).to_a.compact
            match[0] = :entitydecl
            ref = false
            if match[1] == '%'
              ref = true
              match.delete_at 1
            end
            # Now we have to sort out what kind of entity reference this is
            if match[2] == 'SYSTEM'
              # External reference
              match[3] = match[3][1..-2] # PUBID
              match.delete_at(4) if match.size > 4 # Chop out NDATA decl
              # match is [ :entity, name, SYSTEM, pubid(, ndata)? ]
            elsif match[2] == 'PUBLIC'
              # External reference
              match[3] = match[3][1..-2] # PUBID
              match[4] = match[4][1..-2] # HREF
              # match is [ :entity, name, PUBLIC, pubid, href ]
            else
              match[2] = match[2][1..-2]
              match.pop if match.size == 4
              # match is [ :entity, name, value ]
            end
            match << '%' if ref
            return match
          when ATTLISTDECL_START
            md = @source.match( ATTLISTDECL_PATTERN, true )
            raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil?
            element = md[1]
            contents = md[0]

            pairs = {}
            values = md[0].scan( ATTDEF_RE )
            values.each do |attdef|
              unless attdef[3] == "#IMPLIED"
                attdef.compact!
                val = attdef[3]
                val = attdef[4] if val == "#FIXED "
                pairs[attdef[0]] = val
                if attdef[0] =~ /^xmlns:(.*)/
                  @nsstack[0] << $1
                end
              end
            end
            return [ :attlistdecl, element, pairs, contents ]
          when NOTATIONDECL_START
            md = nil
            if @source.match( PUBLIC )
              md = @source.match( PUBLIC, true )
              vals = [md[1],md[2],md[4],md[6]]
            elsif @source.match( SYSTEM )
              md = @source.match( SYSTEM, true )
              vals = [md[1],md[2],nil,md[4]]
            else
              raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
            end
            return [ :notationdecl, *vals ]
          when CDATA_END
            @document_status = :after_doctype
            @source.match( CDATA_END, true )
            return [ :end_doctype ]
          end
        end
        begin
          if @source.buffer[0] == ?<
            if @source.buffer[1] == ?/
              @nsstack.shift
              last_tag = @tags.pop
              #md = @source.match_to_consume( '>', CLOSE_MATCH)
              md = @source.match( CLOSE_MATCH, true )
              raise REXML::ParseException.new( "Missing end tag for "+
                "'#{last_tag}' (got \"#{md[1]}\")",
                @source) unless last_tag == md[1]
              return [ :end_element, last_tag ]
            elsif @source.buffer[1] == ?!
              md = @source.match(/\A(\s*[^>]*>)/um)
              #STDERR.puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}"
              raise REXML::ParseException.new("Malformed node", @source) unless md
              if md[0][2] == ?-
                md = @source.match( COMMENT_PATTERN, true )
                return [ :comment, md[1] ] if md
              else
                md = @source.match( CDATA_PATTERN, true )
                return [ :cdata, md[1] ] if md
              end
              raise REXML::ParseException.new( "Declarations can only occur "+
                "in the doctype declaration.", @source)
            elsif @source.buffer[1] == ??
              md = @source.match( INSTRUCTION_PATTERN, true )
              return [ :processing_instruction, md[1], md[2] ] if md
              raise REXML::ParseException.new( "Bad instruction declaration",
                @source)
            else
              # Get the next tag
              md = @source.match(TAG_MATCH, true)
              unless md
                # Check for missing attribute quotes
                raise REXML::ParseException.new("missing attribute quote", @source) if @source.match(MISSING_ATTRIBUTE_QUOTES )
                raise REXML::ParseException.new("malformed XML: missing tag start", @source)
              end
              attributes = {}
              prefixes = Set.new
              prefixes << md[2] if md[2]
              @nsstack.unshift(curr_ns=Set.new)
              if md[4].size > 0
                attrs = md[4].scan( ATTRIBUTE_PATTERN )
                raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
                attrs.each { |a,b,c,d,e|
                  if b == "xmlns"
                    if c == "xml"
                      if d != "http://www.w3.org/XML/1998/namespace"
                        msg = "The 'xml' prefix must not be bound to any other namespace "+
                        "(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
                        raise REXML::ParseException.new( msg, @source, self )
                      end
                    elsif c == "xmlns"
                      msg = "The 'xmlns' prefix must not be declared "+
                      "(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
                      raise REXML::ParseException.new( msg, @source, self)
                    end
                    curr_ns << c
                  elsif b
                    prefixes << b unless b == "xml"
                  end
                  attributes[a] = e
                }
              end

              # Verify that all of the prefixes have been defined
              for prefix in prefixes
                unless @nsstack.find{|k| k.member?(prefix)}
                  raise UndefinedNamespaceException.new(prefix,@source,self)
                end
              end

              if md[6]
                @closed = md[1]
                @nsstack.shift
              else
                @tags.push( md[1] )
              end
              return [ :start_element, md[1], attributes ]
            end
          else
            md = @source.match( TEXT_PATTERN, true )
            if md[0].length == 0
              @source.match( /(\s+)/, true )
            end
            #STDERR.puts "GOT #{md[1].inspect}" unless md[0].length == 0
            #return [ :text, "" ] if md[0].length == 0
            # unnormalized = Text::unnormalize( md[1], self )
            # return PullEvent.new( :text, md[1], unnormalized )
            return [ :text, md[1] ]
          end
        rescue REXML::UndefinedNamespaceException
          raise
        rescue REXML::ParseException
          raise
        rescue Exception, NameError => error
          raise REXML::ParseException.new( "Exception parsing",
            @source, self, (error ? error : $!) )
        end
        return [ :dummy ]
      end


entity (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 424
      def entity( reference, entities )
        value = nil
        value = entities[ reference ] if entities
        if not value
          value = DEFAULT_ENTITIES[ reference ]
          value = value[2] if value
        end
        unnormalize( value, entities ) if value
      end


normalize (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 435
      def normalize( input, entities=nil, entity_filter=nil )
        copy = input.clone
        # Doing it like this rather than in a loop improves the speed
        copy.gsub!( EREFERENCE, '&amp;' )
        entities.each do |key, value|
          copy.gsub!( value, "&#{key};" ) unless entity_filter and
                                      entity_filter.include?(entity)
        end if entities
        copy.gsub!( EREFERENCE, '&amp;' )
        DEFAULT_ENTITIES.each do |key, value|
          copy.gsub!( value[3], value[1] )
        end
        copy
      end


unnormalize (REXML::Parsers::BaseParser)

# File lib/rexml/parsers/baseparser.rb, line 451
      def unnormalize( string, entities=nil, filter=nil )
        rv = string.clone
        rv.gsub!( /\r\n?/, "\n" )
        matches = rv.scan( REFERENCE_RE )
        return rv if matches.size == 0
        rv.gsub!( /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {|m|
          m=$1
          m = "0#{m}" if m[0] == ?x
          [Integer(m)].pack('U*')
        }
        matches.collect!{|x|x[0]}.compact!
        if matches.size > 0
          matches.each do |entity_reference|
            unless filter and filter.include?(entity_reference)
              entity_value = entity( entity_reference, entities )
              if entity_value
                re = /&#{entity_reference};/
                rv.gsub!( re, entity_value )
              end
            end
          end
          matches.each do |entity_reference|
            unless filter and filter.include?(entity_reference)
              er = DEFAULT_ENTITIES[entity_reference]
              rv.gsub!( er[0], er[2] ) if er
            end
          end
          rv.gsub!( /&amp;/, '&' )
        end
        rv
      end


new (REXML::Parsers::LightParser)

# File lib/rexml/parsers/lightparser.rb, line 8
                        def initialize stream
                                @stream = stream
                                @parser = REXML::Parsers::BaseParser.new( stream )
                        end


add_listener (REXML::Parsers::LightParser)

# File lib/rexml/parsers/lightparser.rb, line 13
      def add_listener( listener )
        @parser.add_listener( listener )
      end


rewind (REXML::Parsers::LightParser)

# File lib/rexml/parsers/lightparser.rb, line 17
      def rewind
        @stream.rewind
        @parser.stream = @stream
      end


parse (REXML::Parsers::LightParser)

# File lib/rexml/parsers/lightparser.rb, line 22
                        def parse
                                root = context = [ :document ]
                                while true
                                        event = @parser.pull
                                        case event[0]
                                        when :end_document
                                                break
                                        when :end_doctype
                                                context = context[1]
                                        when :start_element, :start_doctype
                                                new_node = event
                                                context << new_node
                                                new_node[1,0] = [context]
                                                context = new_node
                                        when :end_element, :end_doctype
                                                context = context[1]
                                        else
                                                new_node = event
                                                context << new_node
                                                new_node[1,0] = [context]
                                        end
                                end
                                root
                        end


new (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 94
      def initialize(arg)
        @contents = arg
      end


[] (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 98
      def []( start, endd=nil)
        if start.kind_of? Range
          @contents.slice( start.begin+1 .. start.end )
        elsif start.kind_of? Numeric
          if endd.nil?
            @contents.slice( start+1 )
          else
            @contents.slice( start+1, endd )
          end
        else
          raise "Illegal argument #{start.inspect} (#{start.class})"
        end
      end


event_type (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 112
      def event_type
        @contents[0]
      end


start_element? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 117
      def start_element?
        @contents[0] == :start_element
      end


end_element? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 122
      def end_element?
        @contents[0] == :end_element
      end


text? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 127
      def text?
        @contents[0] == :text
      end


instruction? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 132
      def instruction?
        @contents[0] == :processing_instruction
      end


comment? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 137
      def comment?
        @contents[0] == :comment
      end


doctype? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 142
      def doctype?
        @contents[0] == :start_doctype
      end


attlistdecl? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 147
      def attlistdecl?
        @contents[0] == :attlistdecl
      end


elementdecl? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 152
      def elementdecl?
        @contents[0] == :elementdecl
      end


entitydecl? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 163
      def entitydecl?
        @contents[0] == :entitydecl
      end


notationdecl? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 168
      def notationdecl?
        @contents[0] == :notationdecl
      end


entity? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 173
      def entity?
        @contents[0] == :entity
      end


cdata? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 178
      def cdata?
        @contents[0] == :cdata
      end


xmldecl? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 183
      def xmldecl?
        @contents[0] == :xmldecl
      end


error? (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 187
      def error?
        @contents[0] == :error
      end


inspect (REXML::Parsers::PullEvent)

# File lib/rexml/parsers/pullparser.rb, line 191
      def inspect
        @contents[0].to_s + ": " + @contents[1..-1].inspect
      end


new (REXML::Parsers::PullParser)

# File lib/rexml/parsers/pullparser.rb, line 37
      def initialize stream
        @entities = {}
        @listeners = nil
        @parser = BaseParser.new( stream )
        @my_stack = []
      end


add_listener (REXML::Parsers::PullParser)

# File lib/rexml/parsers/pullparser.rb, line 44
      def add_listener( listener )
        @listeners = [] unless @listeners
        @listeners << listener
      end


each (REXML::Parsers::PullParser)

# File lib/rexml/parsers/pullparser.rb, line 49
      def each
        while has_next?
          yield self.pull
        end
      end


peek (REXML::Parsers::PullParser)

# File lib/rexml/parsers/pullparser.rb, line 55
      def peek depth=0
        if @my_stack.length <= depth
          (depth - @my_stack.length + 1).times {
            e = PullEvent.new(@parser.pull)
            @my_stack.push(e)
          }
        end
        @my_stack[depth]
      end


pull (REXML::Parsers::PullParser)

# File lib/rexml/parsers/pullparser.rb, line 65
      def pull
        return @my_stack.shift if @my_stack.length > 0

        event = @parser.pull
        case event[0]
        when :entitydecl
          @entities[ event[1] ] =
            event[2] unless event[2] =~ /PUBLIC|SYSTEM/
        when :text
          unnormalized = @parser.unnormalize( event[1], @entities )
          event << unnormalized
        end
        PullEvent.new( event )
      end


unshift (REXML::Parsers::PullParser)

# File lib/rexml/parsers/pullparser.rb, line 80
      def unshift token
        @my_stack.unshift token
      end


new (REXML::Parsers::SAX2Parser)

# File lib/rexml/parsers/sax2parser.rb, line 10
                        def initialize source
                                @parser = BaseParser.new(source)
                                @listeners = []
                                @procs = []
                                @namespace_stack = []
                                @has_listeners = false
                                @tag_stack = []
        @entities = {}
                        end


source (REXML::Parsers::SAX2Parser)

# File lib/rexml/parsers/sax2parser.rb, line 20
      def source
        @parser.source
      end


add_listener (REXML::Parsers::SAX2Parser)

# File lib/rexml/parsers/sax2parser.rb, line 24
      def add_listener( listener )
        @parser.add_listener( listener )
      end


listen (REXML::Parsers::SAX2Parser)

# File lib/rexml/parsers/sax2parser.rb, line 58
                        def listen( *args, &blok )
                                if args[0].kind_of? Symbol
                                        if args.size == 2
                                                args[1].each { |match| @procs << [args[0], match, blok] }
                                        else
                                                add( [args[0], nil, blok] )
                                        end
                                elsif args[0].kind_of? Array
                                        if args.size == 2
                                                args[0].each { |match| add( [nil, match, args[1]] ) }
                                        else
                                                args[0].each { |match| add( [ :start_element, match, blok ] ) }
                                        end
                                else
                                        add([nil, nil, args[0]])
                                end
                        end


deafen (REXML::Parsers::SAX2Parser)

# File lib/rexml/parsers/sax2parser.rb, line 76
                        def deafen( listener=nil, &blok )
                                if listener
                                        @listeners.delete_if {|item| item[-1] == listener }
                                        @has_listeners = false if @listeners.size == 0
                                else
                                        @procs.delete_if {|item| item[-1] == blok }
                                end
                        end


parse (REXML::Parsers::SAX2Parser)

# File lib/rexml/parsers/sax2parser.rb, line 85
                        def parse
                                @procs.each { |sym,match,block| block.call if sym == :start_document }
                                @listeners.each { |sym,match,block|
                                        block.start_document if sym == :start_document or sym.nil?
                                }
                                root = context = []
                                while true
                                        event = @parser.pull
                                        case event[0]
                                        when :end_document
                                                handle( :end_document )
                                                break
          when :start_doctype
            handle( :doctype, *event[1..-1])
                                        when :end_doctype
                                                context = context[1]
                                        when :start_element
                                                @tag_stack.push(event[1])
                                                # find the observers for namespaces
                                                procs = get_procs( :start_prefix_mapping, event[1] )
                                                listeners = get_listeners( :start_prefix_mapping, event[1] )
                                                if procs or listeners
                                                        # break out the namespace declarations
                                                        # The attributes live in event[2]
                                                        event[2].each {|n, v| event[2][n] = @parser.normalize(v)}
                                                        nsdecl = event[2].find_all { |n, value| n =~ /^xmlns(:|$)/ }
                                                        nsdecl.collect! { |n, value| [ n[6..-1], value ] }
                                                        @namespace_stack.push({})
                                                        nsdecl.each do |n,v|
                                                                @namespace_stack[-1][n] = v
                                                                # notify observers of namespaces
                                                                procs.each { |ob| ob.call( n, v ) } if procs
                                                                listeners.each { |ob| ob.start_prefix_mapping(n, v) } if listeners
                                                        end
                                                end
                                                event[1] =~ Namespace::NAMESPLIT
                                                prefix = $1
                                                local = $2
                                                uri = get_namespace(prefix)
                                                # find the observers for start_element
                                                procs = get_procs( :start_element, event[1] )
                                                listeners = get_listeners( :start_element, event[1] )
                                                # notify observers
                                                procs.each { |ob| ob.call( uri, local, event[1], event[2] ) } if procs
                                                listeners.each { |ob|
                                                        ob.start_element( uri, local, event[1], event[2] )
                                                } if listeners
                                        when :end_element
                                                @tag_stack.pop
                                                event[1] =~ Namespace::NAMESPLIT
                                                prefix = $1
                                                local = $2
                                                uri = get_namespace(prefix)
                                                # find the observers for start_element
                                                procs = get_procs( :end_element, event[1] )
                                                listeners = get_listeners( :end_element, event[1] )
                                                # notify observers
                                                procs.each { |ob| ob.call( uri, local, event[1] ) } if procs
                                                listeners.each { |ob|
                                                        ob.end_element( uri, local, event[1] )
                                                } if listeners

                                                namespace_mapping = @namespace_stack.pop
                                                # find the observers for namespaces
                                                procs = get_procs( :end_prefix_mapping, event[1] )
                                                listeners = get_listeners( :end_prefix_mapping, event[1] )
                                                if procs or listeners
                                                        namespace_mapping.each do |prefix, uri|
                                                                # notify observers of namespaces
                                                                procs.each { |ob| ob.call( prefix ) } if procs
                                                                listeners.each { |ob| ob.end_prefix_mapping(prefix) } if listeners
                                                        end
                                                end
                                        when :text
            #normalized = @parser.normalize( event[1] )
            #handle( :characters, normalized )
            copy = event[1].clone
            @entities.each { |key, value| copy = copy.gsub("&#{key};", value) }
            copy.gsub!( Text::NUMERICENTITY ) {|m|
              m=$1
              m = "0#{m}" if m[0] == ?x
              [Integer(m)].pack('U*')
            }
            handle( :characters, copy )
          when :entitydecl
            @entities[ event[1] ] = event[2] if event.size == 3
                                                handle( *event )
                                        when :processing_instruction, :comment, :attlistdecl,
                                                :elementdecl, :cdata, :notationdecl, :xmldecl
                                                handle( *event )
                                        end
          handle( :progress, @parser.position )
                                end
                        end


new (REXML::Parsers::StreamParser)

# File lib/rexml/parsers/streamparser.rb, line 4
      def initialize source, listener
        @listener = listener
        @parser = BaseParser.new( source )
      end


add_listener (REXML::Parsers::StreamParser)

# File lib/rexml/parsers/streamparser.rb, line 9
      def add_listener( listener )
        @parser.add_listener( listener )
      end


parse (REXML::Parsers::StreamParser)

# File lib/rexml/parsers/streamparser.rb, line 13
      def parse
        # entity string
        while true
          event = @parser.pull
          case event[0]
          when :end_document
            return
          when :start_element
            attrs = event[2].each do |n, v|
              event[2][n] = @parser.unnormalize( v )
            end
            @listener.tag_start( event[1], attrs )
          when :end_element
            @listener.tag_end( event[1] )
          when :text
            normalized = @parser.unnormalize( event[1] )
            @listener.text( normalized )
          when :processing_instruction
            @listener.instruction( *event[1,2] )
          when :start_doctype
            @listener.doctype( *event[1..-1] )
          when :end_doctype
            # FIXME: remove this condition for milestone:3.2
            @listener.doctype_end if @listener.respond_to? :doctype_end
          when :comment, :attlistdecl, :cdata, :xmldecl, :elementdecl
            @listener.send( event[0].to_s, *event[1..-1] )
          when :entitydecl, :notationdecl
            @listener.send( event[0].to_s, event[1..-1] )
          end
        end
      end


new (REXML::Parsers::TreeParser)

# File lib/rexml/parsers/treeparser.rb, line 7
      def initialize( source, build_context = Document.new )
        @build_context = build_context
        @parser = Parsers::BaseParser.new( source )
      end


add_listener (REXML::Parsers::TreeParser)

# File lib/rexml/parsers/treeparser.rb, line 12
      def add_listener( listener )
        @parser.add_listener( listener )
      end


parse (REXML::Parsers::TreeParser)

# File lib/rexml/parsers/treeparser.rb, line 16
      def parse
        tag_stack = []
        in_doctype = false
        entities = nil
        begin
          while true
            event = @parser.pull
            #STDERR.puts "TREEPARSER GOT #{event.inspect}"
            case event[0]
            when :end_document
              unless tag_stack.empty?
                #raise ParseException.new("No close tag for #{tag_stack.inspect}")
                raise ParseException.new("No close tag for #{@build_context.xpath}")
              end
              return
            when :start_element
              tag_stack.push(event[1])
              el = @build_context = @build_context.add_element( event[1], event[2] )
            when :end_element
              tag_stack.pop
              @build_context = @build_context.parent
            when :text
              if not in_doctype
                if @build_context[-1].instance_of? Text
                  @build_context[-1] << event[1]
                else
                  @build_context.add(
                    Text.new(event[1], @build_context.whitespace, nil, true)
                  ) unless (
                    @build_context.ignore_whitespace_nodes and
                    event[1].strip.size==0
                  )
                end
              end
            when :comment
              c = Comment.new( event[1] )
              @build_context.add( c )
            when :cdata
              c = CData.new( event[1] )
              @build_context.add( c )
            when :processing_instruction
              @build_context.add( Instruction.new( event[1], event[2] ) )
            when :end_doctype
              in_doctype = false
              entities.each { |k,v| entities[k] = @build_context.entities[k].value }
              @build_context = @build_context.parent
            when :start_doctype
              doctype = DocType.new( event[1..-1], @build_context )
              @build_context = doctype
              entities = {}
              in_doctype = true
            when :attlistdecl
              n = AttlistDecl.new( event[1..-1] )
              @build_context.add( n )
            when :externalentity
              n = ExternalEntity.new( event[1] )
              @build_context.add( n )
            when :elementdecl
              n = ElementDecl.new( event[1] )
              @build_context.add(n)
            when :entitydecl
              entities[ event[1] ] = event[2] unless event[2] =~ /PUBLIC|SYSTEM/
              @build_context.add(Entity.new(event))
            when :notationdecl
              n = NotationDecl.new( *event[1..-1] )
              @build_context.add( n )
            when :xmldecl
              x = XMLDecl.new( event[1], event[2], event[3] )
              @build_context.add( x )
            end
          end
        rescue REXML::Validation::ValidationException
          raise
        rescue REXML::UndefinedNamespaceException
          raise
        rescue
          raise ParseException.new( $!.message, @parser.source, @parser, $! )
        end
      end


new (REXML::Parsers::UltraLightParser)

# File lib/rexml/parsers/ultralightparser.rb, line 7
                        def initialize stream
                                @stream = stream
                                @parser = REXML::Parsers::BaseParser.new( stream )
                        end


add_listener (REXML::Parsers::UltraLightParser)

# File lib/rexml/parsers/ultralightparser.rb, line 12
      def add_listener( listener )
        @parser.add_listener( listener )
      end


rewind (REXML::Parsers::UltraLightParser)

# File lib/rexml/parsers/ultralightparser.rb, line 16
      def rewind
        @stream.rewind
        @parser.stream = @stream
      end


parse (REXML::Parsers::UltraLightParser)

# File lib/rexml/parsers/ultralightparser.rb, line 21
                        def parse
                                root = context = []
                                while true
                                        event = @parser.pull
                                        case event[0]
                                        when :end_document
                                                break
                                        when :end_doctype
                                                context = context[1]
                                        when :start_element, :doctype
                                                context << event
                                                event[1,0] = [context]
                                                context = event
                                        when :end_element
                                                context = context[1]
                                        else
                                                context << event
                                        end
                                end
                                root
                        end


namespaces= (REXML::Parsers::XPathParser)

# File lib/rexml/parsers/xpathparser.rb, line 14
      def namespaces=( namespaces )
        Functions::namespace_context = namespaces
        @namespaces = namespaces
      end


parse (REXML::Parsers::XPathParser)

# File lib/rexml/parsers/xpathparser.rb, line 19
      def parse path
        path.gsub!(/([\(\[])\s+/, '\1') # Strip ignorable spaces
        path.gsub!( /\s+([\]\)])/, '\1' )
        parsed = []
        path = OrExpr(path, parsed)
        parsed
      end


predicate (REXML::Parsers::XPathParser)

# File lib/rexml/parsers/xpathparser.rb, line 27
      def predicate path
        parsed = []
        Predicate( "[#{path}]", parsed )
        parsed
      end


abbreviate (REXML::Parsers::XPathParser)

# File lib/rexml/parsers/xpathparser.rb, line 33
      def abbreviate( path )
        path = path.kind_of?(String) ? parse( path ) : path
        string = ""
        document = false
        while path.size > 0
          op = path.shift
          case op
          when :node
          when :attribute
                                                string << "/" if string.size > 0
                                                string << "@"
          when :child
                                                string << "/" if string.size > 0
          when :descendant_or_self
            string << "/"
          when :self
            string << "."
          when :parent
            string << ".."
          when :any
            string << "*"
                                        when :text
                                                string << "text()"
          when :following, :following_sibling,
                :ancestor, :ancestor_or_self, :descendant,
                :namespace, :preceding, :preceding_sibling
            string << "/" unless string.size == 0
            string << op.to_s.tr("_", "-")
            string << "::"
          when :qname
            prefix = path.shift
            name = path.shift
            string << prefix+":" if prefix.size > 0
            string << name
          when :predicate
            string << '['
            string << predicate_to_string( path.shift ) {|x| abbreviate( x ) }
            string << ']'
          when :document
            document = true
                                        when :function
                                                string << path.shift
                                                string << "( "
                                                string << predicate_to_string( path.shift[0] ) {|x| abbreviate( x )}
                                                string << " )"
                                        when :literal
                                                string << %Q{ "#{path.shift}" }
          else
            string << "/" unless string.size == 0
            string << "UNKNOWN("
            string << op.inspect
            string << ")"
          end
        end
                                string = "/"+string if document
        return string
      end


expand (REXML::Parsers::XPathParser)

# File lib/rexml/parsers/xpathparser.rb, line 91
      def expand( path )
        path = path.kind_of?(String) ? parse( path ) : path
        string = ""
        document = false
        while path.size > 0
          op = path.shift
          case op
          when :node
            string << "node()"
          when :attribute, :child, :following, :following_sibling,
                :ancestor, :ancestor_or_self, :descendant, :descendant_or_self,
                :namespace, :preceding, :preceding_sibling, :self, :parent
            string << "/" unless string.size == 0
            string << op.to_s.tr("_", "-")
            string << "::"
          when :any
            string << "*"
          when :qname
            prefix = path.shift
            name = path.shift
            string << prefix+":" if prefix.size > 0
            string << name
          when :predicate
            string << '['
            string << predicate_to_string( path.shift ) { |x| expand(x) }
            string << ']'
          when :document
            document = true
          else
            string << "/" unless string.size == 0
            string << "UNKNOWN("
            string << op.inspect
            string << ")"
          end
        end
        string = "/"+string if document
        return string
      end


predicate_to_string (REXML::Parsers::XPathParser)

# File lib/rexml/parsers/xpathparser.rb, line 130
      def predicate_to_string( path, &block )
        string = ""
        case path[0]
        when :and, :or, :mult, :plus, :minus, :neq, :eq, :lt, :gt, :lteq, :gteq, :div, :mod, :union
          op = path.shift
          case op
          when :eq
            op = "="
          when :lt
            op = "<"
          when :gt
            op = ">"
          when :lteq
            op = "<="
          when :gteq
            op = ">="
          when :neq
            op = "!="
          when :union
            op = "|"
          end
          left = predicate_to_string( path.shift, &block )
          right = predicate_to_string( path.shift, &block )
          string << " "
          string << left
          string << " "
          string << op.to_s
          string << " "
          string << right
          string << " "
        when :function
          path.shift
          name = path.shift
          string << name
          string << "( "
          string << predicate_to_string( path.shift, &block )
          string << " )"
        when :literal
          path.shift
          string << " "
          string << path.shift.inspect
          string << " "
        else
          string << " "
          string << yield( path )
          string << " "
        end
        return string.squeeze(" ")
      end


first (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 11
                def QuickPath::first element, path, namespaces=EMPTY_HASH
                        match(element, path, namespaces)[0]
                end


each (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 15
                def QuickPath::each element, path, namespaces=EMPTY_HASH, &block
                        path = "*" unless path
                        match(element, path, namespaces).each( &block )
                end


match (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 20
                def QuickPath::match element, path, namespaces=EMPTY_HASH
                        raise "nil is not a valid xpath" unless path
                        results = nil
                        Functions::namespace_context = namespaces
                        case path
                        when /^\/([^\/]|$)/u
                                # match on root
                                path = path[1..-1]
                                return [element.root.parent] if path == ''
                                results = filter([element.root], path)
                        when /^[-\w]*::/u
                                results = filter([element], path)
                        when /^\*/u
                                results = filter(element.to_a, path)
                        when /^[\[!\w:]/u
                                # match on child
                                matches = []
                                children = element.to_a
                                results = filter(children, path)
                        else
                                results = filter([element], path)
                        end
                        return results
                end


filter (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 48
                def QuickPath::filter elements, path
                        return elements if path.nil? or path == '' or elements.size == 0
                        case path
                        when /^\/\//u                                                                                        # Descendant
                                return axe( elements, "descendant-or-self", $' )
                        when /^\/?\b(\w[-\w]*)\b::/u                                                 # Axe
                                axe_name = $1
                                rest = $'
                                return axe( elements, $1, $' )
                        when /^\/(?=\b([:!\w][-\.\w]*:)?[-!\*\.\w]*\b([^:(]|$)|\*)/u # Child
                                rest = $'
                                results = []
                                elements.each do |element|
                                        results |= filter( element.to_a, rest )
                                end
                                return results
                        when /^\/?(\w[-\w]*)\(/u                                                     # / Function
                                return function( elements, $1, $' )
                        when Namespace::NAMESPLIT            # Element name
                                name = $2
                                ns = $1
                                rest = $'
                                elements.delete_if do |element|
                                        !(element.kind_of? Element and
                                                (element.expanded_name == name or
                                                 (element.name == name and
                                                  element.namespace == Functions.namespace_context[ns])))
                                end
                                return filter( elements, rest )
                        when /^\/\[/u
                                matches = []
                                elements.each do |element|
                                        matches |= predicate( element.to_a, path[1..-1] ) if element.kind_of? Element
                                end
                                return matches
                        when /^\[/u                                                                                          # Predicate
                                return predicate( elements, path )
                        when /^\/?\.\.\./u                                                                           # Ancestor
                                return axe( elements, "ancestor", $' )
                        when /^\/?\.\./u                                                                                     # Parent
                                return filter( elements.collect{|e|e.parent}, $' )
                        when /^\/?\./u                                                                                               # Self
                                return filter( elements, $' )
                        when /^\*/u                                                                                                  # Any
                                results = []
                                elements.each do |element|
                                        results |= filter( [element], $' ) if element.kind_of? Element
                                        #if element.kind_of? Element
                                        #  children = element.to_a
                                        #  children.delete_if { |child| !child.kind_of?(Element) }
                                        #  results |= filter( children, $' )
                                        #end
                                end
                                return results
                        end
                        return []
                end


axe (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 106
                def QuickPath::axe( elements, axe_name, rest )
                        matches = []
                        matches = filter( elements.dup, rest ) if axe_name =~ /-or-self$/u
                        case axe_name
                        when /^descendant/u
                                elements.each do |element|
                                        matches |= filter( element.to_a, "descendant-or-self::#{rest}" ) if element.kind_of? Element
                                end
                        when /^ancestor/u
                                elements.each do |element|
                                        while element.parent
                                                matches << element.parent
                                                element = element.parent
                                        end
                                end
                                matches = filter( matches, rest )
                        when "self"
                                matches = filter( elements, rest )
                        when "child"
                                elements.each do |element|
                                        matches |= filter( element.to_a, rest ) if element.kind_of? Element
                                end
                        when "attribute"
                                elements.each do |element|
                                        matches << element.attributes[ rest ] if element.kind_of? Element
                                end
                        when "parent"
                                matches = filter(elements.collect{|element| element.parent}.uniq, rest)
                        when "following-sibling"
                                matches = filter(elements.collect{|element| element.next_sibling}.uniq,
                                        rest)
                        when "previous-sibling"
                                matches = filter(elements.collect{|element|
                                        element.previous_sibling}.uniq, rest )
                        end
                        return matches.uniq
                end


predicate (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 160
                def QuickPath::predicate( elements, path )
                        ind = 1
                        bcount = 1
                        while bcount > 0
                                bcount += 1 if path[ind] == ?[
                                bcount -= 1 if path[ind] == ?]
                                ind += 1
                        end
                        ind -= 1
                        predicate = path[1..ind-1]
                        rest = path[ind+1..-1]

                        # have to change 'a [=<>] b [=<>] c' into 'a [=<>] b and b [=<>] c'
                        predicate.gsub!( /([^\s(and)(or)<>=]+)\s*([<>=])\s*([^\s(and)(or)<>=]+)\s*([<>=])\s*([^\s(and)(or)<>=]+)/u ) {
                                "#$1 #$2 #$3 and #$3 #$4 #$5"
                        }
                        # Let's do some Ruby trickery to avoid some work:
                        predicate.gsub!( /&/u, "&&" )
                        predicate.gsub!( /=/u, "==" )
                        predicate.gsub!( /@(\w[-\w.]*)/u ) {
                                "attribute(\"#$1\")"
                        }
                        predicate.gsub!( /\bmod\b/u, "%" )
                        predicate.gsub!( /\b(\w[-\w.]*\()/u ) {
                                fname = $1
                                fname.gsub( /-/u, "_" )
                        }

                        Functions.pair = [ 0, elements.size ]
                        results = []
                        elements.each do |element|
                                Functions.pair[0] += 1
                                Functions.node = element
                                res = eval( predicate )
                                case res
                                when true
                                        results << element
                                when Fixnum
                                        results << element if Functions.pair[0] == res
                                when String
                                        results << element
                                end
                        end
                        return filter( results, rest )
                end


attribute (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 206
                def QuickPath::attribute( name )
                        return Functions.node.attributes[name] if Functions.node.kind_of? Element
                end


name (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 210
                def QuickPath::name()
                        return Functions.node.name if Functions.node.kind_of? Element
                end


method_missing (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 214
                def QuickPath::method_missing( id, *args )
                        begin
                                Functions.send( id.id2name, *args )
                        rescue Exception
                                raise "METHOD: #{id.id2name}(#{args.join ', '})\n#{$!.message}"
                        end
                end


function (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 222
                def QuickPath::function( elements, fname, rest )
                        args = parse_args( elements, rest )
                        Functions.pair = [0, elements.size]
                        results = []
                        elements.each do |element|
                                Functions.pair[0] += 1
                                Functions.node = element
                                res = Functions.send( fname, *args )
                                case res
                                when true
                                        results << element
                                when Fixnum
                                        results << element if Functions.pair[0] == res
                                end
                        end
                        return results
                end


parse_args (REXML::QuickPath)

# File lib/rexml/quickpath.rb, line 240
                def QuickPath::parse_args( element, string )
                        # /.*?(?:\)|,)/
                        arguments = []
                        buffer = ""
                        while string and string != ""
                                c = string[0]
                                string.sub!(/^./u, "")
                                case c
                                when ?,
                                        # if depth = 1, then we start a new argument
                                        arguments << evaluate( buffer )
                                        #arguments << evaluate( string[0..count] )
                                when ?(
                                        # start a new method call
                                        function( element, buffer, string )
                                        buffer = ""
                                when ?)
                                        # close the method call and return arguments
                                        return arguments
                                else
                                        buffer << c
                                end
                        end
                        ""
                end


start_document (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 23
                def start_document
                end


end_document (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 25
                def end_document
                end


start_prefix_mapping (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 27
                def start_prefix_mapping prefix, uri
                end


end_prefix_mapping (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 29
                def end_prefix_mapping prefix
                end


start_element (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 31
                def start_element uri, localname, qname, attributes
                end


end_element (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 33
                def end_element uri, localname, qname
                end


characters (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 35
                def characters text
                end


processing_instruction (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 37
                def processing_instruction target, data
                end


doctype (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 45
                def doctype name, pub_sys, long_name, uri
                end


attlistdecl (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 52
                def attlistdecl(element, pairs, contents)
                end


elementdecl (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 55
                def elementdecl content
                end


entitydecl (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 73
                def entitydecl name, decl
                end


notationdecl (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 76
                def notationdecl content
                end


cdata (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 80
                def cdata content
                end


xmldecl (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 88
                def xmldecl version, encoding, standalone
                end


comment (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 92
                def comment comment
                end


progress (REXML::SAX2Listener)

# File lib/rexml/sax2listener.rb, line 94
    def progress position
    end


new (REXML::Source)

# File lib/rexml/source.rb, line 40
    def initialize(arg, encoding=nil)
      @orig = @buffer = arg
      if encoding
        self.encoding = encoding
      else
        self.encoding = check_encoding( @buffer )
      end
      @line = 0
    end


encoding= (REXML::Source)

# File lib/rexml/source.rb, line 53
    def encoding=(enc)
      return unless super
      @line_break = encode( '>' )
      if enc != UTF_8
        @buffer = decode(@buffer)
        @to_utf = true
      else
        @to_utf = false
      end
    end


scan (REXML::Source)

# File lib/rexml/source.rb, line 80
    def scan(pattern, cons=false)
      return nil if @buffer.nil?
      rv = @buffer.scan(pattern)
      @buffer = $' if cons and rv.size>0
      rv
    end


read (REXML::Source)

# File lib/rexml/source.rb, line 87
    def read
    end


consume (REXML::Source)

# File lib/rexml/source.rb, line 90
    def consume( pattern )
      @buffer = $' if pattern.match( @buffer )
    end


match_to (REXML::Source)

# File lib/rexml/source.rb, line 94
    def match_to( char, pattern )
      return pattern.match(@buffer)
    end


match_to_consume (REXML::Source)

# File lib/rexml/source.rb, line 98
    def match_to_consume( char, pattern )
      md = pattern.match(@buffer)
      @buffer = $'
      return md
    end


match (REXML::Source)

# File lib/rexml/source.rb, line 104
    def match(pattern, cons=false)
      md = pattern.match(@buffer)
      @buffer = $' if cons and md
      return md
    end


empty? (REXML::Source)

# File lib/rexml/source.rb, line 111
    def empty?
      @buffer == ""
    end


position (REXML::Source)

# File lib/rexml/source.rb, line 115
    def position
      @orig.index( @buffer )
    end


current_line (REXML::Source)

# File lib/rexml/source.rb, line 120
    def current_line
      lines = @orig.split
      res = lines.grep @buffer[0..30]
      res = res[-1] if res.kind_of? Array
      lines.index( res ) if res
    end


create_from (REXML::SourceFactory)

# File lib/rexml/source.rb, line 9
    def SourceFactory::create_from(arg)
      if arg.kind_of? String
        Source.new(arg)
      elsif arg.respond_to? :read and
            arg.respond_to? :readline and
            arg.respond_to? :nil? and
            arg.respond_to? :eof?
        IOSource.new(arg)
      elsif arg.kind_of? Source
        arg
      else
        raise "#{arg.class} is not a valid input stream.  It must walk \n"+
          "like either a String, an IO, or a Source."
      end
    end


tag_start (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 13
                def tag_start name, attrs
                end


tag_end (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 18
                def tag_end name
                end


text (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 22
                def text text
                end


instruction (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 28
                def instruction name, instruction
                end


comment (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 32
                def comment comment
                end


doctype (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 40
                def doctype name, pub_sys, long_name, uri
                end


doctype_end (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 43
                def doctype_end
                end


attlistdecl (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 50
                def attlistdecl element_name, attributes, raw_content
                end


elementdecl (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 53
                def elementdecl content
                end


entitydecl (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 71
                def entitydecl content
                end


notationdecl (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 74
                def notationdecl content
                end


entity (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 78
                def entity content
                end


cdata (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 82
                def cdata content
                end


xmldecl (REXML::StreamListener)

# File lib/rexml/streamlistener.rb, line 89
                def xmldecl version, encoding, standalone
                end


new (REXML::SyncEnumerator)

# File lib/rexml/syncenumerator.rb, line 7
    def initialize(*enums)
      @gens = enums
      @biggest = @gens[0]
      @gens.each {|x| @biggest = x if x.size > @biggest.size }
    end


size (REXML::SyncEnumerator)

# File lib/rexml/syncenumerator.rb, line 15
    def size
      @gens.size
    end


length (REXML::SyncEnumerator)

# File lib/rexml/syncenumerator.rb, line 21
    def length
      @gens.length
    end


each (REXML::SyncEnumerator)

# File lib/rexml/syncenumerator.rb, line 26
    def each
      @biggest.zip( *@gens ) {|a|
        yield(*a[1..-1])
      }
      self
    end


new (REXML::Text)

# File lib/rexml/text.rb, line 60
    def initialize(arg, respect_whitespace=false, parent=nil, raw=nil,
      entity_filter=nil, illegal=ILLEGAL )

      @raw = false

      if parent
        super( parent )
        @raw = parent.raw
      else
        @parent = nil
      end

      @raw = raw unless raw.nil?
      @entity_filter = entity_filter
      @normalized = @unnormalized = nil

      if arg.kind_of? String
        @string = arg.clone
        @string.squeeze!(" \n\t") unless respect_whitespace
      elsif arg.kind_of? Text
        @string = arg.to_s
        @raw = arg.raw
      elsif
        raise "Illegal argument of type #{arg.type} for Text constructor (#{arg})"
      end

      @string.gsub!( /\r\n?/, "\n" )

      # check for illegal characters
      if @raw
        if @string =~ illegal
          raise "Illegal character '#{$1}' in raw string \"#{@string}\""
        end
      end
    end


node_type (REXML::Text)

# File lib/rexml/text.rb, line 96
    def node_type
      :text
    end


empty? (REXML::Text)

# File lib/rexml/text.rb, line 100
    def empty?
      @string.size==0
    end


clone (REXML::Text)

# File lib/rexml/text.rb, line 105
    def clone
      return Text.new(self)
    end


<< (REXML::Text)

# File lib/rexml/text.rb, line 112
    def <<( to_append )
      @string << to_append.gsub( /\r\n?/, "\n" )
    end


<=> (REXML::Text)

# File lib/rexml/text.rb, line 119
    def <=>( other )
      to_s() <=> other.to_s
    end


to_s (REXML::Text)

# File lib/rexml/text.rb, line 137
    def to_s
      return @string if @raw
      return @normalized if @normalized

      doctype = nil
      if @parent
        doc = @parent.document
        doctype = doc.doctype if doc
      end

      @normalized = Text::normalize( @string, doctype, @entity_filter )
    end


inspect (REXML::Text)

# File lib/rexml/text.rb, line 150
    def inspect
      @string.inspect
    end


value (REXML::Text)

# File lib/rexml/text.rb, line 167
    def value
      @unnormalized if @unnormalized
      doctype = nil
      if @parent
        doc = @parent.document
        doctype = doc.doctype if doc
      end
      @unnormalized = Text::unnormalize( @string, doctype )
    end


value= (REXML::Text)

# File lib/rexml/text.rb, line 184
    def value=( val )
      @string = val.gsub( /\r\n?/, "\n" )
      @unnormalized = nil
      @normalized = nil
      @raw = false
    end


wrap (REXML::Text)

# File lib/rexml/text.rb, line 191
     def wrap(string, width, addnewline=false)
       # Recursivly wrap string at width.
       return string if string.length <= width
       place = string.rindex(' ', width) # Position in string with last ' ' before cutoff
       if addnewline then
         return "\n" + string[0,place] + "\n" + wrap(string[place+1..-1], width)
       else
         return string[0,place] + "\n" + wrap(string[place+1..-1], width)
       end
     end


indent_text (REXML::Text)

# File lib/rexml/text.rb, line 202
    def indent_text(string, level=1, style="\t", indentfirstline=true)
      return string if level < 0
      new_string = ''
      string.each { |line|
        indent_string = style * level
        new_line = (indent_string + line).sub(/[\s]+$/,'')
        new_string << new_line
      }
      new_string.strip! unless indentfirstline
      return new_string
    end


write (REXML::Text)

# File lib/rexml/text.rb, line 217
    def write( writer, indent=-1, transitive=false, ie_hack=false )
      Kernel.warn("#{self.class.name}.write is deprecated.  See REXML::Formatters")
      formatter = if indent > -1
          REXML::Formatters::Pretty.new( indent )
        else
          REXML::Formatters::Default.new
        end
      formatter.write( self, writer )
    end


xpath (REXML::Text)

# File lib/rexml/text.rb, line 229
    def xpath
      path = @parent.xpath
      path += "/text()"
      return path
    end


write_with_substitution (REXML::Text)

# File lib/rexml/text.rb, line 249
    def write_with_substitution out, input
      copy = input.clone
      # Doing it like this rather than in a loop improves the speed
      copy.gsub!( SPECIALS[0], SUBSTITUTES[0] )
      copy.gsub!( SPECIALS[1], SUBSTITUTES[1] )
      copy.gsub!( SPECIALS[2], SUBSTITUTES[2] )
      copy.gsub!( SPECIALS[3], SUBSTITUTES[3] )
      copy.gsub!( SPECIALS[4], SUBSTITUTES[4] )
      copy.gsub!( SPECIALS[5], SUBSTITUTES[5] )
      out << copy
    end


read_with_substitution (REXML::Text)

# File lib/rexml/text.rb, line 262
    def Text::read_with_substitution( input, illegal=nil )
      copy = input.clone

      if copy =~ illegal
        raise ParseException.new( "malformed text: Illegal character #$& in \"#{copy}\"" )
      end if illegal

      copy.gsub!( /\r\n?/, "\n" )
      if copy.include? ?&
        copy.gsub!( SETUTITSBUS[0], SLAICEPS[0] )
        copy.gsub!( SETUTITSBUS[1], SLAICEPS[1] )
        copy.gsub!( SETUTITSBUS[2], SLAICEPS[2] )
        copy.gsub!( SETUTITSBUS[3], SLAICEPS[3] )
        copy.gsub!( SETUTITSBUS[4], SLAICEPS[4] )
        copy.gsub!( /&#0*((?:\d+)|(?:x[a-f0-9]+));/ ) {|m|
          m=$1
          #m='0' if m==''
          m = "0#{m}" if m[0] == ?x
          [Integer(m)].pack('U*')
        }
      end
      copy
    end


normalize (REXML::Text)

# File lib/rexml/text.rb, line 288
    def Text::normalize( input, doctype=nil, entity_filter=nil )
      copy = input
      # Doing it like this rather than in a loop improves the speed
      #copy = copy.gsub( EREFERENCE, '&amp;' )
      copy = copy.gsub( "&", "&amp;" )
      if doctype
        # Replace all ampersands that aren't part of an entity
        doctype.entities.each_value do |entity|
          copy = copy.gsub( entity.value,
            "&#{entity.name};" ) if entity.value and
              not( entity_filter and entity_filter.include?(entity) )
        end
      else
        # Replace all ampersands that aren't part of an entity
        DocType::DEFAULT_ENTITIES.each_value do |entity|
          copy = copy.gsub(entity.value, "&#{entity.name};" )
        end
      end
      copy
    end


unnormalize (REXML::Text)

# File lib/rexml/text.rb, line 310
    def Text::unnormalize( string, doctype=nil, filter=nil, illegal=nil )
      rv = string.clone
      rv.gsub!( /\r\n?/, "\n" )
      matches = rv.scan( REFERENCE )
      return rv if matches.size == 0
      rv.gsub!( NUMERICENTITY ) {|m|
        m=$1
        m = "0#{m}" if m[0] == ?x
        [Integer(m)].pack('U*')
      }
      matches.collect!{|x|x[0]}.compact!
      if matches.size > 0
        if doctype
          matches.each do |entity_reference|
            unless filter and filter.include?(entity_reference)
              entity_value = doctype.entity( entity_reference )
              re = /&#{entity_reference};/
              rv.gsub!( re, entity_value ) if entity_value
            end
          end
        else
          matches.each do |entity_reference|
            unless filter and filter.include?(entity_reference)
              entity_value = DocType::DEFAULT_ENTITIES[ entity_reference ]
              re = /&#{entity_reference};/
              rv.gsub!( re, entity_value.value ) if entity_value
            end
          end
        end
        rv.gsub!( /&amp;/, '&' )
      end
      rv
    end


new (REXML::UndefinedNamespaceException)

# File lib/rexml/undefinednamespaceexception.rb, line 4
    def initialize( prefix, source, parser )
      super( "Undefined prefix #{prefix} found" )
    end


new (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 363
      def initialize context
        super
        @choices = []
      end


reset (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 368
      def reset
        super
        @events = []
        @choices.each { |c| c.each { |s| s.reset if s.kind_of? State } }
      end


<< (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 374
      def <<( event )
        add_event_to_arry( @choices, event )
      end


next (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 378
      def next( event )
        # Make the choice if we haven't
        if @events.size == 0
          c = 0 ; max = @choices.size
          while c < max
            if @choices[c][0].class == Ref
              expand_ref_in( @choices[c], 0 )
              @choices += @choices[c]
              @choices.delete( @choices[c] )
              max -= 1
            else
              c += 1
            end
          end
          @events = @choices.find { |evt| evt[0].matches? event }
          # Remove the references
          # Find the events
        end
        #puts "In next with #{event.inspect}."
        #puts "events is #{@events.inspect}"
        unless @events
          @events = []
          return nil
        end
        #puts "current = #@current"
        super
      end


matches? (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 406
      def matches?( event )
        return @events[@current].matches?( event ) if @events.size > 0
        !@choices.find{|evt| evt[0].matches?(event)}.nil?
      end


expected (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 411
      def expected
        #puts "IN CHOICE EXPECTED"
        #puts "EVENTS = #{@events.inspect}"
        return [@events[@current]] if @events.size > 0
        return @choices.collect do |x|
          if x[0].kind_of? State
            x[0].expected
          else
            x[0]
          end
        end.flatten
      end


inspect (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 424
      def inspect
        "< #{to_s} #{@choices.collect{|e| e.collect{|f|f.to_s}.join(', ')}.join(' or ')} >"
      end


add_event_to_arry (REXML::Validation::Choice)

# File lib/rexml/validation/relaxng.rb, line 429
      def add_event_to_arry( arry, evt )
        if evt.kind_of? State or evt.class == Ref
          arry << [evt]
        elsif evt[0] == :text
         if arry[-1] and
            arry[-1][-1].kind_of?( Event ) and
            arry[-1][-1].event_type == :text and @value

            arry[-1][-1].event_arg = evt[1]
            @value = false
          end
        else
          arry << [] if evt[0] == :start_element
          arry[-1] << generate_event( evt )
        end
      end


new (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 80
      def initialize(event_type, event_arg=nil )
        @event_type = event_type
        @event_arg = event_arg
      end


done? (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 88
      def done?
        @done
      end


single? (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 92
      def single?
        return (@event_type != :start_element and @event_type != :start_attribute)
      end


matches? (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 96
      def matches?( event )
        #puts "#@event_type =? #{event[0]} && #@event_arg =? #{event[1]} "
        return false unless event[0] == @event_type
        case event[0]
        when nil
          return true
        when :start_element
          return true if event[1] == @event_arg
        when :end_element
          return true
        when :start_attribute
          return true if event[1] == @event_arg
        when :end_attribute
          return true
        when :end_document
          return true
        when :text
          return (@event_arg.nil? or @event_arg == event[1])
??
        else
          false
        end
      end


== (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 141
      def ==( other )
        return false unless other.kind_of? Event
        @event_type == other.event_type and @event_arg == other.event_arg
      end


to_s (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 146
      def to_s
        inspect
      end


inspect (REXML::Validation::Event)

# File lib/rexml/validation/validation.rb, line 150
      def inspect
        "#{@event_type.inspect}( #@event_arg )"
      end


new (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 449
      def initialize context
        super
        @choice = 0
      end


reset (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 454
      def reset
        @choice = 0
      end


next_current (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 458
      def next_current( event )
        # Expand references
        c = 0 ; max = @choices.size
        while c < max
          if @choices[c][0].class == Ref
            expand_ref_in( @choices[c], 0 )
            @choices += @choices[c]
            @choices.delete( @choices[c] )
            max -= 1
          else
            c += 1
          end
        end
        @events = @choices[@choice..-1].find { |evt| evt[0].matches? event }
        @current = 0
        if @events
          # reorder the choices
          old = @choices[@choice]
          idx = @choices.index( @events )
          @choices[@choice] = @events
          @choices[idx] = old
          @choice += 1
        end

       #puts "In next with #{event.inspect}."
       #puts "events is #{@events.inspect}"
        @events = [] unless @events
      end


next (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 488
      def next( event )
        # Find the next series
        next_current(event) unless @events[@current]
        return nil unless @events[@current]

        expand_ref_in( @events, @current ) if @events[@current].class == Ref
       #puts "In next with #{event.inspect}."
       #puts "Next (#@current) is #{@events[@current]}"
        if ( @events[@current].kind_of? State )
          @current += 1
          @events[@current-1].previous = self
          return @events[@current-1].next( event )
        end
       #puts "Current isn't a state"
        return @previous.pop.next( event ) if @events[@current].nil?
        if ( @events[@current].matches?(event) )
          @current += 1
          if @events[@current].nil?
           #puts "#{inspect[0,5]} 1RETURNING self" unless @choices[@choice].nil?
            return self unless @choices[@choice].nil?
           #puts "#{inspect[0,5]} 1RETURNING #{@previous[-1].inspect[0,5]}"
            return @previous.pop
          elsif @events[@current].kind_of? State
            @current += 1
           #puts "#{inspect[0,5]} 2RETURNING (#{@current-1}) #{@events[@current-1].inspect[0,5]}; on return, next is #{@events[@current]}"
            @events[@current-1].previous = self
            return @events[@current-1]
          else
           #puts "#{inspect[0,5]} RETURNING self w/ next(#@current) = #{@events[@current]}"
            return self
          end
        else
          return nil
        end
      end


matches? (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 524
      def matches?( event )
        return @events[@current].matches?( event ) if @events[@current]
        !@choices[@choice..-1].find{|evt| evt[0].matches?(event)}.nil?
      end


expected (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 529
      def expected
        #puts "IN CHOICE EXPECTED"
        #puts "EVENTS = #{@events.inspect}"
        return [@events[@current]] if @events[@current]
        return @choices[@choice..-1].collect do |x|
          if x[0].kind_of? State
            x[0].expected
          else
            x[0]
          end
        end.flatten
      end


inspect (REXML::Validation::Interleave)

# File lib/rexml/validation/relaxng.rb, line 542
      def inspect
        "< #{to_s} #{@choices.collect{|e| e.collect{|f|f.to_s}.join(', ')}.join(' and ')} >"
      end


new (REXML::Validation::OneOrMore)

# File lib/rexml/validation/relaxng.rb, line 316
      def initialize context
        super
        @ord = 0
      end


reset (REXML::Validation::OneOrMore)

# File lib/rexml/validation/relaxng.rb, line 321
      def reset
        super
        @ord = 0
      end


next (REXML::Validation::OneOrMore)

# File lib/rexml/validation/relaxng.rb, line 326
      def next( event )
        expand_ref_in( @events, @current ) if @events[@current].class == Ref
        if ( @events[@current].matches?(event) )
          @current += 1
          @ord += 1
          if @events[@current].nil?
            @current = 0
            return self
          elsif @events[@current].kind_of? State
            @current += 1
            @events[@current-1].previous = self
            return @events[@current-1]
          else
            return self
          end
        else
          return @previous.pop.next( event ) if @current == 0 and @ord > 0
          return nil
        end
      end


matches? (REXML::Validation::OneOrMore)

# File lib/rexml/validation/relaxng.rb, line 347
      def matches?( event )
        @events[@current].matches?(event) ||
        (@current == 0 and @ord > 0 and @previous[-1].matches?(event))
      end


expected (REXML::Validation::OneOrMore)

# File lib/rexml/validation/relaxng.rb, line 352
      def expected
        if @current == 0 and @ord > 0
          return [@previous[-1].expected, @events[0]].flatten
        else
          return [@events[@current]]
        end
      end


next (REXML::Validation::Optional)

# File lib/rexml/validation/relaxng.rb, line 264
      def next( event )
        if @current == 0
          rv = super
          return rv if rv
          @prior = @previous.pop
          return @prior.next( event )
        end
        super
      end


matches? (REXML::Validation::Optional)

# File lib/rexml/validation/relaxng.rb, line 274
      def matches?(event)
        @events[@current].matches?(event) ||
        (@current == 0 and @previous[-1].matches?(event))
      end


expected (REXML::Validation::Optional)

# File lib/rexml/validation/relaxng.rb, line 279
      def expected
        return [ @prior.expected, @events[0] ].flatten if @current == 0
        return [@events[@current]]
      end


new (REXML::Validation::Ref)

# File lib/rexml/validation/relaxng.rb, line 548
      def initialize value
        @value = value
      end


to_s (REXML::Validation::Ref)

# File lib/rexml/validation/relaxng.rb, line 551
      def to_s
        @value
      end


inspect (REXML::Validation::Ref)

# File lib/rexml/validation/relaxng.rb, line 554
      def inspect
        "{#{to_s}}"
      end


new (REXML::Validation::RelaxNG)

# File lib/rexml/validation/relaxng.rb, line 45
      def initialize source
        parser = REXML::Parsers::BaseParser.new( source )

        @count = 0
        @references = {}
        @root = @current = Sequence.new(self)
        @root.previous = true
        states = [ @current ]
        begin
          event = parser.pull
          case event[0]
          when :start_element
            case event[1]
            when "empty"
            when "element", "attribute", "text", "value"
              states[-1] << event
            when "optional"
              states << Optional.new( self )
              states[-2] << states[-1]
            when "choice"
              states << Choice.new( self )
              states[-2] << states[-1]
            when "oneOrMore"
              states << OneOrMore.new( self )
              states[-2] << states[-1]
            when "zeroOrMore"
              states << ZeroOrMore.new( self )
              states[-2] << states[-1]
            when "group"
              states << Sequence.new( self )
              states[-2] << states[-1]
            when "interleave"
              states << Interleave.new( self )
              states[-2] << states[-1]
            when "mixed"
              states << Interleave.new( self )
              states[-2] << states[-1]
              states[-1] << TEXT
            when "define"
              states << [ event[2]["name"] ]
            when "ref"
              states[-1] << Ref.new( event[2]["name"] )
            when "anyName"
              states << AnyName.new( self )
              states[-2] << states[-1]
            when "nsName"
            when "except"
            when "name"
            when "data"
            when "param"
            when "include"
            when "grammar"
            when "start"
            when "externalRef"
            when "notAllowed"
            end
          when :end_element
            case event[1]
            when "element", "attribute"
              states[-1] << event
            when "zeroOrMore", "oneOrMore", "choice", "optional",
              "interleave", "group", "mixed"
              states.pop
            when "define"
              ref = states.pop
              @references[ ref.shift ] = ref
            #when "empty"
            end
          when :end_document
            states[-1] << event
          when :text
            states[-1] << event
          end
        end while event[0] != :end_document
      end


receive (REXML::Validation::RelaxNG)

# File lib/rexml/validation/relaxng.rb, line 121
      def receive event
        validate( event )
      end


matches? (REXML::Validation::Sequence)

# File lib/rexml/validation/relaxng.rb, line 257
      def matches?(event)
        @events[@current].matches?( event )
      end


new (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 127
      def initialize( context )
        @previous = []
        @events = []
        @current = 0
        @count = context.count += 1
        @references = context.references
        @value = false
      end


reset (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 136
      def reset
        return if @current == 0
        @current = 0
        @events.each {|s| s.reset if s.kind_of? State }
      end


previous= (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 142
      def previous=( previous )
        @previous << previous
      end


next (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 146
      def next( event )
        #print "In next with #{event.inspect}.  "
        #puts "Next (#@current) is #{@events[@current]}"
        #p @previous
        return @previous.pop.next( event ) if @events[@current].nil?
        expand_ref_in( @events, @current ) if @events[@current].class == Ref
        if ( @events[@current].kind_of? State )
          @current += 1
          @events[@current-1].previous = self
          return @events[@current-1].next( event )
        end
        #puts "Current isn't a state"
        if ( @events[@current].matches?(event) )
          @current += 1
          if @events[@current].nil?
            #puts "#{inspect[0,5]} 1RETURNING #{@previous.inspect[0,5]}"
            return @previous.pop
          elsif @events[@current].kind_of? State
            @current += 1
            #puts "#{inspect[0,5]} 2RETURNING (#{@current-1}) #{@events[@current-1].inspect[0,5]}; on return, next is #{@events[@current]}"
            @events[@current-1].previous = self
            return @events[@current-1]
          else
            #puts "#{inspect[0,5]} RETURNING self w/ next(#@current) = #{@events[@current]}"
            return self
          end
        else
          return nil
        end
      end


to_s (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 177
      def to_s
        # Abbreviated:
        self.class.name =~ /(?:::)(\w)\w+$/
        # Full:
        #self.class.name =~ /(?:::)(\w+)$/
        "#$1.#@count"
      end


inspect (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 185
      def inspect
        "< #{to_s} #{@events.collect{|e|
          pre = e == @events[@current] ? '#' : ''
          pre + e.inspect unless self == e
        }.join(', ')} >"
      end


expected (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 192
      def expected
        return [@events[@current]]
      end


<< (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 196
      def <<( event )
        add_event_to_arry( @events, event )
      end


expand_ref_in (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 202
      def expand_ref_in( arry, ind )
        new_events = []
        @references[ arry[ind].to_s ].each{ |evt|
          add_event_to_arry(new_events,evt)
        }
        arry[ind,1] = new_events
      end


add_event_to_arry (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 210
      def add_event_to_arry( arry, evt )
        evt = generate_event( evt )
        if evt.kind_of? String
          arry[-1].event_arg = evt if arry[-1].kind_of? Event and @value
          @value = false
        else
          arry << evt
        end
      end


generate_event (REXML::Validation::State)

# File lib/rexml/validation/relaxng.rb, line 220
      def generate_event( event )
        return event if event.kind_of? State or event.class == Ref
        evt = nil
        arg = nil
        case event[0]
        when :start_element
          case event[1]
          when "element"
            evt = :start_element
            arg = event[2]["name"]
          when "attribute"
            evt = :start_attribute
            arg = event[2]["name"]
          when "text"
            evt = :text
          when "value"
            evt = :text
            @value = true
          end
        when :text
          return event[1]
        when :end_document
          return Event.new( event[0] )
        else # then :end_element
          case event[1]
          when "element"
            evt = :end_element
          when "attribute"
            evt = :end_attribute
          end
        end
        return Event.new( evt, arg )
      end


new (REXML::Validation::ValidationException)

# File lib/rexml/validation/validationexception.rb, line 4
      def initialize msg
        super
      end


reset (REXML::Validation::Validator)

# File lib/rexml/validation/validation.rb, line 7
      def reset
        @current = @root
        @root.reset
        @root.previous = true
        @attr_stack = []
        self
      end


dump (REXML::Validation::Validator)

# File lib/rexml/validation/validation.rb, line 14
      def dump
        puts @root.inspect
      end


validate (REXML::Validation::Validator)

# File lib/rexml/validation/validation.rb, line 17
      def validate( event )
        #puts "Current: #@current"
        #puts "Event: #{event.inspect}"
        @attr_stack = [] unless defined? @attr_stack
        match = @current.next(event)
        raise ValidationException.new( "Validation error.  Expected: "+
          @current.expected.join( " or " )+" from #{@current.inspect} "+
          " but got #{Event.new( event[0], event[1] ).inspect}" ) unless match
        @current = match

        # Check for attributes
        case event[0]
        when :start_element
          #puts "Checking attributes"
          @attr_stack << event[2]
          begin
            sattr = [:start_attribute, nil]
            eattr = [:end_attribute]
            text = [:text, nil]
            k,v = event[2].find { |k,v|
              sattr[1] = k
              #puts "Looking for #{sattr.inspect}"
              m = @current.next( sattr )
              #puts "Got #{m.inspect}"
              if m
                # If the state has text children...
                #puts "Looking for #{eattr.inspect}"
                #puts "Expect #{m.expected}"
                if m.matches?( eattr )
                  #puts "Got end"
                  @current = m
                else
                  #puts "Didn't get end"
                  text[1] = v
                  #puts "Looking for #{text.inspect}"
                  m = m.next( text )
                  #puts "Got #{m.inspect}"
                  text[1] = nil
                  return false unless m
                  @current = m if m
                end
                m = @current.next( eattr )
                if m
                  @current = m
                  true
                else
                  false
                end
              else
                false
              end
            }
            event[2].delete(k) if k
          end while k
        when :end_element
          attrs = @attr_stack.pop
          raise ValidationException.new( "Validation error.  Illegal "+
            " attributes: #{attrs.inspect}") if attrs.length > 0
        end
      end


next (REXML::Validation::ZeroOrMore)

# File lib/rexml/validation/relaxng.rb, line 287
      def next( event )
        expand_ref_in( @events, @current ) if @events[@current].class == Ref
        if ( @events[@current].matches?(event) )
          @current += 1
          if @events[@current].nil?
            @current = 0
            return self
          elsif @events[@current].kind_of? State
            @current += 1
            @events[@current-1].previous = self
            return @events[@current-1]
          else
            return self
          end
        else
          @prior = @previous.pop
          return @prior.next( event ) if @current == 0
          return nil
        end
      end


expected (REXML::Validation::ZeroOrMore)

# File lib/rexml/validation/relaxng.rb, line 308
      def expected
        return [ @prior.expected, @events[0] ].flatten if @current == 0
        return [@events[@current]]
      end


new (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 18
                def initialize(version=DEFAULT_VERSION, encoding=nil, standalone=nil)
      @writethis = true
      @writeencoding = !encoding.nil?
                        if version.kind_of? XMLDecl
                                super()
                                @version = version.version
                                self.encoding = version.encoding
        @writeencoding = version.writeencoding
                                @standalone = version.standalone
                        else
                                super()
                                @version = version
                                self.encoding = encoding
                                @standalone = standalone
                        end
                        @version = DEFAULT_VERSION if @version.nil?
                end


clone (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 36
                def clone
                        XMLDecl.new(self)
                end


write (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 46
                def write(writer, indent=-1, transitive=false, ie_hack=false)
      return nil unless @writethis or writer.kind_of? Output
                        writer << START.sub(/\\/u, '')
      if writer.kind_of? Output
        writer << " #{content writer.encoding}"
      else
        writer << " #{content encoding}"
      end
                        writer << STOP.sub(/\\/u, '')
                end


== (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 57
                def ==( other )
                  other.kind_of?(XMLDecl) and
                  other.version == @version and
                  other.encoding == self.encoding and
                  other.standalone == @standalone
                end


xmldecl (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 64
                def xmldecl version, encoding, standalone
                        @version = version
                        self.encoding = encoding
                        @standalone = standalone
                end


node_type (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 70
                def node_type
                        :xmldecl
                end


encoding= (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 77
    def encoding=( enc )
      if enc.nil?
        self.old_enc = "UTF-8"
        @writeencoding = false
      else
        self.old_enc = enc
        @writeencoding = true
      end
      self.dowrite
    end


default (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 93
    def XMLDecl.default
      rv = XMLDecl.new( "1.0" )
      rv.nowrite
      rv
    end


nowrite (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 99
    def nowrite
      @writethis = false
    end


dowrite (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 103
    def dowrite
      @writethis = true
    end


inspect (REXML::XMLDecl)

# File lib/rexml/xmldecl.rb, line 107
    def inspect
      START.sub(/\\/u, '') + " ... " + STOP.sub(/\\/u, '')
    end


first (REXML::XPath)

# File lib/rexml/xpath.rb, line 22
    def XPath::first element, path=nil, namespaces=nil, variables={}
      raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
      raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
                        parser = XPathParser.new
                        parser.namespaces = namespaces
                        parser.variables = variables
                        path = "*" unless path
                        element = [element] unless element.kind_of? Array
                        parser.parse(path, element).flatten[0]
                end


each (REXML::XPath)

# File lib/rexml/xpath.rb, line 45
                def XPath::each element, path=nil, namespaces=nil, variables={}, &block
      raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
      raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
                        parser = XPathParser.new
                        parser.namespaces = namespaces
                        parser.variables = variables
                        path = "*" unless path
                        element = [element] unless element.kind_of? Array
                        parser.parse(path, element).each( &block )
                end


match (REXML::XPath)

# File lib/rexml/xpath.rb, line 57
                def XPath::match element, path=nil, namespaces=nil, variables={}
                        parser = XPathParser.new
                        parser.namespaces = namespaces
                        parser.variables = variables
                        path = "*" unless path
                        element = [element] unless element.kind_of? Array
                        parser.parse(path,element)
                end


new (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 39
    def initialize( )
      @parser = REXML::Parsers::XPathParser.new
      @namespaces = nil
      @variables = {}
    end


namespaces= (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 45
    def namespaces=( namespaces={} )
      Functions::namespace_context = namespaces
      @namespaces = namespaces
    end


variables= (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 50
    def variables=( vars={} )
      Functions::variables = vars
      @variables = vars
    end


parse (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 55
    def parse path, nodeset
     #puts "#"*40
     path_stack = @parser.parse( path )
     #puts "PARSE: #{path} => #{path_stack.inspect}"
     #puts "PARSE: nodeset = #{nodeset.inspect}"
     match( path_stack, nodeset )
    end


get_first (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 63
    def get_first path, nodeset
     #puts "#"*40
     path_stack = @parser.parse( path )
     #puts "PARSE: #{path} => #{path_stack.inspect}"
     #puts "PARSE: nodeset = #{nodeset.inspect}"
     first( path_stack, nodeset )
    end


predicate (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 71
    def predicate path, nodeset
      path_stack = @parser.parse( path )
      expr( path_stack, nodeset )
    end


[]= (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 76
    def []=( variable_name, value )
      @variables[ variable_name ] = value
    end


first (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 85
    def first( path_stack, node )
      #puts "#{depth}) Entering match( #{path.inspect}, #{tree.inspect} )"
      return nil if path.size == 0

      case path[0]
      when :document
        # do nothing
        return first( path[1..-1], node )
      when :child
        for c in node.children
          #puts "#{depth}) CHILD checking #{name(c)}"
          r = first( path[1..-1], c )
          #puts "#{depth}) RETURNING #{r.inspect}" if r
          return r if r
        end
      when :qname
        name = path[2]
        #puts "#{depth}) QNAME #{name(tree)} == #{name} (path => #{path.size})"
        if node.name == name
          #puts "#{depth}) RETURNING #{tree.inspect}" if path.size == 3
          return node if path.size == 3
          return first( path[3..-1], node )
        else
          return nil
        end
      when :descendant_or_self
        r = first( path[1..-1], node )
        return r if r
        for c in node.children
          r = first( path, c )
          return r if r
        end
      when :node
        return first( path[1..-1], node )
      when :any
        return first( path[1..-1], node )
      end
      return nil
    end


match (REXML::XPathParser)

# File lib/rexml/xpath_parser.rb, line 126
    def match( path_stack, nodeset )
      #puts "MATCH: path_stack = #{path_stack.inspect}"
      #puts "MATCH: nodeset = #{nodeset.inspect}"
      r = expr( path_stack, nodeset )
      #puts "MAIN EXPR => #{r.inspect}"
      r
    end


new (RI::AnsiFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 405
    def initialize(*args)
      print "\033[0m"
      super
    end


write_attribute_text (RI::AnsiFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 410
    def write_attribute_text(prefix, line)
      print prefix
      curr_attr = 0
      line.each do |achar|
        attr = achar.attr
        if achar.attr != curr_attr
          update_attributes(achar.attr)
          curr_attr = achar.attr
        end
        print achar.char
      end
      update_attributes(0) unless curr_attr.zero?
      puts
    end


bold_print (RI::AnsiFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 426
    def bold_print(txt)
      print "\033[1m#{txt}\033[m"
    end


display_heading (RI::AnsiFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 436
    def display_heading(text, level, indent)
      level = 3 if level > 3
      heading = HEADINGS[level]
      print indent
      print heading[0]
      print strip_attributes(text)
      puts heading[1]
    end


new (RI::Attribute)

# File lib/rdoc/ri/ri_descriptions.rb, line 34
    def initialize(name, rw, comment)
      super(name)
      @rw = rw
      @comment = comment
    end


new (RI::AttributeFormatter::AttrChar)

# File lib/rdoc/ri/ri_formatter.rb, line 260
      def initialize(char, attr)
        @char = char
        @attr = attr
      end


new (RI::AttributeFormatter::AttributeString)

# File lib/rdoc/ri/ri_formatter.rb, line 270
      def initialize
        @txt = []
        @optr = 0
      end


<< (RI::AttributeFormatter::AttributeString)

# File lib/rdoc/ri/ri_formatter.rb, line 275
      def <<(char)
        @txt << char
      end


empty? (RI::AttributeFormatter::AttributeString)

# File lib/rdoc/ri/ri_formatter.rb, line 279
      def empty?
        @optr >= @txt.length
      end


next_word (RI::AttributeFormatter::AttributeString)

# File lib/rdoc/ri/ri_formatter.rb, line 284
      def next_word
        start = @optr
        len = @txt.length

        while @optr < len && @txt[@optr].char != " "
          @optr += 1
        end

        while @optr < len && @txt[@optr].char == " "
          @optr += 1
        end

        @txt[start...@optr]
      end


wrap (RI::AttributeFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 305
    def wrap(txt,  prefix=@indent, linelen=@width)
      return unless txt && !txt.empty?

      txt = add_attributes_to(txt)
      next_prefix = prefix.tr("^ ", " ")
      linelen -= prefix.size

      line = []

      until txt.empty?
        word = txt.next_word
        if word.size + line.size > linelen
          write_attribute_text(prefix, line)
          prefix = next_prefix
          line = []
        end
        line.concat(word)
      end

      write_attribute_text(prefix, line) if line.length > 0
    end


write_attribute_text (RI::AttributeFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 331
    def write_attribute_text(prefix, line)
      print prefix
      line.each do |achar|
        print achar.char
      end
      puts
    end


bold_print (RI::AttributeFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 341
    def bold_print(txt)
      print txt
    end


display_name (RI::ClassDescription)

# File lib/rdoc/ri/ri_descriptions.rb, line 128
    def display_name
      "Class"
    end


superclass_string (RI::ClassDescription)

# File lib/rdoc/ri/ri_descriptions.rb, line 132
    def superclass_string
      if @superclass && @superclass != "Object"
        @superclass
      else
        nil
      end
    end


new (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 8
    def initialize(path_name, name, in_class)
      @path_names = [ path_name ]
      @name = name
      @in_class = in_class
      @class_methods    = []
      @instance_methods = []
      @inferior_classes = []
    end


add_path (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 19
    def add_path(path)
      @path_names << path
    end


load_from (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 30
    def load_from(dir)
      Dir.foreach(dir) do |name|
        next if name =~ /^\./

        # convert from external to internal form, and
        # extract the instance/class flag

        if name =~ /^(.*?)-(c|i).yaml$/
          external_name = $1
          is_class_method = $2 == "c"
          internal_name = RiWriter.external_to_internal(external_name)
          list = is_class_method ? @class_methods : @instance_methods
          path = File.join(dir, name)
          list << MethodEntry.new(path, internal_name, is_class_method, self)
        else
          full_name = File.join(dir, name)
          if File.directory?(full_name)
            inf_class = @inferior_classes.find {|c| c.name == name }
            if inf_class
              inf_class.add_path(full_name)
            else
              inf_class = ClassEntry.new(full_name, name, self)
              @inferior_classes << inf_class
            end
            inf_class.load_from(full_name)
          end
        end
      end
    end


contained_modules_matching (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 63
    def contained_modules_matching(name)
      @inferior_classes.find_all {|c| c.name[name]}
    end


classes_and_modules (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 67
    def classes_and_modules
      @inferior_classes
    end


contained_class_named (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 72
    def contained_class_named(name)
      @inferior_classes.find {|c| c.name == name}
    end


methods_matching (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 79
    def methods_matching(name, is_class_method)
      local_methods_matching(name, is_class_method)
    end


recursively_find_methods_matching (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 85
    def recursively_find_methods_matching(name, is_class_method)
      res = local_methods_matching(name, is_class_method)
      @inferior_classes.each do |c|
        res.concat(c.recursively_find_methods_matching(name, is_class_method))
      end
      res
    end


full_name (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 95
    def full_name
      res = @in_class.full_name
      res << "::" unless res.empty?
      res << @name
    end


all_method_names (RI::ClassEntry)

# File lib/rdoc/ri/ri_cache.rb, line 102
    def all_method_names
      res = @class_methods.map {|m| m.full_name }
      @instance_methods.each {|m| res << m.full_name}
      res
    end


new (RI::Constant)

# File lib/rdoc/ri/ri_descriptions.rb, line 43
    def initialize(name, value, comment)
      super(name)
      @value = value
      @comment = comment
    end


serialize (RI::Description)

# File lib/rdoc/ri/ri_descriptions.rb, line 67
    def serialize
      self.to_yaml
    end


deserialize (RI::Description)

# File lib/rdoc/ri/ri_descriptions.rb, line 71
    def Description.deserialize(from)
      YAML.load(from)
    end


<=> (RI::Description)

# File lib/rdoc/ri/ri_descriptions.rb, line 75
    def <=>(other)
      @name <=> other.name
    end


new (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 470
    def initialize(*args)
      super
    end


write_attribute_text (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 474
    def write_attribute_text(prefix, line)
      curr_attr = 0
      line.each do |achar|
        attr = achar.attr
        if achar.attr != curr_attr
          update_attributes(curr_attr, achar.attr)
          curr_attr = achar.attr
        end
        print(escape(achar.char))
      end
      update_attributes(curr_attr, 0) unless curr_attr.zero?
    end


draw_line (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 487
    def draw_line(label=nil)
      if label != nil
        bold_print(label)
      end
      puts("<hr>")
    end


bold_print (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 494
    def bold_print(txt)
      tag("b") { txt }
    end


blankline (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 498
    def blankline()
      puts("<p>")
    end


break_to_newline (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 502
    def break_to_newline
      puts("<br>")
    end


display_heading (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 506
    def display_heading(text, level, indent)
      level = 4 if level > 4
      tag("h#{level}") { text }
      puts
    end


display_list (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 514
    def display_list(list)

      case list.type
      when SM::ListBase::BULLET
        list_type = "ul"
        prefixer = proc { |ignored| "<li>" }

      when SM::ListBase::NUMBER,
      SM::ListBase::UPPERALPHA,
      SM::ListBase::LOWERALPHA
        list_type = "ol"
        prefixer = proc { |ignored| "<li>" }

      when SM::ListBase::LABELED
        list_type = "dl"
        prefixer = proc do |li|
          "<dt><b>" + escape(li.label) + "</b><dd>"
        end

      when SM::ListBase::NOTE
        list_type = "table"
        prefixer = proc do |li|
          %{<tr valign="top"><td>#{li.label.gsub(/ /, '&nbsp;')}</td><td>}
        end
      else
        fail "unknown list type"
      end

      print "<#{list_type}>"
      list.contents.each do |item|
        if item.kind_of? SM::Flow::LI
          prefix = prefixer.call(item)
          print prefix
          display_flow_item(item, prefix)
        else
          display_flow_item(item)
        end
      end
      print "</#{list_type}>"
    end


display_verbatim_flow_item (RI::HtmlFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 555
    def display_verbatim_flow_item(item, prefix=@indent)
        print("<pre>")
        puts item.body
        puts("</pre>")
    end


new (RI::MethodEntry)

# File lib/rdoc/ri/ri_cache.rb, line 149
    def initialize(path_name, name, is_class_method, in_class)
      @path_name = path_name
      @name = name
      @is_class_method = is_class_method
      @in_class = in_class
    end


full_name (RI::MethodEntry)

# File lib/rdoc/ri/ri_cache.rb, line 156
    def full_name
      res = @in_class.full_name
      unless res.empty?
        if @is_class_method
          res << "::"
        else
          res << "#"
        end
      end
      res << @name
    end


new (RI::MethodSummary)

# File lib/rdoc/ri/ri_descriptions.rb, line 55
    def initialize(name="")
      super
    end


merge_in (RI::ModuleDescription)

# File lib/rdoc/ri/ri_descriptions.rb, line 89
    def merge_in(old)
      merge(@class_methods, old.class_methods)
      merge(@instance_methods, old.instance_methods)
      merge(@attributes, old.attributes)
      merge(@constants, old.constants)
      merge(@includes, old.includes)
      if @comment.nil? || @comment.empty?
        @comment = old.comment
      else
        unless old.comment.nil? or old.comment.empty? then
          @comment << SM::Flow::RULE.new
          @comment.concat old.comment
        end
      end
    end


display_name (RI::ModuleDescription)

# File lib/rdoc/ri/ri_descriptions.rb, line 105
    def display_name
      "Module"
    end


superclass_string (RI::ModuleDescription)

# File lib/rdoc/ri/ri_descriptions.rb, line 111
    def superclass_string
      nil
    end


new (RI::NamedThing)

# File lib/rdoc/ri/ri_descriptions.rb, line 11
    def initialize(name)
      @name = name
    end


<=> (RI::NamedThing)

# File lib/rdoc/ri/ri_descriptions.rb, line 14
    def <=>(other)
      @name <=> other.name
    end


hash (RI::NamedThing)

# File lib/rdoc/ri/ri_descriptions.rb, line 18
    def hash
      @name.hash
    end


eql? (RI::NamedThing)

# File lib/rdoc/ri/ri_descriptions.rb, line 22
    def eql?(other)
      @name.eql?(other)
    end


options (RI::Options::OptionList)

# File lib/rdoc/ri/ri_options.rb, line 94
      def OptionList.options
        OPTION_LIST.map do |long, short, arg,|
          option = []
          option << long
          option << short unless short.nil?
          option << (arg ? GetoptLong::REQUIRED_ARGUMENT :
                           GetoptLong::NO_ARGUMENT)
          option
        end
      end


strip_output (RI::Options::OptionList)

# File lib/rdoc/ri/ri_options.rb, line 106
      def OptionList.strip_output(text)
        text =~ /^\s+/
        leading_spaces = $&
        text.gsub!(/^#{leading_spaces}/, '')
        $stdout.puts text
      end


error (RI::Options::OptionList)

# File lib/rdoc/ri/ri_options.rb, line 116
      def OptionList.error(msg)
        $stderr.puts
        $stderr.puts msg
        $stderr.puts "\nFor help on options, try 'ri --help'\n\n"
        exit 1
      end


usage (RI::Options::OptionList)

# File lib/rdoc/ri/ri_options.rb, line 125
      def OptionList.usage(short_form=false)

        puts
        puts(RI::VERSION_STRING)
        puts

        name = File.basename($0)

        directories = [
          RI::Paths::SYSDIR,
          RI::Paths::SITEDIR,
          RI::Paths::HOMEDIR
        ]

        directories << "#{Gem.path}/doc/*/ri" if RI::Paths::GEMDIRS

        directories = directories.join("\n    ")

        OptionList.strip_output("Usage:\n\n\#{name} [options]  [names...]\n\nDisplay information on Ruby classes, modules, and methods.\nGive the names of classes or methods to see their documentation.\nPartial names may be given: if the names match more than\none entity, a list will be shown, otherwise details on\nthat entity will be displayed.\n\nNested classes and modules can be specified using the normal\nName::Name notation, and instance methods can be distinguished\nfrom class methods using \".\" (or \"#\") instead of \"::\".\n\nFor example:\n\nri  File\nri  File.new\nri  F.n\nri  zip\n\nNote that shell quoting may be required for method names\ncontaining punctuation:\n\nri 'Array.[]'\nri compact\\\\!\n\nBy default ri searches for documentation in the following\ndirectories:\n\n\#{directories}\n\nSpecifying the --system, --site, --home, --gems or --doc-dir\noptions will limit ri to searching only the specified\ndirectories.\n\n")

        if short_form
          puts "For help on options, type 'ri -h'"
          puts "For a list of classes I know about, type 'ri -c'"
        else
          puts "Options:\n\n"
          OPTION_LIST.each do|long, short, arg, desc|
            opt = ''
            opt << (short ? sprintf("%15s", "#{long}, #{short}") :
                            sprintf("%15s", long))
            if arg
              opt << " " << arg
            end
            print opt
            desc = desc.split("\n")
            if opt.size < 17
              print " "*(18-opt.size)
              puts desc.shift
            else
              puts
            end
            desc.each do |line|
              puts(" "*18 + line)
            end
            puts
          end
          puts "Options may also be passed in the 'RI' environment variable"
          exit 0
        end
      end


show_version (RI::Options)

# File lib/rdoc/ri/ri_options.rb, line 215
    def show_version
      puts VERSION_STRING
      exit(0)
    end


new (RI::Options)

# File lib/rdoc/ri/ri_options.rb, line 220
    def initialize
      @use_stdout   = !STDOUT.tty?
      @width        = 72
      @formatter    = RI::TextFormatter.for("plain")
      @list_classes = false
      @list_names   = false

      # By default all paths are used.  If any of these are true, only those
      # directories are used.
      @use_system = false
      @use_site = false
      @use_home = false
      @use_gems = false
      @doc_dirs = []
    end


parse (RI::Options)

# File lib/rdoc/ri/ri_options.rb, line 238
    def parse(args)

      old_argv = ARGV.dup

      ARGV.replace(args)

      begin

        go = GetoptLong.new(*OptionList.options)
        go.quiet = true

        go.each do |opt, arg|
          case opt
          when "--help"       then OptionList.usage
          when "--version"    then show_version
          when "--list-names" then @list_names = true
          when "--no-pager"   then @use_stdout = true
          when "--classes"    then @list_classes = true

          when "--system"     then @use_system = true
          when "--site"       then @use_site = true
          when "--home"       then @use_home = true
          when "--gems"       then @use_gems = true

          when "--doc-dir"
            if File.directory?(arg)
              @doc_dirs << arg
            else
              $stderr.puts "Invalid directory: #{arg}"
              exit 1
            end

          when "--format"
            @formatter = RI::TextFormatter.for(arg)
            unless @formatter
              $stderr.print "Invalid formatter (should be one of "
              $stderr.puts RI::TextFormatter.list + ")"
              exit 1
            end
          when "--width"
            begin
              @width = Integer(arg)
            rescue
              $stderr.puts "Invalid width: '#{arg}'"
              exit 1
            end
          end
        end

      rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => error
        OptionList.error(error.message)

      end
    end


path (RI::Options)

# File lib/rdoc/ri/ri_options.rb, line 295
    def path
      RI::Paths.path(@use_system, @use_site, @use_home, @use_gems, *@doc_dirs)
    end


raw_path (RI::Options)

# File lib/rdoc/ri/ri_options.rb, line 299
    def raw_path
      RI::Paths.raw_path(@use_system, @use_site, @use_home, @use_gems,
                         *@doc_dirs)
    end


displayer (RI::Options)

# File lib/rdoc/ri/ri_options.rb, line 308
    def displayer
      ::RiDisplay.new(self)
    end


write_attribute_text (RI::OverstrikeFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 374
    def write_attribute_text(prefix, line)
      print prefix
      line.each do |achar|
        attr = achar.attr
        if (attr & (ITALIC+CODE)) != 0
          print "_", BS
        end
        if (attr & BOLD) != 0
          print achar.char, BS
        end
        print achar.char
      end
      puts
    end


bold_print (RI::OverstrikeFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 390
    def bold_print(text)
      text.split(//).each do |ch|
        print ch, BS, ch
      end
    end


new (RI::RiCache)

# File lib/rdoc/ri/ri_cache.rb, line 176
    def initialize(dirs)
      # At the top level we have a dummy module holding the
      # overall namespace
      @toplevel = TopLevelEntry.new('', '::', nil)

      dirs.each do |dir|
        @toplevel.load_from(dir)
      end
    end


new (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 8
    def initialize(ri_cache)
      @cache = ri_cache
    end


top_level_namespace (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 12
    def top_level_namespace
      [ @cache.toplevel ]
    end


lookup_namespace_in (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 16
    def lookup_namespace_in(target, namespaces)
      result = []
      for n in namespaces
        result.concat(n.contained_modules_matching(target))
      end
      result
    end


find_class_by_name (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 24
    def find_class_by_name(full_name)
      names = full_name.split(/::/)
      ns = @cache.toplevel
      for name in names
        ns = ns.contained_class_named(name)
        return nil if ns.nil?
      end
      get_class(ns)
    end


find_methods (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 34
    def find_methods(name, is_class_method, namespaces)
      result = []
      namespaces.each do |ns|
        result.concat ns.methods_matching(name, is_class_method)
      end
      result
    end


get_method (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 44
    def get_method(method_entry)
      path = method_entry.path_name
      File.open(path) { |f| RI::Description.deserialize(f) }
    end


get_class (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 50
    def get_class(class_entry)
      result = nil
      for path in class_entry.path_names
        path = RiWriter.class_desc_path(path, class_entry)
        desc = File.open(path) {|f| RI::Description.deserialize(f) }
        if result
          result.merge_in(desc)
        else
          result = desc
        end
      end
      result
    end


full_class_names (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 65
    def full_class_names
      res = []
      find_classes_in(res, @cache.toplevel)
    end


all_names (RI::RiReader)

# File lib/rdoc/ri/ri_reader.rb, line 71
    def all_names
      res = []
      find_names_in(res, @cache.toplevel)
    end


class_desc_path (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 6
    def RiWriter.class_desc_path(dir, class_desc)
      File.join(dir, "cdesc-" + class_desc.name + ".yaml")
    end


internal_to_external (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 15
    def RiWriter.internal_to_external(name)
      name.gsub(/\W/) { sprintf("%%%02x", $&[0]) }
    end


external_to_internal (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 20
    def RiWriter.external_to_internal(name)
      name.gsub(/%([0-9a-f]{2,2})/) { $1.to_i(16).chr }
    end


new (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 24
    def initialize(base_dir)
      @base_dir = base_dir
    end


remove_class (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 28
    def remove_class(class_desc)
      FileUtils.rm_rf(path_to_dir(class_desc.full_name))
    end


add_class (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 32
    def add_class(class_desc)
      dir = path_to_dir(class_desc.full_name)
      FileUtils.mkdir_p(dir)
      class_file_name = RiWriter.class_desc_path(dir, class_desc)
      File.open(class_file_name, "w") do |f|
        f.write(class_desc.serialize)
      end
    end


add_method (RI::RiWriter)

# File lib/rdoc/ri/ri_writer.rb, line 41
    def add_method(class_desc, method_desc)
      dir = path_to_dir(class_desc.full_name)
      file_name = RiWriter.internal_to_external(method_desc.name)
      meth_file_name = File.join(dir, file_name)
      if method_desc.is_singleton
        meth_file_name += "-c.yaml"
      else
        meth_file_name += "-i.yaml"
      end

      File.open(meth_file_name, "w") do |f|
        f.write(method_desc.serialize)
      end
    end


blankline (RI::SimpleFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 615
    def blankline
    end


draw_line (RI::SimpleFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 622
    def draw_line(label=nil)
      unless label.nil? then
        bold_print(label)
        puts
      end
    end


display_heading (RI::SimpleFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 633
    def display_heading(text, level, indent)
      text = strip_attributes(text)
      case level
      when 1
        puts "= " + text.upcase
      when 2
        puts "-- " + text
      else
        print indent, text, "\n"
      end
    end


new (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 6
    def initialize(options, indent)
      @options = options
      @width   = options.width
      @indent  = indent
    end


draw_line (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 15
    def draw_line(label=nil)
      len = @width
      len -= (label.size+1) if label
      print "-"*len
      if label
        print(" ")
        bold_print(label)
      end
      puts
    end


wrap (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 28
    def wrap(txt,  prefix=@indent, linelen=@width)
      return unless txt && !txt.empty?
      work = conv_markup(txt)
      textLen = linelen - prefix.length
      patt = Regexp.new("^(.{0,#{textLen}})[ \n]")
      next_prefix = prefix.tr("^ ", " ")

      res = []

      while work.length > textLen
        if work =~ patt
          res << $1
          work.slice!(0, $&.length)
        else
          res << work.slice!(0, textLen)
        end
      end
      res << work if work.length.nonzero?
      puts(prefix + res.join("\n" + next_prefix))
    end


blankline (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 51
    def blankline
      puts
    end


break_to_newline (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 61
    def break_to_newline
    end


bold_print (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 66
    def bold_print(txt)
      print txt
    end


raw_print_line (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 72
    def raw_print_line(txt)
      puts txt
    end


conv_html (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 79
    def conv_html(txt)
      txt.
          gsub(/&gt;/, '>').
          gsub(/&lt;/, '<').
          gsub(/&quot;/, '"').
          gsub(/&amp;/, '&')

    end


conv_markup (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 89
    def conv_markup(txt)
      txt.
          gsub(%r{<tt>(.*?)</tt>}) { "+#$1+" } .
          gsub(%r{<code>(.*?)</code>}) { "+#$1+" } .
          gsub(%r{<b>(.*?)</b>}) { "*#$1*" } .
          gsub(%r{<em>(.*?)</em>}) { "_#$1_" }
    end


display_list (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 99
    def display_list(list)
      case list.type

      when SM::ListBase::BULLET
        prefixer = proc { |ignored| @indent + "*   " }

      when SM::ListBase::NUMBER,
      SM::ListBase::UPPERALPHA,
      SM::ListBase::LOWERALPHA

        start = case list.type
                when SM::ListBase::NUMBER      then 1
                when  SM::ListBase::UPPERALPHA then 'A'
                when SM::ListBase::LOWERALPHA  then 'a'
                end
        prefixer = proc do |ignored|
          res = @indent + "#{start}.".ljust(4)
          start = start.succ
          res
        end

      when SM::ListBase::LABELED
        prefixer = proc do |li|
          li.label
        end

      when SM::ListBase::NOTE
        longest = 0
        list.contents.each do |item|
          if item.kind_of?(SM::Flow::LI) && item.label.length > longest
            longest = item.label.length
          end
        end

        prefixer = proc do |li|
          @indent + li.label.ljust(longest+1)
        end

      else
        fail "unknown list type"

      end

      list.contents.each do |item|
        if item.kind_of? SM::Flow::LI
          prefix = prefixer.call(item)
          display_flow_item(item, prefix)
        else
          display_flow_item(item)
        end
       end
    end


display_flow_item (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 154
    def display_flow_item(item, prefix=@indent)
      case item
      when SM::Flow::P, SM::Flow::LI
        wrap(conv_html(item.body), prefix)
        blankline

      when SM::Flow::LIST
        display_list(item)

      when SM::Flow::VERB
        display_verbatim_flow_item(item, @indent)

      when SM::Flow::H
        display_heading(conv_html(item.text), item.level, @indent)

      when SM::Flow::RULE
        draw_line

      else
        fail "Unknown flow element: #{item.class}"
      end
    end


display_verbatim_flow_item (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 179
    def display_verbatim_flow_item(item, prefix=@indent)
        item.body.split(/\n/).each do |line|
          print @indent, conv_html(line), "\n"
        end
        blankline
    end


display_heading (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 188
    def display_heading(text, level, indent)
      text = strip_attributes(text)
      case level
      when 1
        ul = "=" * text.length
        puts
        puts text.upcase
        puts ul
#        puts

      when 2
        ul = "-" * text.length
        puts
        puts text
        puts ul
#        puts
      else
        print indent, text, "\n"
      end
    end


display_flow (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 210
    def display_flow(flow)
      flow.each do |f|
        display_flow_item(f)
      end
    end


strip_attributes (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 216
    def strip_attributes(txt)
      tokens = txt.split(%r{(</?(?:b|code|em|i|tt)>)})
      text = []
      attributes = 0
      tokens.each do |tok|
        case tok
        when %r{^</(\w+)>$}, %r{^<(\w+)>$}
          ;
        else
          text << tok
        end
      end
      text.join
    end


list (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 660
    def TextFormatter.list
      FORMATTERS.keys.sort.join(", ")
    end


for (RI::TextFormatter)

# File lib/rdoc/ri/ri_formatter.rb, line 664
    def TextFormatter.for(name)
      FORMATTERS[name.downcase]
    end


methods_matching (RI::TopLevelEntry)

# File lib/rdoc/ri/ri_cache.rb, line 131
    def methods_matching(name, is_class_method)
      res = recursively_find_methods_matching(name, is_class_method)
    end


full_name (RI::TopLevelEntry)

# File lib/rdoc/ri/ri_cache.rb, line 135
    def full_name
      ""
    end


module_named (RI::TopLevelEntry)

# File lib/rdoc/ri/ri_cache.rb, line 139
    def module_named(name)

    end


append_features (RiDisplay)

# File lib/rdoc/ri/ri_display.rb, line 22
  def RiDisplay.append_features(display_class)
    @@display_class = display_class
  end


new (RiDisplay)

# File lib/rdoc/ri/ri_display.rb, line 26
  def RiDisplay.new(*args)
    @@display_class.new(*args)
  end


new (RiDriver)

# File lib/rdoc/ri/ri_driver.rb, line 14
  def initialize
    @options = RI::Options.instance

    args = ARGV
    if ENV["RI"]
      args = ENV["RI"].split.concat(ARGV)
    end

    @options.parse(args)

    path = @options.path
    report_missing_documentation @options.raw_path if path.empty?

    @ri_reader = RI::RiReader.new(RI::RiCache.new(path))
    @display   = @options.displayer
  end


report_missing_documentation (RiDriver)

# File lib/rdoc/ri/ri_driver.rb, line 33
  def report_missing_documentation(path)
    STDERR.puts "No ri documentation found in:"
    path.each do |d|
      STDERR.puts "     #{d}"
    end
    STDERR.puts "\nWas rdoc run to create documentation?\n\n"
    RDoc::usage("Installing Documentation")
  end


report_method_stuff (RiDriver)

# File lib/rdoc/ri/ri_driver.rb, line 49
  def report_method_stuff(requested_method_name, methods)
    if methods.size == 1
      method = @ri_reader.get_method(methods[0])
      @display.display_method_info(method)
    else
      entries = methods.find_all {|m| m.name == requested_method_name}
      if entries.size == 1
        method = @ri_reader.get_method(entries[0])
        @display.display_method_info(method)
      else
        @display.display_method_list(methods)
      end
    end
  end


report_class_stuff (RiDriver)

# File lib/rdoc/ri/ri_driver.rb, line 66
  def report_class_stuff(namespaces)
    if namespaces.size == 1
      klass = @ri_reader.get_class(namespaces[0])
      @display.display_class_info(klass, @ri_reader)
    else
#      entries = namespaces.find_all {|m| m.full_name == requested_class_name}
#      if entries.size == 1
#        klass = @ri_reader.get_class(entries[0])
#        @display.display_class_info(klass, @ri_reader)
#      else
        @display.display_class_list(namespaces)
#      end
    end
  end


get_info_for (RiDriver)

# File lib/rdoc/ri/ri_driver.rb, line 84
  def get_info_for(arg)
    desc = NameDescriptor.new(arg)

    namespaces = @ri_reader.top_level_namespace

    for class_name in desc.class_names
      namespaces = @ri_reader.lookup_namespace_in(class_name, namespaces)
      if namespaces.empty?
        raise RiError.new("Nothing known about #{arg}")
      end
    end

    # at this point, if we have multiple possible namespaces, but one
    # is an exact match for our requested class, prune down to just it

    full_class_name = desc.full_class_name
    entries = namespaces.find_all {|m| m.full_name == full_class_name}
    namespaces = entries if entries.size == 1

    if desc.method_name.nil?
      report_class_stuff(namespaces)
    else
      methods = @ri_reader.find_methods(desc.method_name,
                                        desc.is_class_method,
                                        namespaces)

      if methods.empty?
        raise RiError.new("Nothing known about #{arg}")
      else
        report_method_stuff(desc.method_name, methods)
      end
    end
  end


process_args (RiDriver)

# File lib/rdoc/ri/ri_driver.rb, line 120
  def process_args
    if @options.list_classes
      classes = @ri_reader.full_class_names
      @display.list_known_classes(classes)
    elsif @options.list_names
      names = @ri_reader.all_names
      @display.list_known_names(names)
    else
      if ARGV.size.zero?
        @display.display_usage
      else
        begin
          ARGV.each do |arg|
            get_info_for(arg)
          end
        rescue RiError => e
          STDERR.puts(e.message)
          exit(1)
        end
      end
    end
  end


new (Rinda::DRbObjectTemplate)

# File lib/rinda/rinda.rb, line 183
    def initialize(uri=nil, ref=nil)
      @drb_uri = uri
      @drb_ref = ref
    end


=== (Rinda::DRbObjectTemplate)

# File lib/rinda/rinda.rb, line 192
    def ===(ro)
      return true if super(ro)
      unless @drb_uri.nil?
        return false unless (@drb_uri === ro.__drburi rescue false)
      end
      unless @drb_ref.nil?
        return false unless (@drb_ref === ro.__drbref rescue false)
      end
      true
    end


new (Rinda::NotifyTemplateEntry)

# File lib/rinda/tuplespace.rb, line 244
    def initialize(place, event, tuple, expires=nil)
      ary = [event, Rinda::Template.new(tuple)]
      super(ary, expires)
      @queue = Queue.new
      @done = false
    end


notify (Rinda::NotifyTemplateEntry)

# File lib/rinda/tuplespace.rb, line 254
    def notify(ev)
      @queue.push(ev)
    end


pop (Rinda::NotifyTemplateEntry)

# File lib/rinda/tuplespace.rb, line 262
    def pop
      raise RequestExpiredError if @done
      it = @queue.pop
      @done = true if it[0] == 'close'
      return it
    end


each (Rinda::NotifyTemplateEntry)

# File lib/rinda/tuplespace.rb, line 272
    def each # :yields: event, tuple
      while !@done
        it = pop
        yield(it)
      end
    rescue
    ensure
      cancel
    end


finger (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 106
    def self.finger
      unless @@finger
        @@finger = self.new
        @@finger.lookup_ring_any
      end
      @@finger
    end


primary (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 117
    def self.primary
      finger.primary
    end


to_a (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 124
    def self.to_a
      finger.to_a
    end


new (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 147
    def initialize(broadcast_list=@@broadcast_list, port=Ring_PORT)
      @broadcast_list = broadcast_list || ['localhost']
      @port = port
      @primary = nil
      @rings = []
    end


to_a (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 157
    def to_a
      @rings
    end


each (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 164
    def each
      lookup_ring_any unless @primary
      return unless @primary
      yield(@primary)
      @rings.each { |x| yield(x) }
    end


lookup_ring (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 176
    def lookup_ring(timeout=5, &block)
      return lookup_ring_any(timeout) unless block_given?

      msg = Marshal.dump([[:lookup_ring, DRbObject.new(block)], timeout])
      @broadcast_list.each do |it|
        soc = UDPSocket.open
        begin
          soc.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
          soc.send(msg, 0, it, @port)
        rescue
          nil
        ensure
          soc.close
        end
      end
      sleep(timeout)
    end


lookup_ring_any (Rinda::RingFinger)

# File lib/rinda/ring.rb, line 198
    def lookup_ring_any(timeout=5)
      queue = Queue.new

      th = Thread.new do
        self.lookup_ring(timeout) do |ts|
          queue.push(ts)
        end
        queue.push(nil)
        while it = queue.pop
          @rings.push(it)
        end
      end

      @primary = queue.pop
      raise('RingNotFound') if @primary.nil?
      @primary
    end


new (Rinda::RingProvider)

# File lib/rinda/ring.rb, line 232
    def initialize(klass, front, desc, renewer = nil)
      @tuple = [:name, klass, front, desc]
      @renewer = renewer || Rinda::SimpleRenewer.new
    end


provide (Rinda::RingProvider)

# File lib/rinda/ring.rb, line 240
    def provide
      ts = Rinda::RingFinger.primary
      ts.write(@tuple, @renewer)
    end


new (Rinda::RingServer)

# File lib/rinda/ring.rb, line 32
    def initialize(ts, port=Ring_PORT)
      @ts = ts
      @soc = UDPSocket.open
      @soc.bind('', port)
      @w_service = write_service
      @r_service = reply_service
    end


write_service (Rinda::RingServer)

# File lib/rinda/ring.rb, line 44
    def write_service
      Thread.new do
        loop do
          msg = @soc.recv(1024)
          do_write(msg)
        end
      end
    end


do_write (Rinda::RingServer)

# File lib/rinda/ring.rb, line 57
    def do_write(msg)
      Thread.new do
        begin
          tuple, sec = Marshal.load(msg)
          @ts.write(tuple, sec)
        rescue
        end
      end
    end


reply_service (Rinda::RingServer)

# File lib/rinda/ring.rb, line 70
    def reply_service
      Thread.new do
        loop do
          do_reply
        end
      end
    end


do_reply (Rinda::RingServer)

# File lib/rinda/ring.rb, line 82
    def do_reply
      tuple = @ts.take([:lookup_ring, nil])
      Thread.new { tuple[1].call(@ts) rescue nil}
    rescue
    end


new (Rinda::SimpleRenewer)

# File lib/rinda/rinda.rb, line 270
    def initialize(sec=180)
      @sec = sec
    end


renew (Rinda::SimpleRenewer)

# File lib/rinda/rinda.rb, line 277
    def renew
      @sec
    end


match (Rinda::Template)

# File lib/rinda/rinda.rb, line 148
    def match(tuple)
      return false unless tuple.respond_to?(:size)
      return false unless tuple.respond_to?(:fetch)
      return false unless self.size == tuple.size
      each do |k, v|
        begin
          it = tuple.fetch(k)
        rescue
          return false
        end
        next if v.nil?
        next if v == it
        next if v === it
        return false
      end
      return true
    end


=== (Rinda::Template)

# File lib/rinda/rinda.rb, line 169
    def ===(tuple)
      match(tuple)
    end


match (Rinda::TemplateEntry)

# File lib/rinda/tuplespace.rb, line 166
    def match(tuple)
      @tuple.match(tuple)
    end


new (Rinda::Tuple)

# File lib/rinda/rinda.rb, line 51
    def initialize(ary_or_hash)
      if hash?(ary_or_hash)
        init_with_hash(ary_or_hash)
      else
        init_with_ary(ary_or_hash)
      end
    end


size (Rinda::Tuple)

# File lib/rinda/rinda.rb, line 62
    def size
      @tuple.size
    end


[] (Rinda::Tuple)

# File lib/rinda/rinda.rb, line 69
    def [](k)
      @tuple[k]
    end


fetch (Rinda::Tuple)

# File lib/rinda/rinda.rb, line 76
    def fetch(k)
      @tuple.fetch(k)
    end


each (Rinda::Tuple)

# File lib/rinda/rinda.rb, line 84
    def each # FIXME
      if Hash === @tuple
        @tuple.each { |k, v| yield(k, v) }
      else
        @tuple.each_with_index { |v, k| yield(k, v) }
      end
    end


value (Rinda::Tuple)

# File lib/rinda/rinda.rb, line 94
    def value
      @tuple
    end


has_expires? (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 297
    def has_expires?
      @hash.each do |k, v|
        v.each do |tuple|
          return true if tuple.expires
        end
      end
      false
    end


push (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 309
    def push(ary)
      size = ary.size
      @hash[size] ||= []
      @hash[size].push(ary)
    end


delete (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 318
    def delete(ary)
      size = ary.size
      @hash.fetch(size, []).delete(ary)
    end


find_all (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 326
    def find_all(template)
      @hash.fetch(template.size, []).find_all do |tuple|
        tuple.alive? && template.match(tuple)
      end
    end


find (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 335
    def find(template)
      @hash.fetch(template.size, []).find do |tuple|
        tuple.alive? && template.match(tuple)
      end
    end


find_all_template (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 345
    def find_all_template(tuple)
      @hash.fetch(tuple.size, []).find_all do |template|
        template.alive? && template.match(tuple)
      end
    end


delete_unless_alive (Rinda::TupleBag)

# File lib/rinda/tuplespace.rb, line 355
    def delete_unless_alive
      deleted = []
      @hash.keys.each do |size|
        ary = []
        @hash[size].each do |tuple|
          if tuple.alive?
            ary.push(tuple)
          else
            deleted.push(tuple)
          end
        end
        @hash[size] = ary
      end
      deleted
    end


new (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 25
    def initialize(ary, sec=nil)
      @cancel = false
      @expires = nil
      @tuple = make_tuple(ary)
      @renewer = nil
      renew(sec)
    end


cancel (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 36
    def cancel
      @cancel = true
    end


alive? (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 43
    def alive?
      !canceled? && !expired?
    end


value (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 51
    def value; @tuple.value; end


canceled? (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 56
    def canceled?; @cancel; end


expired? (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 64
    def expired?
      return true unless @expires
      return false if @expires > Time.now
      return true if @renewer.nil?
      renew(@renewer)
      return true unless @expires
      return @expires < Time.now
    end


renew (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 83
    def renew(sec_or_renewer)
      sec, @renewer = get_renewer(sec_or_renewer)
      @expires = make_expires(sec)
    end


make_expires (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 95
    def make_expires(sec=nil)
      case sec
      when Numeric
        Time.now + sec
      when true
        Time.at(1)
      when nil
        Time.at(2**31-1)
      end
    end


[] (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 109
    def [](key)
      @tuple[key]
    end


fetch (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 116
    def fetch(key)
      @tuple.fetch(key)
    end


size (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 123
    def size
      @tuple.size
    end


make_tuple (Rinda::TupleEntry)

# File lib/rinda/tuplespace.rb, line 130
    def make_tuple(ary)
      Rinda::Tuple.new(ary)
    end


new (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 392
    def initialize(period=60)
      super()
      @bag = TupleBag.new
      @read_waiter = TupleBag.new
      @take_waiter = TupleBag.new
      @notify_waiter = TupleBag.new
      @period = period
      @keeper = nil
    end


write (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 405
    def write(tuple, sec=nil)
      entry = TupleEntry.new(tuple, sec)
      synchronize do
        if entry.expired?
          @read_waiter.find_all_template(entry).each do |template|
            template.read(tuple)
          end
          notify_event('write', entry.value)
          notify_event('delete', entry.value)
        else
          @bag.push(entry)
          start_keeper if entry.expires
          @read_waiter.find_all_template(entry).each do |template|
            template.read(tuple)
          end
          @take_waiter.find_all_template(entry).each do |template|
            template.signal
          end
          notify_event('write', entry.value)
        end
      end
      entry
    end


take (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 432
    def take(tuple, sec=nil, &block)
      move(nil, tuple, sec, &block)
    end


move (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 439
    def move(port, tuple, sec=nil)
      template = WaitTemplateEntry.new(self, tuple, sec)
      yield(template) if block_given?
      synchronize do
        entry = @bag.find(template)
        if entry
          port.push(entry.value) if port
          @bag.delete(entry)
          notify_event('take', entry.value)
          return entry.value
        end
        raise RequestExpiredError if template.expired?

        begin
          @take_waiter.push(template)
          start_keeper if template.expires
          while true
            raise RequestCanceledError if template.canceled?
            raise RequestExpiredError if template.expired?
            entry = @bag.find(template)
            if entry
              port.push(entry.value) if port
              @bag.delete(entry)
              notify_event('take', entry.value)
              return entry.value
            end
            template.wait
          end
        ensure
          @take_waiter.delete(template)
        end
      end
    end


read (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 476
    def read(tuple, sec=nil)
      template = WaitTemplateEntry.new(self, tuple, sec)
      yield(template) if block_given?
      synchronize do
        entry = @bag.find(template)
        return entry.value if entry
        raise RequestExpiredError if template.expired?

        begin
          @read_waiter.push(template)
          start_keeper if template.expires
          template.wait
          raise RequestCanceledError if template.canceled?
          raise RequestExpiredError if template.expired?
          return template.found
        ensure
          @read_waiter.delete(template)
        end
      end
    end


read_all (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 500
    def read_all(tuple)
      template = WaitTemplateEntry.new(self, tuple, nil)
      synchronize do
        entry = @bag.find_all(template)
        entry.collect do |e|
          e.value
        end
      end
    end


notify (Rinda::TupleSpace)

# File lib/rinda/tuplespace.rb, line 522
    def notify(event, tuple, sec=nil)
      template = NotifyTemplateEntry.new(self, event, tuple, sec)
      synchronize do
        @notify_waiter.push(template)
      end
      template
    end


new (Rinda::TupleSpaceProxy)

# File lib/rinda/rinda.rb, line 213
    def initialize(ts)
      @ts = ts
    end


write (Rinda::TupleSpaceProxy)

# File lib/rinda/rinda.rb, line 220
    def write(tuple, sec=nil)
      @ts.write(tuple, sec)
    end


take (Rinda::TupleSpaceProxy)

# File lib/rinda/rinda.rb, line 227
    def take(tuple, sec=nil, &block)
      port = []
      @ts.move(DRbObject.new(port), tuple, sec, &block)
      port[0]
    end


read (Rinda::TupleSpaceProxy)

# File lib/rinda/rinda.rb, line 236
    def read(tuple, sec=nil, &block)
      @ts.read(tuple, sec, &block)
    end


read_all (Rinda::TupleSpaceProxy)

# File lib/rinda/rinda.rb, line 244
    def read_all(tuple)
      @ts.read_all(tuple)
    end


notify (Rinda::TupleSpaceProxy)

# File lib/rinda/rinda.rb, line 252
    def notify(ev, tuple, sec=nil)
      @ts.notify(ev, tuple, sec)
    end


new (Rinda::WaitTemplateEntry)

# File lib/rinda/tuplespace.rb, line 185
    def initialize(place, ary, expires=nil)
      super(ary, expires)
      @place = place
      @cond = place.new_cond
      @found = nil
    end


cancel (Rinda::WaitTemplateEntry)

# File lib/rinda/tuplespace.rb, line 192
    def cancel
      super
      signal
    end


wait (Rinda::WaitTemplateEntry)

# File lib/rinda/tuplespace.rb, line 197
    def wait
      @cond.wait
    end


read (Rinda::WaitTemplateEntry)

# File lib/rinda/tuplespace.rb, line 201
    def read(tuple)
      @found = tuple
      signal
    end


signal (Rinda::WaitTemplateEntry)

# File lib/rinda/tuplespace.rb, line 206
    def signal
      @place.synchronize do
        @cond.signal
      end
    end


append_features (RSS::BaseDublinCoreModel)

# File lib/rss/dublincore.rb, line 11
    def append_features(klass)
      super

      return if klass.instance_of?(Module)
      DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
        plural = plural_name || "#{name}s"
        full_name = "#{DC_PREFIX}_#{name}"
        full_plural_name = "#{DC_PREFIX}_#{plural}"
        klass_name = "DublinCore#{Utils.to_class_name(name)}"
        klass.install_must_call_validator(DC_PREFIX, DC_URI)
        klass.install_have_children_element(name, DC_URI, "*",
                                            full_name, full_plural_name)
        klass.module_eval("remove_method :\#{full_name}\nremove_method :\#{full_name}=\nremove_method :set_\#{full_name}\n\ndef \#{full_name}\n@\#{full_name}.first and @\#{full_name}.first.value\nend\n\ndef \#{full_name}=(new_value)\n@\#{full_name}[0] = Utils.new_with_value_if_need(\#{klass_name}, new_value)\nend\nalias set_\#{full_name} \#{full_name}=\n", *get_file_and_line_from_caller(0))
      end
      klass.module_eval("alias date \#{DC_PREFIX}_date\nalias date= \#{DC_PREFIX}_date=\n", *get_file_and_line_from_caller(0))
    end


setter (RSS::BaseListener)

# File lib/rss/parser.rb, line 181
      def setter(uri, tag_name)
        begin
          @@setters[uri][tag_name]
        rescue NameError
          nil
        end
      end


available_tags (RSS::BaseListener)

# File lib/rss/parser.rb, line 191
      def available_tags(uri)
        begin
          @@setters[uri].keys
        rescue NameError
          []
        end
      end


register_uri (RSS::BaseListener)

# File lib/rss/parser.rb, line 200
      def register_uri(uri, name)
        @@registered_uris[name] ||= {}
        @@registered_uris[name][uri] = nil
      end


uri_registered? (RSS::BaseListener)

# File lib/rss/parser.rb, line 206
      def uri_registered?(uri, name)
        @@registered_uris[name].has_key?(uri)
      end


install_class_name (RSS::BaseListener)

# File lib/rss/parser.rb, line 211
      def install_class_name(uri, tag_name, class_name)
        @@class_names[uri] ||= {}
        @@class_names[uri][tag_name] = class_name
      end


class_name (RSS::BaseListener)

# File lib/rss/parser.rb, line 218
      def class_name(uri, tag_name)
        begin
          @@class_names[uri][tag_name]
        rescue NameError
          tag_name[0,1].upcase + tag_name[1..-1]
        end
      end


install_get_text_element (RSS::BaseListener)

# File lib/rss/parser.rb, line 226
      def install_get_text_element(uri, name, setter)
        install_setter(uri, name, setter)
        def_get_text_element(uri, name, *get_file_and_line_from_caller(1))
      end


raise_for_undefined_entity? (RSS::BaseListener)

# File lib/rss/parser.rb, line 231
      def raise_for_undefined_entity?
        true
      end


install_have_child_element (RSS::BaseModel)

# File lib/rss/rss.rb, line 144
    def install_have_child_element(tag_name, uri, occurs, name=nil)
      name ||= tag_name
      add_need_initialize_variable(name)
      install_model(tag_name, uri, occurs, name)

      attr_accessor name
      install_element(name) do |n, elem_name|
        "if @\#{n}\n\"\\\#{@\#{n}.to_s(need_convert, indent)}\"\nelse\n''\nend\n"
      end
    end


install_have_children_element (RSS::BaseModel)

# File lib/rss/rss.rb, line 163
    def install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil)
      name ||= tag_name
      plural_name ||= "#{name}s"
      add_have_children_element(name, plural_name)
      add_plural_form(name, plural_name)
      install_model(tag_name, uri, occurs, plural_name)

      def_children_accessor(name, plural_name)
      install_element(name, "s") do |n, elem_name|
        "rv = []\n@\#{n}.each do |x|\nvalue = \"\\\#{x.to_s(need_convert, indent)}\"\nrv << value if /\\\\A\\\\s*\\\\z/ !~ value\nend\nrv.join(\"\\n\")\n"
      end
    end


install_text_element (RSS::BaseModel)

# File lib/rss/rss.rb, line 184
    def install_text_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil)
      name ||= tag_name
      disp_name ||= name
      self::ELEMENTS << name
      add_need_initialize_variable(name)
      install_model(tag_name, uri, occurs, name)

      def_corresponded_attr_writer name, type, disp_name
      convert_attr_reader name
      install_element(name) do |n, elem_name|
        "if @\#{n}\nrv = \"\\\#{indent}<\#{elem_name}>\"\nvalue = html_escape(@\#{n})\nif need_convert\nrv << convert(value)\nelse\nrv << value\nend\nrv << \"</\#{elem_name}>\"\nrv\nelse\n''\nend\n"
      end
    end


install_date_element (RSS::BaseModel)

# File lib/rss/rss.rb, line 213
    def install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil)
      name ||= tag_name
      type ||= :w3cdtf
      disp_name ||= name
      self::ELEMENTS << name
      add_need_initialize_variable(name)
      install_model(tag_name, uri, occurs, name)

      # accessor
      convert_attr_reader name
      date_writer(name, type, disp_name)

      install_element(name) do |n, elem_name|
        "if @\#{n}\nrv = \"\\\#{indent}<\#{elem_name}>\"\nvalue = html_escape(@\#{n}.\#{type})\nif need_convert\nrv << convert(value)\nelse\nrv << value\nend\nrv << \"</\#{elem_name}>\"\nrv\nelse\n''\nend\n"
      end

    end


raise_for_undefined_entity? (RSS::BaseParser)

# File lib/rss/parser.rb, line 131
      def raise_for_undefined_entity?
        listener.raise_for_undefined_entity?
      end


new (RSS::BaseParser)

# File lib/rss/parser.rb, line 136
    def initialize(rss)
      @listener = self.class.listener.new
      @rss = rss
    end


rss (RSS::BaseParser)

# File lib/rss/parser.rb, line 141
    def rss
      @listener.rss
    end


ignore_unknown_element (RSS::BaseParser)

# File lib/rss/parser.rb, line 145
    def ignore_unknown_element
      @listener.ignore_unknown_element
    end


ignore_unknown_element= (RSS::BaseParser)

# File lib/rss/parser.rb, line 149
    def ignore_unknown_element=(new_value)
      @listener.ignore_unknown_element = new_value
    end


do_validate (RSS::BaseParser)

# File lib/rss/parser.rb, line 153
    def do_validate
      @listener.do_validate
    end


do_validate= (RSS::BaseParser)

# File lib/rss/parser.rb, line 157
    def do_validate=(new_value)
      @listener.do_validate = new_value
    end


parse (RSS::BaseParser)

# File lib/rss/parser.rb, line 161
    def parse
      if @listener.rss.nil?
        _parse
      end
      @listener.rss
    end


append_features (RSS::BaseTrackBackModel)

# File lib/rss/trackback.rb, line 27
    def append_features(klass)
      super

      unless klass.class == Module
        klass.module_eval {include TrackBackUtils}

        klass.install_must_call_validator(TRACKBACK_PREFIX, TRACKBACK_URI)
        %w(ping).each do |name|
          var_name = "#{TRACKBACK_PREFIX}_#{name}"
          klass_name = "TrackBack#{Utils.to_class_name(name)}"
          klass.install_have_child_element(name, TRACKBACK_URI, "?", var_name)
          klass.module_eval("remove_method :\#{var_name}\ndef \#{var_name}\n@\#{var_name} and @\#{var_name}.value\nend\n\nremove_method :\#{var_name}=\ndef \#{var_name}=(value)\n@\#{var_name} = Utils.new_with_value_if_need(\#{klass_name}, value)\nend\n", __FILE__, __LINE__)
        end

        [%w(about s)].each do |name, postfix|
          var_name = "#{TRACKBACK_PREFIX}_#{name}"
          klass_name = "TrackBack#{Utils.to_class_name(name)}"
          klass.install_have_children_element(name, TRACKBACK_URI, "*",
                                              var_name)
          klass.module_eval("remove_method :\#{var_name}\ndef \#{var_name}(*args)\nif args.empty?\n@\#{var_name}.first and @\#{var_name}.first.value\nelse\nret = @\#{var_name}.__send__(\"[]\", *args)\nif ret.is_a?(Array)\nret.collect {|x| x.value}\nelse\nret.value\nend\nend\nend\n\nremove_method :\#{var_name}=\nremove_method :set_\#{var_name}\ndef \#{var_name}=(*args)\nif args.size == 1\nitem = Utils.new_with_value_if_need(\#{klass_name}, args[0])\n@\#{var_name}.push(item)\nelse\nnew_val = args.last\nif new_val.is_a?(Array)\nnew_val = new_value.collect do |val|\nUtils.new_with_value_if_need(\#{klass_name}, val)\nend\nelse\nnew_val = Utils.new_with_value_if_need(\#{klass_name}, new_val)\nend\n@\#{var_name}.__send__(\"[]=\", *(args[0..-2] + [new_val]))\nend\nend\nalias set_\#{var_name} \#{var_name}=\n", __FILE__, __LINE__)
        end
      end
    end


append_features (RSS::ContentModel)

# File lib/rss/content.rb, line 16
    def self.append_features(klass)
      super

      klass.install_must_call_validator(CONTENT_PREFIX, CONTENT_URI)
      %w(encoded).each do |name|
        klass.install_text_element(name, CONTENT_URI, "?",
                                   "#{CONTENT_PREFIX}_#{name}")
      end
    end


new (RSS::ConversionError)

# File lib/rss/rss.rb, line 123
    def initialize(string, to, from)
      @string = string
      @to = to
      @from = from
      super("can't convert #{@string} to #{to} from #{from}.")
    end


new (RSS::Converter)

# File lib/rss/converter.rb, line 9
    def initialize(to_enc, from_enc=nil)
      normalized_to_enc = to_enc.downcase.gsub(/-/, '_')
      from_enc ||= 'utf-8'
      normalized_from_enc = from_enc.downcase.gsub(/-/, '_')
      if normalized_to_enc == normalized_from_enc
        def_same_enc()
      else
        def_diff_enc = "def_to_#{normalized_to_enc}_from_#{normalized_from_enc}"
        if respond_to?(def_diff_enc)
          __send__(def_diff_enc)
        else
          def_else_enc(to_enc, from_enc)
        end
      end
    end


convert (RSS::Converter)

# File lib/rss/converter.rb, line 25
    def convert(value)
      value
    end


def_convert (RSS::Converter)

# File lib/rss/converter.rb, line 29
    def def_convert(depth=0)
      instance_eval("def convert(value)\nif value.kind_of?(String)\n\#{yield('value')}\nelse\nvalue\nend\nend\n", *get_file_and_line_from_caller(depth))
    end


def_iconv_convert (RSS::Converter)

# File lib/rss/converter.rb, line 42
    def def_iconv_convert(to_enc, from_enc, depth=0)
      begin
        require "iconv"
        @iconv = Iconv.new(to_enc, from_enc)
        def_convert(depth+1) do |value|
          "begin\n@iconv.iconv(\#{value})\nrescue Iconv::Failure\nraise ConversionError.new(\#{value}, \"\#{to_enc}\", \"\#{from_enc}\")\nend\n"
        end
      rescue LoadError, ArgumentError, SystemCallError
        raise UnknownConversionMethodError.new(to_enc, from_enc)
      end
    end


def_else_enc (RSS::Converter)

# File lib/rss/converter.rb, line 61
    def def_else_enc(to_enc, from_enc)
      def_iconv_convert(to_enc, from_enc, 0)
    end


def_same_enc (RSS::Converter)

# File lib/rss/converter.rb, line 65
    def def_same_enc()
      def_convert do |value|
        value
      end
    end


def_uconv_convert_if_can (RSS::Converter)

# File lib/rss/converter.rb, line 71
    def def_uconv_convert_if_can(meth, to_enc, from_enc, nkf_arg)
      begin
        require "uconv"
        def_convert(1) do |value|
          "begin\nUconv.\#{meth}(\#{value})\nrescue Uconv::Error\nraise ConversionError.new(\#{value}, \"\#{to_enc}\", \"\#{from_enc}\")\nend\n"
        end
      rescue LoadError
        require 'nkf'
        def_convert(1) do |value|
          "NKF.nkf(#{nkf_arg.dump}, #{value})"
        end
      end
    end


def_to_euc_jp_from_utf_8 (RSS::Converter)

# File lib/rss/converter.rb, line 92
    def def_to_euc_jp_from_utf_8
      def_uconv_convert_if_can('u8toeuc', 'EUC-JP', 'UTF-8', '-We')
    end


def_to_utf_8_from_euc_jp (RSS::Converter)

# File lib/rss/converter.rb, line 96
    def def_to_utf_8_from_euc_jp
      def_uconv_convert_if_can('euctou8', 'UTF-8', 'EUC-JP', '-Ew')
    end


def_to_shift_jis_from_utf_8 (RSS::Converter)

# File lib/rss/converter.rb, line 100
    def def_to_shift_jis_from_utf_8
      def_uconv_convert_if_can('u8tosjis', 'Shift_JIS', 'UTF-8', '-Ws')
    end


def_to_utf_8_from_shift_jis (RSS::Converter)

# File lib/rss/converter.rb, line 104
    def def_to_utf_8_from_shift_jis
      def_uconv_convert_if_can('sjistou8', 'UTF-8', 'Shift_JIS', '-Sw')
    end


def_to_euc_jp_from_shift_jis (RSS::Converter)

# File lib/rss/converter.rb, line 108
    def def_to_euc_jp_from_shift_jis
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Se', #{value})"
      end
    end


def_to_shift_jis_from_euc_jp (RSS::Converter)

# File lib/rss/converter.rb, line 115
    def def_to_shift_jis_from_euc_jp
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Es', #{value})"
      end
    end


def_to_euc_jp_from_iso_2022_jp (RSS::Converter)

# File lib/rss/converter.rb, line 122
    def def_to_euc_jp_from_iso_2022_jp
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Je', #{value})"
      end
    end


def_to_iso_2022_jp_from_euc_jp (RSS::Converter)

# File lib/rss/converter.rb, line 129
    def def_to_iso_2022_jp_from_euc_jp
      require "nkf"
      def_convert do |value|
        "NKF.nkf('-Ej', #{value})"
      end
    end


def_to_utf_8_from_iso_8859_1 (RSS::Converter)

# File lib/rss/converter.rb, line 136
    def def_to_utf_8_from_iso_8859_1
      def_convert do |value|
        "#{value}.unpack('C*').pack('U*')"
      end
    end


def_to_iso_8859_1_from_utf_8 (RSS::Converter)

# File lib/rss/converter.rb, line 142
    def def_to_iso_8859_1_from_utf_8
      def_convert do |value|
        "array_utf8 = \#{value}.unpack('U*')\narray_enc = []\narray_utf8.each do |num|\nif num <= 0xFF\narray_enc << num\nelse\narray_enc.concat \"&\\#\\\#{num};\".unpack('C*')\nend\nend\narray_enc.pack('C*')\n"
      end
    end


must_call_validators (RSS::Element)

# File lib/rss/rss.rb, line 425
      def must_call_validators
        MUST_CALL_VALIDATORS
      end


models (RSS::Element)

# File lib/rss/rss.rb, line 428
      def models
        MODELS
      end


get_attributes (RSS::Element)

# File lib/rss/rss.rb, line 431
      def get_attributes
        GET_ATTRIBUTES
      end


have_children_elements (RSS::Element)

# File lib/rss/rss.rb, line 434
      def have_children_elements
        HAVE_CHILDREN_ELEMENTS
      end


to_element_methods (RSS::Element)

# File lib/rss/rss.rb, line 437
      def to_element_methods
        TO_ELEMENT_METHODS
      end


need_initialize_variables (RSS::Element)

# File lib/rss/rss.rb, line 440
      def need_initialize_variables
        NEED_INITIALIZE_VARIABLES
      end


plural_forms (RSS::Element)

# File lib/rss/rss.rb, line 443
      def plural_forms
        PLURAL_FORMS
      end


inherited (RSS::Element)

# File lib/rss/rss.rb, line 448
      def inherited(klass)
        klass.const_set("MUST_CALL_VALIDATORS", {})
        klass.const_set("MODELS", [])
        klass.const_set("GET_ATTRIBUTES", [])
        klass.const_set("HAVE_CHILDREN_ELEMENTS", [])
        klass.const_set("TO_ELEMENT_METHODS", [])
        klass.const_set("NEED_INITIALIZE_VARIABLES", [])
        klass.const_set("PLURAL_FORMS", {})

        klass.module_eval("public\n\n@tag_name = name.split(/::/).last\n@tag_name[0,1] = @tag_name[0,1].downcase\n@have_content = false\n\ndef self.must_call_validators\nsuper.merge(MUST_CALL_VALIDATORS)\nend\ndef self.models\nMODELS + super\nend\ndef self.get_attributes\nGET_ATTRIBUTES + super\nend\ndef self.have_children_elements\nHAVE_CHILDREN_ELEMENTS + super\nend\ndef self.to_element_methods\nTO_ELEMENT_METHODS + super\nend\ndef self.need_initialize_variables\nNEED_INITIALIZE_VARIABLES + super\nend\ndef self.plural_forms\nsuper.merge(PLURAL_FORMS)\nend\n\n\ndef self.install_must_call_validator(prefix, uri)\nMUST_CALL_VALIDATORS[uri] = prefix\nend\n\ndef self.install_model(tag, uri, occurs=nil, getter=nil)\ngetter ||= tag\nif m = MODELS.find {|t, u, o, g| t == tag and u == uri}\nm[2] = occurs\nelse\nMODELS << [tag, uri, occurs, getter]\nend\nend\n\ndef self.install_get_attribute(name, uri, required=true,\ntype=nil, disp_name=nil,\nelement_name=nil)\ndisp_name ||= name\nelement_name ||= name\ndef_corresponded_attr_writer name, type, disp_name\nconvert_attr_reader name\nif type == :boolean and /^is/ =~ name\nalias_method \"\\\#{$POSTMATCH}?\", name\nend\nGET_ATTRIBUTES << [name, uri, required, element_name]\nadd_need_initialize_variable(disp_name)\nend\n\ndef self.def_corresponded_attr_writer(name, type=nil, disp_name=name)\ncase type\nwhen :integer\ninteger_writer name, disp_name\nwhen :positive_integer\npositive_integer_writer name, disp_name\nwhen :boolean\nboolean_writer name, disp_name\nwhen :w3cdtf, :rfc822, :rfc2822\ndate_writer name, type, disp_name\nelse\nattr_writer name\nend\nend\n\ndef self.content_setup(type=nil)\ndef_corresponded_attr_writer \"content\", type\nconvert_attr_reader :content\n@have_content = true\nend\n\ndef self.have_content?\n@have_content\nend\n\ndef self.add_have_children_element(variable_name, plural_name)\nHAVE_CHILDREN_ELEMENTS << [variable_name, plural_name]\nend\n\ndef self.add_to_element_method(method_name)\nTO_ELEMENT_METHODS << method_name\nend\n\ndef self.add_need_initialize_variable(variable_name)\nNEED_INITIALIZE_VARIABLES << variable_name\nend\n\ndef self.add_plural_form(singular, plural)\nPLURAL_FORMS[singular] = plural\nend\n\n")
      end


required_prefix (RSS::Element)

# File lib/rss/rss.rb, line 559
      def required_prefix
        nil
      end


required_uri (RSS::Element)

# File lib/rss/rss.rb, line 563
      def required_uri
        ""
      end


install_ns (RSS::Element)

# File lib/rss/rss.rb, line 567
      def install_ns(prefix, uri)
        if self::NSPOOL.has_key?(prefix)
          raise OverlappedPrefixError.new(prefix)
        end
        self::NSPOOL[prefix] = uri
      end


tag_name (RSS::Element)

# File lib/rss/rss.rb, line 574
      def tag_name
        @tag_name
      end


new (RSS::Element)

# File lib/rss/rss.rb, line 581
    def initialize(do_validate=true, attrs={})
      @converter = nil
      @do_validate = do_validate
      initialize_variables(attrs)
    end


tag_name (RSS::Element)

# File lib/rss/rss.rb, line 587
    def tag_name
      self.class.tag_name
    end


full_name (RSS::Element)

# File lib/rss/rss.rb, line 591
    def full_name
      tag_name
    end


converter= (RSS::Element)

# File lib/rss/rss.rb, line 595
    def converter=(converter)
      @converter = converter
      targets = children.dup
      self.class.have_children_elements.each do |variable_name, plural_name|
        targets.concat(__send__(plural_name))
      end
      targets.each do |target|
        target.converter = converter unless target.nil?
      end
    end


convert (RSS::Element)

# File lib/rss/rss.rb, line 606
    def convert(value)
      if @converter
        @converter.convert(value)
      else
        value
      end
    end


validate (RSS::Element)

# File lib/rss/rss.rb, line 614
    def validate(ignore_unknown_element=true)
      validate_attribute
      __validate(ignore_unknown_element)
    end


validate_for_stream (RSS::Element)

# File lib/rss/rss.rb, line 619
    def validate_for_stream(tags, ignore_unknown_element=true)
      validate_attribute
      __validate(ignore_unknown_element, tags, false)
    end


setup_maker (RSS::Element)

# File lib/rss/rss.rb, line 624
    def setup_maker(maker)
      target = maker_target(maker)
      unless target.nil?
        setup_maker_attributes(target)
        setup_maker_element(target)
        setup_maker_elements(target)
      end
    end


to_s (RSS::Element)

# File lib/rss/rss.rb, line 633
    def to_s(need_convert=true, indent='')
      if self.class.have_content?
        return "" unless @content
        rv = tag(indent) do |next_indent|
          h(@content)
        end
      else
        rv = tag(indent) do |next_indent|
          self.class.to_element_methods.collect do |method_name|
            __send__(method_name, false, next_indent)
          end
        end
      end
      rv = convert(rv) if need_convert
      rv
    end


required_prefix (RSS::ImageFaviconModel::ImageFavicon)

# File lib/rss/image.rb, line 127
        def required_prefix
          IMAGE_PREFIX
        end


required_uri (RSS::ImageFaviconModel::ImageFavicon)

# File lib/rss/image.rb, line 131
        def required_uri
          IMAGE_URI
        end


size= (RSS::ImageFaviconModel::ImageFavicon)

# File lib/rss/image.rb, line 147
      def size=(new_value)
        if @do_validate and !new_value.nil?
          new_value = new_value.strip
          unless AVAILABLE_SIZES.include?(new_value)
            attr_name = "#{IMAGE_PREFIX}:size"
            raise NotAvailableValueError.new(full_name, new_value, attr_name)
          end
        end
        __send__(:_size=, new_value)
      end


new (RSS::ImageFaviconModel::ImageFavicon)

# File lib/rss/image.rb, line 161
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
          self.size = args[1]
        end
      end


full_name (RSS::ImageFaviconModel::ImageFavicon)

# File lib/rss/image.rb, line 171
      def full_name
        tag_name_with_prefix(IMAGE_PREFIX)
      end


append_features (RSS::ImageFaviconModel)

# File lib/rss/image.rb, line 110
    def self.append_features(klass)
      super

      unless klass.class == Module
        klass.install_have_child_element("favicon", IMAGE_URI, "?",
                                         "#{IMAGE_PREFIX}_favicon")
        klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI)
      end
    end


required_prefix (RSS::ImageItemModel::ImageItem)

# File lib/rss/image.rb, line 48
        def required_prefix
          IMAGE_PREFIX
        end


required_uri (RSS::ImageItemModel::ImageItem)

# File lib/rss/image.rb, line 52
        def required_uri
          IMAGE_URI
        end


new (RSS::ImageItemModel::ImageItem)

# File lib/rss/image.rb, line 80
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
          self.resource = args[1]
        end
      end


full_name (RSS::ImageItemModel::ImageItem)

# File lib/rss/image.rb, line 90
      def full_name
        tag_name_with_prefix(IMAGE_PREFIX)
      end


append_features (RSS::ImageItemModel)

# File lib/rss/image.rb, line 33
    def self.append_features(klass)
      super

      klass.install_have_child_element("item", IMAGE_URI, "?",
                                       "#{IMAGE_PREFIX}_item")
      klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI)
    end


validate_one_tag_name (RSS::ImageModelUtils)

# File lib/rss/image.rb, line 20
    def validate_one_tag_name(ignore_unknown_element, name, tags)
      if !ignore_unknown_element
        invalid = tags.find {|tag| tag != name}
        raise UnknownTagError.new(invalid, IMAGE_URI) if invalid
      end
      raise TooMuchTagError.new(name, tag_name) if tags.size > 1
    end


new (RSS::ListenerMixin)

# File lib/rss/parser.rb, line 271
    def initialize
      @rss = nil
      @ignore_unknown_element = true
      @do_validate = true
      @ns_stack = [{}]
      @tag_stack = [[]]
      @text_stack = ['']
      @proc_stack = []
      @last_element = nil
      @version = @encoding = @standalone = nil
      @xml_stylesheets = []
    end


xmldecl (RSS::ListenerMixin)

# File lib/rss/parser.rb, line 285
    def xmldecl(version, encoding, standalone)
      @version, @encoding, @standalone = version, encoding, standalone
    end


instruction (RSS::ListenerMixin)

# File lib/rss/parser.rb, line 289
    def instruction(name, content)
      if name == "xml-stylesheet"
        params = parse_pi_content(content)
        if params.has_key?("href")
          @xml_stylesheets << XMLStyleSheet.new(*params)
        end
      end
    end


tag_start (RSS::ListenerMixin)

# File lib/rss/parser.rb, line 298
    def tag_start(name, attributes)
      @text_stack.push('')

      ns = @ns_stack.last.dup
      attrs = {}
      attributes.each do |n, v|
        if /\Axmlns(?:\z|:)/ =~ n
          ns[$POSTMATCH] = v
        else
          attrs[n] = v
        end
      end
      @ns_stack.push(ns)

      prefix, local = split_name(name)
      @tag_stack.last.push([_ns(ns, prefix), local])
      @tag_stack.push([])
      if respond_to?("start_#{local}", true)
        __send__("start_#{local}", local, prefix, attrs, ns.dup)
      else
        start_else_element(local, prefix, attrs, ns.dup)
      end
    end


tag_end (RSS::ListenerMixin)

# File lib/rss/parser.rb, line 322
    def tag_end(name)
      if DEBUG
        p "end tag #{name}"
        p @tag_stack
      end
      text = @text_stack.pop
      tags = @tag_stack.pop
      pr = @proc_stack.pop
      pr.call(text, tags) unless pr.nil?
      @ns_stack.pop
    end


text (RSS::ListenerMixin)

# File lib/rss/parser.rb, line 334
    def text(data)
      @text_stack.last << data
    end


append_features (RSS::Maker::Base)

# File lib/rss/maker/base.rb, line 10
      def self.append_features(klass)
        super

        klass.module_eval("\nOTHER_ELEMENTS = []\nNEED_INITIALIZE_VARIABLES = []\n\ndef self.inherited(subclass)\nsubclass.const_set(\"OTHER_ELEMENTS\", [])\nsubclass.const_set(\"NEED_INITIALIZE_VARIABLES\", [])\n\nsubclass.module_eval(<<-EOEOC, __FILE__, __LINE__)\ndef self.other_elements\nOTHER_ELEMENTS + super\nend\n\ndef self.need_initialize_variables\nNEED_INITIALIZE_VARIABLES + super\nend\nEOEOC\nend\n\ndef self.add_other_element(variable_name)\nOTHER_ELEMENTS << variable_name\nend\n\ndef self.other_elements\nOTHER_ELEMENTS\nend\n\ndef self.add_need_initialize_variable(variable_name, init_value=\"nil\")\nNEED_INITIALIZE_VARIABLES << [variable_name, init_value]\nend\n\ndef self.need_initialize_variables\nNEED_INITIALIZE_VARIABLES\nend\n\ndef self.def_array_element(name)\ninclude Enumerable\nextend Forwardable\n\ndef_delegators(\"@\\\#{name}\", :<<, :[], :[]=, :first, :last)\ndef_delegators(\"@\\\#{name}\", :push, :pop, :shift, :unshift)\ndef_delegators(\"@\\\#{name}\", :each, :size)\n\nadd_need_initialize_variable(name, \"[]\")\nend\n", __FILE__, __LINE__)
      end


new (RSS::Maker::Base)

# File lib/rss/maker/base.rb, line 63
      def initialize(maker)
        @maker = maker
        initialize_variables
      end


have_required_values? (RSS::Maker::Base)

# File lib/rss/maker/base.rb, line 68
      def have_required_values?
        true
      end


new_category (RSS::Maker::ChannelBase::CategoriesBase)

# File lib/rss/maker/base.rb, line 371
        def new_category
          category = self.class::Category.new(@maker)
          @categories << category
          if block_given?
            yield category
          else
            category
          end
        end


current_element (RSS::Maker::ChannelBase::CloudBase)

# File lib/rss/maker/base.rb, line 360
        def current_element(rss)
          rss.channel.cloud
        end


current_element (RSS::Maker::ChannelBase::SkipDaysBase::DayBase)

# File lib/rss/maker/base.rb, line 311
          def current_element(rss)
            rss.channel.skipDays.last
          end


new_day (RSS::Maker::ChannelBase::SkipDaysBase)

# File lib/rss/maker/base.rb, line 289
        def new_day
          day = self.class::Day.new(@maker)
          @days << day
          if block_given?
            yield day
          else
            day
          end
        end


current_element (RSS::Maker::ChannelBase::SkipDaysBase)

# File lib/rss/maker/base.rb, line 299
        def current_element(rss)
          rss.channel.skipDays
        end


current_element (RSS::Maker::ChannelBase::SkipHoursBase::HourBase)

# File lib/rss/maker/base.rb, line 345
          def current_element(rss)
            rss.channel.skipHours.last
          end


new_hour (RSS::Maker::ChannelBase::SkipHoursBase)

# File lib/rss/maker/base.rb, line 323
        def new_hour
          hour = self.class::Hour.new(@maker)
          @hours << hour
          if block_given?
            yield hour
          else
            hour
          end
        end


current_element (RSS::Maker::ChannelBase::SkipHoursBase)

# File lib/rss/maker/base.rb, line 333
        def current_element(rss)
          rss.channel.skipHours
        end


current_element (RSS::Maker::ChannelBase)

# File lib/rss/maker/base.rb, line 280
      def current_element(rss)
        rss.channel
      end


append_features (RSS::Maker::ContentModel)

# File lib/rss/maker/content.rb, line 7
      def self.append_features(klass)
        super

        ::RSS::ContentModel::ELEMENTS.each do |element|
          klass.add_need_initialize_variable(element)
          klass.add_other_element(element)
          klass.module_eval("attr_accessor :\#{element}\ndef setup_\#{element}(rss, current)\nif \#{element} and current.respond_to?(:\#{element}=)\ncurrent.\#{element} = @\#{element} if @\#{element}\nend\nend\n", __FILE__, __LINE__+1)
        end
      end


append_features (RSS::Maker::DublinCoreModel)

# File lib/rss/maker/dublincore.rb, line 7
      def self.append_features(klass)
        super

        ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
          plural_name ||= "#{name}s"
          full_name = "#{RSS::DC_PREFIX}_#{name}"
          full_plural_name = "#{RSS::DC_PREFIX}_#{plural_name}"
          klass_name = Utils.to_class_name(name)
          plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
          full_plural_klass_name = "self.class::#{plural_klass_name}"
          full_klass_name = "#{full_plural_klass_name}::#{klass_name}"
          klass.add_need_initialize_variable(full_plural_name,
                                             "make_#{full_plural_name}")
          klass.add_other_element(full_plural_name)
          klass.module_eval("attr_accessor :\#{full_plural_name}\ndef make_\#{full_plural_name}\n\#{full_plural_klass_name}.new(@maker)\nend\n\ndef setup_\#{full_plural_name}(rss, current)\n@\#{full_plural_name}.to_rss(rss, current)\nend\n\ndef \#{full_name}\n@\#{full_plural_name}[0] and @\#{full_plural_name}[0].value\nend\n\ndef \#{full_name}=(new_value)\n@\#{full_plural_name}[0] = \#{full_klass_name}.new(self)\n@\#{full_plural_name}[0].value = new_value\nend\n", __FILE__, __LINE__+1)
        end
      end


install_dublin_core (RSS::Maker::DublinCoreModel)

# File lib/rss/maker/dublincore.rb, line 87
      def self.install_dublin_core(klass)
        ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
          plural_name ||= "#{name}s"
          klass_name = Utils.to_class_name(name)
          plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
          full_klass_name = "DublinCore#{klass_name}"
          klass.module_eval("class \#{plural_klass_name} < \#{plural_klass_name}Base\nclass \#{klass_name} < \#{klass_name}Base\ndef to_rss(rss, current)\nif value and current.respond_to?(:dc_\#{name})\nnew_item = current.class::\#{full_klass_name}.new(value)\ncurrent.dc_\#{plural_name} << new_item\nend\nend\nend\nend\n", *Utils.get_file_and_line_from_caller(1))
        end
      end


link (RSS::Maker::ImageBase)

# File lib/rss/maker/base.rb, line 400
      def link
        @maker.channel.link
      end


current_element (RSS::Maker::ImageBase)

# File lib/rss/maker/base.rb, line 404
      def current_element(rss)
        rss.image
      end


have_required_values? (RSS::Maker::ImageFaviconModel::ImageFaviconBase)

# File lib/rss/maker/image.rb, line 81
        def have_required_values?
          @about and @image_size
        end


append_features (RSS::Maker::ImageFaviconModel)

# File lib/rss/maker/image.rb, line 50
      def self.append_features(klass)
        super

        name = "#{RSS::IMAGE_PREFIX}_favicon"
        klass.add_need_initialize_variable(name, "make_#{name}")
        klass.add_other_element(name)
        klass.module_eval("attr_reader :\#{name}\ndef setup_\#{name}(rss, current)\nif @\#{name}\n@\#{name}.to_rss(rss, current)\nend\nend\n\ndef make_\#{name}\nself.class::\#{Utils.to_class_name(name)}.new(@maker)\nend\n", __FILE__, __LINE__+1)
      end


have_required_values? (RSS::Maker::ImageItemModel::ImageItemBase)

# File lib/rss/maker/image.rb, line 43
        def have_required_values?
          @about
        end


append_features (RSS::Maker::ImageItemModel)

# File lib/rss/maker/image.rb, line 8
      def self.append_features(klass)
        super

        name = "#{RSS::IMAGE_PREFIX}_item"
        klass.add_need_initialize_variable(name, "make_#{name}")
        klass.add_other_element(name)
        klass.module_eval("attr_reader :\#{name}\ndef setup_\#{name}(rss, current)\nif @\#{name}\n@\#{name}.to_rss(rss, current)\nend\nend\n\ndef make_\#{name}\nself.class::\#{Utils.to_class_name(name)}.new(@maker)\nend\n", __FILE__, __LINE__+1)
      end


<=> (RSS::Maker::ItemsBase::ItemBase)

# File lib/rss/maker/base.rb, line 487
        def <=>(other)
          if date and other.date
            date <=> other.date
          elsif date
            1
          elsif other.date
            -1
          else
            0
          end
        end


current_element (RSS::Maker::ItemsBase::ItemBase)

# File lib/rss/maker/base.rb, line 499
        def current_element(rss)
          rss.items.last
        end


new (RSS::Maker::ItemsBase)

# File lib/rss/maker/base.rb, line 416
      def initialize(maker)
        super
        @do_sort = false
        @max_size = -1
      end


normalize (RSS::Maker::ItemsBase)

# File lib/rss/maker/base.rb, line 422
      def normalize
        if @max_size >= 0
          sort_if_need[0...@max_size]
        else
          sort_if_need[0..@max_size]
        end
      end


current_element (RSS::Maker::ItemsBase)

# File lib/rss/maker/base.rb, line 430
      def current_element(rss)
        rss.items
      end


new_item (RSS::Maker::ItemsBase)

# File lib/rss/maker/base.rb, line 434
      def new_item
        item = self.class::Item.new(@maker)
        @items << item
        if block_given?
          yield item
        else
          item
        end
      end


to_rss (RSS::Maker::RSS09::Channel::Categories)

# File lib/rss/maker/0.9.rb, line 129
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS09::Channel::Cloud)

# File lib/rss/maker/0.9.rb, line 124
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS09::Channel::ImageFavicon)

# File lib/rss/maker/image.rb, line 140
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS09::Channel::SkipDays::Day)

# File lib/rss/maker/0.9.rb, line 81
            def to_rss(rss, days)
              day = Rss::Channel::SkipDays::Day.new
              set = setup_values(day)
              if set
                days << day
                setup_other_elements(rss)
              end
            end


have_required_values? (RSS::Maker::RSS09::Channel::SkipDays::Day)

# File lib/rss/maker/0.9.rb, line 90
            def have_required_values?
              @content
            end


to_rss (RSS::Maker::RSS09::Channel::SkipDays)

# File lib/rss/maker/0.9.rb, line 70
          def to_rss(rss, channel)
            unless @days.empty?
              skipDays = Rss::Channel::SkipDays.new
              channel.skipDays = skipDays
              @days.each do |day|
                day.to_rss(rss, skipDays.days)
              end
            end
          end


to_rss (RSS::Maker::RSS09::Channel::SkipHours::Hour)

# File lib/rss/maker/0.9.rb, line 108
            def to_rss(rss, hours)
              hour = Rss::Channel::SkipHours::Hour.new
              set = setup_values(hour)
              if set
                hours << hour
                setup_other_elements(rss)
              end
            end


have_required_values? (RSS::Maker::RSS09::Channel::SkipHours::Hour)

# File lib/rss/maker/0.9.rb, line 117
            def have_required_values?
              @content
            end


to_rss (RSS::Maker::RSS09::Channel::SkipHours)

# File lib/rss/maker/0.9.rb, line 97
          def to_rss(rss, channel)
            unless @hours.empty?
              skipHours = Rss::Channel::SkipHours.new
              channel.skipHours = skipHours
              @hours.each do |hour|
                hour.to_rss(rss, skipHours.hours)
              end
            end
          end


to_rss (RSS::Maker::RSS09::Channel)

# File lib/rss/maker/0.9.rb, line 25
        def to_rss(rss)
          channel = Rss::Channel.new
          set = setup_values(channel)
          if set
            rss.channel = channel
            setup_items(rss)
            setup_image(rss)
            setup_textinput(rss)
            setup_other_elements(rss)
            if rss.channel.image
              rss
            else
              nil
            end
          elsif variable_is_set?
            raise NotSetError.new("maker.channel", not_set_required_variables)
          end
        end


have_required_values? (RSS::Maker::RSS09::Channel)

# File lib/rss/maker/0.9.rb, line 44
        def have_required_values?
          @title and @link and @description and @language
        end


to_rss (RSS::Maker::RSS09::Image)

# File lib/rss/maker/0.9.rb, line 138
        def to_rss(rss)
          image = Rss::Channel::Image.new
          set = setup_values(image)
          if set
            image.link = link
            rss.channel.image = image
            setup_other_elements(rss)
          end
        end


have_required_values? (RSS::Maker::RSS09::Image)

# File lib/rss/maker/0.9.rb, line 148
        def have_required_values?
          @url and @title and link
        end


to_rss (RSS::Maker::RSS09::Items::Item::Categories)

# File lib/rss/maker/0.9.rb, line 194
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS09::Items::Item::Enclosure)

# File lib/rss/maker/0.9.rb, line 184
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS09::Items::Item::Guid)

# File lib/rss/maker/0.9.rb, line 179
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS09::Items::Item::ImageItem)

# File lib/rss/maker/image.rb, line 131
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS09::Items::Item::Source)

# File lib/rss/maker/0.9.rb, line 189
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS09::Items::Item::TrackBackAbouts)

# File lib/rss/maker/trackback.rb, line 105
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS09::Items::Item)

# File lib/rss/maker/0.9.rb, line 164
          def to_rss(rss)
            item = Rss::Channel::Item.new
            set = setup_values(item)
            if set
              rss.items << item
              setup_other_elements(rss)
            end
          end


to_rss (RSS::Maker::RSS09::Items)

# File lib/rss/maker/0.9.rb, line 154
        def to_rss(rss)
          if rss.channel
            normalize.each do |item|
              item.to_rss(rss)
            end
            setup_other_elements(rss)
          end
        end


to_rss (RSS::Maker::RSS09::Textinput)

# File lib/rss/maker/0.9.rb, line 205
        def to_rss(rss)
          textInput = Rss::Channel::TextInput.new
          set = setup_values(textInput)
          if set
            rss.channel.textInput = textInput
            setup_other_elements(rss)
          end
        end


new (RSS::Maker::RSS09)

# File lib/rss/maker/0.9.rb, line 10
      def initialize(rss_version="0.91")
        super
      end


to_rss (RSS::Maker::RSS10::Channel::Categories)

# File lib/rss/maker/1.0.rb, line 101
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS10::Channel::Cloud)

# File lib/rss/maker/1.0.rb, line 96
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS10::Channel::ImageFavicon)

# File lib/rss/maker/image.rb, line 113
          def to_rss(rss, current)
            if @about and @image_size
              args = [@about, @image_size]
              favicon = ::RSS::ImageFaviconModel::ImageFavicon.new(*args)
              setup_values(favicon)
              setup_other_elements(favicon)
              current.image_favicon = favicon
            end
          end


to_rss (RSS::Maker::RSS10::Channel::SkipDays)

# File lib/rss/maker/1.0.rb, line 80
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS10::Channel::SkipHours)

# File lib/rss/maker/1.0.rb, line 88
          def to_rss(*args)
          end


to_rss (RSS::Maker::RSS10::Channel)

# File lib/rss/maker/1.0.rb, line 28
        def to_rss(rss)
          set = false
          if @about
            channel = RDF::Channel.new(@about)
            set = setup_values(channel)
            if set
              channel.dc_dates.clear
              rss.channel = channel
              setup_items(rss)
              setup_image(rss)
              setup_textinput(rss)
              setup_other_elements(rss)
            end
          end

          if (!@about or !set) and variable_is_set?
            raise NotSetError.new("maker.channel", not_set_required_variables)
          end
        end


have_required_values? (RSS::Maker::RSS10::Channel)

# File lib/rss/maker/1.0.rb, line 48
        def have_required_values?
          @about and @title and @link and @description
        end


to_rss (RSS::Maker::RSS10::Image)

# File lib/rss/maker/1.0.rb, line 110
        def to_rss(rss)
          if @url
            image = RDF::Image.new(@url)
            set = setup_values(image)
            if set
              rss.image = image
              setup_other_elements(rss)
            end
          end
        end


have_required_values? (RSS::Maker::RSS10::Image)

# File lib/rss/maker/1.0.rb, line 121
        def have_required_values?
          @url and @title and link and @maker.channel.have_required_values?
        end


to_rss (RSS::Maker::RSS10::Items::Item::Categories)

# File lib/rss/maker/1.0.rb, line 174
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS10::Items::Item::Enclosure)

# File lib/rss/maker/1.0.rb, line 164
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS10::Items::Item::Guid)

# File lib/rss/maker/1.0.rb, line 159
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS10::Items::Item::ImageItem)

# File lib/rss/maker/image.rb, line 98
            def to_rss(rss, current)
              if @about
                item = ::RSS::ImageItemModel::ImageItem.new(@about, @resource)
                setup_values(item)
                setup_other_elements(item)
                current.image_item = item
              end
            end


to_rss (RSS::Maker::RSS10::Items::Item::Source)

# File lib/rss/maker/1.0.rb, line 169
            def to_rss(*args)
            end


to_rss (RSS::Maker::RSS10::Items::Item::TrackBackAbouts::TrackBackAbout)

# File lib/rss/maker/trackback.rb, line 89
              def to_rss(rss, current)
                if resource
                  about = ::RSS::TrackBackModel10::TrackBackAbout.new(resource)
                  current.trackback_abouts << about
                end
              end


to_rss (RSS::Maker::RSS10::Items::Item)

# File lib/rss/maker/1.0.rb, line 142
          def to_rss(rss)
            if @link
              item = RDF::Item.new(@link)
              set = setup_values(item)
              if set
                item.dc_dates.clear
                rss.items << item
                setup_other_elements(rss)
              end
            end
          end


have_required_values? (RSS::Maker::RSS10::Items::Item)

# File lib/rss/maker/1.0.rb, line 154
          def have_required_values?
            @title and @link
          end


to_rss (RSS::Maker::RSS10::Items)

# File lib/rss/maker/1.0.rb, line 132
        def to_rss(rss)
          if rss.channel
            normalize.each do |item|
              item.to_rss(rss)
            end
            setup_other_elements(rss)
          end
        end


to_rss (RSS::Maker::RSS10::Textinput)

# File lib/rss/maker/1.0.rb, line 184
        def to_rss(rss)
          if @link
            textinput = RDF::Textinput.new(@link)
            set = setup_values(textinput)
            if set
              rss.textinput = textinput
              setup_other_elements(rss)
            end
          end
        end


have_required_values? (RSS::Maker::RSS10::Textinput)

# File lib/rss/maker/1.0.rb, line 195
        def have_required_values?
          @title and @description and @name and @link and
            @maker.channel.have_required_values?
        end


new (RSS::Maker::RSS10)

# File lib/rss/maker/1.0.rb, line 10
      def initialize
        super("1.0")
      end


to_rss (RSS::Maker::RSS20::Channel::Categories::Category)

# File lib/rss/maker/2.0.rb, line 58
            def to_rss(rss, channel)
              category = Rss::Channel::Category.new
              set = setup_values(category)
              if set
                channel.categories << category
                setup_other_elements(rss)
              end
            end


have_required_values? (RSS::Maker::RSS20::Channel::Categories::Category)

# File lib/rss/maker/2.0.rb, line 67
            def have_required_values?
              @content
            end


to_rss (RSS::Maker::RSS20::Channel::Categories)

# File lib/rss/maker/2.0.rb, line 51
          def to_rss(rss, channel)
            @categories.each do |category|
              category.to_rss(rss, channel)
            end
          end


to_rss (RSS::Maker::RSS20::Channel::Cloud)

# File lib/rss/maker/2.0.rb, line 35
          def to_rss(rss, channel)
            cloud = Rss::Channel::Cloud.new
            set = setup_values(cloud)
            if set
              channel.cloud = cloud
              setup_other_elements(rss)
            end
          end


have_required_values? (RSS::Maker::RSS20::Channel::Cloud)

# File lib/rss/maker/2.0.rb, line 44
          def have_required_values?
            @domain and @port and @path and
              @registerProcedure and @protocol
          end


have_required_values? (RSS::Maker::RSS20::Channel)

# File lib/rss/maker/2.0.rb, line 16
        def have_required_values?
          @title and @link and @description
        end


required_variable_names (RSS::Maker::RSS20::Channel)

# File lib/rss/maker/2.0.rb, line 20
        def required_variable_names
          %w(title link description)
        end


to_rss (RSS::Maker::RSS20::Items::Item::Categories::Category)

# File lib/rss/maker/2.0.rb, line 144
              def to_rss(rss, item)
                category = Rss::Channel::Item::Category.new
                set = setup_values(category)
                if set
                  item.categories << category
                  setup_other_elements(rss)
                end
              end


have_required_values? (RSS::Maker::RSS20::Items::Item::Categories::Category)

# File lib/rss/maker/2.0.rb, line 153
              def have_required_values?
                @content
              end


to_rss (RSS::Maker::RSS20::Items::Item::Categories)

# File lib/rss/maker/2.0.rb, line 137
            def to_rss(rss, item)
              @categories.each do |category|
                category.to_rss(rss, item)
              end
            end


to_rss (RSS::Maker::RSS20::Items::Item::Enclosure)

# File lib/rss/maker/2.0.rb, line 107
            def to_rss(rss, item)
              enclosure = Rss::Channel::Item::Enclosure.new
              set = setup_values(enclosure)
              if set
                item.enclosure = enclosure
                setup_other_elements(rss)
              end
            end


have_required_values? (RSS::Maker::RSS20::Items::Item::Enclosure)

# File lib/rss/maker/2.0.rb, line 116
            def have_required_values?
              @url and @length and @type
            end


to_rss (RSS::Maker::RSS20::Items::Item::Guid)

# File lib/rss/maker/2.0.rb, line 92
            def to_rss(rss, item)
              guid = Rss::Channel::Item::Guid.new
              set = setup_values(guid)
              if set
                item.guid = guid
                setup_other_elements(rss)
              end
            end


have_required_values? (RSS::Maker::RSS20::Items::Item::Guid)

# File lib/rss/maker/2.0.rb, line 101
            def have_required_values?
              @content
            end


to_rss (RSS::Maker::RSS20::Items::Item::Source)

# File lib/rss/maker/2.0.rb, line 122
            def to_rss(rss, item)
              source = Rss::Channel::Item::Source.new
              set = setup_values(source)
              if set
                item.source = source
                setup_other_elements(rss)
              end
            end


have_required_values? (RSS::Maker::RSS20::Items::Item::Source)

# File lib/rss/maker/2.0.rb, line 131
            def have_required_values?
              @url and @content
            end


to_rss (RSS::Maker::RSS20::Items::Item::TrackBackAbouts::TrackBackAbout)

# File lib/rss/maker/trackback.rb, line 119
              def to_rss(rss, current)
                if content
                  about = ::RSS::TrackBackModel20::TrackBackAbout.new(content)
                  current.trackback_abouts << about
                end
              end


have_required_values? (RSS::Maker::RSS20::Items::Item)

# File lib/rss/maker/2.0.rb, line 82
          def have_required_values?
            @title or @description
          end


new (RSS::Maker::RSS20)

# File lib/rss/maker/2.0.rb, line 10
      def initialize(rss_version="2.0")
        super
      end


make (RSS::Maker::RSSBase)

# File lib/rss/maker/base.rb, line 137
        def make(&block)
          new.make(&block)
        end


new (RSS::Maker::RSSBase)

# File lib/rss/maker/base.rb, line 161
      def initialize(rss_version)
        super(self)
        @rss_version = rss_version
        @version = "1.0"
        @encoding = "UTF-8"
        @standalone = nil
      end


make (RSS::Maker::RSSBase)

# File lib/rss/maker/base.rb, line 169
      def make
        if block_given?
          yield(self)
          to_rss
        else
          nil
        end
      end


to_rss (RSS::Maker::RSSBase)

# File lib/rss/maker/base.rb, line 178
      def to_rss
        rss = make_rss
        setup_xml_stylesheets(rss)
        setup_elements(rss)
        setup_other_elements(rss)
        if rss.channel
          rss
        else
          nil
        end
      end


append_features (RSS::Maker::SyndicationModel)

# File lib/rss/maker/syndication.rb, line 7
      def self.append_features(klass)
        super

        ::RSS::SyndicationModel::ELEMENTS.each do |element|
          klass.add_need_initialize_variable(element)
          klass.add_other_element(element)
          klass.module_eval("attr_accessor :\#{element}\ndef setup_\#{element}(rss, current)\nif \#{element} and current.respond_to?(:\#{element}=)\ncurrent.\#{element} = @\#{element} if @\#{element}\nend\nend\n", __FILE__, __LINE__+1)
        end
      end


have_required_values? (RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase::TaxonomyTopicBase)

# File lib/rss/maker/taxonomy.rb, line 137
          def have_required_values?
            @value
          end


new_taxo_topic (RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase)

# File lib/rss/maker/taxonomy.rb, line 111
        def new_taxo_topic
          taxo_topic = self.class::TaxonomyTopic.new(self)
          @taxo_topics << taxo_topic
          if block_given?
            yield taxo_topic
          else
            taxo_topic
          end
        end


to_rss (RSS::Maker::TaxonomyTopicModel::TaxonomyTopicsBase)

# File lib/rss/maker/taxonomy.rb, line 121
        def to_rss(rss, current)
          @taxo_topics.each do |taxo_topic|
            taxo_topic.to_rss(rss, current)
          end
        end


append_features (RSS::Maker::TaxonomyTopicModel)

# File lib/rss/maker/taxonomy.rb, line 53
      def self.append_features(klass)
        super

        klass.add_need_initialize_variable("taxo_topics", "make_taxo_topics")
        klass.add_other_element("taxo_topics")
        klass.module_eval("attr_reader :taxo_topics\ndef make_taxo_topics\nself.class::TaxonomyTopics.new(@maker)\nend\n\ndef setup_taxo_topics(rss, current)\n@taxo_topics.to_rss(rss, current)\nend\n\ndef taxo_topic\n@taxo_topics[0] and @taxo_topics[0].value\nend\n\ndef taxo_topic=(new_value)\n@taxo_topic[0] = self.class::TaxonomyTopic.new(self)\n@taxo_topic[0].value = new_value\nend\n", __FILE__, __LINE__ + 1)
      end


install_taxo_topic (RSS::Maker::TaxonomyTopicModel)

# File lib/rss/maker/taxonomy.rb, line 80
      def self.install_taxo_topic(klass)
        klass.module_eval("class TaxonomyTopics < TaxonomyTopicsBase\nclass TaxonomyTopic < TaxonomyTopicBase\nDublinCoreModel.install_dublin_core(self)\nTaxonomyTopicsModel.install_taxo_topics(self)\n\ndef to_rss(rss, current)\nif current.respond_to?(:taxo_topics)\ntopic = current.class::TaxonomyTopic.new(value)\ntopic.taxo_link = value\ntaxo_topics.to_rss(rss, topic) if taxo_topics\ncurrent.taxo_topics << topic\nsetup_other_elements(rss)\nend\nend\n\ndef current_element(rss)\nsuper.taxo_topics.last\nend\nend\nend\n", *Utils.get_file_and_line_from_caller(1))
      end


append_features (RSS::Maker::TaxonomyTopicsModel)

# File lib/rss/maker/taxonomy.rb, line 8
      def self.append_features(klass)
        super

        klass.add_need_initialize_variable("taxo_topics", "make_taxo_topics")
        klass.add_other_element("taxo_topics")
        klass.module_eval("attr_reader :taxo_topics\ndef make_taxo_topics\nself.class::TaxonomyTopics.new(@maker)\nend\n\ndef setup_taxo_topics(rss, current)\n@taxo_topics.to_rss(rss, current)\nend\n", __FILE__, __LINE__ + 1)
      end


install_taxo_topics (RSS::Maker::TaxonomyTopicsModel)

# File lib/rss/maker/taxonomy.rb, line 26
      def self.install_taxo_topics(klass)
        klass.module_eval("class TaxonomyTopics < TaxonomyTopicsBase\ndef to_rss(rss, current)\nif current.respond_to?(:taxo_topics)\ntopics = current.class::TaxonomyTopics.new\nbag = topics.Bag\n@resources.each do |resource|\nbag.lis << RDF::Bag::Li.new(resource)\nend\ncurrent.taxo_topics = topics\nend\nend\nend\n", *Utils.get_file_and_line_from_caller(1))
      end


current_element (RSS::Maker::TextinputBase)

# File lib/rss/maker/base.rb, line 543
      def current_element(rss)
        rss.textinput
      end


have_required_values? (RSS::Maker::TrackBackModel::TrackBackAboutsBase::TrackBackAboutBase)

# File lib/rss/maker/trackback.rb, line 72
          def have_required_values?
            @value
          end


new_about (RSS::Maker::TrackBackModel::TrackBackAboutsBase)

# File lib/rss/maker/trackback.rb, line 45
        def new_about
          about = self.class::TrackBackAbout.new(@maker)
          @abouts << about
          if block_given?
            yield about
          else
            about
          end
        end


to_rss (RSS::Maker::TrackBackModel::TrackBackAboutsBase)

# File lib/rss/maker/trackback.rb, line 55
        def to_rss(rss, current)
          @abouts.each do |about|
            about.to_rss(rss, current)
          end
        end


append_features (RSS::Maker::TrackBackModel)

# File lib/rss/maker/trackback.rb, line 8
      def self.append_features(klass)
        super

        name = "#{RSS::TRACKBACK_PREFIX}_ping"
        klass.add_need_initialize_variable(name)
        klass.add_other_element(name)
        klass.module_eval("attr_accessor :\#{name}\ndef setup_\#{name}(rss, current)\nif \#{name} and current.respond_to?(:\#{name}=)\ncurrent.\#{name} = \#{name}\nend\nend\n", __FILE__, __LINE__+1)

        name = "#{RSS::TRACKBACK_PREFIX}_abouts"
        klass.add_need_initialize_variable(name, "make_#{name}")
        klass.add_other_element(name)
        klass.module_eval("attr_accessor :\#{name}\ndef make_\#{name}\nself.class::TrackBackAbouts.new(self)\nend\n\ndef setup_\#{name}(rss, current)\n@\#{name}.to_rss(rss, current)\nend\n", __FILE__, __LINE__+1)
      end


to_rss (RSS::Maker::XMLStyleSheets::XMLStyleSheet)

# File lib/rss/maker/base.rb, line 227
        def to_rss(rss)
          xss = ::RSS::XMLStyleSheet.new
          guess_type_if_need(xss)
          set = setup_values(xss)
          if set
            rss.xml_stylesheets << xss
          end
        end


have_required_values? (RSS::Maker::XMLStyleSheets::XMLStyleSheet)

# File lib/rss/maker/base.rb, line 236
        def have_required_values?
          @href and @type
        end


to_rss (RSS::Maker::XMLStyleSheets)

# File lib/rss/maker/base.rb, line 203
      def to_rss(rss)
        @xml_stylesheets.each do |xss|
          xss.to_rss(rss)
        end
      end


new_xml_stylesheet (RSS::Maker::XMLStyleSheets)

# File lib/rss/maker/base.rb, line 209
      def new_xml_stylesheet
        xss = XMLStyleSheet.new(@maker)
        @xml_stylesheets << xss
        if block_given?
          yield xss
        else
          xss
        end
      end


make (RSS::Maker)

# File lib/rss/maker.rb, line 10
      def make(version, &block)
        maker(version).make(&block)
      end


maker (RSS::Maker)

# File lib/rss/maker.rb, line 14
      def maker(version)
        MAKERS[version]
      end


add_maker (RSS::Maker)

# File lib/rss/maker.rb, line 18
      def add_maker(version, maker)
        MAKERS[version] = maker
      end


filename_to_version (RSS::Maker)

# File lib/rss/maker.rb, line 22
      def filename_to_version(filename)
        File.basename(filename, ".*")
      end


new (RSS::MissingAttributeError)

# File lib/rss/rss.rb, line 75
    def initialize(tag, attribute)
      @tag, @attribute = tag, attribute
      super("attribute <#{attribute}> is missing in tag <#{tag}>")
    end


new (RSS::MissingTagError)

# File lib/rss/rss.rb, line 59
    def initialize(tag, parent)
      @tag, @parent = tag, parent
      super("tag <#{tag}> is missing in tag <#{parent}>")
    end


new (RSS::NotAvailableValueError)

# File lib/rss/rss.rb, line 101
    def initialize(tag, value, attribute=nil)
      @tag, @value, @attribute = tag, value, attribute
      message = "value <#{value}> of "
      message << "attribute <#{attribute}> of " if attribute
      message << "tag <#{tag}> is not available."
      super(message)
    end


new (RSS::NotExpectedTagError)

# File lib/rss/rss.rb, line 91
    def initialize(tag, uri, parent)
      @tag, @uri, @parent = tag, uri, parent
      super("tag <{#{uri}}#{tag}> is not expected in tag <#{parent}>")
    end


new (RSS::NotSetError)

# File lib/rss/rss.rb, line 133
    def initialize(name, variables)
      @name = name
      @variables = variables
      super("required variables of #{@name} are not set: #{@variables.join(', ')}")
    end


new (RSS::NotValidXMLParser)

# File lib/rss/parser.rb, line 34
    def initialize(parser)
      super("#{parser} is not an available XML parser. " <<
            "Available XML parser"<<
            (AVAILABLE_PARSERS.size > 1 ? "s are ": " is ") <<
            "#{AVAILABLE_PARSERS.inspect}.")
    end


new (RSS::NotWellFormedError)

# File lib/rss/parser.rb, line 14
    def initialize(line=nil, element=nil)
      message = "This is not well formed XML"
      if element or line
        message << "\nerror occurred"
        message << " in #{element}" if element
        message << " at about #{line} line" if line
      end
      message << "\n#{yield}" if block_given?
      super(message)
    end


new (RSS::NSError)

# File lib/rss/parser.rb, line 44
    def initialize(tag, prefix, require_uri)
      @tag, @prefix, @uri = tag, prefix, require_uri
      super("prefix <#{prefix}> doesn't associate uri " <<
            "<#{require_uri}> in tag <#{tag}>")
    end


new (RSS::OverlappedPrefixError)

# File lib/rss/rss.rb, line 50
    def initialize(prefix)
      @prefix = prefix
    end


default_parser (RSS::Parser)

# File lib/rss/parser.rb, line 59
      def default_parser
        @@default_parser || AVAILABLE_PARSERS.first
      end


default_parser= (RSS::Parser)

# File lib/rss/parser.rb, line 65
      def default_parser=(new_value)
        if AVAILABLE_PARSERS.include?(new_value)
          @@default_parser = new_value
        else
          raise NotValidXMLParser.new(new_value)
        end
      end


parse (RSS::Parser)

# File lib/rss/parser.rb, line 73
      def parse(rss, do_validate=true, ignore_unknown_element=true,
                parser_class=default_parser)
        parser = new(rss, parser_class)
        parser.do_validate = do_validate
        parser.ignore_unknown_element = ignore_unknown_element
        parser.parse
      end


new (RSS::Parser)

# File lib/rss/parser.rb, line 87
    def initialize(rss, parser_class=self.class.default_parser)
      @parser = parser_class.new(normalize_rss(rss))
    end


required_uri (RSS::RDF::Bag)

# File lib/rss/1.0.rb, line 132
        def required_uri
          URI
        end


new (RSS::RDF::Bag)

# File lib/rss/1.0.rb, line 142
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          @li = args[0] if args[0]
        end
      end


full_name (RSS::RDF::Bag)

# File lib/rss/1.0.rb, line 151
      def full_name
        tag_name_with_prefix(PREFIX)
      end


setup_maker (RSS::RDF::Bag)

# File lib/rss/1.0.rb, line 155
      def setup_maker(target)
        lis.each do |li|
          target << li.resource
        end
      end


required_uri (RSS::RDF::Channel::Image)

# File lib/rss/1.0.rb, line 216
          def required_uri
            ::RSS::URI
          end


new (RSS::RDF::Channel::Image)

# File lib/rss/1.0.rb, line 229
        def initialize(*args)
          if Utils.element_initialize_arguments?(args)
            super
          else
            super()
            self.resource = args[0]
          end
        end


required_uri (RSS::RDF::Channel::Items)

# File lib/rss/1.0.rb, line 276
          def required_uri
            ::RSS::URI
          end


new (RSS::RDF::Channel::Items)

# File lib/rss/1.0.rb, line 285
        def initialize(*args)
          if Utils.element_initialize_arguments?(args)
            super
          else
            super()
            self.Seq = args[0]
          end
          self.Seq ||= Seq.new
        end


resources (RSS::RDF::Channel::Items)

# File lib/rss/1.0.rb, line 295
        def resources
          if @Seq
            @Seq.lis.collect do |li|
              li.resource
            end
          else
            []
          end
        end


required_uri (RSS::RDF::Channel::Textinput)

# File lib/rss/1.0.rb, line 245
          def required_uri
            ::RSS::URI
          end


new (RSS::RDF::Channel::Textinput)

# File lib/rss/1.0.rb, line 258
        def initialize(*args)
          if Utils.element_initialize_arguments?(args)
            super
          else
            super()
            self.resource = args[0]
          end
        end


required_uri (RSS::RDF::Channel)

# File lib/rss/1.0.rb, line 168
        def required_uri
          ::RSS::URI
        end


new (RSS::RDF::Channel)

# File lib/rss/1.0.rb, line 192
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
        end
      end


required_uri (RSS::RDF::Image)

# File lib/rss/1.0.rb, line 313
        def required_uri
          ::RSS::URI
        end


new (RSS::RDF::Image)

# File lib/rss/1.0.rb, line 330
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
        end
      end


required_uri (RSS::RDF::Item)

# File lib/rss/1.0.rb, line 351
        def required_uri
          ::RSS::URI
        end


new (RSS::RDF::Item)

# File lib/rss/1.0.rb, line 373
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
        end
      end


required_uri (RSS::RDF::Li)

# File lib/rss/1.0.rb, line 63
        def required_uri
          URI
        end


new (RSS::RDF::Li)

# File lib/rss/1.0.rb, line 74
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.resource = args[0]
        end
      end


full_name (RSS::RDF::Li)

# File lib/rss/1.0.rb, line 83
      def full_name
        tag_name_with_prefix(PREFIX)
      end


required_uri (RSS::RDF::Seq)

# File lib/rss/1.0.rb, line 95
        def required_uri
          URI
        end


new (RSS::RDF::Seq)

# File lib/rss/1.0.rb, line 105
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          @li = args[0] if args[0]
        end
      end


full_name (RSS::RDF::Seq)

# File lib/rss/1.0.rb, line 114
      def full_name
        tag_name_with_prefix(PREFIX)
      end


setup_maker (RSS::RDF::Seq)

# File lib/rss/1.0.rb, line 118
      def setup_maker(target)
        lis.each do |li|
          target << li.resource
        end
      end


required_uri (RSS::RDF::Textinput)

# File lib/rss/1.0.rb, line 398
        def required_uri
          ::RSS::URI
        end


new (RSS::RDF::Textinput)

# File lib/rss/1.0.rb, line 415
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
        end
      end


required_uri (RSS::RDF)

# File lib/rss/1.0.rb, line 24
      def required_uri
        URI
      end


new (RSS::RDF)

# File lib/rss/1.0.rb, line 50
    def initialize(version=nil, encoding=nil, standalone=nil)
      super('1.0', version, encoding, standalone)
    end


full_name (RSS::RDF)

# File lib/rss/1.0.rb, line 54
    def full_name
      tag_name_with_prefix(PREFIX)
    end


listener= (RSS::REXMLLikeXMLParser)

# File lib/rss/xmlparser.rb, line 34
    def listener=(listener)
      @listener = listener
    end


startElement (RSS::REXMLLikeXMLParser)

# File lib/rss/xmlparser.rb, line 38
    def startElement(name, attrs)
      @listener.tag_start(name, attrs)
    end


endElement (RSS::REXMLLikeXMLParser)

# File lib/rss/xmlparser.rb, line 42
    def endElement(name)
      @listener.tag_end(name)
    end


character (RSS::REXMLLikeXMLParser)

# File lib/rss/xmlparser.rb, line 46
    def character(data)
      @listener.text(data)
    end


xmlDecl (RSS::REXMLLikeXMLParser)

# File lib/rss/xmlparser.rb, line 50
    def xmlDecl(version, encoding, standalone)
      @listener.xmldecl(version, encoding, standalone == 1)
    end


processingInstruction (RSS::REXMLLikeXMLParser)

# File lib/rss/xmlparser.rb, line 54
    def processingInstruction(target, content)
      @listener.instruction(target, content)
    end


raise_for_undefined_entity? (RSS::REXMLListener)

# File lib/rss/rexmlparser.rb, line 40
      def raise_for_undefined_entity?
        false
      end


xmldecl (RSS::REXMLListener)

# File lib/rss/rexmlparser.rb, line 45
    def xmldecl(version, encoding, standalone)
      super(version, encoding, standalone == "yes")
      # Encoding is converted to UTF-8 when REXML parse XML.
      @encoding = 'UTF-8'
    end


listener (RSS::REXMLParser)

# File lib/rss/rexmlparser.rb, line 14
      def listener
        REXMLListener
      end


new (RSS::RootElementMixin)

# File lib/rss/rss.rb, line 956
    def initialize(rss_version, version=nil, encoding=nil, standalone=nil)
      super()
      @rss_version = rss_version
      @version = version || '1.0'
      @encoding = encoding
      @standalone = standalone
      @output_encoding = nil
    end


output_encoding= (RSS::RootElementMixin)

# File lib/rss/rss.rb, line 965
    def output_encoding=(enc)
      @output_encoding = enc
      self.converter = Converter.new(@output_encoding, @encoding)
    end


setup_maker (RSS::RootElementMixin)

# File lib/rss/rss.rb, line 970
    def setup_maker(maker)
      maker.version = version
      maker.encoding = encoding
      maker.standalone = standalone

      xml_stylesheets.each do |xss|
        xss.setup_maker(maker)
      end

      setup_maker_elements(maker)
    end


to_xml (RSS::RootElementMixin)

# File lib/rss/rss.rb, line 982
    def to_xml(version=nil, &block)
      if version.nil? or version == @rss_version
        to_s
      else
        RSS::Maker.make(version) do |maker|
          setup_maker(maker)
          block.call(maker) if block
        end.to_s
      end
    end


new (RSS::Rss::Channel::Cloud)

# File lib/rss/0.9.rb, line 224
        def initialize(*args)
          if Utils.element_initialize_arguments?(args)
            super
          else
            super()
            self.domain = args[0]
            self.port = args[1]
            self.path = args[2]
            self.registerProcedure = args[3]
            self.protocol = args[4]
          end
        end


new (RSS::Rss::Channel::Image)

# File lib/rss/0.9.rb, line 190
        def initialize(*args)
          if Utils.element_initialize_arguments?(args)
            super
          else
            super()
            self.url = args[0]
            self.title = args[1]
            self.link = args[2]
            self.width = args[3]
            self.height = args[4]
            self.description = args[5]
          end
        end


new (RSS::Rss::Channel::Item::Category)

# File lib/rss/0.9.rb, line 348
          def initialize(*args)
            if Utils.element_initialize_arguments?(args)
              super
            else
              super()
              self.domain = args[0]
              self.content = args[1]
            end
          end


new (RSS::Rss::Channel::Item::Enclosure)

# File lib/rss/0.9.rb, line 313
          def initialize(*args)
            if Utils.element_initialize_arguments?(args)
              super
            else
              super()
              self.url = args[0]
              self.length = args[1]
              self.type = args[2]
            end
          end


new (RSS::Rss::Channel::Item::Guid)

# File lib/rss/2.0.rb, line 73
          def initialize(*args)
            if Utils.element_initialize_arguments?(args)
              super
            else
              super()
              self.isPermaLink = args[0]
              self.content = args[1]
            end
          end


PermaLink? (RSS::Rss::Channel::Item::Guid)

# File lib/rss/2.0.rb, line 85
          def PermaLink?
            perma = _PermaLink?
            perma or perma.nil?
          end


new (RSS::Rss::Channel::Item::Source)

# File lib/rss/0.9.rb, line 280
          def initialize(*args)
            if Utils.element_initialize_arguments?(args)
              super
            else
              super()
              self.url = args[0]
              self.content = args[1]
            end
          end


new (RSS::Rss::Channel::SkipDays::Day)

# File lib/rss/0.9.rb, line 136
          def initialize(*args)
            if Utils.element_initialize_arguments?(args)
              super
            else
              super()
              self.content = args[0]
            end
          end


new (RSS::Rss::Channel::SkipHours::Hour)

# File lib/rss/0.9.rb, line 163
          def initialize(*args)
            if Utils.element_initialize_arguments?(args)
              super
            else
              super()
              self.content = args[0]
            end
          end


new (RSS::Rss::Channel::TextInput)

# File lib/rss/0.9.rb, line 380
        def initialize(*args)
          if Utils.element_initialize_arguments?(args)
            super
          else
            super()
            self.title = args[0]
            self.description = args[1]
            self.name = args[2]
            self.link = args[3]
          end
        end


new (RSS::Rss)

# File lib/rss/0.9.rb, line 27
    def initialize(rss_version, version=nil, encoding=nil, standalone=nil)
      super
    end


items (RSS::Rss)

# File lib/rss/0.9.rb, line 31
    def items
      if @channel
        @channel.items
      else
        []
      end
    end


image (RSS::Rss)

# File lib/rss/0.9.rb, line 39
    def image
      if @channel
        @channel.image
      else
        nil
      end
    end


textinput (RSS::Rss)

# File lib/rss/0.9.rb, line 47
    def textinput
      if @channel
        @channel.textInput
      else
        nil
      end
    end


setup_maker_elements (RSS::Rss)

# File lib/rss/0.9.rb, line 55
    def setup_maker_elements(maker)
      super
      items.each do |item|
        item.setup_maker(maker.items)
      end
    end


append_features (RSS::RSS09)

# File lib/rss/0.9.rb, line 9
    def self.append_features(klass)
      super

      klass.install_must_call_validator('', "")
    end


append_features (RSS::RSS10)

# File lib/rss/1.0.rb, line 9
    def self.append_features(klass)
      super

      klass.install_must_call_validator('', ::RSS::URI)
    end


append_features (RSS::SyndicationModel)

# File lib/rss/syndication.rb, line 16
    def self.append_features(klass)
      super

      klass.install_must_call_validator(SY_PREFIX, SY_URI)
      klass.module_eval do
        [
          ["updatePeriod"],
          ["updateFrequency", :positive_integer]
        ].each do |name, type|
          install_text_element(name, SY_URI, "?",
                               "#{SY_PREFIX}_#{name}", type,
                               "#{SY_PREFIX}:#{name}")
        end

        %w(updateBase).each do |name|
          install_date_element(name, SY_URI, "?",
                               "#{SY_PREFIX}_#{name}", 'w3cdtf', name)
        end

        alias_method(:_sy_updatePeriod=, :sy_updatePeriod=)
        def sy_updatePeriod=(new_value)
          new_value = new_value.strip
          validate_sy_updatePeriod(new_value) if @do_validate
          self._sy_updatePeriod = new_value
        end
      end
    end


sy_updatePeriod= (RSS::SyndicationModel)

# File lib/rss/syndication.rb, line 36
        def sy_updatePeriod=(new_value)
          new_value = new_value.strip
          validate_sy_updatePeriod(new_value) if @do_validate
          self._sy_updatePeriod = new_value
        end


required_prefix (RSS::TaxonomyTopicModel::TaxonomyTopic)

# File lib/rss/taxonomy.rb, line 104
        def required_prefix
          TAXO_PREFIX
        end


required_uri (RSS::TaxonomyTopicModel::TaxonomyTopic)

# File lib/rss/taxonomy.rb, line 108
        def required_uri
          TAXO_URI
        end


new (RSS::TaxonomyTopicModel::TaxonomyTopic)

# File lib/rss/taxonomy.rb, line 119
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.about = args[0]
        end
      end


full_name (RSS::TaxonomyTopicModel::TaxonomyTopic)

# File lib/rss/taxonomy.rb, line 128
      def full_name
        tag_name_with_prefix(TAXO_PREFIX)
      end


maker_target (RSS::TaxonomyTopicModel::TaxonomyTopic)

# File lib/rss/taxonomy.rb, line 132
      def maker_target(target)
        target.new_taxo_topic
      end


append_features (RSS::TaxonomyTopicModel)

# File lib/rss/taxonomy.rb, line 91
    def self.append_features(klass)
      super
      var_name = "#{TAXO_PREFIX}_topic"
      klass.install_have_children_element("topic", TAXO_URI, "*", var_name)
    end


required_prefix (RSS::TaxonomyTopicsModel::TaxonomyTopics)

# File lib/rss/taxonomy.rb, line 44
        def required_prefix
          TAXO_PREFIX
        end


required_uri (RSS::TaxonomyTopicsModel::TaxonomyTopics)

# File lib/rss/taxonomy.rb, line 48
        def required_uri
          TAXO_URI
        end


new (RSS::TaxonomyTopicsModel::TaxonomyTopics)

# File lib/rss/taxonomy.rb, line 58
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.Bag = args[0]
        end
        self.Bag ||= Bag.new
      end


full_name (RSS::TaxonomyTopicsModel::TaxonomyTopics)

# File lib/rss/taxonomy.rb, line 68
      def full_name
        tag_name_with_prefix(TAXO_PREFIX)
      end


maker_target (RSS::TaxonomyTopicsModel::TaxonomyTopics)

# File lib/rss/taxonomy.rb, line 72
      def maker_target(target)
        target.taxo_topics
      end


resources (RSS::TaxonomyTopicsModel::TaxonomyTopics)

# File lib/rss/taxonomy.rb, line 76
      def resources
        if @Bag
          @Bag.lis.collect do |li|
            li.resource
          end
        else
          []
        end
      end


append_features (RSS::TaxonomyTopicsModel)

# File lib/rss/taxonomy.rb, line 28
    def self.append_features(klass)
      super

      klass.install_must_call_validator(TAXO_PREFIX, TAXO_URI)
      %w(topics).each do |name|
        klass.install_have_child_element(name, TAXO_URI, "?",
                                         "#{TAXO_PREFIX}_#{name}")
      end
    end


new (RSS::TooMuchTagError)

# File lib/rss/rss.rb, line 67
    def initialize(tag, parent)
      @tag, @parent = tag, parent
      super("tag <#{tag}> is too much in tag <#{parent}>")
    end


required_prefix (RSS::TrackBackModel10::TrackBackAbout)

# File lib/rss/trackback.rb, line 147
        def required_prefix
          TRACKBACK_PREFIX
        end


required_uri (RSS::TrackBackModel10::TrackBackAbout)

# File lib/rss/trackback.rb, line 151
        def required_uri
          TRACKBACK_URI
        end


new (RSS::TrackBackModel10::TrackBackAbout)

# File lib/rss/trackback.rb, line 169
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.resource = args[0]
        end
      end


full_name (RSS::TrackBackModel10::TrackBackAbout)

# File lib/rss/trackback.rb, line 178
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end


required_prefix (RSS::TrackBackModel10::TrackBackPing)

# File lib/rss/trackback.rb, line 107
        def required_prefix
          TRACKBACK_PREFIX
        end


required_uri (RSS::TrackBackModel10::TrackBackPing)

# File lib/rss/trackback.rb, line 111
        def required_uri
          TRACKBACK_URI
        end


new (RSS::TrackBackModel10::TrackBackPing)

# File lib/rss/trackback.rb, line 128
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.resource = args[0]
        end
      end


full_name (RSS::TrackBackModel10::TrackBackPing)

# File lib/rss/trackback.rb, line 137
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end


required_prefix (RSS::TrackBackModel20::TrackBackAbout)

# File lib/rss/trackback.rb, line 244
        def required_prefix
          TRACKBACK_PREFIX
        end


required_uri (RSS::TrackBackModel20::TrackBackAbout)

# File lib/rss/trackback.rb, line 248
        def required_uri
          TRACKBACK_URI
        end


new (RSS::TrackBackModel20::TrackBackAbout)

# File lib/rss/trackback.rb, line 257
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.content = args[0]
        end
      end


full_name (RSS::TrackBackModel20::TrackBackAbout)

# File lib/rss/trackback.rb, line 266
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end


required_prefix (RSS::TrackBackModel20::TrackBackPing)

# File lib/rss/trackback.rb, line 207
        def required_prefix
          TRACKBACK_PREFIX
        end


required_uri (RSS::TrackBackModel20::TrackBackPing)

# File lib/rss/trackback.rb, line 211
        def required_uri
          TRACKBACK_URI
        end


new (RSS::TrackBackModel20::TrackBackPing)

# File lib/rss/trackback.rb, line 220
      def initialize(*args)
        if Utils.element_initialize_arguments?(args)
          super
        else
          super()
          self.content = args[0]
        end
      end


full_name (RSS::TrackBackModel20::TrackBackPing)

# File lib/rss/trackback.rb, line 229
      def full_name
        tag_name_with_prefix(TRACKBACK_PREFIX)
      end


new (RSS::UnknownConversionMethodError)

# File lib/rss/rss.rb, line 112
    def initialize(to, from)
      @to = to
      @from = from
      super("can't convert to #{to} from #{from}.")
    end


new (RSS::UnknownTagError)

# File lib/rss/rss.rb, line 83
    def initialize(tag, uri)
      @tag, @uri = tag, uri
      super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>")
    end


to_class_name (RSS::Utils)

# File lib/rss/utils.rb, line 6
    def to_class_name(name)
      name.split(/_/).collect do |part|
        "#{part[0, 1].upcase}#{part[1..-1]}"
      end.join("")
    end


get_file_and_line_from_caller (RSS::Utils)

# File lib/rss/utils.rb, line 12
    def get_file_and_line_from_caller(i=0)
      file, line, = caller[i].split(':')
      [file, line.to_i]
    end


html_escape (RSS::Utils)

# File lib/rss/utils.rb, line 18
    def html_escape(s)
      s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
    end


new_with_value_if_need (RSS::Utils)

# File lib/rss/utils.rb, line 25
    def new_with_value_if_need(klass, value)
      if value.is_a?(klass)
        value
      else
        klass.new(value)
      end
    end


element_initialize_arguments? (RSS::Utils)

# File lib/rss/utils.rb, line 33
    def element_initialize_arguments?(args)
      [true, false].include?(args[0]) and args[1].is_a?(Hash)
    end


xmldecl (RSS::XMLParserListener)

# File lib/rss/xmlparser.rb, line 85
    def xmldecl(version, encoding, standalone)
      super
      # Encoding is converted to UTF-8 when XMLParser parses XML.
      @encoding = 'UTF-8'
    end


new (RSS::XMLParserNotFound)

# File lib/rss/parser.rb, line 27
    def initialize
      super("available XML parser was not found in " <<
            "#{AVAILABLE_PARSER_LIBRARIES.inspect}.")
    end


listener (RSS::XMLParserParser)

# File lib/rss/xmlparser.rb, line 63
      def listener
        XMLParserListener
      end


on_xmldecl_version (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 45
    def on_xmldecl_version(str)
      @version = str
    end


on_xmldecl_encoding (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 49
    def on_xmldecl_encoding(str)
      @encoding = str
    end


on_xmldecl_standalone (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 53
    def on_xmldecl_standalone(str)
      @standalone = str
    end


on_xmldecl_end (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 57
    def on_xmldecl_end
      xmldecl(@version, @encoding, @standalone == "yes")
    end


on_etag (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 65
    def on_etag(name)
      tag_end(name)
    end


on_entityref (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 69
    def on_entityref(ref)
      text(entity(ref))
    end


on_charref (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 73
    def on_charref(code)
      text([code].pack('U'))
    end


on_stag (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 79
    def on_stag(name)
      @attrs = {}
    end


on_attribute (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 83
    def on_attribute(name)
      @attrs[name] = @current_attr = ''
    end


on_attr_value (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 87
    def on_attr_value(str)
      @current_attr << str
    end


on_attr_entityref (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 91
    def on_attr_entityref(ref)
      @current_attr << entity(ref)
    end


on_attr_charref (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 95
    def on_attr_charref(code)
      @current_attr << [code].pack('U')
    end


on_stag_end (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 101
    def on_stag_end(name)
      tag_start(name, @attrs)
    end


on_stag_end_empty (RSS::XMLScanListener)

# File lib/rss/xmlscanner.rb, line 105
    def on_stag_end_empty(name)
      tag_start(name, @attrs)
      tag_end(name)
    end


listener (RSS::XMLScanParser)

# File lib/rss/xmlscanner.rb, line 9
      def listener
        XMLScanListener
      end


new (RSS::XMLStyleSheet)

# File lib/rss/xml-stylesheet.rb, line 37
    def initialize(*attrs)
      @do_validate = true
      ATTRIBUTES.each do |attr|
        __send__("#{attr}=", nil)
      end
      vars = ATTRIBUTES.dup
      vars.unshift(:do_validate)
      attrs.each do |name, value|
        if vars.include?(name.to_s)
          __send__("#{name}=", value)
        end
      end
    end


to_s (RSS::XMLStyleSheet)

# File lib/rss/xml-stylesheet.rb, line 51
    def to_s
      rv = ""
      if @href
        rv << %Q[<?xml-stylesheet]
        ATTRIBUTES.each do |name|
          if __send__(name)
            rv << %Q[ #{name}="#{h __send__(name)}"]
          end
        end
        rv << %Q[?>]
      end
      rv
    end


href= (RSS::XMLStyleSheet)

# File lib/rss/xml-stylesheet.rb, line 66
    def href=(value)
      @href = value
      if @href and @type.nil?
        @type = guess_type(@href)
      end
      @href
    end


alternate= (RSS::XMLStyleSheet)

# File lib/rss/xml-stylesheet.rb, line 75
    def alternate=(value)
      if value.nil? or /\A(?:yes|no)\z/ =~ value
        @alternate = value
      else
        if @do_validate
          args = ["?xml-stylesheet?", %Q[alternate="#{value}"]]
          raise NotAvailableValueError.new(*args)
        end
      end
      @alternate
    end


setup_maker (RSS::XMLStyleSheet)

# File lib/rss/xml-stylesheet.rb, line 87
    def setup_maker(maker)
      xss = maker.xml_stylesheets.new_xml_stylesheet
      ATTRIBUTES.each do |attr|
        xss.__send__("#{attr}=", __send__(attr))
      end
    end


new (RSS::XMLStyleSheetMixin)

# File lib/rss/xml-stylesheet.rb, line 7
    def initialize(*args)
      super
      @xml_stylesheets = []
    end


new (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 348
    def initialize(content)
      if /\t/ =~ content
        tab_width = Options.instance.tab_width
        content = content.split(/\n/).map do |line|
          1 while line.gsub!(/\t+/) { ' ' * (tab_width*$&.length - $`.length % tab_width)}  && $~ #`
          line
        end .join("\n")
      end
      @content   = content
      @content << "\n" unless @content[-1,1] == "\n"
      @size      = @content.size
      @offset    = 0
      @hwm       = 0
      @line_num  = 1
      @read_back_offset = 0
      @last_newline = 0
      @newline_pending = false
    end


column (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 367
    def column
      @offset - @last_newline
    end


getc (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 371
    def getc
      return nil if @offset >= @size
      ch = @content[@offset, 1]

      @offset += 1
      @hwm = @offset if @hwm < @offset

      if @newline_pending
        @line_num += 1
        @last_newline = @offset - 1
        @newline_pending = false
      end

      if ch == "\n"
        @newline_pending = true
      end
      ch
    end


getc_already_read (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 390
    def getc_already_read
      getc
    end


ungetc (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 394
    def ungetc(ch)
      raise "unget past beginning of file" if @offset <= 0
      @offset -= 1
      if @content[@offset] == ?\n
        @newline_pending = false
      end
    end


get_read (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 402
    def get_read
      res = @content[@read_back_offset...@offset]
      @read_back_offset = @offset
      res
    end


peek (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 408
    def peek(at)
      pos = @offset + at
      if pos >= @size
        nil
      else
        @content[pos, 1]
      end
    end


peek_equal (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 417
    def peek_equal(str)
      @content[@offset, str.length] == str
    end


divert_read_from (RubyLex::BufferedReader)

# File lib/rdoc/parsers/parse_rb.rb, line 421
    def divert_read_from(reserve)
      @content[@offset, 0] = reserve
      @size      = @content.size
    end


debug? (RubyLex)

# File lib/irb/ruby-lex.rb, line 34
    def debug?
      @debug_level > 0
    end


new (RubyLex)

# File lib/irb/ruby-lex.rb, line 40
  def initialize
    lex_init
    set_input(STDIN)

    @seek = 0
    @exp_line_no = @line_no = 1
    @base_char_no = 0
    @char_no = 0
    @rests = []
    @readed = []
    @here_readed = []

    @indent = 0
    @indent_stack = []
    @lex_state = EXPR_BEG
    @space_seen = false
    @here_header = false

    @continue = false
    @line = ""

    @skip_space = false
    @readed_auto_clean_up = false
    @exception_on_syntax_error = true

    @prompt = nil
  end


set_input (RubyLex)

# File lib/irb/ruby-lex.rb, line 78
  def set_input(io, p = nil, &block)
    @io = io
    if p.respond_to?(:call)
      @input = p
    elsif block_given?
      @input = block
    else
      @input = Proc.new{@io.gets}
    end
  end


get_readed (RubyLex)

# File lib/irb/ruby-lex.rb, line 89
  def get_readed
    if idx = @readed.reverse.index("\n")
      @base_char_no = idx
    else
      @base_char_no += @readed.size
    end

    readed = @readed.join("")
    @readed = []
    readed
  end


getc (RubyLex)

# File lib/irb/ruby-lex.rb, line 101
  def getc
    while @rests.empty?
#      return nil unless buf_input
      @rests.push nil unless buf_input
    end
    c = @rests.shift
    if @here_header
      @here_readed.push c
    else
      @readed.push c
    end
    @seek += 1
    if c == "\n"
      @line_no += 1
      @char_no = 0
    else
      @char_no += 1
    end
    c
  end


gets (RubyLex)

# File lib/irb/ruby-lex.rb, line 122
  def gets
    l = ""
    while c = getc
      l.concat(c)
      break if c == "\n"
    end
    return nil if l == "" and c.nil?
    l
  end


eof? (RubyLex)

# File lib/irb/ruby-lex.rb, line 132
  def eof?
    @io.eof?
  end


getc_of_rests (RubyLex)

# File lib/irb/ruby-lex.rb, line 136
  def getc_of_rests
    if @rests.empty?
      nil
    else
      getc
    end
  end


ungetc (RubyLex)

# File lib/irb/ruby-lex.rb, line 144
  def ungetc(c = nil)
    if @here_readed.empty?
      c2 = @readed.pop
    else
      c2 = @here_readed.pop
    end
    c = c2 unless c
    @rests.unshift c #c =
      @seek -= 1
    if c == "\n"
      @line_no -= 1
      if idx = @readed.reverse.index("\n")
        @char_no = @readed.size - idx
      else
        @char_no = @base_char_no + @readed.size
      end
    else
      @char_no -= 1
    end
  end


peek_equal? (RubyLex)

# File lib/irb/ruby-lex.rb, line 165
  def peek_equal?(str)
    chrs = str.split(//)
    until @rests.size >= chrs.size
      return false unless buf_input
    end
    @rests[0, chrs.size] == chrs
  end


peek_match? (RubyLex)

# File lib/irb/ruby-lex.rb, line 173
  def peek_match?(regexp)
    while @rests.empty?
      return false unless buf_input
    end
    regexp =~ @rests.join("")
  end


peek (RubyLex)

# File lib/irb/ruby-lex.rb, line 180
  def peek(i = 0)
    while @rests.size <= i
      return nil unless buf_input
    end
    @rests[i]
  end


set_prompt (RubyLex)

# File lib/irb/ruby-lex.rb, line 196
  def set_prompt(p = nil, &block)
    p = block if block_given?
    if p.respond_to?(:call)
      @prompt = p
    else
      @prompt = Proc.new{print p}
    end
  end


prompt (RubyLex)

# File lib/irb/ruby-lex.rb, line 205
  def prompt
    if @prompt
      @prompt.call(@ltype, @indent, @continue, @line_no)
    end
  end


initialize_input (RubyLex)

# File lib/irb/ruby-lex.rb, line 211
  def initialize_input
    @ltype = nil
    @quoted = nil
    @indent = 0
    @indent_stack = []
    @lex_state = EXPR_BEG
    @space_seen = false
    @here_header = false

    @continue = false
    prompt

    @line = ""
    @exp_line_no = @line_no
  end


each_top_level_statement (RubyLex)

# File lib/irb/ruby-lex.rb, line 227
  def each_top_level_statement
    initialize_input
    catch(:TERM_INPUT) do
      loop do
        begin
          @continue = false
          prompt
          unless l = lex
            throw :TERM_INPUT if @line == ''
          else
            #p l
            @line.concat l
            if @ltype or @continue or @indent > 0
              next
            end
          end
          if @line != "\n"
            yield @line, @exp_line_no
          end
          break unless l
          @line = ''
          @exp_line_no = @line_no

          @indent = 0
          @indent_stack = []
          prompt
        rescue TerminateLineInput
          initialize_input
          prompt
          get_readed
        end
      end
    end
  end


lex (RubyLex)

# File lib/irb/ruby-lex.rb, line 262
  def lex
    until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
             !@continue or
             tk.nil?)
      #p tk
      #p @lex_state
      #p self
    end
    line = get_readed
    #      print self.inspect
    if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
      nil
    else
      line
    end
  end


token (RubyLex)

# File lib/irb/ruby-lex.rb, line 279
  def token
    #      require "tracer"
    #      Tracer.on
    @prev_seek = @seek
    @prev_line_no = @line_no
    @prev_char_no = @char_no
    begin
      begin
        tk = @OP.match(self)
        @space_seen = tk.kind_of?(TkSPACE)
      rescue SyntaxError
        raise if @exception_on_syntax_error
        tk = TkError.new(@seek, @line_no, @char_no)
      end
    end while @skip_space and tk.kind_of?(TkSPACE)
    if @readed_auto_clean_up
      get_readed
    end
    #      Tracer.off
    tk
  end


lex_init (RubyLex)

# File lib/irb/ruby-lex.rb, line 339
  def lex_init()
    @OP = IRB::SLex.new
    @OP.def_rules("\0", "\004", "\032") do |op, io|
      Token(TkEND_OF_SCRIPT)
    end

    @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io|
      @space_seen = true
      while getc =~ /[ \t\f\r\13]/; end
      ungetc
      Token(TkSPACE)
    end

    @OP.def_rule("#") do |op, io|
      identify_comment
    end

    @OP.def_rule("=begin",
                 proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do
      |op, io|
      @ltype = "="
      until getc == "\n"; end
      until peek_equal?("=end") && peek(4) =~ /\s/
        until getc == "\n"; end
      end
      gets
      @ltype = nil
      Token(TkRD_COMMENT)
    end

    @OP.def_rule("\n") do |op, io|
      print "\\n\n" if RubyLex.debug?
      case @lex_state
      when EXPR_BEG, EXPR_FNAME, EXPR_DOT
        @continue = true
      else
        @continue = false
        @lex_state = EXPR_BEG
        until (@indent_stack.empty? ||
               [TkLPAREN, TkLBRACK, TkLBRACE,
                 TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
          @indent_stack.pop
        end
      end
      @here_header = false
      @here_readed = []
      Token(TkNL)
    end

    @OP.def_rules("*", "**",
                  "=", "==", "===",
                  "=~", "<=>",
                  "<", "<=",
                  ">", ">=", ">>") do
      |op, io|
      case @lex_state
      when EXPR_FNAME, EXPR_DOT
        @lex_state = EXPR_ARG
      else
        @lex_state = EXPR_BEG
      end
      Token(op)
    end

    @OP.def_rules("!", "!=", "!~") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op)
    end

    @OP.def_rules("<<") do
      |op, io|
      tk = nil
      if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
          (@lex_state != EXPR_ARG || @space_seen)
        c = peek(0)
        if /\S/ =~ c && (/["'`]/ =~ c || /[\w_]/ =~ c || c == "-")
          tk = identify_here_document
        end
      end
      unless tk
        tk = Token(op)
        case @lex_state
        when EXPR_FNAME, EXPR_DOT
          @lex_state = EXPR_ARG
        else
          @lex_state = EXPR_BEG
        end
      end
      tk
    end

    @OP.def_rules("'", '"') do
      |op, io|
      identify_string(op)
    end

    @OP.def_rules("`") do
      |op, io|
      if @lex_state == EXPR_FNAME
        @lex_state = EXPR_END
        Token(op)
      else
        identify_string(op)
      end
    end

    @OP.def_rules('?') do
      |op, io|
      if @lex_state == EXPR_END
        @lex_state = EXPR_BEG
        Token(TkQUESTION)
      else
        ch = getc
        if @lex_state == EXPR_ARG && ch =~ /\s/
          ungetc
          @lex_state = EXPR_BEG;
          Token(TkQUESTION)
        else
          if (ch == '\\')
            read_escape
          end
          @lex_state = EXPR_END
          Token(TkINTEGER)
        end
      end
    end

    @OP.def_rules("&", "&&", "|", "||") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op)
    end

    @OP.def_rules("+=", "-=", "*=", "**=",
                  "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
      |op, io|
      @lex_state = EXPR_BEG
      op =~ /^(.*)=$/
      Token(TkOPASGN, $1)
    end

    @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do
      |op, io|
      @lex_state = EXPR_ARG
      Token(op)
    end

    @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do
      |op, io|
      @lex_state = EXPR_ARG
      Token(op)
    end

    @OP.def_rules("+", "-") do
      |op, io|
      catch(:RET) do
        if @lex_state == EXPR_ARG
          if @space_seen and peek(0) =~ /[0-9]/
            throw :RET, identify_number
          else
            @lex_state = EXPR_BEG
          end
        elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/
          throw :RET, identify_number
        else
          @lex_state = EXPR_BEG
        end
        Token(op)
      end
    end

    @OP.def_rule(".") do
      |op, io|
      @lex_state = EXPR_BEG
      if peek(0) =~ /[0-9]/
        ungetc
        identify_number
      else
        # for "obj.if" etc.
        @lex_state = EXPR_DOT
        Token(TkDOT)
      end
    end

    @OP.def_rules("..", "...") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op)
    end

    lex_int2
  end


lex_int2 (RubyLex)

# File lib/irb/ruby-lex.rb, line 533
  def lex_int2
    @OP.def_rules("]", "}", ")") do
      |op, io|
      @lex_state = EXPR_END
      @indent -= 1
      @indent_stack.pop
      Token(op)
    end

    @OP.def_rule(":") do
      |op, io|
      if @lex_state == EXPR_END || peek(0) =~ /\s/
        @lex_state = EXPR_BEG
        Token(TkCOLON)
      else
        @lex_state = EXPR_FNAME;
        Token(TkSYMBEG)
      end
    end

    @OP.def_rule("::") do
       |op, io|
#      p @lex_state.id2name, @space_seen
      if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
        @lex_state = EXPR_BEG
        Token(TkCOLON3)
      else
        @lex_state = EXPR_DOT
        Token(TkCOLON2)
      end
    end

    @OP.def_rule("/") do
      |op, io|
      if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
        identify_string(op)
      elsif peek(0) == '='
        getc
        @lex_state = EXPR_BEG
        Token(TkOPASGN, "/") #/)
      elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
        identify_string(op)
      else
        @lex_state = EXPR_BEG
        Token("/") #/)
      end
    end

    @OP.def_rules("^") do
      |op, io|
      @lex_state = EXPR_BEG
      Token("^")
    end

    #       @OP.def_rules("^=") do
    #   @lex_state = EXPR_BEG
    #   Token(OP_ASGN, :^)
    #       end

    @OP.def_rules(",") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op)
    end

    @OP.def_rules(";") do
      |op, io|
      @lex_state = EXPR_BEG
      until (@indent_stack.empty? ||
             [TkLPAREN, TkLBRACK, TkLBRACE,
               TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
        @indent_stack.pop
      end
      Token(op)
    end

    @OP.def_rule("~") do
      |op, io|
      @lex_state = EXPR_BEG
      Token("~")
    end

    @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do
      |op, io|
      @lex_state = EXPR_BEG
      Token("~")
    end

    @OP.def_rule("(") do
      |op, io|
      @indent += 1
      if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
        @lex_state = EXPR_BEG
        tk_c = TkfLPAREN
      else
        @lex_state = EXPR_BEG
        tk_c = TkLPAREN
      end
      @indent_stack.push tk_c
      tk = Token(tk_c)
    end

    @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do
      |op, io|
      @lex_state = EXPR_ARG
      Token("[]")
    end

    @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do
      |op, io|
      @lex_state = EXPR_ARG
      Token("[]=")
    end

    @OP.def_rule("[") do
      |op, io|
      @indent += 1
      if @lex_state == EXPR_FNAME
        tk_c = TkfLBRACK
      else
        if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
          tk_c = TkLBRACK
        elsif @lex_state == EXPR_ARG && @space_seen
          tk_c = TkLBRACK
        else
          tk_c = TkfLBRACK
        end
        @lex_state = EXPR_BEG
      end
      @indent_stack.push tk_c
      Token(tk_c)
    end

    @OP.def_rule("{") do
      |op, io|
      @indent += 1
      if @lex_state != EXPR_END && @lex_state != EXPR_ARG
        tk_c = TkLBRACE
      else
        tk_c = TkfLBRACE
      end
      @lex_state = EXPR_BEG
      @indent_stack.push tk_c
      Token(tk_c)
    end

    @OP.def_rule('\\') do
      |op, io|
      if getc == "\n"
        @space_seen = true
        @continue = true
        Token(TkSPACE)
      else
        ungetc
        Token("\\")
      end
    end

    @OP.def_rule('%') do
      |op, io|
      if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
        identify_quotation
      elsif peek(0) == '='
        getc
        Token(TkOPASGN, :%)
      elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
        identify_quotation
      else
        @lex_state = EXPR_BEG
        Token("%") #))
      end
    end

    @OP.def_rule('$') do
      |op, io|
      identify_gvar
    end

    @OP.def_rule('@') do
      |op, io|
      if peek(0) =~ /[\w_@]/
        ungetc
        identify_identifier
      else
        Token("@")
      end
    end

    #       @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do
    #   |op, io|
    #   @indent += 1
    #   @lex_state = EXPR_FNAME
    # # @lex_state = EXPR_END
    # # until @rests[0] == "\n" or @rests[0] == ";"
    # #   rests.shift
    # # end
    #       end

    @OP.def_rule("") do
      |op, io|
      printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug?
      if peek(0) =~ /[0-9]/
        t = identify_number
      elsif peek(0) =~ /[\w_]/
        t = identify_identifier
      end
      printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug?
      t
    end

    p @OP if RubyLex.debug?
  end


identify_gvar (RubyLex)

# File lib/irb/ruby-lex.rb, line 746
  def identify_gvar
    @lex_state = EXPR_END

    case ch = getc
    when /[~_*$?!@\/\\;,=:<>".]/   #"
      Token(TkGVAR, "$" + ch)
    when "-"
      Token(TkGVAR, "$-" + getc)
    when "&", "`", "'", "+"
      Token(TkBACK_REF, "$"+ch)
    when /[1-9]/
      while getc =~ /[0-9]/; end
      ungetc
      Token(TkNTH_REF)
    when /\w/
      ungetc
      ungetc
      identify_identifier
    else
      ungetc
      Token("$")
    end
  end


identify_identifier (RubyLex)

# File lib/irb/ruby-lex.rb, line 770
  def identify_identifier
    token = ""
    if peek(0) =~ /[$@]/
      token.concat(c = getc)
      if c == "@" and peek(0) == "@"
        token.concat getc
      end
    end

    while (ch = getc) =~ /\w|_/
      print ":", ch, ":" if RubyLex.debug?
      token.concat ch
    end
    ungetc

    if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "="
      token.concat getc
    end

    # almost fix token

    case token
    when /^\$/
      return Token(TkGVAR, token)
    when /^\@\@/
      @lex_state = EXPR_END
      # p Token(TkCVAR, token)
      return Token(TkCVAR, token)
    when /^\@/
      @lex_state = EXPR_END
      return Token(TkIVAR, token)
    end

    if @lex_state != EXPR_DOT
      print token, "\n" if RubyLex.debug?

      token_c, *trans = TkReading2Token[token]
      if token_c
        # reserved word?

        if (@lex_state != EXPR_BEG &&
            @lex_state != EXPR_FNAME &&
            trans[1])
          # modifiers
          token_c = TkSymbol2Token[trans[1]]
          @lex_state = trans[0]
        else
          if @lex_state != EXPR_FNAME
            if ENINDENT_CLAUSE.include?(token)
              # check for ``class = val'' etc.
              valid = true
              case token
              when "class"
                valid = false unless peek_match?(/^\s*(<<|\w|::)/)
              when "def"
                valid = false if peek_match?(/^\s*(([+-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/)
              when "do"
                valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&)/)
              when *ENINDENT_CLAUSE
                valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&|\|)/)
              else
                # no nothing
              end
              if valid
                if token == "do"
                  if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last)
                    @indent += 1
                    @indent_stack.push token_c
                  end
                else
                  @indent += 1
                  @indent_stack.push token_c
                end
#               p @indent_stack
              end

            elsif DEINDENT_CLAUSE.include?(token)
              @indent -= 1
              @indent_stack.pop
            end
            @lex_state = trans[0]
          else
            @lex_state = EXPR_END
          end
        end
        return Token(token_c, token)
      end
    end

    if @lex_state == EXPR_FNAME
      @lex_state = EXPR_END
      if peek(0) == '='
        token.concat getc
      end
    elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT
      @lex_state = EXPR_ARG
    else
      @lex_state = EXPR_END
    end

    if token[0, 1] =~ /[A-Z]/
      return Token(TkCONSTANT, token)
    elsif token[token.size - 1, 1] =~ /[!?]/
      return Token(TkFID, token)
    else
      return Token(TkIDENTIFIER, token)
    end
  end


identify_here_document (RubyLex)

# File lib/irb/ruby-lex.rb, line 879
  def identify_here_document
    ch = getc
#    if lt = PERCENT_LTYPE[ch]
    if ch == "-"
      ch = getc
      indent = true
    end
    if /['"`]/ =~ ch
      lt = ch
      quoted = ""
      while (c = getc) && c != lt
        quoted.concat c
      end
    else
      lt = '"'
      quoted = ch.dup
      while (c = getc) && c =~ /\w/
        quoted.concat c
      end
      ungetc
    end

    ltback, @ltype = @ltype, lt
    reserve = []
    while ch = getc
      reserve.push ch
      if ch == "\\"
        reserve.push ch = getc
      elsif ch == "\n"
        break
      end
    end

    @here_header = false
    while l = gets
      l = l.sub(/(:?\r)?\n\z/, '')
      if (indent ? l.strip : l) == quoted
        break
      end
    end

    @here_header = true
    @here_readed.concat reserve
    while ch = reserve.pop
      ungetc ch
    end

    @ltype = ltback
    @lex_state = EXPR_END
    Token(Ltype2Token[lt])
  end


identify_quotation (RubyLex)

# File lib/irb/ruby-lex.rb, line 931
  def identify_quotation
    ch = getc
    if lt = PERCENT_LTYPE[ch]
      ch = getc
    elsif ch =~ /\W/
      lt = "\""
    else
      RubyLex.fail SyntaxError, "unknown type of %string"
    end
#     if ch !~ /\W/
#       ungetc
#       next
#     end
    #@ltype = lt
    @quoted = ch unless @quoted = PERCENT_PAREN[ch]
    identify_string(lt, @quoted)
  end


identify_number (RubyLex)

# File lib/irb/ruby-lex.rb, line 949
  def identify_number
    @lex_state = EXPR_END

    if peek(0) == "0" && peek(1) !~ /[.eE]/
      getc
      case peek(0)
      when /[xX]/
        ch = getc
        match = /[0-9a-fA-F_]/
      when /[bB]/
        ch = getc
        match = /[01_]/
      when /[oO]/
        ch = getc
        match = /[0-7_]/
      when /[dD]/
        ch = getc
        match = /[0-9_]/
      when /[0-7]/
        match = /[0-7_]/
      when /[89]/
        RubyLex.fail SyntaxError, "Illegal octal digit"
      else
        return Token(TkINTEGER)
      end

      len0 = true
      non_digit = false
      while ch = getc
        if match =~ ch
          if ch == "_"
            if non_digit
              RubyLex.fail SyntaxError, "trailing `#{ch}' in number"
            else
              non_digit = ch
            end
          else
            non_digit = false
            len0 = false
          end
        else
          ungetc
          if len0
            RubyLex.fail SyntaxError, "numeric literal without digits"
          end
          if non_digit
            RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
          end
          break
        end
      end
      return Token(TkINTEGER)
    end

    type = TkINTEGER
    allow_point = true
    allow_e = true
    non_digit = false
    while ch = getc
      case ch
      when /[0-9]/
        non_digit = false
      when "_"
        non_digit = ch
      when allow_point && "."
        if non_digit
          RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
        end
        type = TkFLOAT
        if peek(0) !~ /[0-9]/
          type = TkINTEGER
          ungetc
          break
        end
        allow_point = false
      when allow_e && "e", allow_e && "E"
        if non_digit
          RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
        end
        type = TkFLOAT
        if peek(0) =~ /[+-]/
          getc
        end
        allow_e = false
        allow_point = false
        non_digit = ch
      else
        if non_digit
          RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
        end
        ungetc
        break
      end
    end
    Token(type)
  end


identify_string (RubyLex)

# File lib/irb/ruby-lex.rb, line 1046
  def identify_string(ltype, quoted = ltype)
    @ltype = ltype
    @quoted = quoted
    subtype = nil
    begin
      nest = 0
      while ch = getc
        if @quoted == ch and nest == 0
          break
        elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#"
          subtype = true
        elsif ch == '\\' #'
          read_escape
        end
        if PERCENT_PAREN.values.include?(@quoted)
          if PERCENT_PAREN[ch] == @quoted
            nest += 1
          elsif ch == @quoted
            nest -= 1
          end
        end
      end
      if @ltype == "/"
        if peek(0) =~ /i|m|x|o|e|s|u|n/
          getc
        end
      end
      if subtype
        Token(DLtype2Token[ltype])
      else
        Token(Ltype2Token[ltype])
      end
    ensure
      @ltype = nil
      @quoted = nil
      @lex_state = EXPR_END
    end
  end


identify_comment (RubyLex)

# File lib/irb/ruby-lex.rb, line 1085
  def identify_comment
    @ltype = "#"

    while ch = getc
#      if ch == "\\" #"
#       read_escape
#      end
      if ch == "\n"
        @ltype = nil
        ungetc
        break
      end
    end
    return Token(TkCOMMENT)
  end


read_escape (RubyLex)

# File lib/irb/ruby-lex.rb, line 1101
  def read_escape
    case ch = getc
    when "\n", "\r", "\f"
    when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #"
    when /[0-7]/
      ungetc ch
      3.times do
        case ch = getc
        when /[0-7]/
        when nil
          break
        else
          ungetc
          break
        end
      end

    when "x"
      2.times do
        case ch = getc
        when /[0-9a-fA-F]/
        when nil
          break
        else
          ungetc
          break
        end
      end

    when "M"
      if (ch = getc) != '-'
        ungetc
      else
        if (ch = getc) == "\\" #"
          read_escape
        end
      end

    when "C", "c" #, "^"
      if ch == "C" and (ch = getc) != "-"
        ungetc
      elsif (ch = getc) == "\\" #"
        read_escape
      end
    else
      # other characters
    end
  end


debug? (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 443
  def RubyLex.debug?
    false
  end


new (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 447
  def initialize(content)
    lex_init

    @reader = BufferedReader.new(content)

    @exp_line_no = @line_no = 1
    @base_char_no = 0
    @indent = 0

    @ltype = nil
    @quoted = nil
    @lex_state = EXPR_BEG
    @space_seen = false

    @continue = false
    @line = ""

    @skip_space = false
    @read_auto_clean_up = false
    @exception_on_syntax_error = true
  end


line_no (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 476
  def line_no
    @reader.line_num
  end


char_no (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 480
  def char_no
    @reader.column
  end


get_read (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 484
  def get_read
    @reader.get_read
  end


getc (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 488
  def getc
    @reader.getc
  end


getc_of_rests (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 492
  def getc_of_rests
    @reader.getc_already_read
  end


gets (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 496
  def gets
    c = getc or return
    l = ""
    begin
      l.concat c unless c == "\r"
      break if c == "\n"
    end while c = getc
    l
  end


ungetc (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 507
  def ungetc(c = nil)
    @reader.ungetc(c)
  end


peek_equal? (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 511
  def peek_equal?(str)
    @reader.peek_equal(str)
  end


peek (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 515
  def peek(i = 0)
    @reader.peek(i)
  end


lex (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 519
  def lex
    until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
             !@continue or
             tk.nil?)
    end
    line = get_read

    if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
      nil
    else
      line
    end
  end


token (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 533
  def token
    set_token_position(line_no, char_no)
    begin
      begin
        tk = @OP.match(self)
        @space_seen = tk.kind_of?(TkSPACE)
      rescue SyntaxError
        abort if @exception_on_syntax_error
        tk = TkError.new(line_no, char_no)
      end
    end while @skip_space and tk.kind_of?(TkSPACE)
    if @read_auto_clean_up
      get_read
    end
#   throw :eof unless tk
    p tk if $DEBUG
    tk
  end


lex_init (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 589
  def lex_init()
    @OP = SLex.new
    @OP.def_rules("\0", "\004", "\032") do |chars, io|
      Token(TkEND_OF_SCRIPT).set_text(chars)
    end

    @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |chars, io|
      @space_seen = TRUE
      while (ch = getc) =~ /[ \t\f\r\13]/
        chars << ch
      end
      ungetc
      Token(TkSPACE).set_text(chars)
    end

    @OP.def_rule("#") do
      |op, io|
      identify_comment
    end

    @OP.def_rule("=begin", proc{@prev_char_no == 0 && peek(0) =~ /\s/}) do
      |op, io|
      str = op
      @ltype = "="

      begin
        line = ""
        begin
          ch = getc
          line << ch
        end until ch == "\n"
        str << line
      end until line =~ /^=end/

      ungetc

      @ltype = nil

      if str =~ /\A=begin\s+rdoc/i
        str.sub!(/\A=begin.*\n/, '')
        str.sub!(/^=end.*/m, '')
        Token(TkCOMMENT).set_text(str)
      else
        Token(TkRD_COMMENT)#.set_text(str)
      end
    end

    @OP.def_rule("\n") do
      print "\\n\n" if RubyLex.debug?
      case @lex_state
      when EXPR_BEG, EXPR_FNAME, EXPR_DOT
        @continue = TRUE
      else
        @continue = FALSE
        @lex_state = EXPR_BEG
      end
      Token(TkNL).set_text("\n")
    end

    @OP.def_rules("*", "**",
                  "!", "!=", "!~",
                  "=", "==", "===",
                  "=~", "<=>",
                  "<", "<=",
                  ">", ">=", ">>") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op).set_text(op)
    end

    @OP.def_rules("<<") do
      |op, io|
      tk = nil
      if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
          (@lex_state != EXPR_ARG || @space_seen)
        c = peek(0)
        if /[-\w_\"\'\`]/ =~ c
          tk = identify_here_document
        end
      end
      if !tk
        @lex_state = EXPR_BEG
        tk = Token(op).set_text(op)
      end
      tk
    end

    @OP.def_rules("'", '"') do
      |op, io|
      identify_string(op)
    end

    @OP.def_rules("`") do
      |op, io|
      if @lex_state == EXPR_FNAME
        Token(op).set_text(op)
      else
        identify_string(op)
      end
    end

    @OP.def_rules('?') do
      |op, io|
      if @lex_state == EXPR_END
        @lex_state = EXPR_BEG
        Token(TkQUESTION).set_text(op)
      else
        ch = getc
        if @lex_state == EXPR_ARG && ch !~ /\s/
          ungetc
          @lex_state = EXPR_BEG;
          Token(TkQUESTION).set_text(op)
        else
          str = op
          str << ch
          if (ch == '\\') #'
            str << read_escape
          end
          @lex_state = EXPR_END
          Token(TkINTEGER).set_text(str)
        end
      end
    end

    @OP.def_rules("&", "&&", "|", "||") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op).set_text(op)
    end

    @OP.def_rules("+=", "-=", "*=", "**=",
                  "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
      |op, io|
      @lex_state = EXPR_BEG
      op =~ /^(.*)=$/
      Token(TkOPASGN, $1).set_text(op)
    end

    @OP.def_rule("+@", proc{@lex_state == EXPR_FNAME}) do |op, io|
      Token(TkUPLUS).set_text(op)
    end

    @OP.def_rule("-@", proc{@lex_state == EXPR_FNAME}) do |op, io|
      Token(TkUMINUS).set_text(op)
    end

    @OP.def_rules("+", "-") do
      |op, io|
      catch(:RET) do
        if @lex_state == EXPR_ARG
          if @space_seen and peek(0) =~ /[0-9]/
            throw :RET, identify_number(op)
          else
            @lex_state = EXPR_BEG
          end
        elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/
          throw :RET, identify_number(op)
        else
          @lex_state = EXPR_BEG
        end
        Token(op).set_text(op)
      end
    end

    @OP.def_rule(".") do
      @lex_state = EXPR_BEG
      if peek(0) =~ /[0-9]/
        ungetc
        identify_number("")
      else
        # for obj.if
        @lex_state = EXPR_DOT
        Token(TkDOT).set_text(".")
      end
    end

    @OP.def_rules("..", "...") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op).set_text(op)
    end

    lex_int2
  end


lex_int2 (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 775
  def lex_int2
    @OP.def_rules("]", "}", ")") do
      |op, io|
      @lex_state = EXPR_END
      @indent -= 1
      Token(op).set_text(op)
    end

    @OP.def_rule(":") do
      if @lex_state == EXPR_END || peek(0) =~ /\s/
        @lex_state = EXPR_BEG
        tk = Token(TkCOLON)
      else
        @lex_state = EXPR_FNAME;
        tk = Token(TkSYMBEG)
      end
      tk.set_text(":")
    end

    @OP.def_rule("::") do
#      p @lex_state.id2name, @space_seen
      if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
        @lex_state = EXPR_BEG
        tk = Token(TkCOLON3)
      else
        @lex_state = EXPR_DOT
        tk = Token(TkCOLON2)
      end
      tk.set_text("::")
    end

    @OP.def_rule("/") do
      |op, io|
      if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
        identify_string(op)
      elsif peek(0) == '='
        getc
        @lex_state = EXPR_BEG
        Token(TkOPASGN, :/).set_text("/=") #")
      elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
        identify_string(op)
      else
        @lex_state = EXPR_BEG
        Token("/").set_text(op)
      end
    end

    @OP.def_rules("^") do
      @lex_state = EXPR_BEG
      Token("^").set_text("^")
    end

    #       @OP.def_rules("^=") do
    #   @lex_state = EXPR_BEG
    #   Token(TkOPASGN, :^)
    #       end

    @OP.def_rules(",", ";") do
      |op, io|
      @lex_state = EXPR_BEG
      Token(op).set_text(op)
    end

    @OP.def_rule("~") do
      @lex_state = EXPR_BEG
      Token("~").set_text("~")
    end

    @OP.def_rule("~@", proc{@lex_state = EXPR_FNAME}) do
      @lex_state = EXPR_BEG
      Token("~").set_text("~@")
    end

    @OP.def_rule("(") do
      @indent += 1
      if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
        @lex_state = EXPR_BEG
        tk = Token(TkfLPAREN)
      else
        @lex_state = EXPR_BEG
        tk = Token(TkLPAREN)
      end
      tk.set_text("(")
    end

    @OP.def_rule("[]", proc{@lex_state == EXPR_FNAME}) do
      Token("[]").set_text("[]")
    end

    @OP.def_rule("[]=", proc{@lex_state == EXPR_FNAME}) do
      Token("[]=").set_text("[]=")
    end

    @OP.def_rule("[") do
      @indent += 1
      if @lex_state == EXPR_FNAME
        t = Token(TkfLBRACK)
      else
        if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
          t = Token(TkLBRACK)
        elsif @lex_state == EXPR_ARG && @space_seen
          t = Token(TkLBRACK)
        else
          t = Token(TkfLBRACK)
        end
        @lex_state = EXPR_BEG
      end
      t.set_text("[")
    end

    @OP.def_rule("{") do
      @indent += 1
      if @lex_state != EXPR_END && @lex_state != EXPR_ARG
        t = Token(TkLBRACE)
      else
        t = Token(TkfLBRACE)
      end
      @lex_state = EXPR_BEG
      t.set_text("{")
    end

    @OP.def_rule('\\') do   #'
      if getc == "\n"
        @space_seen = true
        @continue = true
        Token(TkSPACE).set_text("\\\n")
      else
        ungetc
        Token("\\").set_text("\\")  #"
      end
    end

    @OP.def_rule('%') do
      |op, io|
      if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
        identify_quotation('%')
      elsif peek(0) == '='
        getc
        Token(TkOPASGN, "%").set_text("%=")
      elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
        identify_quotation('%')
      else
        @lex_state = EXPR_BEG
        Token("%").set_text("%")
      end
    end

    @OP.def_rule('$') do  #'
      identify_gvar
    end

    @OP.def_rule('@') do
      if peek(0) =~ /[@\w_]/
        ungetc
        identify_identifier
      else
        Token("@").set_text("@")
      end
    end

    #       @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do
    #   |op, io|
    #   @indent += 1
    #   @lex_state = EXPR_FNAME
    # # @lex_state = EXPR_END
    # # until @rests[0] == "\n" or @rests[0] == ";"
    # #   rests.shift
    # # end
    #       end

    @OP.def_rule("__END__", proc{@prev_char_no == 0 && peek(0) =~ /[\r\n]/}) do
      throw :eof
    end

    @OP.def_rule("") do
      |op, io|
      printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug?
      if peek(0) =~ /[0-9]/
        t = identify_number("")
      elsif peek(0) =~ /[\w_]/
        t = identify_identifier
      end
      printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug?
      t
    end

    p @OP if RubyLex.debug?
  end


identify_gvar (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 964
  def identify_gvar
    @lex_state = EXPR_END
    str = "$"

    tk = case ch = getc
         when /[~_*$?!@\/\\;,=:<>".]/   #"
           str << ch
           Token(TkGVAR, str)

         when "-"
           str << "-" << getc
           Token(TkGVAR, str)

         when "&", "`", "'", "+"
           str << ch
           Token(TkBACK_REF, str)

         when /[1-9]/
           str << ch
           while (ch = getc) =~ /[0-9]/
             str << ch
           end
           ungetc
           Token(TkNTH_REF)
         when /\w/
           ungetc
           ungetc
           return identify_identifier
         else
           ungetc
           Token("$")
         end
    tk.set_text(str)
  end


identify_identifier (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 999
  def identify_identifier
    token = ""
    token.concat getc if peek(0) =~ /[$@]/
    token.concat getc if peek(0) == "@"

    while (ch = getc) =~ /\w|_/
      print ":", ch, ":" if RubyLex.debug?
      token.concat ch
    end
    ungetc

    if ch == "!" or ch == "?"
      token.concat getc
    end
    # fix token

    # $stderr.puts "identifier - #{token}, state = #@lex_state"

    case token
    when /^\$/
      return Token(TkGVAR, token).set_text(token)
    when /^\@/
      @lex_state = EXPR_END
      return Token(TkIVAR, token).set_text(token)
    end

    if @lex_state != EXPR_DOT
      print token, "\n" if RubyLex.debug?

      token_c, *trans = TkReading2Token[token]
      if token_c
        # reserved word?

        if (@lex_state != EXPR_BEG &&
            @lex_state != EXPR_FNAME &&
            trans[1])
          # modifiers
          token_c = TkSymbol2Token[trans[1]]
          @lex_state = trans[0]
        else
          if @lex_state != EXPR_FNAME
            if ENINDENT_CLAUSE.include?(token)
              @indent += 1
            elsif DEINDENT_CLAUSE.include?(token)
              @indent -= 1
            end
            @lex_state = trans[0]
          else
            @lex_state = EXPR_END
          end
        end
        return Token(token_c, token).set_text(token)
      end
    end

    if @lex_state == EXPR_FNAME
      @lex_state = EXPR_END
      if peek(0) == '='
        token.concat getc
      end
    elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT
      @lex_state = EXPR_ARG
    else
      @lex_state = EXPR_END
    end

    if token[0, 1] =~ /[A-Z]/
      return Token(TkCONSTANT, token).set_text(token)
    elsif token[token.size - 1, 1] =~ /[!?]/
      return Token(TkFID, token).set_text(token)
    else
      return Token(TkIDENTIFIER, token).set_text(token)
    end
  end


identify_here_document (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1074
  def identify_here_document
    ch = getc
    if ch == "-"
      ch = getc
      indent = true
    end
    if /['"`]/ =~ ch            # '
      lt = ch
      quoted = ""
      while (c = getc) && c != lt
        quoted.concat c
      end
    else
      lt = '"'
      quoted = ch.dup
      while (c = getc) && c =~ /\w/
        quoted.concat c
      end
      ungetc
    end

    ltback, @ltype = @ltype, lt
    reserve = ""

    while ch = getc
      reserve << ch
      if ch == "\\"    #"
        ch = getc
        reserve << ch
      elsif ch == "\n"
        break
      end
    end

    str = ""
    while (l = gets)
      l.chomp!
      l.strip! if indent
      break if l == quoted
      str << l.chomp << "\n"
    end

    @reader.divert_read_from(reserve)

    @ltype = ltback
    @lex_state = EXPR_END
    Token(Ltype2Token[lt], str).set_text(str.dump)
  end


identify_quotation (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1123
  def identify_quotation(initial_char)
    ch = getc
    if lt = PERCENT_LTYPE[ch]
      initial_char += ch
      ch = getc
    elsif ch =~ /\W/
      lt = "\""
    else
      RubyLex.fail SyntaxError, "unknown type of %string ('#{ch}')"
    end
#     if ch !~ /\W/
#       ungetc
#       next
#     end
    #@ltype = lt
    @quoted = ch unless @quoted = PERCENT_PAREN[ch]
    identify_string(lt, @quoted, ch, initial_char)
  end


identify_number (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1142
  def identify_number(start)
    str = start.dup

    if start == "+" or start == "-" or start == ""
      start = getc
      str << start
    end

    @lex_state = EXPR_END

    if start == "0"
      if peek(0) == "x"
        ch = getc
        str << ch
        match = /[0-9a-f_]/
      else
        match = /[0-7_]/
      end
      while ch = getc
        if ch !~ match
          ungetc
          break
        else
          str << ch
        end
      end
      return Token(TkINTEGER).set_text(str)
    end

    type = TkINTEGER
    allow_point = TRUE
    allow_e = TRUE
    while ch = getc
      case ch
      when /[0-9_]/
        str << ch

      when allow_point && "."
        type = TkFLOAT
        if peek(0) !~ /[0-9]/
          ungetc
          break
        end
        str << ch
        allow_point = false

      when allow_e && "e", allow_e && "E"
        str << ch
        type = TkFLOAT
        if peek(0) =~ /[+-]/
          str << getc
        end
        allow_e = false
        allow_point = false
      else
        ungetc
        break
      end
    end
    Token(type).set_text(str)
  end


identify_string (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1204
  def identify_string(ltype, quoted = ltype, opener=nil, initial_char = nil)
    @ltype = ltype
    @quoted = quoted
    subtype = nil

    str = ""
    str << initial_char if initial_char
    str << (opener||quoted)

    nest = 0
    begin
      while ch = getc
        str << ch
        if @quoted == ch
          if nest == 0
            break
          else
            nest -= 1
          end
        elsif opener == ch
          nest += 1
        elsif @ltype != "'" && @ltype != "]" and ch == "#"
          ch = getc
          if ch == "{"
            subtype = true
            str << ch << skip_inner_expression
          else
            ungetc(ch)
          end
        elsif ch == '\\' #'
          str << read_escape
        end
      end
      if @ltype == "/"
        if peek(0) =~ /i|o|n|e|s/
          str << getc
        end
      end
      if subtype
        Token(DLtype2Token[ltype], str)
      else
        Token(Ltype2Token[ltype], str)
      end.set_text(str)
    ensure
      @ltype = nil
      @quoted = nil
      @lex_state = EXPR_END
    end
  end


skip_inner_expression (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1254
  def skip_inner_expression
    res = ""
    nest = 0
    while (ch = getc)
      res << ch
      if ch == '}'
        break if nest.zero?
        nest -= 1
      elsif ch == '{'
        nest += 1
      end
    end
    res
  end


identify_comment (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1269
  def identify_comment
    @ltype = "#"
    comment = "#"
    while ch = getc
      if ch == "\\"
        ch = getc
        if ch == "\n"
          ch = " "
        else
          comment << "\\"
        end
      else
        if ch == "\n"
          @ltype = nil
          ungetc
          break
        end
      end
      comment << ch
    end
    return Token(TkCOMMENT).set_text(comment)
  end


read_escape (RubyLex)

# File lib/rdoc/parsers/parse_rb.rb, line 1292
  def read_escape
    res = ""
    case ch = getc
    when /[0-7]/
      ungetc ch
      3.times do
        case ch = getc
        when /[0-7]/
        when nil
          break
        else
          ungetc
          break
        end
        res << ch
      end

    when "x"
      res << ch
      2.times do
        case ch = getc
        when /[0-9a-fA-F]/
        when nil
          break
        else
          ungetc
          break
        end
        res << ch
      end

    when "M"
      res << ch
      if (ch = getc) != '-'
        ungetc
      else
        res << ch
        if (ch = getc) == "\\" #"
          res << ch
          res << read_escape
        else
          res << ch
        end
      end

    when "C", "c" #, "^"
      res << ch
      if ch == "C" and (ch = getc) != "-"
        ungetc
      else
        res << ch
        if (ch = getc) == "\\" #"
          res << ch
          res << read_escape
        else
          res << ch
        end
      end
    else
      res << ch
    end
    res
  end


new (RubyToken::TkId)

# File lib/irb/ruby-token.rb, line 45
    def initialize(seek, line_no, char_no, name)
      super(seek, line_no, char_no)
      @name = name
    end


new (RubyToken::TkId)

# File lib/rdoc/parsers/parse_rb.rb, line 64
    def initialize(line_no, char_no, name)
      super(line_no, char_no)
      @name = name
    end


new (RubyToken::TkNode)

# File lib/irb/ruby-token.rb, line 38
    def initialize(seek, line_no, char_no)
      super
    end


name (RubyToken::TkOp)

# File lib/rdoc/parsers/parse_rb.rb, line 82
    def name
      self.class.op_name
    end


new (RubyToken::TkOPASGN)

# File lib/irb/ruby-token.rb, line 65
    def initialize(seek, line_no, char_no, op)
      super(seek, line_no, char_no)
      op = TkReading2Token[op][0] unless op.kind_of?(Symbol)
      @op = op
    end


new (RubyToken::TkOPASGN)

# File lib/rdoc/parsers/parse_rb.rb, line 88
    def initialize(line_no, char_no, op)
      super(line_no, char_no)
      op = TkReading2Token[op] unless op.kind_of?(Symbol)
      @op = op
    end


new (RubyToken::TkUnknownChar)

# File lib/irb/ruby-token.rb, line 74
    def initialize(seek, line_no, char_no, id)
      super(seek, line_no, char_no)
      @name = name
    end


new (RubyToken::TkUnknownChar)

# File lib/rdoc/parsers/parse_rb.rb, line 97
    def initialize(line_no, char_no, id)
      super(line_no, char_no)
      @name = char_no.chr
    end


new (RubyToken::TkVal)

# File lib/irb/ruby-token.rb, line 53
    def initialize(seek, line_no, char_no, value = nil)
      super(seek, line_no, char_no)
      @value = value
    end


new (RubyToken::TkVal)

# File lib/rdoc/parsers/parse_rb.rb, line 75
    def initialize(line_no, char_no, value = nil)
      super(line_no, char_no)
      set_text(value)
    end


new (RubyToken::Token)

# File lib/irb/ruby-token.rb, line 27
    def initialize(seek, line_no, char_no)
      @seek = seek
      @line_no = line_no
      @char_no = char_no
    end


new (RubyToken::Token)

# File lib/rdoc/parsers/parse_rb.rb, line 43
    def initialize(line_no, char_no)
      @line_no = line_no
      @char_no = char_no
      @text    = NO_TEXT
    end


set_text (RubyToken::Token)

# File lib/rdoc/parsers/parse_rb.rb, line 51
    def set_text(text)
      @text = text
      self
    end


Token (RubyToken)

# File lib/irb/ruby-token.rb, line 84
  def Token(token, value = nil)
    case token
    when String
      if (tk = TkReading2Token[token]).nil?
        IRB.fail TkReading2TokenNoKey, token
      end
      tk = Token(tk[0], value)
      if tk.kind_of?(TkOp)
        tk.name = token
      end
      return tk
    when Symbol
      if (tk = TkSymbol2Token[token]).nil?
        IRB.fail TkSymbol2TokenNoKey, token
      end
      return Token(tk[0], value)
    else
      if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty?
        token.new(@prev_seek, @prev_line_no, @prev_char_no)
      else
        token.new(@prev_seek, @prev_line_no, @prev_char_no, value)
      end
    end
  end


def_token (RubyToken)

# File lib/irb/ruby-token.rb, line 250
  def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts)
    token_n = token_n.id2name if token_n.kind_of?(Symbol)
    if RubyToken.const_defined?(token_n)
      IRB.fail AlreadyDefinedToken, token_n
    end
    token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}")

    if reading
      if TkReading2Token[reading]
        IRB.fail TkReading2TokenDuplicateError, token_n, reading
      end
      if opts.empty?
        TkReading2Token[reading] = [token_c]
      else
        TkReading2Token[reading] = [token_c].concat(opts)
      end
    end
    TkSymbol2Token[token_n.intern] = token_c
  end


set_token_position (RubyToken)

# File lib/rdoc/parsers/parse_rb.rb, line 107
  def set_token_position(line, char)
    @prev_line_no = line
    @prev_char_no = char
  end


Token (RubyToken)

# File lib/rdoc/parsers/parse_rb.rb, line 112
  def Token(token, value = nil)
    tk = nil
    case token
    when String, Symbol
      source = token.kind_of?(String) ? TkReading2Token : TkSymbol2Token
      if (tk = source[token]).nil?
        IRB.fail TkReading2TokenNoKey, token
      end
      tk = Token(tk[0], value)
    else
      tk = if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty?
             token.new(@prev_line_no, @prev_char_no)
           else
             token.new(@prev_line_no, @prev_char_no, value)
           end
    end
    tk
  end


def_token (RubyToken)

# File lib/rdoc/parsers/parse_rb.rb, line 270
  def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts)
    token_n = token_n.id2name unless token_n.kind_of?(String)
    if RubyToken.const_defined?(token_n)
      IRB.fail AlreadyDefinedToken, token_n
    end

    token_c =  Class.new super_token
    RubyToken.const_set token_n, token_c
#    token_c.inspect

    if reading
      if TkReading2Token[reading]
        IRB.fail TkReading2TokenDuplicateError, token_n, reading
      end
      if opts.empty?
        TkReading2Token[reading] = [token_c]
      else
        TkReading2Token[reading] = [token_c].concat(opts)
      end
    end
    TkSymbol2Token[token_n.intern] = token_c

    if token_c <= TkOp
      token_c.class_eval %{
        def self.op_name; "#{reading}"; end
      }
    end
  end


setup_assert (RUNIT::Assert)

# File lib/runit/assert.rb, line 12
    def setup_assert
    end


assert_no_exception (RUNIT::Assert)

# File lib/runit/assert.rb, line 15
    def assert_no_exception(*args, &block)
      assert_nothing_raised(*args, &block)
    end


assert_match (RUNIT::Assert)

# File lib/runit/assert.rb, line 23
    def assert_match(actual_string, expected_re, message="")
      _wrap_assertion {
        full_message = build_message(message, "Expected <?> to match <?>", actual_string, expected_re)
        assert_block(full_message) {
          expected_re =~ actual_string
        }
        Regexp.last_match
      }
    end


assert_not_nil (RUNIT::Assert)

# File lib/runit/assert.rb, line 33
    def assert_not_nil(actual, message="")
      assert(!actual.nil?, message)
    end


assert_not_match (RUNIT::Assert)

# File lib/runit/assert.rb, line 37
    def assert_not_match(actual_string, expected_re, message="")
      assert_no_match(expected_re, actual_string, message)
    end


assert_matches (RUNIT::Assert)

# File lib/runit/assert.rb, line 41
    def assert_matches(*args)
      assert_match(*args)
    end


assert_fail (RUNIT::Assert)

# File lib/runit/assert.rb, line 45
    def assert_fail(message="")
      flunk(message)
    end


assert_equal_float (RUNIT::Assert)

# File lib/runit/assert.rb, line 49
    def assert_equal_float(expected, actual, delta, message="")
      assert_in_delta(expected, actual, delta, message)
    end


assert_send (RUNIT::Assert)

# File lib/runit/assert.rb, line 53
    def assert_send(object, method, *args)
      super([object, method, *args])
    end


assert_exception (RUNIT::Assert)

# File lib/runit/assert.rb, line 57
    def assert_exception(exception, message="", &block)
      assert_raises(exception, message, &block)
    end


assert_respond_to (RUNIT::Assert)

# File lib/runit/assert.rb, line 61
    def assert_respond_to(method, object, message="")
      if (called_internally?)
        super
      else
        super(object, method, message)
      end
    end


called_internally? (RUNIT::Assert)

# File lib/runit/assert.rb, line 69
    def called_internally?
      /assertions\.rb/.match(caller[1])
    end


run (RUNIT::CUI::TestRunner)

# File lib/runit/cui/testrunner.rb, line 13
      def self.run(suite)
        self.new().run(suite)
      end


new (RUNIT::CUI::TestRunner)

# File lib/runit/cui/testrunner.rb, line 17
      def initialize
        super nil
      end


run (RUNIT::CUI::TestRunner)

# File lib/runit/cui/testrunner.rb, line 21
      def run(suite, quiet_mode=@@quiet_mode)
        @suite = suite
        def @suite.suite
          self
        end
        @output_level = (quiet_mode ? Test::Unit::UI::PROGRESS_ONLY : Test::Unit::UI::VERBOSE)
        start
      end


create_mediator (RUNIT::CUI::TestRunner)

# File lib/runit/cui/testrunner.rb, line 30
      def  create_mediatorcreate_mediator(suite)
        mediator = Test::Unit::UI::TestRunnerMediator.new(suite)
        class << mediator
          attr_writer :result_delegate
          def create_result
            return @result_delegate.create_result
          end
        end
        mediator.result_delegate = self
        return mediator
      end


create_result (RUNIT::CUI::TestRunner)

# File lib/runit/cui/testrunner.rb, line 42
      def create_result
        return RUNIT::TestResult.new
      end


quiet_mode= (RUNIT::CUI::TestRunner)

# File lib/runit/cui/testrunner.rb, line 46
      def self.quiet_mode=(boolean)
        @@quiet_mode = boolean
      end


suite (RUNIT::TestCase)

# File lib/runit/testcase.rb, line 15
    def self.suite
      method_names = instance_methods(true)
      tests = method_names.delete_if { |method_name| method_name !~ /^test/ }
      suite = TestSuite.new(name)
      tests.each {
        |test|
        catch(:invalid_test) {
          suite << new(test, name)
        }
      }
      return suite
    end


new (RUNIT::TestCase)

# File lib/runit/testcase.rb, line 28
    def initialize(test_name, suite_name=self.class.name)
      super(test_name)
    end


assert_equals (RUNIT::TestCase)

# File lib/runit/testcase.rb, line 32
    def assert_equals(*args)
      assert_equal(*args)
    end


name (RUNIT::TestCase)

# File lib/runit/testcase.rb, line 36
    def name
      super.sub(/^(.*?)\((.*)\)$/, '\2#\1')
    end


run (RUNIT::TestCase)

# File lib/runit/testcase.rb, line 40
    def run(result, &progress_block)
      progress_block = proc {} unless (block_given?)
      super(result, &progress_block)
    end


succeed? (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 10
    def succeed?
      return passed?
    end


failure_size (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 13
    def failure_size
      return failure_count
    end


run_asserts (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 16
    def run_asserts
      return assertion_count
    end


error_size (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 19
    def error_size
      return error_count
    end


run_tests (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 22
    def run_tests
      return run_count
    end


add_failure (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 25
    def add_failure(failure)
      def failure.at
        return location
      end
      def failure.err
        return message
      end
      super(failure)
    end


add_error (RUNIT::TestResult)

# File lib/runit/testresult.rb, line 34
    def   add_erroradd_erroradd_error(error)
      def error.at
        return location
      end
      def error.err
        return exception
      end
      super(error)
    end


add_test (RUNIT::TestSuite)

# File lib/runit/testsuite.rb, line 9
    def add_test(*args)
      add(*args)
    end


add (RUNIT::TestSuite)

# File lib/runit/testsuite.rb, line 13
    def add(*args)
      self.<<(*args)
    end


count_test_cases (RUNIT::TestSuite)

# File lib/runit/testsuite.rb, line 17
    def count_test_cases
      return size
    end


run (RUNIT::TestSuite)

# File lib/runit/testsuite.rb, line 21
    def run(result, &progress_block)
      progress_block = proc {} unless (block_given?)
      super(result, &progress_block)
    end


to_s (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 323
    def to_s
      @spec_string
    end


count_space? (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 327
    def count_space?
      /(?:\A|\S)%\*?\d*c|\[/.match(@spec_string)
    end


new (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 331
    def initialize(str)
      @spec_string = str
      h = '[A-Fa-f0-9]'

      @re_string, @handler =
        case @spec_string

          # %[[:...:]]
        when /%\*?(\[\[:[a-z]+:\]\])/
          [ "(#{$1}+)", :extract_plain ]

          # %5[[:...:]]
        when /%\*?(\d+)(\[\[:[a-z]+:\]\])/
          [ "(#{$2}{1,#{$1}})", :extract_plain ]

          # %[...]
        when /%\*?\[([^\]]*)\]/
          yes = $1
          if /^\^/.match(yes) then no = yes[1..-1] else no = '^' + yes end
          [ "([#{yes}]+)(?=[#{no}]|\\z)", :extract_plain ]

          # %5[...]
        when /%\*?(\d+)\[([^\]]*)\]/
          yes = $2
          w = $1
          [ "([#{yes}]{1,#{w}})", :extract_plain ]

          # %i
        when /%\*?i/
          [ "([-+]?(?:(?:0[0-7]+)|(?:0[Xx]#{h}+)|(?:[1-9]\\d+)))", :extract_integer ]

          # %5i
        when /%\*?(\d+)i/
          n = $1.to_i
          s = "("
          if n > 1 then s += "[1-9]\\d{1,#{n-1}}|" end
          if n > 1 then s += "0[0-7]{1,#{n-1}}|" end
          if n > 2 then s += "[-+]0[0-7]{1,#{n-2}}|" end
          if n > 2 then s += "[-+][1-9]\\d{1,#{n-2}}|" end
          if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end
          if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end
          s += "\\d"
          s += ")"
          [ s, :extract_integer ]

          # %d, %u
        when /%\*?[du]/
          [ '([-+]?\d+)', :extract_decimal ]

          # %5d, %5u
        when /%\*?(\d+)[du]/
          n = $1.to_i
          s = "("
          if n > 1 then s += "[-+]\\d{1,#{n-1}}|" end
          s += "\\d{1,#{$1}})"
          [ s, :extract_decimal ]

          # %x
        when /%\*?[Xx]/
          [ "([-+]?(?:0[Xx])?#{h}+)", :extract_hex ]

          # %5x
        when /%\*?(\d+)[Xx]/
          n = $1.to_i
          s = "("
          if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end
          if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end
          if n > 1 then s += "[-+]#{h}{1,#{n-1}}|" end
          s += "#{h}{1,#{n}}"
          s += ")"
          [ s, :extract_hex ]

          # %o
        when /%\*?o/
          [ '([-+]?[0-7]+)', :extract_octal ]

          # %5o
        when /%\*?(\d+)o/
          [ "([-+][0-7]{1,#{$1.to_i-1}}|[0-7]{1,#{$1}})", :extract_octal ]

          # %f
        when /%\*?f/
          [ '([-+]?((\d+(?>(?=[^\d.]|$)))|(\d*(\.(\d*([eE][-+]?\d+)?)))))', :extract_float ]

          # %5f
        when /%\*?(\d+)f/
          [ "(\\S{1,#{$1}})", :extract_float ]

          # %5s
        when /%\*?(\d+)s/
          [ "(\\S{1,#{$1}})", :extract_plain ]

          # %s
        when /%\*?s/
          [ '(\S+)', :extract_plain ]

          # %c
        when /\s%\*?c/
          [ "\\s*(.)", :extract_plain ]

          # %c
        when /%\*?c/
          [ "(.)", :extract_plain ]

          # %5c (whitespace issues are handled by the count_*_space? methods)
        when /%\*?(\d+)c/
          [ "(.{1,#{$1}})", :extract_plain ]

          # %%
        when /%%/
          [ '(\s*%)', :nil_proc ]

          # literal characters
        else
          [ "(#{Regexp.escape(@spec_string)})", :nil_proc ]
        end

      @re_string = '\A' + @re_string
    end


to_re (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 451
    def to_re
      Regexp.new(@re_string,Regexp::MULTILINE)
    end


match (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 455
    def match(str)
      @matched = false
      s = str.dup
      s.sub!(/\A\s+/,'') unless count_space?
      res = to_re.match(s)
      if res
        @conversion = send(@handler, res[1])
        @matched_string = @conversion.to_s
        @matched = true
      end
      res
    end


letter (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 468
    def letter
      /%\*?\d*([a-z\[])/.match(@spec_string).to_a[1]
    end


width (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 472
    def width
      w = /%\*?(\d+)/.match(@spec_string).to_a[1]
      w && w.to_i
    end


mid_match? (Scanf::FormatSpecifier)

# File lib/scanf.rb, line 477
    def mid_match?
      return false unless @matched
      cc_no_width    = letter == '[' &&! width
      c_or_cc_width  = (letter == 'c' || letter == '[') && width
      width_left     = c_or_cc_width && (matched_string.size < width)

      return width_left || cc_no_width
    end


new (Scanf::FormatString)

# File lib/scanf.rb, line 514
    def initialize(str)
      @specs = []
      @i = 1
      s = str.to_s
      return unless /\S/.match(s)
      @space = true if /\s\z/.match(s)
      @specs.replace s.scan(REGEX).map {|spec| FormatSpecifier.new(spec) }
    end


to_s (Scanf::FormatString)

# File lib/scanf.rb, line 523
    def to_s
      @specs.join('')
    end


prune (Scanf::FormatString)

# File lib/scanf.rb, line 527
    def prune(n=matched_count)
      n.times { @specs.shift }
    end


spec_count (Scanf::FormatString)

# File lib/scanf.rb, line 531
    def spec_count
      @specs.size
    end


last_spec (Scanf::FormatString)

# File lib/scanf.rb, line 535
    def last_spec
      @i == spec_count - 1
    end


match (Scanf::FormatString)

# File lib/scanf.rb, line 539
    def match(str)
      accum = []
      @string_left = str
      @matched_count = 0

      @specs.each_with_index do |spec,@i|
        @last_spec_tried = spec
        @last_match_tried = spec.match(@string_left)
        break unless @last_match_tried
        @matched_count += 1

        accum << spec.conversion

        @string_left = @last_match_tried.post_match
        break if @string_left.empty?
      end
      return accum.compact
    end


[] (Set)

# File lib/set.rb, line 55
  def self.[](*ary)
    new(ary)
  end


new (Set)

# File lib/set.rb, line 64
  def initialize(enum = nil, &block) # :yields: o
    @hash ||= Hash.new

    enum.nil? and return

    if block
      enum.each { |o| add(block[o]) }
    else
      merge(enum)
    end
  end


initialize_copy (Set)

# File lib/set.rb, line 77
  def initialize_copy(orig)
    @hash = orig.instance_eval{@hash}.dup
  end


size (Set)

# File lib/set.rb, line 82
  def size
    @hash.size
  end


empty? (Set)

# File lib/set.rb, line 88
  def empty?
    @hash.empty?
  end


clear (Set)

# File lib/set.rb, line 93
  def clear
    @hash.clear
    self
  end


replace (Set)

# File lib/set.rb, line 100
  def replace(enum)
    if enum.class == self.class
      @hash.replace(enum.instance_eval { @hash })
    else
      enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
      clear
      enum.each { |o| add(o) }
    end

    self
  end


to_a (Set)

# File lib/set.rb, line 113
  def to_a
    @hash.keys
  end


flatten_merge (Set)

# File lib/set.rb, line 117
  def flatten_merge(set, seen = Set.new)
    set.each { |e|
      if e.is_a?(Set)
        if seen.include?(e_id = e.object_id)
          raise ArgumentError, "tried to flatten recursive Set"
        end

        seen.add(e_id)
        flatten_merge(e, seen)
        seen.delete(e_id)
      else
        add(e)
      end
    }

    self
  end


flatten (Set)

# File lib/set.rb, line 138
  def flatten
    self.class.new.flatten_merge(self)
  end


flatten! (Set)

# File lib/set.rb, line 144
  def flatten!
    if detect { |e| e.is_a?(Set) }
      replace(flatten())
    else
      nil
    end
  end


include? (Set)

# File lib/set.rb, line 153
  def include?(o)
    @hash.include?(o)
  end


superset? (Set)

# File lib/set.rb, line 159
  def superset?(set)
    set.is_a?(Set) or raise ArgumentError, "value must be a set"
    return false if size < set.size
    set.all? { |o| include?(o) }
  end


proper_superset? (Set)

# File lib/set.rb, line 166
  def proper_superset?(set)
    set.is_a?(Set) or raise ArgumentError, "value must be a set"
    return false if size <= set.size
    set.all? { |o| include?(o) }
  end


subset? (Set)

# File lib/set.rb, line 173
  def subset?(set)
    set.is_a?(Set) or raise ArgumentError, "value must be a set"
    return false if set.size < size
    all? { |o| set.include?(o) }
  end


proper_subset? (Set)

# File lib/set.rb, line 180
  def proper_subset?(set)
    set.is_a?(Set) or raise ArgumentError, "value must be a set"
    return false if set.size <= size
    all? { |o| set.include?(o) }
  end


each (Set)

# File lib/set.rb, line 188
  def each
    @hash.each_key { |o| yield(o) }
    self
  end


add (Set)

# File lib/set.rb, line 195
  def add(o)
    @hash[o] = true
    self
  end


add? (Set)

# File lib/set.rb, line 203
  def add?(o)
    if include?(o)
      nil
    else
      add(o)
    end
  end


delete (Set)

# File lib/set.rb, line 213
  def delete(o)
    @hash.delete(o)
    self
  end


delete? (Set)

# File lib/set.rb, line 220
  def delete?(o)
    if include?(o)
      delete(o)
    else
      nil
    end
  end


delete_if (Set)

# File lib/set.rb, line 230
  def delete_if
    @hash.delete_if { |o,| yield(o) }
    self
  end


collect! (Set)

# File lib/set.rb, line 236
  def collect!
    set = self.class.new
    each { |o| set << yield(o) }
    replace(set)
  end


reject! (Set)

# File lib/set.rb, line 245
  def reject!
    n = size
    delete_if { |o| yield(o) }
    size == n ? nil : self
  end


merge (Set)

# File lib/set.rb, line 253
  def merge(enum)
    if enum.is_a?(Set)
      @hash.update(enum.instance_eval { @hash })
    else
      enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
      enum.each { |o| add(o) }
    end

    self
  end


subtract (Set)

# File lib/set.rb, line 266
  def subtract(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    enum.each { |o| delete(o) }
    self
  end


| (Set)

# File lib/set.rb, line 274
  def |(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    dup.merge(enum)
  end


- (Set)

# File lib/set.rb, line 283
  def -(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    dup.subtract(enum)
  end


& (Set)

# File lib/set.rb, line 291
  def &(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    n = self.class.new
    enum.each { |o| n.add(o) if include?(o) }
    n
  end


^ (Set)

# File lib/set.rb, line 302
  def ^(enum)
    enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
    n = Set.new(enum)
    each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
    n
  end


== (Set)

# File lib/set.rb, line 311
  def ==(set)
    equal?(set) and return true

    set.is_a?(Set) && size == set.size or return false

    hash = @hash.dup
    set.all? { |o| hash.include?(o) }
  end


classify (Set)

# File lib/set.rb, line 342
  def classify # :yields: o
    h = {}

    each { |i|
      x = yield(i)
      (h[x] ||= self.class.new).add(i)
    }

    h
  end


divide (Set)

# File lib/set.rb, line 369
  def divide(&func)
    if func.arity == 2
      require 'tsort'

      class << dig = {}         # :nodoc:
        include TSort

        alias tsort_each_node each_key
        def tsort_each_child(node, &block)
          fetch(node).each(&block)
        end
      end

      each { |u|
        dig[u] = a = []
        each{ |v| func.call(u, v) and a << v }
      }

      set = Set.new()
      dig.each_strongly_connected_component { |css|
        set.add(self.class.new(css))
      }
      set
    else
      Set.new(classify(&func).values)
    end
  end


inspect (Set)

# File lib/set.rb, line 401
  def inspect
    ids = (Thread.current[InspectKey] ||= [])

    if ids.include?(object_id)
      return sprintf('#<%s: {...}>', self.class.name)
    end

    begin
      ids << object_id
      return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
    ensure
      ids.pop
    end
  end


new (Shell::AppendFile)

# File lib/shell/builtin-command.rb, line 111
    def initialize(sh, to_filename, filter)
      @file_name = to_filename
      io = sh.open(to_filename, "a")
      super(sh, io, filter)
    end


input= (Shell::AppendFile)

# File lib/shell/builtin-command.rb, line 117
    def input=(filter)
      begin
        super
      ensure
        @io.close
      end
    end


new (Shell::AppendIO)

# File lib/shell/builtin-command.rb, line 95
    def initialize(sh, io, filter)
      super sh
      @input = filter
      @io = io
    end


input= (Shell::AppendIO)

# File lib/shell/builtin-command.rb, line 101
    def input=(filter)
      @input.input=filter
      for l in @input
        @io << l
      end
    end


wait? (Shell::BuiltInCommand)

# File lib/shell/builtin-command.rb, line 17
    def wait?
      false
    end


active? (Shell::BuiltInCommand)

# File lib/shell/builtin-command.rb, line 20
    def active?
      true
    end


new (Shell::Cat)

# File lib/shell/builtin-command.rb, line 40
    def initialize(sh, *filenames)
      super sh
      @cat_files = filenames
    end


each (Shell::Cat)

# File lib/shell/builtin-command.rb, line 45
    def each(rs = nil)
      if @cat_files.empty?
        super
      else
        for src in @cat_files
          @shell.foreach(src, rs){|l| yield l}
        end
      end
    end


initialize (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 30
    def self.initialize

      install_builtin_commands

      # define CommandProccessor#methods to Shell#methods and Filter#methods
      for m in CommandProcessor.instance_methods(false) - NoDelegateMethods
        add_delegate_command_to_shell(m)
      end

      def self.method_added(id)
        add_delegate_command_to_shell(id)
      end
    end


method_added (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 39
      def self.method_added(id)
        add_delegate_command_to_shell(id)
      end


run_config (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 47
    def self.run_config
      begin
        load File.expand_path("~/.rb_shell") if ENV.key?("HOME")
      rescue LoadError, Errno::ENOENT
      rescue
        print "load error: #{rc}\n"
        print $!.class, ": ", $!, "\n"
        for err in $@[0, $@.size - 2]
          print "\t", err, "\n"
        end
      end
    end


new (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 60
    def initialize(shell)
      @shell = shell
      @system_commands = {}
    end


expand_path (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 71
    def expand_path(path)
      @shell.expand_path(path)
    end


foreach (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 93
    def foreach(path = nil, *rs)
      path = "." unless path
      path = expand_path(path)

      if File.directory?(path)
        Dir.foreach(path){|fn| yield fn}
      else
        IO.foreach(path, *rs){|l| yield l}
      end
    end


open (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 114
    def open(path, mode)
      path = expand_path(path)
      if File.directory?(path)
        Dir.open(path)
      else
        effect_umask do
          File.open(path, mode)
        end
      end
    end


unlink (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 132
    def unlink(path)
      path = expand_path(path)
      if File.directory?(path)
        Dir.unlink(path)
      else
        IO.unlink(path)
      end
    end


test (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 158
    def test(command, file1, file2=nil)
      file1 = expand_path(file1)
      file2 = expand_path(file2) if file2
      command = command.id2name if command.kind_of?(Symbol)

      case command
      when Integer
        top_level_test(command, file1, file2)
      when String
        if command.size == 1
          if file2
            top_level_test(command, file1, file2)
          else
            top_level_test(command, file1)
          end
        else
          if file2
            FileTest.send(command, file1, file2)
          else
            FileTest.send(command, file1)
          end
        end
      end
    end


mkdir (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 196
    def mkdir(*path)
      for dir in path
        Dir.mkdir(expand_path(dir))
      end
    end


rmdir (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 207
    def rmdir(*path)
      for dir in path
        Dir.rmdir(expand_path(dir))
      end
    end


system (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 223
    def system(command, *opts)
      if opts.empty?
        if command =~ /\*|\?|\{|\}|\[|\]|<|>|\(|\)|~|&|\||\\|\$|;|'|`|"|\n/
          return SystemCommand.new(@shell, find_system_command("sh"), "-c", command)
        else
          command, *opts = command.split(/\s+/)
        end
      end
      SystemCommand.new(@shell, find_system_command(command), *opts)
    end


rehash (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 238
    def rehash
      @system_commands = {}
    end


check_point (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 245
    def check_point
      @shell.process_controller.wait_all_jobs_execution
    end


transact (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 250
    def transact(&block)
      begin
        @shell.instance_eval(&block)
      ensure
        check_point
      end
    end


out (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 261
    def out(dev = STDOUT, &block)
      dev.print transact(&block)
    end


echo (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 265
    def echo(*strings)
      Echo.new(@shell, *strings)
    end


cat (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 269
    def cat(*filenames)
      Cat.new(@shell, *filenames)
    end


glob (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 277
    def glob(pattern)
      Glob.new(@shell, pattern)
    end


append (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 281
    def append(to, filter)
      case to
      when String
        AppendFile.new(@shell, to, filter)
      when IO
        AppendIO.new(@shell, to, filter)
      else
        Shell.Fail Error::CantApplyMethod, "append", to.class
      end
    end


tee (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 292
    def tee(file)
      Tee.new(@shell, file)
    end


concat (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 296
    def concat(*jobs)
      Concat.new(@shell, *jobs)
    end


notify (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 301
    def notify(*opts, &block)
      Thread.exclusive do
        Shell.notify(*opts) {|mes|
          yield mes if iterator?

          mes.gsub!("%pwd", "#{@cwd}")
          mes.gsub!("%cwd", "#{@cwd}")
        }
      end
    end


find_system_command (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 331
    def find_system_command(command)
      return command if /^\// =~ command
      case path = @system_commands[command]
      when String
        if exists?(path)
          return path
        else
          Shell.Fail Error::CommandNotFound, command
        end
      when false
        Shell.Fail Error::CommandNotFound, command
      end

      for p in @shell.system_path
        path = join(p, command)
        if FileTest.exists?(path)
          @system_commands[command] = path
          return path
        end
      end
      @system_commands[command] = false
      Shell.Fail Error::CommandNotFound, command
    end


def_system_command (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 361
    def self.def_system_command(command, path = command)
      begin
        eval((d = %Q[def #{command}(*opts)
                  SystemCommand.new(@shell, '#{path}', *opts)
               end]), nil, __FILE__, __LINE__ - 1)
      rescue SyntaxError
        Shell.notify "warn: Can't define #{command} path: #{path}."
      end
      Shell.notify "Define #{command} path: #{path}.", Shell.debug?
      Shell.notify("Definition of #{command}: ", d,
             Shell.debug.kind_of?(Integer) && Shell.debug > 1)
    end


undef_system_command (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 374
    def self.undef_system_command(command)
      command = command.id2name if command.kind_of?(Symbol)
      remove_method(command)
      Shell.module_eval{remove_method(command)}
      Filter.module_eval{remove_method(command)}
      self
    end


alias_map (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 388
    def self.alias_map
      @alias_map
    end


alias_command (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 391
    def self.alias_command(ali, command, *opts, &block)
      ali = ali.id2name if ali.kind_of?(Symbol)
      command = command.id2name if command.kind_of?(Symbol)
      begin
        if iterator?
          @alias_map[ali.intern] = proc

          eval((d = %Q[def #{ali}(*opts)
                          @shell.__send__(:#{command},
                                          *(CommandProcessor.alias_map[:#{ali}].call *opts))
                        end]), nil, __FILE__, __LINE__ - 1)

        else
           args = opts.collect{|opt| '"' + opt + '"'}.join(",")
           eval((d = %Q[def #{ali}(*opts)
                          @shell.__send__(:#{command}, #{args}, *opts)
                        end]), nil, __FILE__, __LINE__ - 1)
        end
      rescue SyntaxError
        Shell.notify "warn: Can't alias #{ali} command: #{command}."
        Shell.notify("Definition of #{ali}: ", d)
        raise
      end
      Shell.notify "Define #{ali} command: #{command}.", Shell.debug?
      Shell.notify("Definition of #{ali}: ", d,
             Shell.debug.kind_of?(Integer) && Shell.debug > 1)
      self
    end


unalias_command (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 420
    def self.unalias_command(ali)
      ali = ali.id2name if ali.kind_of?(Symbol)
      @alias_map.delete ali.intern
      undef_system_command(ali)
    end


def_builtin_commands (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 437
    def self.def_builtin_commands(delegation_class, command_specs)
      for meth, args in command_specs
        arg_str = args.collect{|arg| arg.downcase}.join(", ")
        call_arg_str = args.collect{
          |arg|
          case arg
          when /^(FILENAME.*)$/
            format("expand_path(%s)", $1.downcase)
          when /^(\*FILENAME.*)$/
            # \*FILENAME* -> filenames.collect{|fn| expand_path(fn)}.join(", ")
            $1.downcase + '.collect{|fn| expand_path(fn)}'
          else
            arg
          end
        }.join(", ")
        d = %Q[def #{meth}(#{arg_str})
                    #{delegation_class}.#{meth}(#{call_arg_str})
                 end]
        Shell.notify "Define #{meth}(#{arg_str})", Shell.debug?
        Shell.notify("Definition of #{meth}: ", d,
             Shell.debug.kind_of?(Integer) && Shell.debug > 1)
        eval d
      end
    end


install_system_commands (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 471
    def self.install_system_commands(pre = "sys_")
      defined_meth = {}
      for m in Shell.methods
        defined_meth[m] = true
      end
      sh = Shell.new
      for path in Shell.default_system_path
        next unless sh.directory? path
        sh.cd path
        sh.foreach do
          |cn|
          if !defined_meth[pre + cn] && sh.file?(cn) && sh.executable?(cn)
            command = (pre + cn).gsub(/\W/, "_").sub(/^([0-9])/, '_\1')
            begin
              def_system_command(command, sh.expand_path(cn))
            rescue
              Shell.notify "warn: Can't define #{command} path: #{cn}"
            end
            defined_meth[command] = command
          end
        end
      end
    end


add_delegate_command_to_shell (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 500
    def self.add_delegate_command_to_shell(id)
      id = id.intern if id.kind_of?(String)
      name = id.id2name
      if Shell.method_defined?(id)
        Shell.notify "warn: override definnition of Shell##{name}."
        Shell.notify "warn: alias Shell##{name} to Shell##{name}_org.\n"
        Shell.module_eval "alias #{name}_org #{name}"
      end
      Shell.notify "method added: Shell##{name}.", Shell.debug?
      Shell.module_eval(%Q[def #{name}(*args, &block)
                            begin
                              @command_processor.__send__(:#{name}, *args, &block)
                            rescue Exception
                              $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
                              $@.delete_if{|s| /^\\(eval\\):/ =~ s}
                            raise
                            end
                          end], __FILE__, __LINE__)

      if Shell::Filter.method_defined?(id)
        Shell.notify "warn: override definnition of Shell::Filter##{name}."
        Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org."
        Filter.module_eval "alias #{name}_org #{name}"
      end
      Shell.notify "method added: Shell::Filter##{name}.", Shell.debug?
      Filter.module_eval(%Q[def #{name}(*args, &block)
                            begin
                              self | @shell.__send__(:#{name}, *args, &block)
                            rescue Exception
                              $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
                              $@.delete_if{|s| /^\\(eval\\):/ =~ s}
                            raise
                            end
                          end], __FILE__, __LINE__)
    end


install_builtin_commands (Shell::CommandProcessor)

# File lib/shell/command-processor.rb, line 539
    def self.install_builtin_commands
      # method related File.
      # (exclude open/foreach/unlink)
      normal_delegation_file_methods = [
        ["atime", ["FILENAME"]],
        ["basename", ["fn", "*opts"]],
        ["chmod", ["mode", "*FILENAMES"]],
        ["chown", ["owner", "group", "*FILENAME"]],
        ["ctime", ["FILENAMES"]],
        ["delete", ["*FILENAMES"]],
        ["dirname", ["FILENAME"]],
        ["ftype", ["FILENAME"]],
        ["join", ["*items"]],
        ["link", ["FILENAME_O", "FILENAME_N"]],
        ["lstat", ["FILENAME"]],
        ["mtime", ["FILENAME"]],
        ["readlink", ["FILENAME"]],
        ["rename", ["FILENAME_FROM", "FILENAME_TO"]],
        #      ["size", ["FILENAME"]],
        ["split", ["pathname"]],
        ["stat", ["FILENAME"]],
        ["symlink", ["FILENAME_O", "FILENAME_N"]],
        ["truncate", ["FILENAME", "length"]],
        ["utime", ["atime", "mtime", "*FILENAMES"]]]

      def_builtin_commands(File, normal_delegation_file_methods)
      alias_method :rm, :delete

      # method related FileTest
      def_builtin_commands(FileTest,
                   FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]})

      # method related ftools
      normal_delegation_ftools_methods = [
        ["syscopy", ["FILENAME_FROM", "FILENAME_TO"]],
        ["copy", ["FILENAME_FROM", "FILENAME_TO"]],
        ["move", ["FILENAME_FROM", "FILENAME_TO"]],
        ["compare", ["FILENAME_FROM", "FILENAME_TO"]],
        ["safe_unlink", ["*FILENAMES"]],
        ["makedirs", ["*FILENAMES"]],
        #    ["chmod", ["mode", "*FILENAMES"]],
        ["install", ["FILENAME_FROM", "FILENAME_TO", "mode"]],
      ]
      def_builtin_commands(File,
                   normal_delegation_ftools_methods)
      alias_method :cmp, :compare
      alias_method :mv, :move
      alias_method :cp, :copy
      alias_method :rm_f, :safe_unlink
      alias_method :mkpath, :makedirs
    end


new (Shell::Concat)

# File lib/shell/builtin-command.rb, line 143
    def initialize(sh, *jobs)
      super(sh)
      @jobs = jobs
    end


each (Shell::Concat)

# File lib/shell/builtin-command.rb, line 148
    def each(rs = nil)
      while job = @jobs.shift
        job.each{|l| yield l}
      end
    end


new (Shell::Echo)

# File lib/shell/builtin-command.rb, line 26
    def initialize(sh, *strings)
      super sh
      @strings = strings
    end


each (Shell::Echo)

# File lib/shell/builtin-command.rb, line 31
    def each(rs = nil)
      rs =  @shell.record_separator unless rs
      for str  in @strings
        yield str + rs
      end
    end


new (Shell::Filter)

# File lib/shell/filter.rb, line 22
    def initialize(sh)
      @shell = sh         # parent shell
      @input = nil        # input filter
    end


input= (Shell::Filter)

# File lib/shell/filter.rb, line 29
    def input=(filter)
      @input = filter
    end


each (Shell::Filter)

# File lib/shell/filter.rb, line 33
    def each(rs = nil)
      rs = @shell.record_separator unless rs
      if @input
        @input.each(rs){|l| yield l}
      end
    end


< (Shell::Filter)

# File lib/shell/filter.rb, line 40
    def < (src)
      case src
      when String
        cat = Cat.new(@shell, src)
        cat | self
      when IO
        self.input = src
        self
      else
        Shell.Fail Error::CantApplyMethod, "<", to.class
      end
    end


> (Shell::Filter)

# File lib/shell/filter.rb, line 53
    def > (to)
      case to
      when String
        dst = @shell.open(to, "w")
        begin
          each(){|l| dst << l}
        ensure
          dst.close
        end
      when IO
        each(){|l| to << l}
      else
        Shell.Fail Error::CantApplyMethod, ">", to.class
      end
      self
    end


>> (Shell::Filter)

# File lib/shell/filter.rb, line 70
    def >> (to)
      begin
        Shell.cd(@shell.pwd).append(to, self)
      rescue CantApplyMethod
        Shell.Fail Error::CantApplyMethod, ">>", to.class
      end
    end


| (Shell::Filter)

# File lib/shell/filter.rb, line 78
    def | (filter)
      filter.input = self
      if active?
        @shell.process_controller.start_job filter
      end
      filter
    end


+ (Shell::Filter)

# File lib/shell/filter.rb, line 86
    def + (filter)
      Join.new(@shell, self, filter)
    end


to_a (Shell::Filter)

# File lib/shell/filter.rb, line 90
    def to_a
      ary = []
      each(){|l| ary.push l}
      ary
    end


to_s (Shell::Filter)

# File lib/shell/filter.rb, line 96
    def to_s
      str = ""
      each(){|l| str.concat l}
      str
    end


inspect (Shell::Filter)

# File lib/shell/filter.rb, line 102
    def inspect
      if @shell.debug.kind_of?(Integer) && @shell.debug > 2
        super
      else
        to_s
      end
    end


new (Shell::Glob)

# File lib/shell/builtin-command.rb, line 57
    def initialize(sh, pattern)
      super sh

      @pattern = pattern
      Thread.critical = true
      back = Dir.pwd
      begin
        Dir.chdir @shell.cwd
        @files = Dir[pattern]
      ensure
        Dir.chdir back
        Thread.critical = false
      end
    end


each (Shell::Glob)

# File lib/shell/builtin-command.rb, line 72
    def each(rs = nil)
      rs =  @shell.record_separator unless rs
      for f  in @files
        yield f+rs
      end
    end


process_controllers_exclusive (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 25
      def process_controllers_exclusive
        begin
          @ProcessControllers.lock unless Thread.critical
          yield
        ensure
          @ProcessControllers.unlock unless Thread.critical
        end
      end


activate (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 34
      def activate(pc)
        process_controllers_exclusive do
          @ProcessControllers[pc] ||= 0
          @ProcessControllers[pc] += 1
        end
      end


inactivate (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 41
      def inactivate(pc)
        process_controllers_exclusive do
          if @ProcessControllers[pc]
            if (@ProcessControllers[pc] -= 1) == 0
              @ProcessControllers.delete(pc)
            end
          end
        end
      end


each_active_object (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 51
      def each_active_object
        process_controllers_exclusive do
          for ref in @ProcessControllers.keys
            yield ref
          end
        end
      end


new (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 60
    def initialize(shell)
      @shell = shell
      @waiting_jobs = []
      @active_jobs = []
      @jobs_sync = Sync.new

      @job_monitor = Mutex.new
      @job_condition = ConditionVariable.new
    end


jobs (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 70
    def jobs
      jobs = []
      @jobs_sync.synchronize(:SH) do
        jobs.concat @waiting_jobs
        jobs.concat @active_jobs
      end
      jobs
    end


active_jobs (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 79
    def active_jobs
      @active_jobs
    end


waiting_jobs (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 83
    def waiting_jobs
      @waiting_jobs
    end


jobs_exist? (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 87
    def jobs_exist?
      @jobs_sync.synchronize(:SH) do
        @active_jobs.empty? or @waiting_jobs.empty?
      end
    end


active_jobs_exist? (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 93
    def active_jobs_exist?
      @jobs_sync.synchronize(:SH) do
        @active_jobs.empty?
      end
    end


waiting_jobs_exist? (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 99
    def waiting_jobs_exist?
      @jobs_sync.synchronize(:SH) do
        @waiting_jobs.empty?
      end
    end


add_schedule (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 106
    def add_schedule(command)
      @jobs_sync.synchronize(:EX) do
        ProcessController.activate(self)
        if @active_jobs.empty?
          start_job command
        else
          @waiting_jobs.push(command)
        end
      end
    end


start_job (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 118
    def start_job(command = nil)
      @jobs_sync.synchronize(:EX) do
        if command
          return if command.active?
          @waiting_jobs.delete command
        else
          command = @waiting_jobs.shift
          return unless command
        end
        @active_jobs.push command
        command.start

        # start all jobs that input from the job
        for job in @waiting_jobs
          start_job(job) if job.input == command
        end
      end
    end


waiting_job? (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 137
    def waiting_job?(job)
      @jobs_sync.synchronize(:SH) do
        @waiting_jobs.include?(job)
      end
    end


active_job? (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 143
    def active_job?(job)
      @jobs_sync.synchronize(:SH) do
        @active_jobs.include?(job)
      end
    end


terminate_job (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 150
    def terminate_job(command)
      @jobs_sync.synchronize(:EX) do
        @active_jobs.delete command
        ProcessController.inactivate(self)
        if @active_jobs.empty?
          start_job
        end
      end
    end


kill_job (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 161
    def kill_job(sig, command)
      @jobs_sync.synchronize(:SH) do
        if @waiting_jobs.delete command
          ProcessController.inactivate(self)
          return
        elsif @active_jobs.include?(command)
          begin
            r = command.kill(sig)
            ProcessController.inactivate(self)
          rescue
            print "Shell: Warn: $!\n" if @shell.verbose?
            return nil
          end
          @active_jobs.delete command
          r
        end
      end
    end


wait_all_jobs_execution (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 181
    def wait_all_jobs_execution
      @job_monitor.synchronize do
        begin
          while !jobs.empty?
            @job_condition.wait(@job_monitor)
          end
        ensure
          redo unless jobs.empty?
        end
      end
    end


sfork (Shell::ProcessController)

# File lib/shell/process-controller.rb, line 194
    def sfork(command, &block)
      pipe_me_in, pipe_peer_out = IO.pipe
      pipe_peer_in, pipe_me_out = IO.pipe
      Thread.critical = true

      STDOUT.flush
      ProcessController.each_active_object do |pc|
        for jobs in pc.active_jobs
          jobs.flush
        end
      end

      pid = fork {
        Thread.critical = true

        Thread.list.each do |th|
          th.kill unless [Thread.main, Thread.current].include?(th)
        end

        STDIN.reopen(pipe_peer_in)
        STDOUT.reopen(pipe_peer_out)

        ObjectSpace.each_object(IO) do |io|
          if ![STDIN, STDOUT, STDERR].include?(io)
            io.close unless io.closed?
          end
        end
        yield
      }

      pipe_peer_in.close
      pipe_peer_out.close
      command.notify "job(%name:##{pid}) start", @shell.debug?
      Thread.critical = false

      th = Thread.start {
        Thread.critical = true
        begin
          _pid = nil
          command.notify("job(%id) start to waiting finish.", @shell.debug?)
          Thread.critical = false
          _pid = Process.waitpid(pid, nil)
        rescue Errno::ECHILD
          command.notify "warn: job(%id) was done already waitipd."
          _pid = true
        ensure
          # when the process ends, wait until the command termintes
          if _pid
          else
            command.notify("notice: Process finishing...",
                           "wait for Job[%id] to finish.",
                           "You can use Shell#transact or Shell#check_point for more safe execution.")
            redo
          end
          Thread.exclusive do
            @job_monitor.synchronize do
              terminate_job(command)
              @job_condition.signal
              command.notify "job(%id) finish.", @shell.debug?
            end
          end
        end
      }
      return pid, pipe_me_in, pipe_me_out
    end


new (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 17
    def initialize(sh, command, *opts)
      if t = opts.find{|opt| !opt.kind_of?(String) && opt.class}
        Shell.Fail Error::TypeError, t.class, "String"
      end
      super(sh)
      @command = command
      @opts = opts

      @input_queue = Queue.new
      @pid = nil

      sh.process_controller.add_schedule(self)
    end


wait? (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 34
    def wait?
      @shell.process_controller.waiting_job?(self)
    end


active? (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 38
    def active?
      @shell.process_controller.active_job?(self)
    end


input= (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 42
    def input=(inp)
      super
      if active?
        start_export
      end
    end


start (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 49
    def start
      @pid, @pipe_in, @pipe_out = @shell.process_controller.sfork(self) {
        Dir.chdir @shell.pwd
        exec(@command, *@opts)
      }
      if @input
        start_export
      end
      start_import
    end


flush (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 60
    def flush
      @pipe_out.flush if @pipe_out and !@pipe_out.closed?
    end


terminate (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 64
    def terminate
      begin
        @pipe_in.close
      rescue IOError
      end
      begin
        @pipe_out.close
      rescue IOError
      end
    end


kill (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 75
    def kill(sig)
      if @pid
        Process.kill(sig, @pid)
      end
    end


start_import (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 82
    def start_import
#      Thread.critical = true
      notify "Job(%id) start imp-pipe.", @shell.debug?
      rs = @shell.record_separator unless rs
      _eop = true
#      Thread.critical = false
      th = Thread.start {
        Thread.critical = true
        begin
          Thread.critical = false
          while l = @pipe_in.gets
            @input_queue.push l
          end
          _eop = false
        rescue Errno::EPIPE
          _eop = false
        ensure
          if _eop
            notify("warn: Process finishing...",
                   "wait for Job[%id] to finish pipe importing.",
                   "You can use Shell#transact or Shell#check_point for more safe execution.")
#           Tracer.on
            Thread.current.run
            redo
          end
          Thread.exclusive do
            notify "job(%id}) close imp-pipe.", @shell.debug?
            @input_queue.push :EOF
            @pipe_in.close
          end
        end
      }
    end


start_export (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 116
    def start_export
      notify "job(%id) start exp-pipe.", @shell.debug?
      _eop = true
      th = Thread.start{
        Thread.critical = true
        begin
          Thread.critical = false
          @input.each{|l| @pipe_out.print l}
          _eop = false
        rescue Errno::EPIPE
          _eop = false
        ensure
          if _eop
            notify("shell: warn: Process finishing...",
                   "wait for Job(%id) to finish pipe exporting.",
                   "You can use Shell#transact or Shell#check_point for more safe execution.")
#           Tracer.on
            redo
          end
          Thread.exclusive do
            notify "job(%id) close exp-pipe.", @shell.debug?
            @pipe_out.close
          end
        end
      }
    end


each (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 144
    def each(rs = nil)
      while (l = @input_queue.pop) != :EOF
        yield l
      end
    end


notify (Shell::SystemCommand)

# File lib/shell/system-command.rb, line 156
    def notify(*opts, &block)
      Thread.exclusive do
        @shell.notify(*opts) {|mes|
          yield mes if iterator?

          mes.gsub!("%id", "#{@command}:##{@pid}")
          mes.gsub!("%name", "#{@command}")
          mes.gsub!("%pid", "#{@pid}")
        }
      end
    end


new (Shell::Tee)

# File lib/shell/builtin-command.rb, line 127
    def initialize(sh, filename)
      super sh
      @to_filename = filename
    end


each (Shell::Tee)

# File lib/shell/builtin-command.rb, line 132
    def each(rs = nil)
      to = @shell.open(@to_filename, "w")
      begin
        super{|l| to << l; yield l}
      ensure
        to.close
      end
    end


debug= (Shell)

# File lib/shell.rb, line 43
    def debug=(val)
      @debug = val
      @verbose = val if val
    end


cd (Shell)

# File lib/shell.rb, line 48
    def cd(path)
      sh = new
      sh.cd path
      sh
    end


default_system_path (Shell)

# File lib/shell.rb, line 54
    def default_system_path
      if @default_system_path
        @default_system_path
      else
        ENV["PATH"].split(":")
      end
    end


default_system_path= (Shell)

# File lib/shell.rb, line 62
    def default_system_path=(path)
      @default_system_path = path
    end


default_record_separator (Shell)

# File lib/shell.rb, line 66
    def default_record_separator
      if @default_record_separator
        @default_record_separator
      else
        $/
      end
    end


default_record_separator= (Shell)

# File lib/shell.rb, line 74
    def default_record_separator=(rs)
      @default_record_separator = rs
    end


new (Shell)

# File lib/shell.rb, line 79
  def initialize
    @cwd = Dir.pwd
    @dir_stack = []
    @umask = nil

    @system_path = Shell.default_system_path
    @record_separator = Shell.default_record_separator

    @command_processor = CommandProcessor.new(self)
    @process_controller = ProcessController.new(self)

    @verbose = Shell.verbose
    @debug = Shell.debug
  end


system_path= (Shell)

# File lib/shell.rb, line 96
  def system_path=(path)
    @system_path = path
    rehash
  end


debug= (Shell)

# File lib/shell.rb, line 107
  def debug=(val)
    @debug = val
    @verbose = val if val
  end


expand_path (Shell)

# File lib/shell.rb, line 118
  def expand_path(path)
    File.expand_path(path, @cwd)
  end


chdir (Shell)

# File lib/shell.rb, line 144
  def chdir(path = nil)
    if iterator?
      cwd_old = @cwd
      begin
        chdir(path)
        yield
      ensure
        chdir(cwd_old)
      end
    else
      path = "~" unless path
      @cwd = expand_path(path)
      notify "current dir: #{@cwd}"
      rehash
      self
    end
  end


pushdir (Shell)

# File lib/shell.rb, line 163
  def pushdir(path = nil)
    if iterator?
      pushdir(path)
      begin
        yield
      ensure
        popdir
      end
    elsif path
      @dir_stack.push @cwd
      chdir path
      notify "dir stack: [#{@dir_stack.join ', '}]"
      self
    else
      if pop = @dir_stack.pop
        @dir_stack.push @cwd
        chdir pop
        notify "dir stack: [#{@dir_stack.join ', '}]"
        self
      else
        Shell.Fail DirStackEmpty
      end
    end
  end


popdir (Shell)

# File lib/shell.rb, line 189
  def popdir
    if pop = @dir_stack.pop
      chdir pop
      notify "dir stack: [#{@dir_stack.join ', '}]"
      self
    else
      Shell.Fail DirStackEmpty
    end
  end


jobs (Shell)

# File lib/shell.rb, line 204
  def jobs
    @process_controller.jobs
  end


kill (Shell)

# File lib/shell.rb, line 208
  def kill(sig, command)
    @process_controller.kill_job(sig, command)
  end


def_system_command (Shell)

# File lib/shell.rb, line 215
  def Shell.def_system_command(command, path = command)
    CommandProcessor.def_system_command(command, path)
  end


undef_system_command (Shell)

# File lib/shell.rb, line 219
  def Shell.undef_system_command(command)
    CommandProcessor.undef_system_command(command)
  end


alias_command (Shell)

# File lib/shell.rb, line 223
  def Shell.alias_command(ali, command, *opts, &block)
    CommandProcessor.alias_command(ali, command, *opts, &block)
  end


unalias_command (Shell)

# File lib/shell.rb, line 227
  def Shell.unalias_command(ali)
    CommandProcessor.unalias_command(ali)
  end


install_system_commands (Shell)

# File lib/shell.rb, line 231
  def Shell.install_system_commands(pre = "sys_")
    CommandProcessor.install_system_commands(pre)
  end


inspect (Shell)

# File lib/shell.rb, line 236
  def inspect
    if debug.kind_of?(Integer) && debug > 2
      super
    else
      to_s
    end
  end


notify (Shell)

# File lib/shell.rb, line 244
  def self.notify(*opts, &block)
    Thread.exclusive do
    if opts[-1].kind_of?(String)
      yorn = verbose?
    else
      yorn = opts.pop
    end
    return unless yorn

    _head = true
    print opts.collect{|mes|
      mes = mes.dup
      yield mes if iterator?
      if _head
        _head = false
        "shell: " + mes
      else
        "       " + mes
      end
    }.join("\n")+"\n"
    end
  end


shellwords (Shellwords)

# File lib/shellwords.rb, line 28
  def shellwords(line)
    line = String.new(line) rescue
      raise(ArgumentError, "Argument must be a string")
    line.lstrip!
    words = []
    until line.empty?
      field = ''
      loop do
        if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then
          snippet = $1.gsub(/\\(.)/, '\1')
        elsif line =~ /\A"/ then
          raise ArgumentError, "Unmatched double quote: #{line}"
        elsif line.sub!(/\A'([^']*)'/, '') then
          snippet = $1
        elsif line =~ /\A'/ then
          raise ArgumentError, "Unmatched single quote: #{line}"
        elsif line.sub!(/\A\\(.)?/, '') then
          snippet = $1 || '\\'
        elsif line.sub!(/\A([^\s\\'"]+)/, '') then
          snippet = $1
        else
          line.lstrip!
          break
        end
        field.concat(snippet)
      end
      words.push(field)
    end
    words
  end


trap (Signal)

/*
 * call-seq:
 *   Signal.trap( signal, proc ) => obj
 *   Signal.trap( signal ) {| | block } => obj
 *
 * Specifies the handling of signals. The first parameter is a signal
 * name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a
 * signal number. The characters ``SIG'' may be omitted from the
 * signal name. The command or block specifies code to be run when the
 * signal is raised. If the command is the string ``IGNORE'' or
 * ``SIG_IGN'', the signal will be ignored. If the command is
 * ``DEFAULT'' or ``SIG_DFL'', the operating system's default handler
 * will be invoked. If the command is ``EXIT'', the script will be
 * terminated by the signal. Otherwise, the given command or block
 * will be run.
 * The special signal name ``EXIT'' or signal number zero will be
 * invoked just prior to program termination.
 * trap returns the previous handler for the given signal.
 *
 *     Signal.trap(0, proc { puts "Terminating: #{$$}" })
 *     Signal.trap("CLD")  { puts "Child died" }
 *     fork && Process.wait
 *
 * produces:
 *     Terminating: 27461
 *     Child died
 *     Terminating: 27460
 */
static VALUE
sig_trap(argc, argv)
    int argc;
    VALUE *argv;
{
    struct trap_arg arg;

    rb_secure(2);
    if (argc == 0 || argc > 2) {
        rb_raise(rb_eArgError, "wrong number of arguments -- trap(sig, cmd)/trap(sig){...}");
    }

    arg.sig = argv[0];
    if (argc == 1) {
        arg.cmd = rb_block_proc();
    }
    else if (argc == 2) {
        arg.cmd = argv[1];
    }

    if (OBJ_TAINTED(arg.cmd)) {
        rb_raise(rb_eSecurityError, "Insecure: tainted signal trap");
    }
#ifndef _WIN32
    /* disable interrupt */
# ifdef HAVE_SIGPROCMASK
    sigfillset(&arg.mask);
    sigprocmask(SIG_BLOCK, &arg.mask, &arg.mask);
# else
    arg.mask = sigblock(~0);
# endif

    return rb_ensure(trap, (VALUE)&arg, trap_ensure, (VALUE)&arg);
#else
    return trap(&arg);
#endif
}


list (Signal)

/*
 * call-seq:
 *   Signal.list => a_hash
 *
 * Returns a list of signal names mapped to the corresponding
 * underlying signal numbers.
 *
 * Signal.list   #=> {"ABRT"=>6, "ALRM"=>14, "BUS"=>7, "CHLD"=>17, "CLD"=>17, "CONT"=>18, "FPE"=>8, "HUP"=>1, "ILL"=>4, "INT"=>2, "IO"=>29, "IOT"=>6, "KILL"=>9, "PIPE"=>13, "POLL"=>29, "PROF"=>27, "PWR"=>30, "QUIT"=>3, "SEGV"=>11, "STOP"=>19, "SYS"=>31, "TERM"=>15, "TRAP"=>5, "TSTP"=>20, "TTIN"=>21, "TTOU"=>22, "URG"=>23, "USR1"=>10, "USR2"=>12, "VTALRM"=>26, "WINCH"=>28, "XCPU"=>24, "XFSZ"=>25}
 */
static VALUE
sig_list()
{
    VALUE h = rb_hash_new();
    struct signals *sigs;

    for (sigs = siglist; sigs->signm; sigs++) {
        rb_hash_aset(h, rb_str_new2(sigs->signm), INT2FIX(sigs->signo));
    }
    return h;
}


new (SimpleDelegator)

# File lib/delegate.rb, line 201
  def initialize(obj)
    super
    @_sd_obj = obj
  end


__getobj__ (SimpleDelegator)

# File lib/delegate.rb, line 207
  def __getobj__
    @_sd_obj
  end


__setobj__ (SimpleDelegator)

# File lib/delegate.rb, line 225
  def __setobj__(obj)
    raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
    @_sd_obj = obj
  end


clone (SimpleDelegator)

# File lib/delegate.rb, line 231
  def clone
    super
    __setobj__(__getobj__.clone)
  end


dup (SimpleDelegator)

# File lib/delegate.rb, line 236
  def dup(obj)
    super
    __setobj__(__getobj__.dup)
  end


def_singleton_delegators (SingleForwardable)

# File lib/forwardable.rb, line 187
  def def_singleton_delegators(accessor, *methods)
    for method in methods
      def_singleton_delegator(accessor, method)
    end
  end


def_singleton_delegator (SingleForwardable)

# File lib/forwardable.rb, line 200
  def def_singleton_delegator(accessor, method, ali = method)
    accessor = accessor.id2name if accessor.kind_of?(Integer)
    method = method.id2name if method.kind_of?(Integer)
    ali = ali.id2name if ali.kind_of?(Integer)

    instance_eval("def \#{ali}(*args, &block)\nbegin\n\#{accessor}.__send__(:\#{method}, *args,&block)\nrescue Exception\n$@.delete_if{|s| /^\\\\(__FORWARDABLE__\\\\):/ =~ s} unless Forwardable::debug\nKernel::raise\nend\nend\n", "(__FORWARDABLE__)", 1)
  end


clone (Singleton)

# File lib/singleton.rb, line 67
  def clone
    raise TypeError, "can't clone instance of singleton #{self.class}"
  end


dup (Singleton)

# File lib/singleton.rb, line 70
  def dup
    raise TypeError, "can't dup instance of singleton #{self.class}"
  end


clone (SingletonClassMethods)

# File lib/singleton.rb, line 130
    def clone
      Singleton.__init__(super)
    end


new (SizedQueue)

# File lib/thread.rb, line 374
  def initialize(max)
    raise ArgumentError, "queue size must be positive" unless max > 0
    @max = max
    @queue_wait = []
    @queue_wait.taint           # enable tainted comunication
    super()
  end


max (SizedQueue)

# File lib/thread.rb, line 385
  def max
    @max
  end


max= (SizedQueue)

# File lib/thread.rb, line 392
  def max=(max)
    Thread.critical = true
    if max <= @max
      @max = max
      Thread.critical = false
    else
      diff = max - @max
      @max = max
      Thread.critical = false
      diff.times do
        begin
          t = @queue_wait.shift
          t.run if t
        rescue ThreadError
          retry
        end
      end
    end
    max
  end


push (SizedQueue)

# File lib/thread.rb, line 417
  def push(obj)
    Thread.critical = true
    while @que.length >= @max
      @queue_wait.push Thread.current
      Thread.stop
      Thread.critical = true
    end
    super
  end


pop (SizedQueue)

# File lib/thread.rb, line 440
  def pop(*args)
    retval = super
    Thread.critical = true
    if @que.length < @max
      begin
        t = @queue_wait.shift
        t.wakeup if t
      rescue ThreadError
        retry
      ensure
        Thread.critical = false
      end
      begin
        t.run if t
      rescue ThreadError
      end
    end
    retval
  end


num_waiting (SizedQueue)

# File lib/thread.rb, line 473
  def num_waiting
    @waiting.size + @queue_wait.size
  end


to_s (SM::AttrChanger)

# File lib/rdoc/markup/simple_markup/inline.rb, line 46
    def to_s
      "Attr: +#{Attribute.as_string(@turn_on)}/-#{Attribute.as_string(@turn_on)}"
    end


bitmap_for (SM::Attribute)

# File lib/rdoc/markup/simple_markup/inline.rb, line 12
    def Attribute.bitmap_for(name)
      bitmap = @@name_to_bitmap[name]
      if !bitmap
        bitmap = @@next_bitmap
        @@next_bitmap <<= 1
        @@name_to_bitmap[name] = bitmap
      end
      bitmap
    end


as_string (SM::Attribute)

# File lib/rdoc/markup/simple_markup/inline.rb, line 22
    def Attribute.as_string(bitmap)
      return "none" if bitmap.zero?
      res = []
      @@name_to_bitmap.each do |name, bit|
        res << name if (bitmap & bit) != 0
      end
      res.join(",")
    end


each_name_of (SM::Attribute)

# File lib/rdoc/markup/simple_markup/inline.rb, line 31
    def Attribute.each_name_of(bitmap)
      @@name_to_bitmap.each do |name, bit|
        next if bit == SPECIAL
        yield name.to_s if (bitmap & bit) != 0
      end
    end


attribute (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 122
    def attribute(turn_on, turn_off)
      AttrChanger.new(turn_on, turn_off)
    end


change_attribute (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 127
    def change_attribute(current, new)
      diff = current ^ new
      attribute(new & diff, current & diff)
    end


changed_attribute_by_name (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 132
    def changed_attribute_by_name(current_set, new_set)
      current = new = 0
      current_set.each {|name| current |= Attribute.bitmap_for(name) }
      new_set.each {|name| new |= Attribute.bitmap_for(name) }
      change_attribute(current, new)
    end


copy_string (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 139
    def copy_string(start_pos, end_pos)
      res = @str[start_pos...end_pos]
      res.gsub!(/\000/, '')
      res
    end


convert_attrs (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 148
    def convert_attrs(str, attrs)
      # first do matching ones
      tags = MATCHING_WORD_PAIRS.keys.join("")
      re = "(^|\\W)([#{tags}])([A-Za-z_]+?)\\2(\\W|\$)"
#      re = "(^|\\W)([#{tags}])(\\S+?)\\2(\\W|\$)"
      1 while str.gsub!(Regexp.new(re)) {
        attr = MATCHING_WORD_PAIRS[$2];
        attrs.set_attrs($`.length + $1.length + $2.length, $3.length, attr)
        $1 + NULL*$2.length + $3 + NULL*$2.length + $4
      }

      # then non-matching
      unless WORD_PAIR_MAP.empty?
        WORD_PAIR_MAP.each do |regexp, attr|
          str.gsub!(regexp) {
            attrs.set_attrs($`.length + $1.length, $2.length, attr)
            NULL*$1.length + $2 + NULL*$3.length
          }
        end
      end
    end


convert_html (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 170
    def convert_html(str, attrs)
      tags = HTML_TAGS.keys.join("|")
      re = "<(#{tags})>(.*?)</\\1>"
      1 while str.gsub!(Regexp.new(re, Regexp::IGNORECASE)) {
        attr = HTML_TAGS[$1.downcase]
        html_length = $1.length + 2
        seq = NULL * html_length
        attrs.set_attrs($`.length + html_length, $2.length, attr)
        seq + $2 + seq + NULL
      }
    end


convert_specials (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 182
    def convert_specials(str, attrs)
      unless SPECIAL.empty?
        SPECIAL.each do |regexp, attr|
          str.scan(regexp) do
            attrs.set_attrs($`.length, $&.length, attr | Attribute::SPECIAL)
          end
        end
      end
    end


mask_protected_sequences (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 199
    def mask_protected_sequences
      protect_pattern = Regexp.new("\\\\([#{Regexp.escape(PROTECTABLE.join(''))}])")
      @str.gsub!(protect_pattern, "\\1#{PROTECT_ATTR}")
    end


unmask_protected_sequences (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 204
    def unmask_protected_sequences
      @str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000")
    end


new (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 208
    def initialize
      add_word_pair("*", "*", :BOLD)
      add_word_pair("_", "_", :EM)
      add_word_pair("+", "+", :TT)

      add_html("em", :EM)
      add_html("i",  :EM)
      add_html("b",  :BOLD)
      add_html("tt",   :TT)
      add_html("code", :TT)

      add_special(/<!--(.*?)-->/, :COMMENT)
    end


add_word_pair (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 222
    def add_word_pair(start, stop, name)
      raise "Word flags may not start '<'" if start[0] == ?<
      bitmap = Attribute.bitmap_for(name)
      if start == stop
        MATCHING_WORD_PAIRS[start] = bitmap
      else
        pattern = Regexp.new("(" + Regexp.escape(start) + ")" +
#                             "([A-Za-z]+)" +
                             "(\\S+)" +
                             "(" + Regexp.escape(stop) +")")
        WORD_PAIR_MAP[pattern] = bitmap
      end
      PROTECTABLE << start[0,1]
      PROTECTABLE.uniq!
    end


add_html (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 238
    def add_html(tag, name)
      HTML_TAGS[tag.downcase] = Attribute.bitmap_for(name)
    end


add_special (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 242
    def add_special(pattern, name)
      SPECIAL[pattern] = Attribute.bitmap_for(name)
    end


flow (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 246
    def flow(str)
      @str = str

      puts("Before flow, str='#{@str.dump}'") if $DEBUG
      mask_protected_sequences

      @attrs = AttrSpan.new(@str.length)

      puts("After protecting, str='#{@str.dump}'") if $DEBUG
      convert_attrs(@str, @attrs)
      convert_html(@str, @attrs)
      convert_specials(str, @attrs)
      unmask_protected_sequences
      puts("After flow, str='#{@str.dump}'") if $DEBUG
      return split_into_flow
    end


display_attributes (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 263
    def display_attributes
      puts
      puts @str.tr(NULL, "!")
      bit = 1
      16.times do |bno|
        line = ""
        @str.length.times do |i|
          if (@attrs[i] & bit) == 0
            line << " "
          else
            if bno.zero?
              line << "S"
            else
              line << ("%d" % (bno+1))
            end
          end
        end
        puts(line) unless line =~ /^ *$/
        bit <<= 1
      end
    end


split_into_flow (SM::AttributeManager)

# File lib/rdoc/markup/simple_markup/inline.rb, line 285
    def split_into_flow

      display_attributes if $DEBUG

      res = []
      current_attr = 0
      str = ""

      str_len = @str.length

      # skip leading invisible text
      i = 0
      i += 1 while i < str_len and @str[i].zero?
      start_pos = i

      # then scan the string, chunking it on attribute changes
      while i < str_len
        new_attr = @attrs[i]
        if new_attr != current_attr
          if i > start_pos
            res << copy_string(start_pos, i)
            start_pos = i
          end

          res << change_attribute(current_attr, new_attr)
          current_attr = new_attr

          if (current_attr & Attribute::SPECIAL) != 0
            i += 1 while i < str_len and (@attrs[i] & Attribute::SPECIAL) != 0
            res << Special.new(current_attr, copy_string(start_pos, i))
            start_pos = i
            next
          end
        end

        # move on, skipping any invisible characters
        begin
          i += 1
        end while i < str_len and @str[i].zero?
      end

      # tidy up trailing text
      if start_pos < str_len
        res << copy_string(start_pos, str_len)
      end

      # and reset to all attributes off
      res << change_attribute(current_attr, 0) if current_attr != 0

      return res
    end


new (SM::AttrSpan)

# File lib/rdoc/markup/simple_markup/inline.rb, line 53
    def initialize(length)
      @attrs = Array.new(length, 0)
    end


set_attrs (SM::AttrSpan)

# File lib/rdoc/markup/simple_markup/inline.rb, line 57
    def set_attrs(start, length, bits)
      for i in start ... (start+length)
        @attrs[i] |= bits
      end
    end


[] (SM::AttrSpan)

# File lib/rdoc/markup/simple_markup/inline.rb, line 63
    def [](n)
      @attrs[n]
    end


new (SM::Flow::LIST)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 13
      def initialize(type)
        @type = type
        @contents = []
      end


<< (SM::Flow::LIST)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 17
      def <<(stuff)
        @contents << stuff
      end


new (SM::Fragment)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 14
    def initialize(level, param, type, txt)
      @level = level
      @param = param
      @type  = type
      @txt   = ""
      add_text(txt) if txt
    end


add_text (SM::Fragment)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 22
    def add_text(txt)
      @txt << " " if @txt.length > 0
      @txt << txt.tr_s("\n ", "  ").strip
    end


to_s (SM::Fragment)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 27
    def to_s
      "L#@level: #{self.class.name.split('::')[-1]}\n#@txt"
    end


type_name (SM::Fragment)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 37
    def Fragment.type_name(name)
      TYPE_MAP[name] = self
    end


for (SM::Fragment)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 41
    def Fragment.for(line)
      klass =  TYPE_MAP[line.type] ||
        raise("Unknown line type: '#{line.type.inspect}:' '#{line.text}'")
      return klass.new(line.level, line.param, line.flag, line.text)
    end


head_level (SM::Heading)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 63
    def head_level
      @param.to_i
    end


new (SM::Line)

# File lib/rdoc/markup/simple_markup/lines.rb, line 42
    def initialize(text)
      @text    = text.dup
      @deleted = false

      # expand tabs
      1 while @text.gsub!(/\t+/) { ' ' * (8*$&.length - $`.length % 8)}  && $~ #`

      # Strip trailing whitespace
      @text.sub!(/\s+$/, '')

      # and look for leading whitespace
      if @text.length > 0
        @text =~ /^(\s*)/
        @leading_spaces = $1.length
      else
        @leading_spaces = INFINITY
      end
    end


isBlank? (SM::Line)

# File lib/rdoc/markup/simple_markup/lines.rb, line 62
    def isBlank?
      @text.length.zero?
    end


stamp (SM::Line)

# File lib/rdoc/markup/simple_markup/lines.rb, line 67
    def stamp(type, level, param="", flag=nil)
      @type, @level, @param, @flag = type, level, param, flag
    end


strip_leading (SM::Line)

# File lib/rdoc/markup/simple_markup/lines.rb, line 75
    def strip_leading(size)
      if @text.size > size
        @text[0,size] = ""
      else
        @text = ""
      end
    end


to_s (SM::Line)

# File lib/rdoc/markup/simple_markup/lines.rb, line 83
    def to_s
      "#@type#@level: #@text"
    end


new (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 127
    def initialize
      @fragments = []
    end


add (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 131
    def add(fragment)
      @fragments << fragment
    end


each (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 135
    def each(&b)
      @fragments.each(&b)
    end


to_a (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 140
    def to_a
      @fragments.map {|fragment| fragment.to_s}
    end


fragment_for (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 145
    def fragment_for(*args)
      Fragment.for(*args)
    end


normalize (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 150
    def normalize
      change_verbatim_blank_lines
      add_list_start_and_ends
      add_list_breaks
      tidy_blank_lines
    end


to_s (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 157
    def to_s
      @fragments.join("\n----\n")
    end


accept (SM::LineCollection)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 161
    def accept(am, visitor)

      visitor.start_accepting

      @fragments.each do |fragment|
        case fragment
        when Verbatim
          visitor.accept_verbatim(am, fragment)
        when Rule
          visitor.accept_rule(am, fragment)
        when ListStart
          visitor.accept_list_start(am, fragment)
        when ListEnd
          visitor.accept_list_end(am, fragment)
        when ListItem
          visitor.accept_list_item(am, fragment)
        when BlankLine
          visitor.accept_blank_line(am, fragment)
        when Heading
          visitor.accept_heading(am, fragment)
        when Paragraph
          visitor.accept_paragraph(am, fragment)
        end
      end

      visitor.end_accepting
    end


new (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 98
    def initialize(lines)
      @lines = lines
      rewind
    end


empty? (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 103
    def empty?
      @lines.size.zero?
    end


each (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 107
    def each
      @lines.each do |line|
        yield line unless line.deleted
      end
    end


rewind (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 117
    def rewind
      @nextline = 0
    end


next (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 121
    def next
      begin
        res = @lines[@nextline]
        @nextline += 1 if @nextline < @lines.size
      end while res and res.deleted and @nextline < @lines.size
      res
    end


unget (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 129
    def unget
      @nextline -= 1
    end


delete (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 133
    def delete(a_line)
      a_line.deleted = true
    end


normalize (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 137
    def normalize
      margin = @lines.collect{|l| l.leading_spaces}.min
      margin = 0 if margin == Line::INFINITY
      @lines.each {|line| line.strip_leading(margin) } if margin > 0
    end


as_text (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 143
    def as_text
      @lines.map {|l| l.text}.join("\n")
    end


line_types (SM::Lines)

# File lib/rdoc/markup/simple_markup/lines.rb, line 147
    def line_types
      @lines.map {|l| l.type }
    end


new (SM::ListEnd)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 98
    def initialize(level, type)
      super(level, "", type, nil)
    end


new (SM::ListStart)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 92
    def initialize(level, param, type)
      super(level, param, type, nil)
    end


new (SM::PreProcess)

# File lib/rdoc/markup/simple_markup/preprocess.rb, line 11
    def initialize(input_file_name, include_path)
      @input_file_name = input_file_name
      @include_path = include_path
    end


handle (SM::PreProcess)

# File lib/rdoc/markup/simple_markup/preprocess.rb, line 20
    def handle(text)
      text.gsub!(/^([ \t#]*):(\w+):\s*(.+)?\n/) do
        prefix    = $1
        directive = $2.downcase
        param     = $3

        case directive
        when "include"
          filename = param.split[0]
          include_file(filename, prefix)

        else
          yield(directive, param)
        end
      end
    end


new (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 207
    def initialize
      @am = AttributeManager.new
      @output = nil
    end


add_word_pair (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 217
    def add_word_pair(start, stop, name)
      @am.add_word_pair(start, stop, name)
    end


add_html (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 225
    def add_html(tag, name)
      @am.add_html(tag, name)
    end


add_special (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 239
    def add_special(pattern, name)
      @am.add_special(pattern, name)
    end


convert (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 249
    def convert(str, op)
      @lines = Lines.new(str.split(/\r?\n/).collect { |aLine|
                           Line.new(aLine) })
      return "" if @lines.empty?
      @lines.normalize
      assign_types_to_lines
      group = group_lines
      # call the output formatter to handle the result
      #      group.to_a.each {|i| p i}
      group.accept(@am, op)
    end


content (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 464
    def content
      @lines.as_text
    end


get_line_types (SM::SimpleMarkup)

# File lib/rdoc/markup/simple_markup.rb, line 470
    def get_line_types
      @lines.line_types
    end


new (SM::Special)

# File lib/rdoc/markup/simple_markup/inline.rb, line 75
    def initialize(type, text)
      @type, @text = type, text
    end


== (SM::Special)

# File lib/rdoc/markup/simple_markup/inline.rb, line 79
    def ==(o)
      self.text == o.text && self.type == o.type
    end


to_s (SM::Special)

# File lib/rdoc/markup/simple_markup/inline.rb, line 83
    def to_s
      "Special: type=#{type}, text=#{text.dump}"
    end


new (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 37
    def initialize
      init_tags
    end


init_tags (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 44
    def init_tags
      @attr_tags = [
        InlineTag.new(SM::Attribute.bitmap_for(:BOLD), "<b>", "</b>"),
        InlineTag.new(SM::Attribute.bitmap_for(:TT),   "<tt>", "</tt>"),
        InlineTag.new(SM::Attribute.bitmap_for(:EM),   "<em>", "</em>"),
      ]
    end


add_tag (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 56
    def add_tag(name, start, stop)
      @attr_tags << InlineTag.new(SM::Attribute.bitmap_for(name), start, stop)
    end


annotate (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 66
    def annotate(tag)
      tag
    end


start_accepting (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 73
    def start_accepting
      @res = []
      @list_stack = []
    end


end_accepting (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 78
    def end_accepting
      @res
    end


accept_paragraph (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 82
    def accept_paragraph(am, fragment)
      @res << Flow::P.new((convert_flow(am.flow(fragment.txt))))
    end


accept_verbatim (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 86
    def accept_verbatim(am, fragment)
      @res << Flow::VERB.new((convert_flow(am.flow(fragment.txt))))
    end


accept_rule (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 90
    def accept_rule(am, fragment)
      size = fragment.param
      size = 10 if size > 10
      @res << Flow::RULE.new(size)
    end


accept_list_start (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 96
    def accept_list_start(am, fragment)
      @list_stack.push(@res)
      list = Flow::LIST.new(fragment.type)
      @res << list
      @res = list
    end


accept_list_end (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 103
    def accept_list_end(am, fragment)
      @res = @list_stack.pop
    end


accept_list_item (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 107
    def accept_list_item(am, fragment)
      @res << Flow::LI.new(fragment.param, convert_flow(am.flow(fragment.txt)))
    end


accept_blank_line (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 111
    def accept_blank_line(am, fragment)
      # @res << annotate("<p />") << "\n"
    end


accept_heading (SM::ToFlow)

# File lib/rdoc/markup/simple_markup/to_flow.rb, line 115
    def accept_heading(am, fragment)
      @res << Flow::H.new(fragment.head_level, convert_flow(am.flow(fragment.txt)))
    end


new (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 21
    def initialize
      init_tags
    end


init_tags (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 28
    def init_tags
      @attr_tags = [
        InlineTag.new(SM::Attribute.bitmap_for(:BOLD), "<b>", "</b>"),
        InlineTag.new(SM::Attribute.bitmap_for(:TT),   "<tt>", "</tt>"),
        InlineTag.new(SM::Attribute.bitmap_for(:EM),   "<em>", "</em>"),
      ]
    end


add_tag (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 40
    def add_tag(name, start, stop)
      @attr_tags << InlineTag.new(SM::Attribute.bitmap_for(name), start, stop)
    end


annotate (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 50
    def annotate(tag)
      tag
    end


start_accepting (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 57
    def start_accepting
      @res = ""
      @in_list_entry = []
    end


end_accepting (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 62
    def end_accepting
      @res
    end


accept_paragraph (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 66
    def accept_paragraph(am, fragment)
      @res << annotate("<p>") + "\n"
      @res << wrap(convert_flow(am.flow(fragment.txt)))
      @res << annotate("</p>") + "\n"
    end


accept_verbatim (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 72
    def accept_verbatim(am, fragment)
      @res << annotate("<pre>") + "\n"
      @res << CGI.escapeHTML(fragment.txt)
      @res << annotate("</pre>") << "\n"
    end


accept_rule (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 78
    def accept_rule(am, fragment)
      size = fragment.param
      size = 10 if size > 10
      @res << "<hr size=\"#{size}\"></hr>"
    end


accept_list_start (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 84
    def accept_list_start(am, fragment)
      @res << html_list_name(fragment.type, true) <<"\n"
      @in_list_entry.push false
    end


accept_list_end (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 89
    def accept_list_end(am, fragment)
      if tag = @in_list_entry.pop
        @res << annotate(tag) << "\n"
      end
      @res << html_list_name(fragment.type, false) <<"\n"
    end


accept_list_item (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 96
    def accept_list_item(am, fragment)
      if tag = @in_list_entry.last
        @res << annotate(tag) << "\n"
      end
      @res << list_item_start(am, fragment)
      @res << wrap(convert_flow(am.flow(fragment.txt))) << "\n"
      @in_list_entry[-1] = list_end_for(fragment.type)
    end


accept_blank_line (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 105
    def accept_blank_line(am, fragment)
      # @res << annotate("<p />") << "\n"
    end


accept_heading (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 109
    def accept_heading(am, fragment)
      @res << convert_heading(fragment.head_level, am.flow(fragment.txt))
    end


wrap (SM::ToHtml)

# File lib/rdoc/markup/simple_markup/to_html.rb, line 115
    def wrap(txt, line_len = 76)
      res = ""
      sp = 0
      ep = txt.length
      while sp < ep
        # scan back for a space
        p = sp + line_len - 1
        if p >= ep
          p = ep
        else
          while p > sp and txt[p] != ?\s
            p -= 1
          end
          if p <= sp
            p = sp + line_len
            while p < ep and txt[p] != ?\s
              p += 1
            end
          end
        end
        res << txt[sp...p] << "\n"
        sp = p
        sp += 1 while sp < ep and txt[sp] == ?\s
      end
      res
    end


l (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 24
    def self.l(str)
      str.tr('\\', BS).tr('{', OB).tr('}', CB).tr('$', DL)
    end


l (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 28
    def l(arg)
      SM::ToLaTeX.l(arg)
    end


new (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 45
    def initialize
      init_tags
      @list_depth = 0
      @prev_list_types = []
    end


init_tags (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 54
    def init_tags
      @attr_tags = [
        InlineTag.new(SM::Attribute.bitmap_for(:BOLD), l("\\textbf{"), l("}")),
        InlineTag.new(SM::Attribute.bitmap_for(:TT),   l("\\texttt{"), l("}")),
        InlineTag.new(SM::Attribute.bitmap_for(:EM),   l("\\emph{"), l("}")),
      ]
    end


escape (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 64
    def escape(str)
# $stderr.print "FE: ", str
      s = str.
#        sub(/\s+$/, '').
        gsub(/([_\${}&%#])/, "#{BS}\\1").
        gsub(/\\/, BACKSLASH).
        gsub(/\^/, HAT).
        gsub(/~/,  TILDE).
        gsub(/</,  LESSTHAN).
        gsub(/>/,  GREATERTHAN).
        gsub(/,,/, ",{},").
        gsub(/\`/,  BACKQUOTE)
# $stderr.print "-> ", s, "\n"
      s
    end


add_tag (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 84
    def add_tag(name, start, stop)
      @attr_tags << InlineTag.new(SM::Attribute.bitmap_for(name), start, stop)
    end


start_accepting (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 92
    def start_accepting
      @res = ""
      @in_list_entry = []
    end


end_accepting (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 97
    def end_accepting
      @res.tr(BS, '\\').tr(OB, '{').tr(CB, '}').tr(DL, '$')
    end


accept_paragraph (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 101
    def accept_paragraph(am, fragment)
      @res << wrap(convert_flow(am.flow(fragment.txt)))
      @res << "\n"
    end


accept_verbatim (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 106
    def accept_verbatim(am, fragment)
      @res << "\n\\begin{code}\n"
      @res << fragment.txt.sub(/[\n\s]+\Z/, '')
      @res << "\n\\end{code}\n\n"
    end


accept_rule (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 112
    def accept_rule(am, fragment)
      size = fragment.param
      size = 10 if size > 10
      @res << "\n\n\\rule{\\linewidth}{#{size}pt}\n\n"
    end


accept_list_start (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 118
    def accept_list_start(am, fragment)
      @res << list_name(fragment.type, true) <<"\n"
      @in_list_entry.push false
    end


accept_list_end (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 123
    def accept_list_end(am, fragment)
      if tag = @in_list_entry.pop
        @res << tag << "\n"
      end
      @res << list_name(fragment.type, false) <<"\n"
    end


accept_list_item (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 130
    def accept_list_item(am, fragment)
      if tag = @in_list_entry.last
        @res << tag << "\n"
      end
      @res << list_item_start(am, fragment)
      @res << wrap(convert_flow(am.flow(fragment.txt))) << "\n"
      @in_list_entry[-1] = list_end_for(fragment.type)
    end


accept_blank_line (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 139
    def accept_blank_line(am, fragment)
      # @res << "\n"
    end


accept_heading (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 143
    def accept_heading(am, fragment)
      @res << convert_heading(fragment.head_level, am.flow(fragment.txt))
    end


wrap (SM::ToLaTeX)

# File lib/rdoc/markup/simple_markup/to_latex.rb, line 149
    def wrap(txt, line_len = 76)
      res = ""
      sp = 0
      ep = txt.length
      while sp < ep
        # scan back for a space
        p = sp + line_len - 1
        if p >= ep
          p = ep
        else
          while p > sp and txt[p] != ?\s
            p -= 1
          end
          if p <= sp
            p = sp + line_len
            while p < ep and txt[p] != ?\s
              p += 1
            end
          end
        end
        res << txt[sp...p] << "\n"
        sp = p
        sp += 1 while sp < ep and txt[sp] == ?\s
      end
      res
    end


add_text (SM::Verbatim)

# File lib/rdoc/markup/simple_markup/fragments.rb, line 109
    def add_text(txt)
      @txt << txt.chomp << "\n"
    end


new (SOAP::Attachment)

# File lib/soap/attachment.rb, line 36
  def initialize(string_or_readable = nil)
    @string_or_readable = string_or_readable
    @contenttype = "application/octet-stream"
    @contentid = nil
  end


contentid (SOAP::Attachment)

# File lib/soap/attachment.rb, line 42
  def contentid
    @contentid ||= Attachment.contentid(self)
  end


contentid= (SOAP::Attachment)

# File lib/soap/attachment.rb, line 46
  def contentid=(contentid)
    @contentid = contentid
  end


mime_contentid (SOAP::Attachment)

# File lib/soap/attachment.rb, line 50
  def mime_contentid
    '<' + contentid + '>'
  end


content (SOAP::Attachment)

# File lib/soap/attachment.rb, line 54
  def content
    if @content == nil and @string_or_readable != nil
      @content = @string_or_readable.respond_to?(:read) ?
        @string_or_readable.read : @string_or_readable
    end
    @content
  end


to_s (SOAP::Attachment)

# File lib/soap/attachment.rb, line 62
  def to_s
    content
  end


write (SOAP::Attachment)

# File lib/soap/attachment.rb, line 66
  def write(out)
    out.write(content)
  end


save (SOAP::Attachment)

# File lib/soap/attachment.rb, line 70
  def save(filename)
    File.open(filename, "wb") do |f|
      write(f)
    end
  end


contentid (SOAP::Attachment)

# File lib/soap/attachment.rb, line 76
  def self.contentid(obj)
    # this needs to be fixed
    [obj.__id__.to_s, Process.pid.to_s].join('.')
  end


mime_contentid (SOAP::Attachment)

# File lib/soap/attachment.rb, line 81
  def self.mime_contentid(obj)
    '<' + contentid(obj) + '>'
  end


new (SOAP::EncodingStyle::ASPDotNetHandler::SOAPTemporalObject)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 80
    def initialize
      @parent = nil
    end


new (SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 86
    def initialize(handler, elename)
      super()
      @handler = handler
      @elename = elename
    end


as_struct (SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 92
    def as_struct
      o = SOAPStruct.decode(@elename, XSD::AnyTypeName)
      o.parent = @parent
      o.type.name = @name
      @handler.decode_parent(@parent, o)
      o
    end


as_string (SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 100
    def as_string
      o = SOAPString.decode(@elename)
      o.parent = @parent
      @handler.decode_parent(@parent, o)
      o
    end


as_nil (SOAP::EncodingStyle::ASPDotNetHandler::SOAPUnknown)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 107
    def as_nil
      o = SOAPNil.decode(@elename)
      o.parent = @parent
      @handler.decode_parent(@parent, o)
      o
    end


new (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 20
  def initialize(charset = nil)
    super(charset)
    @textbuf = ''
    @decode_typemap = nil
  end


encode_data (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 30
  def encode_data(generator, ns, data, parent)
    attrs = {}
    # ASPDotNetHandler is intended to be used for accessing an ASP.NET doc/lit
    # service as an rpc/encoded service.  in the situation, local elements
    # should be qualified.  propagate parent's namespace to children.
    if data.elename.namespace.nil?
      data.elename.namespace = parent.elename.namespace
    end
    name = generator.encode_name(ns, data, attrs)
    case data
    when SOAPRawString
      generator.encode_tag(name, attrs)
      generator.encode_rawstring(data.to_s)
    when XSD::XSDString
      generator.encode_tag(name, attrs)
      generator.encode_string(@charset ?
        XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s)
    when XSD::XSDAnySimpleType
      generator.encode_tag(name, attrs)
      generator.encode_string(data.to_s)
    when SOAPStruct
      generator.encode_tag(name, attrs)
      data.each do |key, value|
        generator.encode_child(ns, value, data)
      end
    when SOAPArray
      generator.encode_tag(name, attrs)
      data.traverse do |child, *rank|
        data.position = nil
        generator.encode_child(ns, child, data)
      end
    else
      raise EncodingStyleError.new(
        "unknown object:#{data} in this encodingStyle")
    end
  end


encode_data_end (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 67
  def encode_data_end(generator, ns, data, parent)
    name = generator.encode_name_end(ns, data)
    cr = data.is_a?(SOAPCompoundtype)
    generator.encode_tag_end(name, cr)
  end


decode_tag (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 115
  def decode_tag(ns, elename, attrs, parent)
    @textbuf = ''
    o = SOAPUnknown.new(self, elename)
    o.parent = parent
    o
  end


decode_tag_end (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 122
  def decode_tag_end(ns, node)
    o = node.node
    if o.is_a?(SOAPUnknown)
      newnode = o.as_string
#       if /\A\s*\z/ =~ @textbuf
#         o.as_struct
#       else
#         o.as_string
#       end
      node.replace_node(newnode)
      o = node.node
    end

    decode_textbuf(o)
    @textbuf = ''
  end


decode_text (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 139
  def decode_text(ns, text)
    # @textbuf is set at decode_tag_end.
    @textbuf << text
  end


decode_prologue (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 144
  def decode_prologue
  end


decode_epilogue (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 147
  def decode_epilogue
  end


decode_parent (SOAP::EncodingStyle::ASPDotNetHandler)

# File lib/soap/encodingstyle/aspDotNetHandler.rb, line 150
  def decode_parent(parent, node)
    case parent.node
    when SOAPUnknown
      newparent = parent.node.as_struct
      node.parent = newparent
      parent.replace_node(newparent)
      decode_parent(parent, node)

    when SOAPStruct
      data = parent.node[node.elename.name]
      case data
      when nil
        parent.node.add(node.elename.name, node)
      when SOAPArray
        name, type_ns = node.elename.name, node.type.namespace
        data.add(node)
        node.elename, node.type.namespace = name, type_ns
      else
        parent.node[node.elename.name] = SOAPArray.new
        name, type_ns = data.elename.name, data.type.namespace
        parent.node[node.elename.name].add(data)
        data.elename.name, data.type.namespace = name, type_ns
        name, type_ns = node.elename.name, node.type.namespace
        parent.node[node.elename.name].add(node)
        node.elename.name, node.type.namespace = name, type_ns
      end

    when SOAPArray
      if node.position
        parent.node[*(decode_arypos(node.position))] = node
        parent.node.sparse = true
      else
        parent.node.add(node)
      end

    when SOAPBasetype
      raise EncodingStyleError.new("SOAP base type must not have a child")

    else
      # SOAPUnknown does not have parent.
      # raise EncodingStyleError.new("illegal parent: #{parent}")
    end
  end


uri (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 24
    def uri
      self::Namespace
    end


handler (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 28
    def handler(uri)
      @@handlers[uri]
    end


each (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 32
    def each
      @@handlers.each do |key, value|
        yield(value)
      end
    end


decode_typemap= (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 47
  def decode_typemap=(definedtypes)
    @decode_typemap = definedtypes
  end


new (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 51
  def initialize(charset)
    @charset = charset
    @generate_explicit_type = true
    @decode_typemap = nil
  end


encode_data (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 61
  def encode_data(generator, ns, data, parent)
    raise NotImplementError
  end


encode_data_end (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 65
  def encode_data_end(generator, ns, data, parent)
    raise NotImplementError
  end


encode_prologue (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 69
  def encode_prologue
  end


encode_epilogue (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 72
  def encode_epilogue
  end


decode_tag (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 79
  def decode_tag(ns, name, attrs, parent)
    raise NotImplementError.new('Method decode_tag must be defined in derived class.')
  end


decode_tag_end (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 83
  def decode_tag_end(ns, name)
    raise NotImplementError.new('Method decode_tag_end must be defined in derived class.')
  end


decode_text (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 87
  def decode_text(ns, text)
    raise NotImplementError.new('Method decode_text must be defined in derived class.')
  end


decode_prologue (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 91
  def decode_prologue
  end


decode_epilogue (SOAP::EncodingStyle::Handler)

# File lib/soap/encodingstyle/handler.rb, line 94
  def decode_epilogue
  end


new (SOAP::EncodingStyle::LiteralHandler::SOAPTemporalObject)

# File lib/soap/encodingstyle/literalHandler.rb, line 99
    def initialize
      @parent = nil
    end


new (SOAP::EncodingStyle::LiteralHandler::SOAPUnknown)

# File lib/soap/encodingstyle/literalHandler.rb, line 105
    def initialize(handler, elename, extraattr)
      super()
      @handler = handler
      @elename = elename
      @extraattr = extraattr
    end


as_element (SOAP::EncodingStyle::LiteralHandler::SOAPUnknown)

# File lib/soap/encodingstyle/literalHandler.rb, line 112
    def as_element
      o = SOAPElement.decode(@elename)
      o.parent = @parent
      o.extraattr.update(@extraattr)
      @handler.decode_parent(@parent, o)
      o
    end


as_string (SOAP::EncodingStyle::LiteralHandler::SOAPUnknown)

# File lib/soap/encodingstyle/literalHandler.rb, line 120
    def as_string
      o = SOAPString.decode(@elename)
      o.parent = @parent
      o.extraattr.update(@extraattr)
      @handler.decode_parent(@parent, o)
      o
    end


as_nil (SOAP::EncodingStyle::LiteralHandler::SOAPUnknown)

# File lib/soap/encodingstyle/literalHandler.rb, line 128
    def as_nil
      o = SOAPNil.decode(@elename)
      o.parent = @parent
      o.extraattr.update(@extraattr)
      @handler.decode_parent(@parent, o)
      o
    end


new (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 20
  def initialize(charset = nil)
    super(charset)
    @textbuf = ''
  end


encode_data (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 29
  def encode_data(generator, ns, data, parent)
    attrs = {}
    name = generator.encode_name(ns, data, attrs)
    data.extraattr.each do |k, v|
      # ToDo: check generator.attributeformdefault here
      if k.is_a?(XSD::QName)
        if k.namespace
          SOAPGenerator.assign_ns(attrs, ns, k.namespace)
          k = ns.name(k)
        else
          k = k.name
        end
      end
      attrs[k] = v
    end
    case data
    when SOAPRawString
      generator.encode_tag(name, attrs)
      generator.encode_rawstring(data.to_s)
    when XSD::XSDString
      generator.encode_tag(name, attrs)
      str = data.to_s
      str = XSD::Charset.encoding_to_xml(str, @charset) if @charset
      generator.encode_string(str)
    when XSD::XSDAnySimpleType
      generator.encode_tag(name, attrs)
      generator.encode_string(data.to_s)
    when SOAPStruct
      generator.encode_tag(name, attrs)
      data.each do |key, value|
        generator.encode_child(ns, value, data)
      end
    when SOAPArray
      generator.encode_tag(name, attrs)
      data.traverse do |child, *rank|
        data.position = nil
        generator.encode_child(ns, child, data)
      end
    when SOAPElement
      # passes 2 times for simplifying namespace definition
      data.each do |key, value|
        if value.elename.namespace
          SOAPGenerator.assign_ns(attrs, ns, value.elename.namespace)
        end
      end
      generator.encode_tag(name, attrs)
      generator.encode_rawstring(data.text) if data.text
      data.each do |key, value|
        generator.encode_child(ns, value, data)
      end
    else
      raise EncodingStyleError.new(
        "unknown object:#{data} in this encodingStyle")
    end
  end


encode_data_end (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 85
  def encode_data_end(generator, ns, data, parent)
    name = generator.encode_name_end(ns, data)
    cr = (data.is_a?(SOAPCompoundtype) or
      (data.is_a?(SOAPElement) and !data.text))
    generator.encode_tag_end(name, cr)
  end


decode_tag (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 137
  def decode_tag(ns, elename, attrs, parent)
    @textbuf = ''
    o = SOAPUnknown.new(self, elename, decode_attrs(ns, attrs))
    o.parent = parent
    o
  end


decode_tag_end (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 144
  def decode_tag_end(ns, node)
    o = node.node
    if o.is_a?(SOAPUnknown)
      newnode = if /\A\s*\z/ =~ @textbuf
          o.as_element
        else
          o.as_string
        end
      node.replace_node(newnode)
      o = node.node
    end

    decode_textbuf(o)
    @textbuf = ''
  end


decode_text (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 160
  def decode_text(ns, text)
    # @textbuf is set at decode_tag_end.
    @textbuf << text
  end


decode_attrs (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 165
  def decode_attrs(ns, attrs)
    extraattr = {}
    attrs.each do |key, value|
      qname = ns.parse_local(key)
      extraattr[qname] = value
    end
    extraattr
  end


decode_prologue (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 174
  def decode_prologue
  end


decode_epilogue (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 177
  def decode_epilogue
  end


decode_parent (SOAP::EncodingStyle::LiteralHandler)

# File lib/soap/encodingstyle/literalHandler.rb, line 180
  def decode_parent(parent, node)
    return unless parent.node
    case parent.node
    when SOAPUnknown
      newparent = parent.node.as_element
      node.parent = newparent
      parent.replace_node(newparent)
      decode_parent(parent, node)
    when SOAPElement
      parent.node.add(node)
      node.parent = parent.node
    when SOAPStruct
      parent.node.add(node.elename.name, node)
      node.parent = parent.node
    when SOAPArray
      if node.position
        parent.node[*(decode_arypos(node.position))] = node
        parent.node.sparse = true
      else
        parent.node.add(node)
      end
      node.parent = parent.node
    else
      raise EncodingStyleError.new("illegal parent: #{parent.node}")
    end
  end


new (SOAP::EncodingStyle::SOAPHandler::SOAPTemporalObject)

# File lib/soap/encodingstyle/soapHandler.rb, line 89
    def initialize
      @parent = nil
      @position = nil
      @id = nil
      @root = nil
    end


new (SOAP::EncodingStyle::SOAPHandler::SOAPUnknown)

# File lib/soap/encodingstyle/soapHandler.rb, line 102
    def initialize(handler, elename, type, extraattr)
      super()
      @handler = handler
      @elename = elename
      @type = type
      @extraattr = extraattr
      @definedtype = nil
    end


as_struct (SOAP::EncodingStyle::SOAPHandler::SOAPUnknown)

# File lib/soap/encodingstyle/soapHandler.rb, line 111
    def as_struct
      o = SOAPStruct.decode(@elename, @type)
      o.id = @id
      o.root = @root
      o.parent = @parent
      o.position = @position
      o.extraattr.update(@extraattr)
      @handler.decode_parent(@parent, o)
      o
    end


as_string (SOAP::EncodingStyle::SOAPHandler::SOAPUnknown)

# File lib/soap/encodingstyle/soapHandler.rb, line 122
    def as_string
      o = SOAPString.decode(@elename)
      o.id = @id
      o.root = @root
      o.parent = @parent
      o.position = @position
      o.extraattr.update(@extraattr)
      @handler.decode_parent(@parent, o)
      o
    end


as_nil (SOAP::EncodingStyle::SOAPHandler::SOAPUnknown)

# File lib/soap/encodingstyle/soapHandler.rb, line 133
    def as_nil
      o = SOAPNil.decode(@elename)
      o.id = @id
      o.root = @root
      o.parent = @parent
      o.position = @position
      o.extraattr.update(@extraattr)
      @handler.decode_parent(@parent, o)
      o
    end


new (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 20
  def initialize(charset = nil)
    super(charset)
    @refpool = []
    @idpool = []
    @textbuf = ''
    @is_first_top_ele = true
  end


encode_data (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 32
  def encode_data(generator, ns, data, parent)
    attrs = encode_attrs(generator, ns, data, parent)
    if parent && parent.is_a?(SOAPArray) && parent.position
      attrs[ns.name(AttrPositionName)] = "[#{parent.position.join(',')}]"
    end
    name = generator.encode_name(ns, data, attrs)
    case data
    when SOAPReference
      attrs['href'] = data.refidstr
      generator.encode_tag(name, attrs)
    when SOAPExternalReference
      data.referred
      attrs['href'] = data.refidstr
      generator.encode_tag(name, attrs)
    when SOAPRawString
      generator.encode_tag(name, attrs)
      generator.encode_rawstring(data.to_s)
    when XSD::XSDString
      generator.encode_tag(name, attrs)
      generator.encode_string(@charset ?
        XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s)
    when XSD::XSDAnySimpleType
      generator.encode_tag(name, attrs)
      generator.encode_string(data.to_s)
    when SOAPStruct
      generator.encode_tag(name, attrs)
      data.each do |key, value|
        generator.encode_child(ns, value, data)
      end
    when SOAPArray
      generator.encode_tag(name, attrs)
      data.traverse do |child, *rank|
        data.position = data.sparse ? rank : nil
        generator.encode_child(ns, child, data)
      end
    else
      raise EncodingStyleError.new(
        "unknown object:#{data} in this encodingStyle")
    end
  end


encode_data_end (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 73
  def encode_data_end(generator, ns, data, parent)
    name = generator.encode_name_end(ns, data)
    cr = data.is_a?(SOAPCompoundtype)
    generator.encode_tag_end(name, cr)
  end


decode_tag (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 145
  def decode_tag(ns, elename, attrs, parent)
    @textbuf = ''
    is_nil, type, arytype, root, offset, position, href, id, extraattr =
      decode_attrs(ns, attrs)
    o = nil
    if is_nil
      o = SOAPNil.decode(elename)
    elsif href
      o = SOAPReference.decode(elename, href)
      @refpool << o
    elsif @decode_typemap
      o = decode_tag_by_wsdl(ns, elename, type, parent.node, arytype, extraattr)
    else
      o = decode_tag_by_type(ns, elename, type, parent.node, arytype, extraattr)
    end

    if o.is_a?(SOAPArray)
      if offset
        o.offset = decode_arypos(offset)
        o.sparse = true
      else
        o.sparse = false
      end
    end

    o.parent = parent
    o.id = id
    o.root = root
    o.position = position

    unless o.is_a?(SOAPTemporalObject)
      @idpool << o if o.id
      decode_parent(parent, o)
    end
    o
  end


decode_tag_end (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 182
  def decode_tag_end(ns, node)
    o = node.node
    if o.is_a?(SOAPUnknown)
      newnode = if /\A\s*\z/ =~ @textbuf
        o.as_struct
      else
        o.as_string
      end
      if newnode.id
        @idpool << newnode
      end
      node.replace_node(newnode)
      o = node.node
    end
    decode_textbuf(o)
    # unlink definedtype
    o.definedtype = nil
  end


decode_text (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 201
  def decode_text(ns, text)
    @textbuf << text
  end


decode_prologue (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 205
  def decode_prologue
    @refpool.clear
    @idpool.clear
    @is_first_top_ele = true
  end


decode_epilogue (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 211
  def decode_epilogue
    decode_resolve_id
  end


decode_parent (SOAP::EncodingStyle::SOAPHandler)

# File lib/soap/encodingstyle/soapHandler.rb, line 215
  def decode_parent(parent, node)
    return unless parent.node
    case parent.node
    when SOAPUnknown
      newparent = parent.node.as_struct
      node.parent = newparent
      if newparent.id
        @idpool << newparent
      end
      parent.replace_node(newparent)
      decode_parent(parent, node)
    when SOAPStruct
      parent.node.add(node.elename.name, node)
      node.parent = parent.node
    when SOAPArray
      if node.position
        parent.node[*(decode_arypos(node.position))] = node
        parent.node.sparse = true
      else
        parent.node.add(node)
      end
      node.parent = parent.node
    else
      raise EncodingStyleError.new("illegal parent: #{parent.node}")
    end
  end


getenv (SOAP::Env)

# File lib/soap/soap.rb, line 108
  def self.getenv(name)
    ENV[name.downcase] || ENV[name.upcase]
  end


new (SOAP::FaultError)

# File lib/soap/soap.rb, line 89
  def initialize(fault)
    @faultcode = fault.faultcode
    @faultstring = fault.faultstring
    @faultactor = fault.faultactor
    @detail = fault.detail
    super(self.to_s)
  end


to_s (SOAP::FaultError)

# File lib/soap/soap.rb, line 97
  def to_s
    str = nil
    if @faultstring and @faultstring.respond_to?('data')
      str = @faultstring.data
    end
    str || '(No faultstring)'
  end


new (SOAP::Header::Handler)

# File lib/soap/header/handler.rb, line 21
  def initialize(elename)
    @elename = elename
    @mustunderstand = false
    @encodingstyle = nil
  end


on_outbound (SOAP::Header::Handler)

# File lib/soap/header/handler.rb, line 28
  def on_outbound
    nil
  end


on_inbound (SOAP::Header::Handler)

# File lib/soap/header/handler.rb, line 33
  def on_inbound(header, mustunderstand = false)
    # do something.
  end


on_outbound_headeritem (SOAP::Header::Handler)

# File lib/soap/header/handler.rb, line 37
  def on_outbound_headeritem
    item = on_outbound
    if item.nil?
      nil
    elsif item.is_a?(::SOAP::SOAPHeaderItem)
      item.elename = @elename
      item
    else
      item.elename = @elename
      ::SOAP::SOAPHeaderItem.new(item, @mustunderstand, @encodingstyle)
    end
  end


on_inbound_headeritem (SOAP::Header::Handler)

# File lib/soap/header/handler.rb, line 50
  def on_inbound_headeritem(header)
    on_inbound(header.element, header.mustunderstand)
  end


new (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 17
  def initialize
    @store = XSD::NamedElements.new
  end


dup (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 21
  def dup
    obj = HandlerSet.new
    obj.store = @store.dup
    obj
  end


add (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 27
  def add(handler)
    @store << handler
  end


delete (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 32
  def delete(handler)
    @store.delete(handler)
  end


include? (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 36
  def include?(handler)
    @store.include?(handler)
  end


on_outbound (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 41
  def on_outbound
    @store.collect { |handler|
      handler.on_outbound_headeritem
    }.compact
  end


on_inbound (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 48
  def on_inbound(headers)
    headers.each do |name, item|
      handler = @store.find { |handler|
        handler.elename == item.element.elename
      }
      if handler
        handler.on_inbound_headeritem(item)
      elsif item.mustunderstand
        raise UnhandledMustUnderstandHeaderError.new(item.element.elename.to_s)
      end
    end
  end


store= (SOAP::Header::HandlerSet)

# File lib/soap/header/handlerset.rb, line 63
  def store=(store)
    @store = store
  end


new (SOAP::Header::SimpleHandler)

# File lib/soap/header/simplehandler.rb, line 18
  def initialize(elename)
    super(elename)
  end


on_simple_outbound (SOAP::Header::SimpleHandler)

# File lib/soap/header/simplehandler.rb, line 23
  def on_simple_outbound
    nil
  end


on_simple_inbound (SOAP::Header::SimpleHandler)

# File lib/soap/header/simplehandler.rb, line 28
  def on_simple_inbound(header, mustunderstand)
  end


on_outbound (SOAP::Header::SimpleHandler)

# File lib/soap/header/simplehandler.rb, line 31
  def on_outbound
    h = on_simple_outbound
    h ? SOAPElement.from_obj(h, elename.namespace) : nil
  end


on_inbound (SOAP::Header::SimpleHandler)

# File lib/soap/header/simplehandler.rb, line 36
  def on_inbound(header, mustunderstand)
    h = header.respond_to?(:to_obj) ? header.to_obj : header.data
    on_simple_inbound(h, mustunderstand)
  end


set_options (SOAP::HTTPConfigLoader)

# File lib/soap/httpconfigloader.rb, line 18
  def set_options(client, options)
    client.proxy = options["proxy"]
    options.add_hook("proxy") do |key, value|
      client.proxy = value
    end
    client.no_proxy = options["no_proxy"]
    options.add_hook("no_proxy") do |key, value|
      client.no_proxy = value
    end
    if client.respond_to?(:protocol_version=)
      client.protocol_version = options["protocol_version"]
      options.add_hook("protocol_version") do |key, value|
        client.protocol_version = value
      end
    end
    ssl_config = options["ssl_config"] ||= ::SOAP::Property.new
    set_ssl_config(client, ssl_config)
    ssl_config.add_hook(true) do |key, value|
      set_ssl_config(client, ssl_config)
    end
    basic_auth = options["basic_auth"] ||= ::SOAP::Property.new
    set_basic_auth(client, basic_auth)
    basic_auth.add_hook do |key, value|
      set_basic_auth(client, basic_auth)
    end
    options.add_hook("connect_timeout") do |key, value|
      client.connect_timeout = value
    end
    options.add_hook("send_timeout") do |key, value|
      client.send_timeout = value
    end
    options.add_hook("receive_timeout") do |key, value|
      client.receive_timeout = value
    end
  end


set_basic_auth (SOAP::HTTPConfigLoader)

# File lib/soap/httpconfigloader.rb, line 54
  def set_basic_auth(client, basic_auth)
    basic_auth.values.each do |url, userid, passwd|
      client.set_basic_auth(url, userid, passwd)
    end
  end


set_ssl_config (SOAP::HTTPConfigLoader)

# File lib/soap/httpconfigloader.rb, line 60
  def set_ssl_config(client, ssl_config)
    ssl_config.each do |key, value|
      cfg = client.ssl_config
      if cfg.nil?
        raise NotImplementedError.new("SSL not supported")
      end
      case key
      when 'client_cert'
        cfg.client_cert = cert_from_file(value)
      when 'client_key'
        cfg.client_key = key_from_file(value)
      when 'client_ca'
        cfg.client_ca = value
      when 'ca_path'
        cfg.set_trust_ca(value)
      when 'ca_file'
        cfg.set_trust_ca(value)
      when 'crl'
        cfg.set_crl(value)
      when 'verify_mode'
        cfg.verify_mode = ssl_config_int(value)
      when 'verify_depth'
        cfg.verify_depth = ssl_config_int(value)
      when 'options'
        cfg.options = value
      when 'ciphers'
        cfg.ciphers = value
      when 'verify_callback'
        cfg.verify_callback = value
      when 'cert_store'
        cfg.cert_store = value
      else
        raise ArgumentError.new("unknown ssl_config property #{key}")
      end
    end
  end


ssl_config_int (SOAP::HTTPConfigLoader)

# File lib/soap/httpconfigloader.rb, line 97
  def ssl_config_int(value)
    if value.nil? or value.to_s.empty?
      nil
    else
      begin
        Integer(value)
      rescue ArgumentError
        ::SOAP::Property::Util.const_from_name(value.to_s)
      end
    end
  end


cert_from_file (SOAP::HTTPConfigLoader)

# File lib/soap/httpconfigloader.rb, line 109
  def cert_from_file(filename)
    OpenSSL::X509::Certificate.new(File.open(filename) { |f| f.read })
  end


key_from_file (SOAP::HTTPConfigLoader)

# File lib/soap/httpconfigloader.rb, line 113
  def key_from_file(filename)
    OpenSSL::PKey::RSA.new(File.open(filename) { |f| f.read })
  end


new (SOAP::HTTPStreamHandler)

# File lib/soap/streamHandler.rb, line 83
  def initialize(options)
    super()
    @client = Client.new(nil, "SOAP4R/#{ Version }")
    @wiredump_file_base = nil
    @charset = @wiredump_dev = nil
    @options = options
    set_options
    @client.debug_dev = @wiredump_dev
    @cookie_store = nil
    @accept_encoding_gzip = false
  end


test_loopback_response (SOAP::HTTPStreamHandler)

# File lib/soap/streamHandler.rb, line 95
  def test_loopback_response
    @client.test_loopback_response
  end


accept_encoding_gzip= (SOAP::HTTPStreamHandler)

# File lib/soap/streamHandler.rb, line 99
  def accept_encoding_gzip=(allow)
    @accept_encoding_gzip = allow
  end


inspect (SOAP::HTTPStreamHandler)

# File lib/soap/streamHandler.rb, line 103
  def inspect
    "#<#{self.class}>"
  end


send (SOAP::HTTPStreamHandler)

# File lib/soap/streamHandler.rb, line 107
  def send(endpoint_url, conn_data, soapaction = nil, charset = @charset)
    conn_data.soapaction ||= soapaction # for backward conpatibility
    send_post(endpoint_url, conn_data, charset)
  end


reset (SOAP::HTTPStreamHandler)

# File lib/soap/streamHandler.rb, line 112
  def reset(endpoint_url = nil)
    if endpoint_url.nil?
      @client.reset_all
    else
      @client.reset(endpoint_url)
    end
    @client.save_cookie_store if @cookie_store
  end


new (SOAP::Mapping::ArrayFactory_)

# File lib/soap/mapping/factory.rb, line 206
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end


obj2soap (SOAP::Mapping::ArrayFactory_)

# File lib/soap/mapping/factory.rb, line 213
  def obj2soap(soap_class, obj, info, map)
    if !@allow_original_mapping and !obj.instance_variables.empty?
      return nil
    end
    arytype = Mapping.obj2element(obj)
    if arytype.name
      arytype.namespace ||= RubyTypeNamespace
    else
      arytype = XSD::AnyTypeName
    end
    soap_obj = SOAPArray.new(ValueArrayName, 1, arytype)
    mark_marshalled_obj(obj, soap_obj)
    obj.each do |item|
      soap_obj.add(Mapping._obj2soap(item, map))
    end
    soap_obj
  end


soap2obj (SOAP::Mapping::ArrayFactory_)

# File lib/soap/mapping/factory.rb, line 231
  def soap2obj(obj_class, node, info, map)
    obj = Mapping.create_empty_object(obj_class)
    mark_unmarshalled_obj(node, obj)
    node.soap2array(obj) do |elem|
      elem ? Mapping._soap2obj(elem, map) : nil
    end
    return true, obj
  end


obj2soap (SOAP::Mapping::AttachmentFactory)

# File lib/soap/attachment.rb, line 89
    def obj2soap(soap_class, obj, info, map)
      soap_obj = soap_class.new(obj)
      mark_marshalled_obj(obj, soap_obj)
      soap_obj
    end


soap2obj (SOAP::Mapping::AttachmentFactory)

# File lib/soap/attachment.rb, line 95
    def soap2obj(obj_class, node, info, map)
      obj = node.data
      mark_unmarshalled_obj(node, obj)
      return true, obj
    end


obj2soap (SOAP::Mapping::Base64Factory_)

# File lib/soap/mapping/factory.rb, line 177
  def obj2soap(soap_class, obj, info, map)
    return nil unless obj.instance_variables.empty?
    soap_obj = soap_class.new(obj)
    mark_marshalled_obj(obj, soap_obj) if soap_obj
    soap_obj
  end


soap2obj (SOAP::Mapping::Base64Factory_)

# File lib/soap/mapping/factory.rb, line 184
  def soap2obj(obj_class, node, info, map)
    obj = node.string
    mark_unmarshalled_obj(node, obj)
    return true, obj
  end


new (SOAP::Mapping::BasetypeFactory_)

# File lib/soap/mapping/factory.rb, line 114
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end


obj2soap (SOAP::Mapping::BasetypeFactory_)

# File lib/soap/mapping/factory.rb, line 119
  def obj2soap(soap_class, obj, info, map)
    if !@allow_original_mapping and !obj.instance_variables.empty?
      return nil
    end
    soap_obj = nil
    begin
      soap_obj = soap_class.new(obj)
    rescue XSD::ValueSpaceError
      return nil
    end
    if @allow_original_mapping
      # Basetype except String should not be multiref-ed in SOAP/1.1.
      mark_marshalled_obj(obj, soap_obj)
    end
    soap_obj
  end


soap2obj (SOAP::Mapping::BasetypeFactory_)

# File lib/soap/mapping/factory.rb, line 136
  def soap2obj(obj_class, node, info, map)
    obj = node.data
    mark_unmarshalled_obj(node, obj)
    return true, obj
  end


new (SOAP::Mapping::DateTimeFactory_)

# File lib/soap/mapping/factory.rb, line 144
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end


obj2soap (SOAP::Mapping::DateTimeFactory_)

# File lib/soap/mapping/factory.rb, line 149
  def obj2soap(soap_class, obj, info, map)
    if !@allow_original_mapping and
        Time === obj and !obj.instance_variables.empty?
      return nil
    end
    soap_obj = nil
    begin
      soap_obj = soap_class.new(obj)
    rescue XSD::ValueSpaceError
      return nil
    end
    mark_marshalled_obj(obj, soap_obj)
    soap_obj
  end


soap2obj (SOAP::Mapping::DateTimeFactory_)

# File lib/soap/mapping/factory.rb, line 164
  def soap2obj(obj_class, node, info, map)
    if node.respond_to?(:to_obj)
      obj = node.to_obj(obj_class)
      return false if obj.nil?
      mark_unmarshalled_obj(node, obj)
      return true, obj
    else
      return false
    end
  end


new (SOAP::Mapping::Factory)

# File lib/soap/mapping/factory.rb, line 16
  def initialize
    # nothing to do
  end


obj2soap (SOAP::Mapping::Factory)

# File lib/soap/mapping/factory.rb, line 20
  def obj2soap(soap_class, obj, info, map)
    raise NotImplementError.new
    # return soap_obj
  end


soap2obj (SOAP::Mapping::Factory)

# File lib/soap/mapping/factory.rb, line 25
  def soap2obj(obj_class, node, info, map)
    raise NotImplementError.new
    # return convert_succeeded_or_not, obj
  end


setiv2obj (SOAP::Mapping::Factory)

# File lib/soap/mapping/factory.rb, line 30
  def setiv2obj(obj, node, map)
    return if node.nil?
    if obj.is_a?(Array)
      setiv2ary(obj, node, map)
    else
      setiv2struct(obj, node, map)
    end
  end


setiv2soap (SOAP::Mapping::Factory)

# File lib/soap/mapping/factory.rb, line 39
  def setiv2soap(node, obj, map)
    if obj.class.class_variables.include?('@@schema_element')
      obj.class.class_eval('@@schema_element').each do |name, info|
        type, qname = info
        if qname
          elename = qname.name
        else
          elename = Mapping.name2elename(name)
        end
        node.add(elename,
          Mapping._obj2soap(obj.instance_variable_get('@' + name), map))
      end
    else
      # should we sort instance_variables?
      obj.instance_variables.each do |var|
        name = var.sub(/^@/, '')
        elename = Mapping.name2elename(name)
        node.add(elename,
          Mapping._obj2soap(obj.instance_variable_get(var), map))
      end
    end
  end


new (SOAP::Mapping::HashFactory_)

# File lib/soap/mapping/factory.rb, line 304
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end


obj2soap (SOAP::Mapping::HashFactory_)

# File lib/soap/mapping/factory.rb, line 309
  def obj2soap(soap_class, obj, info, map)
    if !@allow_original_mapping and !obj.instance_variables.empty?
      return nil
    end
    if !obj.default.nil? or
        (obj.respond_to?(:default_proc) and obj.default_proc)
      return nil
    end
    soap_obj = SOAPStruct.new(MapQName)
    mark_marshalled_obj(obj, soap_obj)
    obj.each do |key, value|
      elem = SOAPStruct.new
      elem.add("key", Mapping._obj2soap(key, map))
      elem.add("value", Mapping._obj2soap(value, map))
      # ApacheAxis allows only 'item' here.
      soap_obj.add("item", elem)
    end
    soap_obj
  end


soap2obj (SOAP::Mapping::HashFactory_)

# File lib/soap/mapping/factory.rb, line 329
  def soap2obj(obj_class, node, info, map)
    unless node.type == MapQName
      return false
    end
    if node.class == SOAPStruct and node.key?('default')
      return false
    end
    obj = Mapping.create_empty_object(obj_class)
    mark_unmarshalled_obj(node, obj)
    if node.class == SOAPStruct
      node.each do |key, value|
        obj[Mapping._soap2obj(value['key'], map)] =
          Mapping._soap2obj(value['value'], map)
      end
    else
      node.each do |value|
        obj[Mapping._soap2obj(value['key'], map)] =
          Mapping._soap2obj(value['value'], map)
      end
    end
    return true, obj
  end


new (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 65
  def initialize
    @__xmlele_type = {}
    @__xmlele = []
    @__xmlattr = {}
  end


inspect (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 71
  def inspect
    sprintf("#<%s:0x%x%s>", self.class.name, __id__,
      @__xmlele.collect { |name, value| " #{name}=#{value.inspect}" }.join)
  end


__xmlattr (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 76
  def __xmlattr
    @__xmlattr
  end


__xmlele (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 80
  def __xmlele
    @__xmlele
  end


[] (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 84
  def [](qname)
    unless qname.is_a?(XSD::QName)
      qname = XSD::QName.new(nil, qname)
    end
    @__xmlele.each do |k, v|
      return v if k == qname
    end
    # fallback
    @__xmlele.each do |k, v|
      return v if k.name == qname.name
    end
    nil
  end


[]= (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 98
  def []=(qname, value)
    unless qname.is_a?(XSD::QName)
      qname = XSD::QName.new(nil, qname)
    end
    found = false
    @__xmlele.each do |pair|
      if pair[0] == qname
        found = true
        pair[1] = value
      end
    end
    unless found
      __define_attr_accessor(qname)
      @__xmlele << [qname, value]
    end
    @__xmlele_type[qname] = :single
  end


__add_xmlele_value (SOAP::Mapping::Object)

# File lib/soap/mapping/registry.rb, line 116
  def __add_xmlele_value(qname, value)
    found = false
    @__xmlele.map! do |k, v|
      if k == qname
        found = true
        [k, __set_xmlele_value(k, v, value)]
      else
        [k, v]
      end
    end
    unless found
      __define_attr_accessor(qname)
      @__xmlele << [qname, value]
      @__xmlele_type[qname] = :single
    end
    value
  end


new (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 179
    def initialize(registry)
      @obj2soap = {}
      @soap2obj = {}
      @registry = registry
    end


obj2soap (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 185
    def obj2soap(obj)
      klass = obj.class
      if map = @obj2soap[klass]
        map.each do |soap_class, factory, info|
          ret = factory.obj2soap(soap_class, obj, info, @registry)
          return ret if ret
        end
      end
      ancestors = klass.ancestors
      ancestors.delete(klass)
      ancestors.delete(::Object)
      ancestors.delete(::Kernel)
      ancestors.each do |klass|
        if map = @obj2soap[klass]
          map.each do |soap_class, factory, info|
            if info[:derived_class]
              ret = factory.obj2soap(soap_class, obj, info, @registry)
              return ret if ret
            end
          end
        end
      end
      nil
    end


soap2obj (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 210
    def soap2obj(node, klass = nil)
      if map = @soap2obj[node.class]
        map.each do |obj_class, factory, info|
          next if klass and obj_class != klass
          conv, obj = factory.soap2obj(obj_class, node, info, @registry)
          return true, obj if conv
        end
      end
      return false, nil
    end


init (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 222
    def init(init_map = [])
      clear
      init_map.reverse_each do |obj_class, soap_class, factory, info|
        add(obj_class, soap_class, factory, info)
      end
    end


add (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 230
    def add(obj_class, soap_class, factory, info)
      info ||= {}
      (@obj2soap[obj_class] ||= []).unshift([soap_class, factory, info])
      (@soap2obj[soap_class] ||= []).unshift([obj_class, factory, info])
    end


clear (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 236
    def clear
      @obj2soap.clear
      @soap2obj.clear
    end


find_mapped_soap_class (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 241
    def find_mapped_soap_class(target_obj_class)
      map = @obj2soap[target_obj_class]
      map.empty? ? nil : map[0][1]
    end


find_mapped_obj_class (SOAP::Mapping::Registry::Map)

# File lib/soap/mapping/registry.rb, line 246
    def find_mapped_obj_class(target_soap_class)
      map = @soap2obj[target_soap_class]
      map.empty? ? nil : map[0][0]
    end


new (SOAP::Mapping::Registry)

# File lib/soap/mapping/registry.rb, line 393
  def initialize(config = {})
    @config = config
    @map = Map.new(self)
    if @config[:allow_original_mapping]
      @allow_original_mapping = true
      @map.init(RubyOriginalMap)
    else
      @allow_original_mapping = false
      @map.init(SOAPBaseMap)
    end
    @allow_untyped_struct = @config.key?(:allow_untyped_struct) ?
      @config[:allow_untyped_struct] : true
    @rubytype_factory = RubytypeFactory.new(
      :allow_untyped_struct => @allow_untyped_struct,
      :allow_original_mapping => @allow_original_mapping
    )
    @default_factory = @rubytype_factory
    @excn_handler_obj2soap = nil
    @excn_handler_soap2obj = nil
  end


add (SOAP::Mapping::Registry)

# File lib/soap/mapping/registry.rb, line 414
  def add(obj_class, soap_class, factory, info = nil)
    @map.add(obj_class, soap_class, factory, info)
  end


obj2soap (SOAP::Mapping::Registry)

# File lib/soap/mapping/registry.rb, line 420
  def obj2soap(obj, type_qname = nil)
    soap = _obj2soap(obj)
    if @allow_original_mapping
      addextend2soap(soap, obj)
    end
    soap
  end


soap2obj (SOAP::Mapping::Registry)

# File lib/soap/mapping/registry.rb, line 428
  def soap2obj(node, klass = nil)
    obj = _soap2obj(node, klass)
    if @allow_original_mapping
      addextend2obj(obj, node.extraattr[RubyExtendName])
      addiv2obj(obj, node.extraattr[RubyIVarName])
    end
    obj
  end


find_mapped_soap_class (SOAP::Mapping::Registry)

# File lib/soap/mapping/registry.rb, line 437
  def find_mapped_soap_class(obj_class)
    @map.find_mapped_soap_class(obj_class)
  end


find_mapped_obj_class (SOAP::Mapping::Registry)

# File lib/soap/mapping/registry.rb, line 441
  def find_mapped_obj_class(soap_class)
    @map.find_mapped_obj_class(soap_class)
  end


new (SOAP::Mapping::RubytypeFactory)

# File lib/soap/mapping/rubytypeFactory.rb, line 25
  def initialize(config = {})
    @config = config
    @allow_untyped_struct = @config.key?(:allow_untyped_struct) ?
      @config[:allow_untyped_struct] : true
    @allow_original_mapping = @config.key?(:allow_original_mapping) ?
      @config[:allow_original_mapping] : false
    @string_factory = StringFactory_.new(true)
    @basetype_factory = BasetypeFactory_.new(true)
    @datetime_factory = DateTimeFactory_.new(true)
    @array_factory = ArrayFactory_.new(true)
    @hash_factory = HashFactory_.new(true)
  end


obj2soap (SOAP::Mapping::RubytypeFactory)

# File lib/soap/mapping/rubytypeFactory.rb, line 38
  def obj2soap(soap_class, obj, info, map)
    param = nil
    case obj
    when ::String
      unless @allow_original_mapping
        return nil
      end
      param = @string_factory.obj2soap(SOAPString, obj, info, map)
      if obj.class != String
        param.extraattr[RubyTypeName] = obj.class.name
      end
      addiv2soapattr(param, obj, map)
    when ::Time
      unless @allow_original_mapping
        return nil
      end
      param = @datetime_factory.obj2soap(SOAPDateTime, obj, info, map)
      if obj.class != Time
        param.extraattr[RubyTypeName] = obj.class.name
      end
      addiv2soapattr(param, obj, map)
    when ::Array
      unless @allow_original_mapping
        return nil
      end
      param = @array_factory.obj2soap(nil, obj, info, map)
      if obj.class != Array
        param.extraattr[RubyTypeName] = obj.class.name
      end
      addiv2soapattr(param, obj, map)
    when ::NilClass
      unless @allow_original_mapping
        return nil
      end
      param = @basetype_factory.obj2soap(SOAPNil, obj, info, map)
      addiv2soapattr(param, obj, map)
    when ::FalseClass, ::TrueClass
      unless @allow_original_mapping
        return nil
      end
      param = @basetype_factory.obj2soap(SOAPBoolean, obj, info, map)
      addiv2soapattr(param, obj, map)
    when ::Integer
      unless @allow_original_mapping
        return nil
      end
      param = @basetype_factory.obj2soap(SOAPInt, obj, info, map)
      param ||= @basetype_factory.obj2soap(SOAPInteger, obj, info, map)
      param ||= @basetype_factory.obj2soap(SOAPDecimal, obj, info, map)
      addiv2soapattr(param, obj, map)
    when ::Float
      unless @allow_original_mapping
        return nil
      end
      param = @basetype_factory.obj2soap(SOAPDouble, obj, info, map)
      if obj.class != Float
        param.extraattr[RubyTypeName] = obj.class.name
      end
      addiv2soapattr(param, obj, map)
    when ::Hash
      unless @allow_original_mapping
        return nil
      end
      if obj.respond_to?(:default_proc) && obj.default_proc
        raise TypeError.new("cannot dump hash with default proc")
      end
      param = SOAPStruct.new(TYPE_HASH)
      mark_marshalled_obj(obj, param)
      if obj.class != Hash
        param.extraattr[RubyTypeName] = obj.class.name
      end
      obj.each do |key, value|
        elem = SOAPStruct.new # Undefined type.
        elem.add("key", Mapping._obj2soap(key, map))
        elem.add("value", Mapping._obj2soap(value, map))
        param.add("item", elem)
      end
      param.add('default', Mapping._obj2soap(obj.default, map))
      addiv2soapattr(param, obj, map)
    when ::Regexp
      unless @allow_original_mapping
        return nil
      end
      param = SOAPStruct.new(TYPE_REGEXP)
      mark_marshalled_obj(obj, param)
      if obj.class != Regexp
        param.extraattr[RubyTypeName] = obj.class.name
      end
      param.add('source', SOAPBase64.new(obj.source))
      if obj.respond_to?('options')
        # Regexp#options is from Ruby/1.7
        options = obj.options
      else
        options = 0
        obj.inspect.sub(/^.*\//, '').each_byte do |c|
          options += case c
            when ?i
              1
            when ?x
              2
            when ?m
              4
            when ?n
              16
            when ?e
              32
            when ?s
              48
            when ?u
              64
            end
        end
      end
      param.add('options', SOAPInt.new(options))
      addiv2soapattr(param, obj, map)
    when ::Range
      unless @allow_original_mapping
        return nil
      end
      param = SOAPStruct.new(TYPE_RANGE)
      mark_marshalled_obj(obj, param)
      if obj.class != Range
        param.extraattr[RubyTypeName] = obj.class.name
      end
      param.add('begin', Mapping._obj2soap(obj.begin, map))
      param.add('end', Mapping._obj2soap(obj.end, map))
      param.add('exclude_end', SOAP::SOAPBoolean.new(obj.exclude_end?))
      addiv2soapattr(param, obj, map)
    when ::Class
      unless @allow_original_mapping
        return nil
      end
      if obj.to_s[0] == ?#
        raise TypeError.new("can't dump anonymous class #{obj}")
      end
      param = SOAPStruct.new(TYPE_CLASS)
      mark_marshalled_obj(obj, param)
      param.add('name', SOAPString.new(obj.name))
      addiv2soapattr(param, obj, map)
    when ::Module
      unless @allow_original_mapping
        return nil
      end
      if obj.to_s[0] == ?#
        raise TypeError.new("can't dump anonymous module #{obj}")
      end
      param = SOAPStruct.new(TYPE_MODULE)
      mark_marshalled_obj(obj, param)
      param.add('name', SOAPString.new(obj.name))
      addiv2soapattr(param, obj, map)
    when ::Symbol
      unless @allow_original_mapping
        return nil
      end
      param = SOAPStruct.new(TYPE_SYMBOL)
      mark_marshalled_obj(obj, param)
      param.add('id', SOAPString.new(obj.id2name))
      addiv2soapattr(param, obj, map)
    when ::Struct
      unless @allow_original_mapping
        # treat it as an user defined class. [ruby-talk:104980]
        #param = unknownobj2soap(soap_class, obj, info, map)
        param = SOAPStruct.new(XSD::AnyTypeName)
        mark_marshalled_obj(obj, param)
        obj.members.each do |member|
          param.add(Mapping.name2elename(member),
            Mapping._obj2soap(obj[member], map))
        end
      else
        param = SOAPStruct.new(TYPE_STRUCT)
        mark_marshalled_obj(obj, param)
        param.add('type', ele_type = SOAPString.new(obj.class.to_s))
        ele_member = SOAPStruct.new
        obj.members.each do |member|
          ele_member.add(Mapping.name2elename(member),
            Mapping._obj2soap(obj[member], map))
        end
        param.add('member', ele_member)
        addiv2soapattr(param, obj, map)
      end
    when ::IO, ::Binding, ::Continuation, ::Data, ::Dir, ::File::Stat,
        ::MatchData, Method, ::Proc, ::Thread, ::ThreadGroup
        # from 1.8: Process::Status, UnboundMethod
      return nil
    when ::SOAP::Mapping::Object
      param = SOAPStruct.new(XSD::AnyTypeName)
      mark_marshalled_obj(obj, param)
      obj.__xmlele.each do |key, value|
        param.add(key.name, Mapping._obj2soap(value, map))
      end
      obj.__xmlattr.each do |key, value|
        param.extraattr[key] = value
      end
    when ::Exception
      typestr = Mapping.name2elename(obj.class.to_s)
      param = SOAPStruct.new(XSD::QName.new(RubyTypeNamespace, typestr))
      mark_marshalled_obj(obj, param)
      param.add('message', Mapping._obj2soap(obj.message, map))
      param.add('backtrace', Mapping._obj2soap(obj.backtrace, map))
      addiv2soapattr(param, obj, map)
    else
      param = unknownobj2soap(soap_class, obj, info, map)
    end
    param
  end


soap2obj (SOAP::Mapping::RubytypeFactory)

# File lib/soap/mapping/rubytypeFactory.rb, line 244
  def soap2obj(obj_class, node, info, map)
    rubytype = node.extraattr[RubyTypeName]
    if rubytype or node.type.namespace == RubyTypeNamespace
      rubytype2obj(node, info, map, rubytype)
    elsif node.type == XSD::AnyTypeName or node.type == XSD::AnySimpleTypeName
      anytype2obj(node, info, map)
    else
      unknowntype2obj(node, info, map)
    end
  end


new (SOAP::Mapping::SOAPException)

# File lib/soap/mapping/registry.rb, line 38
  def initialize(e)
    @excn_type_name = Mapping.name2elename(e.class.to_s)
    @cause = e
  end


to_e (SOAP::Mapping::SOAPException)

# File lib/soap/mapping/registry.rb, line 43
  def to_e
    if @cause.is_a?(::Exception)
      @cause.extend(::SOAP::Mapping::MappedException)
      return @cause
    elsif @cause.respond_to?(:message) and @cause.respond_to?(:backtrace)
      e = RuntimeError.new(@cause.message)
      e.set_backtrace(@cause.backtrace)
      return e
    end
    klass = Mapping.class_from_name(Mapping.elename2name(@excn_type_name.to_s))
    if klass.nil? or not klass <= ::Exception
      return RuntimeError.new(@cause.inspect)
    end
    obj = klass.new(@cause.message)
    obj.extend(::SOAP::Mapping::MappedException)
    obj
  end


new (SOAP::Mapping::StringFactory_)

# File lib/soap/mapping/factory.rb, line 80
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end


obj2soap (SOAP::Mapping::StringFactory_)

# File lib/soap/mapping/factory.rb, line 85
  def obj2soap(soap_class, obj, info, map)
    if !@allow_original_mapping and !obj.instance_variables.empty?
      return nil
    end
    begin
      unless XSD::Charset.is_ces(obj, Thread.current[:SOAPExternalCES])
        return nil
      end
      encoded = XSD::Charset.encoding_conv(obj,
        Thread.current[:SOAPExternalCES], XSD::Charset.encoding)
      soap_obj = soap_class.new(encoded)
    rescue XSD::ValueSpaceError
      return nil
    end
    mark_marshalled_obj(obj, soap_obj)
    soap_obj
  end


soap2obj (SOAP::Mapping::StringFactory_)

# File lib/soap/mapping/factory.rb, line 103
  def soap2obj(obj_class, node, info, map)
    obj = Mapping.create_empty_object(obj_class)
    decoded = XSD::Charset.encoding_conv(node.data, XSD::Charset.encoding,
      Thread.current[:SOAPExternalCES])
    obj.replace(decoded)
    mark_unmarshalled_obj(node, obj)
    return true, obj
  end


mark_marshalled_obj (SOAP::Mapping::TraverseSupport)

# File lib/soap/mapping/mapping.rb, line 26
    def mark_marshalled_obj(obj, soap_obj)
      raise if obj.nil?
      Thread.current[:SOAPMarshalDataKey][obj.__id__] = soap_obj
    end


mark_unmarshalled_obj (SOAP::Mapping::TraverseSupport)

# File lib/soap/mapping/mapping.rb, line 31
    def mark_unmarshalled_obj(node, obj)
      return if obj.nil?
      # node.id is not Object#id but SOAPReference#id
      Thread.current[:SOAPMarshalDataKey][node.id] = obj
    end


new (SOAP::Mapping::TypedArrayFactory_)

# File lib/soap/mapping/factory.rb, line 242
  def initialize(allow_original_mapping = false)
    super()
    @allow_original_mapping = allow_original_mapping
  end


obj2soap (SOAP::Mapping::TypedArrayFactory_)

# File lib/soap/mapping/factory.rb, line 247
  def obj2soap(soap_class, obj, info, map)
    if !@allow_original_mapping and !obj.instance_variables.empty?
      return nil
    end
    arytype = info[:type] || info[0]
    soap_obj = SOAPArray.new(ValueArrayName, 1, arytype)
    mark_marshalled_obj(obj, soap_obj)
    obj.each do |var|
      soap_obj.add(Mapping._obj2soap(var, map))
    end
    soap_obj
  end


soap2obj (SOAP::Mapping::TypedArrayFactory_)

# File lib/soap/mapping/factory.rb, line 260
  def soap2obj(obj_class, node, info, map)
    if node.rank > 1
      return false
    end
    arytype = info[:type] || info[0]
    unless node.arytype == arytype
      return false
    end
    obj = Mapping.create_empty_object(obj_class)
    mark_unmarshalled_obj(node, obj)
    node.soap2array(obj) do |elem|
      elem ? Mapping._soap2obj(elem, map) : nil
    end
    return true, obj
  end


obj2soap (SOAP::Mapping::TypedStructFactory_)

# File lib/soap/mapping/factory.rb, line 278
  def obj2soap(soap_class, obj, info, map)
    type = info[:type] || info[0]
    soap_obj = soap_class.new(type)
    mark_marshalled_obj(obj, soap_obj)
    if obj.class <= SOAP::Marshallable
      setiv2soap(soap_obj, obj, map)
    else
      setiv2soap(soap_obj, obj, map)
    end
    soap_obj
  end


soap2obj (SOAP::Mapping::TypedStructFactory_)

# File lib/soap/mapping/factory.rb, line 290
  def soap2obj(obj_class, node, info, map)
    type = info[:type] || info[0]
    unless node.type == type
      return false
    end
    obj = Mapping.create_empty_object(obj_class)
    mark_unmarshalled_obj(node, obj)
    setiv2obj(obj, node, map)
    return true, obj
  end


obj2soap (SOAP::Mapping::URIFactory_)

# File lib/soap/mapping/factory.rb, line 192
  def obj2soap(soap_class, obj, info, map)
    soap_obj = soap_class.new(obj)
    mark_marshalled_obj(obj, soap_obj) if soap_obj
    soap_obj
  end


soap2obj (SOAP::Mapping::URIFactory_)

# File lib/soap/mapping/factory.rb, line 198
  def soap2obj(obj_class, node, info, map)
    obj = node.data
    mark_unmarshalled_obj(node, obj)
    return true, obj
  end


new (SOAP::Mapping::WSDLEncodedRegistry)

# File lib/soap/mapping/wsdlencodedregistry.rb, line 28
  def initialize(definedtypes = XSD::NamedElements::Empty)
    @definedtypes = definedtypes
    # @definedelements = definedelements  needed?
    @excn_handler_obj2soap = nil
    @excn_handler_soap2obj = nil
    # For mapping AnyType element.
    @rubytype_factory = RubytypeFactory.new(
      :allow_untyped_struct => true,
      :allow_original_mapping => true
    )
    @schema_element_cache = {}
  end


obj2soap (SOAP::Mapping::WSDLEncodedRegistry)

# File lib/soap/mapping/wsdlencodedregistry.rb, line 41
  def obj2soap(obj, qname = nil)
    soap_obj = nil
    if type = @definedtypes[qname]
      soap_obj = obj2typesoap(obj, type)
    else
      soap_obj = any2soap(obj, qname)
    end
    return soap_obj if soap_obj
    if @excn_handler_obj2soap
      soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj|
        Mapping._obj2soap(yield_obj, self)
      }
      return soap_obj if soap_obj
    end
    if qname
      raise MappingError.new("cannot map #{obj.class.name} as #{qname}")
    else
      raise MappingError.new("cannot map #{obj.class.name} to SOAP/OM")
    end
  end


soap2obj (SOAP::Mapping::WSDLEncodedRegistry)

# File lib/soap/mapping/wsdlencodedregistry.rb, line 63
  def soap2obj(node, obj_class = nil)
    begin
      return any2obj(node, obj_class)
    rescue MappingError
    end
    if @excn_handler_soap2obj
      begin
        return @excn_handler_soap2obj.call(node) { |yield_node|
            Mapping._soap2obj(yield_node, self)
          }
      rescue Exception
      end
    end
    raise MappingError.new("cannot map #{node.type.name} to Ruby object")
  end


new (SOAP::Mapping::WSDLLiteralRegistry)

# File lib/soap/mapping/wsdlliteralregistry.rb, line 26
  def initialize(definedtypes = XSD::NamedElements::Empty,
      definedelements = XSD::NamedElements::Empty)
    @definedtypes = definedtypes
    @definedelements = definedelements
    @excn_handler_obj2soap = nil
    @excn_handler_soap2obj = nil
    @schema_element_cache = {}
    @schema_attribute_cache = {}
  end


obj2soap (SOAP::Mapping::WSDLLiteralRegistry)

# File lib/soap/mapping/wsdlliteralregistry.rb, line 36
  def obj2soap(obj, qname)
    soap_obj = nil
    if ele = @definedelements[qname]
      soap_obj = obj2elesoap(obj, ele)
    elsif type = @definedtypes[qname]
      soap_obj = obj2typesoap(obj, type, true)
    else
      soap_obj = any2soap(obj, qname)
    end
    return soap_obj if soap_obj
    if @excn_handler_obj2soap
      soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj|
        Mapping.obj2soap(yield_obj, nil, nil, MAPPING_OPT)
      }
      return soap_obj if soap_obj
    end
    raise MappingError.new("cannot map #{obj.class.name} as #{qname}")
  end


soap2obj (SOAP::Mapping::WSDLLiteralRegistry)

# File lib/soap/mapping/wsdlliteralregistry.rb, line 56
  def soap2obj(node, obj_class = nil)
    # obj_class is given when rpc/literal service.  but ignored for now.
    begin
      return any2obj(node)
    rescue MappingError
    end
    if @excn_handler_soap2obj
      begin
        return @excn_handler_soap2obj.call(node) { |yield_node|
            Mapping.soap2obj(yield_node, nil, nil, MAPPING_OPT)
          }
      rescue Exception
      end
    end
    if node.respond_to?(:type)
      raise MappingError.new("cannot map #{node.type.name} to Ruby object")
    else
      raise MappingError.new("cannot map #{node.elename.name} to Ruby object")
    end
  end


obj2soap (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 40
  def self.obj2soap(obj, registry = nil, type = nil, opt = EMPTY_OPT)
    registry ||= Mapping::DefaultRegistry
    soap_obj = nil
    protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
      Thread.current[:SOAPMarshalDataKey] = {}
      Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
      Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
      soap_obj = _obj2soap(obj, registry, type)
    end
    soap_obj
  end


soap2obj (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 52
  def self.soap2obj(node, registry = nil, klass = nil, opt = EMPTY_OPT)
    registry ||= Mapping::DefaultRegistry
    obj = nil
    protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
      Thread.current[:SOAPMarshalDataKey] = {}
      Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
      Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
      obj = _soap2obj(node, registry, klass)
    end
    obj
  end


ary2soap (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 64
  def self.ary2soap(ary, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)
    registry ||= Mapping::DefaultRegistry
    type = XSD::QName.new(type_ns, typename)
    soap_ary = SOAPArray.new(ValueArrayName, 1, type)
    protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
      Thread.current[:SOAPMarshalDataKey] = {}
      Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
      Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
      ary.each do |ele|
        soap_ary.add(_obj2soap(ele, registry, type))
      end
    end
    soap_ary
  end


ary2md (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 79
  def self.ary2md(ary, rank, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)
    registry ||= Mapping::DefaultRegistry
    type = XSD::QName.new(type_ns, typename)
    md_ary = SOAPArray.new(ValueArrayName, rank, type)
    protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
      Thread.current[:SOAPMarshalDataKey] = {}
      Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
      Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
      add_md_ary(md_ary, ary, [], registry)
    end
    md_ary
  end


fault2exception (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 92
  def self.fault2exception(fault, registry = nil)
    registry ||= Mapping::DefaultRegistry
    detail = if fault.detail
        soap2obj(fault.detail, registry) || ""
      else
        ""
      end
    if detail.is_a?(Mapping::SOAPException)
      begin
        e = detail.to_e
        remote_backtrace = e.backtrace
        e.set_backtrace(nil)
        raise e # ruby sets current caller as local backtrace of e => e2.
      rescue Exception => e
        e.set_backtrace(remote_backtrace + e.backtrace[1..-1])
        raise
      end
    else
      fault.detail = detail
      fault.set_backtrace(
        if detail.is_a?(Array)
          detail
        else
          [detail.to_s]
        end
      )
      raise
    end
  end


_obj2soap (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 122
  def self._obj2soap(obj, registry, type = nil)
    if referent = Thread.current[:SOAPMarshalDataKey][obj.__id__] and
        !Thread.current[:SOAPMarshalNoReference]
      SOAPReference.new(referent)
    elsif registry
      registry.obj2soap(obj, type)
    else
      raise MappingError.new("no mapping registry given")
    end
  end


_soap2obj (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 133
  def self._soap2obj(node, registry, klass = nil)
    if node.nil?
      return nil
    elsif node.is_a?(SOAPReference)
      target = node.__getobj__
      # target.id is not Object#id but SOAPReference#id
      if referent = Thread.current[:SOAPMarshalDataKey][target.id] and
          !Thread.current[:SOAPMarshalNoReference]
        return referent
      else
        return _soap2obj(target, registry, klass)
      end
    end
    return registry.soap2obj(node, klass)
  end


create_empty_object (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 151
    def self.create_empty_object(klass)
      klass.allocate
    end


create_empty_object (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 161
    def self.create_empty_object(klass)
      if klass <= Struct
        name = klass.name
        return ::Marshal.load(sprintf("\004\006S:%c%s\000", name.length + 5, name))
      end
      if MARSHAL_TAG.has_key?(klass)
        tag, terminate = MARSHAL_TAG[klass]
        return ::Marshal.load(sprintf("\004\006%s%s", tag, "\000" * terminate))
      end
      MARSHAL_TAG.each do |k, v|
        if klass < k
          name = klass.name
          tag, terminate = v
          return ::Marshal.load(sprintf("\004\006C:%c%s%s%s", name.length + 5, name, tag, "\000" * terminate))
        end
      end
      name = klass.name
      ::Marshal.load(sprintf("\004\006o:%c%s\000", name.length + 5, name))
    end


name2elename (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 188
  def self.name2elename(name)
    name.gsub(/([^a-zA-Z0-9:_\-]+)/n) {
      '.' << $1.unpack('H2' * $1.size).join('.')
    }.gsub(/::/n, '..')
  end


elename2name (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 194
  def self.elename2name(name)
    name.gsub(/\.\./n, '::').gsub(/((?:\.[0-9a-fA-F]{2})+)/n) {
      [$1.delete('.')].pack('H*')
    }
  end


const_from_name (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 200
  def self.const_from_name(name, lenient = false)
    const = ::Object
    name.sub(/\A::/, '').split('::').each do |const_str|
      if XSD::CodeGen::GenSupport.safeconstname?(const_str)
        if const.const_defined?(const_str)
          const = const.const_get(const_str)
          next
        end
      elsif lenient
        const_str = XSD::CodeGen::GenSupport.safeconstname(const_str)
        if const.const_defined?(const_str)
          const = const.const_get(const_str)
          next
        end
      end
      return nil
    end
    const
  end


class_from_name (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 220
  def self.class_from_name(name, lenient = false)
    const = const_from_name(name, lenient)
    if const.is_a?(::Class)
      const
    else
      nil
    end
  end


module_from_name (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 229
  def self.module_from_name(name, lenient = false)
    const = const_from_name(name, lenient)
    if const.is_a?(::Module)
      const
    else
      nil
    end
  end


class2qname (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 238
  def self.class2qname(klass)
    name = schema_type_definition(klass)
    namespace = schema_ns_definition(klass)
    XSD::QName.new(namespace, name)
  end


class2element (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 244
  def self.class2element(klass)
    type = Mapping.class2qname(klass)
    type.name ||= Mapping.name2elename(klass.name)
    type.namespace ||= RubyCustomTypeNamespace
    type
  end


obj2element (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 251
  def self.obj2element(obj)
    name = namespace = nil
    ivars = obj.instance_variables
    if ivars.include?('@schema_type')
      name = obj.instance_variable_get('@schema_type')
    end
    if ivars.include?('@schema_ns')
      namespace = obj.instance_variable_get('@schema_ns')
    end
    if !name or !namespace
      class2qname(obj.class)
    else
      XSD::QName.new(namespace, name)
    end
  end


define_singleton_method (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 267
  def self.define_singleton_method(obj, name, &block)
    sclass = (class << obj; self; end)
    sclass.class_eval {
      define_method(name, &block)
    }
  end


get_attribute (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 274
  def self.get_attribute(obj, attr_name)
    if obj.is_a?(::Hash)
      obj[attr_name] || obj[attr_name.intern]
    else
      name = XSD::CodeGen::GenSupport.safevarname(attr_name)
      if obj.instance_variables.include?('@' + name)
        obj.instance_variable_get('@' + name)
      elsif ((obj.is_a?(::Struct) or obj.is_a?(Marshallable)) and
          obj.respond_to?(name))
        obj.__send__(name)
      end
    end
  end


set_attributes (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 288
  def self.set_attributes(obj, values)
    if obj.is_a?(::SOAP::Mapping::Object)
      values.each do |attr_name, value|
        obj.__add_xmlele_value(attr_name, value)
      end
    else
      values.each do |attr_name, value|
        name = XSD::CodeGen::GenSupport.safevarname(attr_name)
        setter = name + "="
        if obj.respond_to?(setter)
          obj.__send__(setter, value)
        else
          obj.instance_variable_set('@' + name, value)
          begin
            define_attr_accessor(obj, name,
              proc { instance_variable_get('@' + name) },
              proc { |value| instance_variable_set('@' + name, value) })
          rescue TypeError
            # singleton class may not exist (e.g. Float)
          end
        end
      end
    end
  end


define_attr_accessor (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 313
  def self.define_attr_accessor(obj, name, getterproc, setterproc = nil)
    define_singleton_method(obj, name, &getterproc)
    define_singleton_method(obj, name + '=', &setterproc) if setterproc
  end


schema_type_definition (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 318
  def self.schema_type_definition(klass)
    class_schema_variable(:schema_type, klass)
  end


schema_ns_definition (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 322
  def self.schema_ns_definition(klass)
    class_schema_variable(:schema_ns, klass)
  end


schema_element_definition (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 326
  def self.schema_element_definition(klass)
    schema_element = class_schema_variable(:schema_element, klass) or return nil
    schema_ns = schema_ns_definition(klass)
    elements = []
    as_array = []
    schema_element.each do |varname, definition|
      class_name, name = definition
      if /\[\]$/ =~ class_name
        class_name = class_name.sub(/\[\]$/, '')
        as_array << (name ? name.name : varname)
      end
      elements << [name || XSD::QName.new(schema_ns, varname), class_name]
    end
    [elements, as_array]
  end


schema_attribute_definition (SOAP::Mapping)

# File lib/soap/mapping/mapping.rb, line 342
  def self.schema_attribute_definition(klass)
    class_schema_variable(:schema_attribute, klass)
  end


dump (SOAP::Marshal)

# File lib/soap/marshal.rb, line 28
    def dump(obj, io = nil)
      marshal(obj, MarshalMappingRegistry, io)
    end


load (SOAP::Marshal)

# File lib/soap/marshal.rb, line 32
    def load(stream)
      unmarshal(stream, MarshalMappingRegistry)
    end


marshal (SOAP::Marshal)

# File lib/soap/marshal.rb, line 36
    def marshal(obj, mapping_registry = MarshalMappingRegistry, io = nil)
      elename = Mapping.name2elename(obj.class.to_s)
      soap_obj = Mapping.obj2soap(obj, mapping_registry)
      body = SOAPBody.new
      body.add(elename, soap_obj)
      env = SOAPEnvelope.new(nil, body)
      SOAP::Processor.marshal(env, {}, io)
    end


unmarshal (SOAP::Marshal)

# File lib/soap/marshal.rb, line 45
    def unmarshal(stream, mapping_registry = MarshalMappingRegistry)
      env = SOAP::Processor.unmarshal(stream)
      if env.nil?
        raise ArgumentError.new("Illegal SOAP marshal format.")
      end
      Mapping.soap2obj(env.body.root_node, mapping_registry)
    end


new (SOAP::MIMEMessage::Header)

# File lib/soap/mimemessage.rb, line 28
    def initialize
      @attrs = {}
    end


[] (SOAP::MIMEMessage::Header)

# File lib/soap/mimemessage.rb, line 32
    def [](key)
      @attrs[key]
    end


[]= (SOAP::MIMEMessage::Header)

# File lib/soap/mimemessage.rb, line 36
    def []=(key, value)
      @attrs[key] = value
    end


to_s (SOAP::MIMEMessage::Header)

# File lib/soap/mimemessage.rb, line 40
    def to_s
      @key + ": " + @str
    end


parse (SOAP::MIMEMessage::Headers)

# File lib/soap/mimemessage.rb, line 46
    def self.parse(str)
      new.parse(str)
    end


parse (SOAP::MIMEMessage::Headers)

# File lib/soap/mimemessage.rb, line 50
    def parse(str)
      header_cache = nil
      str.each do |line|
        case line
        when /^\A[^\: \t]+:\s*.+$/
          parse_line(header_cache) if header_cache
          header_cache = line.sub(/\r?\n\z/, '')
        when /^\A\s+(.*)$/
          # a continuous line at the beginning line crashes here.
          header_cache << line
        else
          raise RuntimeError.new("unexpected header: #{line.inspect}")
        end
      end
      parse_line(header_cache) if header_cache
      self
    end


parse_line (SOAP::MIMEMessage::Headers)

# File lib/soap/mimemessage.rb, line 68
    def parse_line(line)
      if /^\A([^\: \t]+):\s*(.+)\z/ =~ line
        header = parse_rhs($2.strip)
        header.key = $1.strip
        self[header.key.downcase] = header
      else
        raise RuntimeError.new("unexpected header line: #{line.inspect}")
      end
    end


parse_rhs (SOAP::MIMEMessage::Headers)

# File lib/soap/mimemessage.rb, line 78
    def parse_rhs(str)
      a = str.split(/;+\s+/)
      header = Header.new
      header.str = str
      header.root = a.shift
      a.each do |pair|
        if pair =~ /(\w+)\s*=\s*"?([^"]+)"?/
          header[$1.downcase] = $2
        else
          raise RuntimeError.new("unexpected header component: #{pair.inspect}")
        end
      end
      header
    end


add (SOAP::MIMEMessage::Headers)

# File lib/soap/mimemessage.rb, line 93
    def add(key, value)
      if key != nil and value != nil
        header = parse_rhs(value)
        header.key = key
        self[key.downcase] = header
      end
    end


to_s (SOAP::MIMEMessage::Headers)

# File lib/soap/mimemessage.rb, line 101
    def to_s
      self.values.collect { |hdr|
        hdr.to_s
      }.join("\r\n")
    end


new (SOAP::MIMEMessage::Part)

# File lib/soap/mimemessage.rb, line 111
    def initialize
      @headers = Headers.new
      @headers.add("Content-Transfer-Encoding", "8bit")
      @body = nil
      @contentid = nil
    end


parse (SOAP::MIMEMessage::Part)

# File lib/soap/mimemessage.rb, line 118
    def self.parse(str)
      new.parse(str)
    end


parse (SOAP::MIMEMessage::Part)

# File lib/soap/mimemessage.rb, line 122
    def parse(str)
      headers, body = str.split(/\r\n\r\n/s)
      if headers != nil and body != nil
        @headers = Headers.parse(headers)
        @body = body.sub(/\r\n\z/, '')
      else
        raise RuntimeError.new("unexpected part: #{str.inspect}")
      end
      self
    end


contentid (SOAP::MIMEMessage::Part)

# File lib/soap/mimemessage.rb, line 133
    def contentid
      if @contentid == nil and @headers.key?('content-id')
        @contentid = @headers['content-id'].str
        @contentid = $1 if @contentid =~ /^<(.+)>$/
      end
      @contentid
    end


to_s (SOAP::MIMEMessage::Part)

# File lib/soap/mimemessage.rb, line 143
    def to_s
      @headers.to_s + "\r\n\r\n" + @body
    end


new (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 148
  def initialize
    @parts = []
    @headers = Headers.new
    @root = nil
  end


parse (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 154
  def self.parse(head, str)
    new.parse(head, str)
  end


close (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 160
  def close
    @headers.add(
      "Content-Type",
      "multipart/related; type=\"text/xml\"; boundary=\"#{boundary}\"; start=\"#{@parts[0].contentid}\""
    )
  end


parse (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 167
  def parse(head, str)
    @headers = Headers.parse(head + "\r\n" + "From: jfh\r\n")
    boundary = @headers['content-type']['boundary']
    if boundary != nil
      parts = str.split(/--#{Regexp.quote(boundary)}\s*(?:\r\n|--\r\n)/)
      part = parts.shift        # preamble must be ignored.
      @parts = parts.collect { |part| Part.parse(part) }
    else
      @parts = [Part.parse(str)]
    end
    if @parts.length < 1
      raise MIMEMessageError.new("This message contains no valid parts!")
    end
    self
  end


root (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 183
  def root
    if @root == nil
      start = @headers['content-type']['start']
      @root = (start && @parts.find { |prt| prt.contentid == start }) ||
        @parts[0]
    end
    @root
  end


boundary (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 192
  def boundary
    if @boundary == nil
      @boundary = "----=Part_" + __id__.to_s + rand.to_s
    end
    @boundary
  end


add_part (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 199
  def add_part(content)
    part = Part.new
    part.headers.add("Content-Type",
      "text/xml; charset=" + XSD::Charset.xml_encoding_label)
    part.headers.add("Content-ID", Attachment.contentid(part))
    part.body = content
    @parts.unshift(part)
  end


add_attachment (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 208
  def add_attachment(attach)
    part = Part.new
    part.headers.add("Content-Type", attach.contenttype)
    part.headers.add("Content-ID", attach.mime_contentid)
    part.body = attach.content
    @parts.unshift(part)
  end


has_parts? (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 216
  def has_parts?
    (@parts.length > 0)
  end


headers_str (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 220
  def headers_str
    @headers.to_s
  end


content_str (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 224
  def content_str
    str = ''
    @parts.each do |prt|
      str << "--" + boundary + "\r\n"
      str << prt.to_s + "\r\n"
    end
    str << '--' + boundary + "--\r\n"
    str
  end


to_s (SOAP::MIMEMessage)

# File lib/soap/mimemessage.rb, line 234
  def to_s
    str = headers_str + "\r\n\r\n" + conent_str
  end


new (SOAP::Parser::ParseFrame::NodeContainer)

# File lib/soap/parser.rb, line 34
      def initialize(node)
        @node = node
      end


node (SOAP::Parser::ParseFrame::NodeContainer)

# File lib/soap/parser.rb, line 38
      def node
        @node
      end


replace_node (SOAP::Parser::ParseFrame::NodeContainer)

# File lib/soap/parser.rb, line 42
      def replace_node(node)
        @node = node
      end


new (SOAP::Parser::ParseFrame)

# File lib/soap/parser.rb, line 49
    def initialize(ns, name, node, encodingstyle)
      @ns = ns
      @name = name
      self.node = node
      @encodingstyle = encodingstyle
    end


node= (SOAP::Parser::ParseFrame)

# File lib/soap/parser.rb, line 56
    def node=(node)
      @node = NodeContainer.new(node)
    end


new (SOAP::Parser)

# File lib/soap/parser.rb, line 68
  def initialize(opt = {})
    @opt = opt
    @parser = XSD::XMLParser.create_parser(self, opt)
    @parsestack = nil
    @lastnode = nil
    @handlers = {}
    @envelopenamespace = opt[:envelopenamespace] || EnvelopeNamespace
    @default_encodingstyle = opt[:default_encodingstyle] || EncodingNamespace
    @decode_typemap = opt[:decode_typemap] || nil
    @allow_unqualified_element = opt[:allow_unqualified_element] || false
  end


charset (SOAP::Parser)

# File lib/soap/parser.rb, line 80
  def charset
    @parser.charset
  end


parse (SOAP::Parser)

# File lib/soap/parser.rb, line 84
  def parse(string_or_readable)
    @parsestack = []
    @lastnode = nil

    @handlers.each do |uri, handler|
      handler.decode_prologue
    end

    @parser.do_parse(string_or_readable)

    unless @parsestack.empty?
      raise FormatDecodeError.new("Unbalanced tag in XML.")
    end

    @handlers.each do |uri, handler|
      handler.decode_epilogue
    end

    @lastnode
  end


start_element (SOAP::Parser)

# File lib/soap/parser.rb, line 105
  def start_element(name, attrs)
    lastframe = @parsestack.last
    ns = parent = parent_encodingstyle = nil
    if lastframe
      ns = lastframe.ns.clone_ns
      parent = lastframe.node
      parent_encodingstyle = lastframe.encodingstyle
    else
      ns = XSD::NS.new
      parent = ParseFrame::NodeContainer.new(nil)
      parent_encodingstyle = nil
    end

    attrs = XSD::XMLParser.filter_ns(ns, attrs)
    encodingstyle = find_encodingstyle(ns, attrs)

    # Children's encodingstyle is derived from its parent.
    if encodingstyle.nil?
      if parent.node.is_a?(SOAPHeader)
        encodingstyle = LiteralNamespace
      else
        encodingstyle = parent_encodingstyle || @default_encodingstyle
      end
    end

    node = decode_tag(ns, name, attrs, parent, encodingstyle)

    @parsestack << ParseFrame.new(ns, name, node, encodingstyle)
  end


characters (SOAP::Parser)

# File lib/soap/parser.rb, line 135
  def characters(text)
    lastframe = @parsestack.last
    if lastframe
      # Need not to be cloned because character does not have attr.
      decode_text(lastframe.ns, text, lastframe.encodingstyle)
    else
      # Ignore Text outside of SOAP Envelope.
      p text if $DEBUG
    end
  end


end_element (SOAP::Parser)

# File lib/soap/parser.rb, line 146
  def end_element(name)
    lastframe = @parsestack.pop
    unless name == lastframe.name
      raise UnexpectedElementError.new("Closing element name '#{ name }' does not match with opening element '#{ lastframe.name }'.")
    end
    decode_tag_end(lastframe.ns, lastframe.node, lastframe.encodingstyle)
    @lastnode = lastframe.node.node
  end


marshal (SOAP::Processor)

# File lib/soap/processor.rb, line 28
    def marshal(env, opt = {}, io = nil)
      generator = create_generator(opt)
      marshalled_str = generator.generate(env, io)
      unless env.external_content.empty?
        opt[:external_content] = env.external_content
      end
      marshalled_str
    end


unmarshal (SOAP::Processor)

# File lib/soap/processor.rb, line 37
    def unmarshal(stream, opt = {})
      parser = create_parser(opt)
      parser.parse(stream)
    end


default_parser_option= (SOAP::Processor)

# File lib/soap/processor.rb, line 42
    def default_parser_option=(rhs)
      @@default_parser_option = rhs
    end


default_parser_option (SOAP::Processor)

# File lib/soap/processor.rb, line 46
    def default_parser_option
      @@default_parser_option
    end


const_from_name (SOAP::Property::Util)

# File lib/soap/property.rb, line 40
    def const_from_name(fqname)
      fqname.split("::").inject(Kernel) { |klass, name| klass.const_get(name) }
    end


require_from_name (SOAP::Property::Util)

# File lib/soap/property.rb, line 45
    def require_from_name(fqname)
      require File.join(fqname.split("::").collect { |ele| ele.downcase })
    end


load (SOAP::Property)

# File lib/soap/property.rb, line 51
  def self.load(stream)
    new.load(stream)
  end


loadproperty (SOAP::Property)

# File lib/soap/property.rb, line 55
  def self.loadproperty(propname)
    new.loadproperty(propname)
  end


new (SOAP::Property)

# File lib/soap/property.rb, line 59
  def initialize
    @store = Hash.new
    @hook = Hash.new
    @self_hook = Array.new
    @locked = false
  end


load (SOAP::Property)

# File lib/soap/property.rb, line 71
  def load(stream)
    key_prefix = ""
    stream.each_with_index do |line, lineno|
      line.sub!(/\r?\n\z/, '')
      case line
      when COMMENT_REGEXP
        next
      when CATDEF_REGEXP
        key_prefix = $1.strip
      when LINE_REGEXP
        key, value = $1.strip, $2.strip
        key = "#{key_prefix}.#{key}" unless key_prefix.empty?
        key, value = loadstr(key), loadstr(value)
        self[key] = value
      else
        raise TypeError.new(
          "property format error at line #{lineno + 1}: `#{line}'")
      end
    end
    self
  end


loadproperty (SOAP::Property)

# File lib/soap/property.rb, line 94
  def loadproperty(propname)
    return loadpropertyfile(propname) if File.file?(propname)
    $:.each do |path|
      if File.file?(file = File.join(path, propname))
        return loadpropertyfile(file)
      end
    end
    nil
  end


[] (SOAP::Property)

# File lib/soap/property.rb, line 105
  def [](name)
    referent(name_to_a(name))
  end


[]= (SOAP::Property)

# File lib/soap/property.rb, line 111
  def []=(name, value)
    name_pair = name_to_a(name).freeze
    hooks = assign(name_pair, value)
    hooks.each do |hook|
      hook.call(name_pair, value)
    end
    value
  end


<< (SOAP::Property)

# File lib/soap/property.rb, line 122
  def <<(value)
    self[generate_new_key] = value
  end


add_hook (SOAP::Property)

# File lib/soap/property.rb, line 129
  def add_hook(name = nil, cascade = false, &hook)
    if name == nil or name == true or name == false
      cascade = name
      assign_self_hook(cascade, &hook)
    else
      assign_hook(name_to_a(name), cascade, &hook)
    end
  end


each (SOAP::Property)

# File lib/soap/property.rb, line 138
  def each
    @store.each do |key, value|
      yield(key, value)
    end
  end


empty? (SOAP::Property)

# File lib/soap/property.rb, line 144
  def empty?
    @store.empty?
  end


keys (SOAP::Property)

# File lib/soap/property.rb, line 148
  def keys
    @store.keys
  end


values (SOAP::Property)

# File lib/soap/property.rb, line 152
  def values
    @store.values
  end


lock (SOAP::Property)

# File lib/soap/property.rb, line 156
  def lock(cascade = false)
    if cascade
      each_key do |key|
        key.lock(cascade)
      end
    end
    @locked = true
    self
  end


unlock (SOAP::Property)

# File lib/soap/property.rb, line 166
  def unlock(cascade = false)
    @locked = false
    if cascade
      each_key do |key|
        key.unlock(cascade)
      end
    end
    self
  end


locked? (SOAP::Property)

# File lib/soap/property.rb, line 176
  def locked?
    @locked
  end


deref_key (SOAP::Property)

# File lib/soap/property.rb, line 182
  def deref_key(key)
    check_lock(key)
    ref = @store[key] ||= self.class.new
    unless propkey?(ref)
      raise ArgumentError.new("key `#{key}' already defined as a value")
    end
    ref
  end


local_referent (SOAP::Property)

# File lib/soap/property.rb, line 191
  def local_referent(key)
    check_lock(key)
    if propkey?(@store[key]) and @store[key].locked?
      raise FrozenError.new("cannot split any key from locked property")
    end
    @store[key]
  end


local_assign (SOAP::Property)

# File lib/soap/property.rb, line 199
  def local_assign(key, value)
    check_lock(key)
    if @locked
      if propkey?(value)
        raise FrozenError.new("cannot add any key to locked property")
      elsif propkey?(@store[key])
        raise FrozenError.new("cannot override any key in locked property")
      end
    end
    @store[key] = value
  end


local_hook (SOAP::Property)

# File lib/soap/property.rb, line 211
  def local_hook(key, direct)
    hooks = []
    (@self_hook + (@hook[key] || NO_HOOK)).each do |hook, cascade|
      hooks << hook if direct or cascade
    end
    hooks
  end


local_assign_hook (SOAP::Property)

# File lib/soap/property.rb, line 219
  def local_assign_hook(key, cascade, &hook)
    check_lock(key)
    @store[key] ||= nil
    (@hook[key] ||= []) << [hook, cascade]
  end


new (SOAP::Response)

# File lib/soap/netHttpClient.rb, line 180
    def initialize(res)
      @status = res.code.to_i
      @reason = res.message
      @contenttype = res['content-type']
      @content = res.body
    end


new (SOAP::RPC::CGIStub::SOAPFCGIRequest)

# File lib/soap/rpc/cgistub.rb, line 61
    def initialize(request)
      @request = request
      @body = @request.in.read
    end


[] (SOAP::RPC::CGIStub::SOAPFCGIRequest)

# File lib/soap/rpc/cgistub.rb, line 66
    def [](var)
      @request.env[var.gsub(/-/, '_').upcase]
    end


meta_vars (SOAP::RPC::CGIStub::SOAPFCGIRequest)

# File lib/soap/rpc/cgistub.rb, line 70
    def meta_vars
      {
        'HTTP_SOAPACTION' => @request.env['HTTP_SOAPAction']
      }
    end


[] (SOAP::RPC::CGIStub::SOAPRequest)

# File lib/soap/rpc/cgistub.rb, line 34
    def [](var); end


meta_vars (SOAP::RPC::CGIStub::SOAPRequest)

# File lib/soap/rpc/cgistub.rb, line 36
    def meta_vars; end


new (SOAP::RPC::CGIStub::SOAPStdinRequest)

# File lib/soap/rpc/cgistub.rb, line 42
    def initialize(stream)
      size = ENV['CONTENT_LENGTH'].to_i || 0
      @body = stream.read(size)
    end


[] (SOAP::RPC::CGIStub::SOAPStdinRequest)

# File lib/soap/rpc/cgistub.rb, line 47
    def [](var)
      ENV[var.gsub(/-/, '_').upcase]
    end


meta_vars (SOAP::RPC::CGIStub::SOAPStdinRequest)

# File lib/soap/rpc/cgistub.rb, line 51
    def meta_vars
      {
        'HTTP_SOAPACTION' => ENV['HTTP_SOAPAction']
      }
    end


new (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 77
  def initialize(appname, default_namespace)
    super(appname)
    set_log(STDERR)
    self.level = ERROR
    @default_namespace = default_namespace
    @remote_host = ENV['REMOTE_HOST'] || ENV['REMOTE_ADDR'] || 'unknown'
    @router = ::SOAP::RPC::Router.new(self.class.name)
    @soaplet = ::SOAP::RPC::SOAPlet.new(@router)
    on_init
  end


on_init (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 88
  def on_init
    # do extra initialization in a derived class if needed.
  end


mapping_registry (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 92
  def mapping_registry
    @router.mapping_registry
  end


mapping_registry= (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 96
  def mapping_registry=(value)
    @router.mapping_registry = value
  end


generate_explicit_type (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 100
  def generate_explicit_type
    @router.generate_explicit_type
  end


generate_explicit_type= (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 104
  def generate_explicit_type=(generate_explicit_type)
    @router.generate_explicit_type = generate_explicit_type
  end


add_rpc_servant (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 110
  def add_rpc_servant(obj, namespace = @default_namespace)
    @router.add_rpc_servant(obj, namespace)
  end


add_headerhandler (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 115
  def add_headerhandler(obj)
    @router.add_headerhandler(obj)
  end


add_rpc_method (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 122
  def add_rpc_method(obj, name, *param)
    add_rpc_method_with_namespace_as(@default_namespace, obj, name, name, *param)
  end


add_rpc_method_as (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 127
  def add_rpc_method_as(obj, name, name_as, *param)
    add_rpc_method_with_namespace_as(@default_namespace, obj, name, name_as, *param)
  end


add_rpc_method_with_namespace (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 132
  def add_rpc_method_with_namespace(namespace, obj, name, *param)
    add_rpc_method_with_namespace_as(namespace, obj, name, name, *param)
  end


add_rpc_method_with_namespace_as (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 137
  def add_rpc_method_with_namespace_as(namespace, obj, name, name_as, *param)
    qname = XSD::QName.new(namespace, name_as)
    soapaction = nil
    param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param)
    @router.add_rpc_operation(obj, qname, soapaction, name, param_def)
  end


add_rpc_operation (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 145
  def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
    @router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt)
  end


add_document_operation (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 149
  def add_document_operation(receiver, soapaction, name, param_def, opt = {})
    @router.add_document_operation(receiver, soapaction, name, param_def, opt)
  end


set_fcgi_request (SOAP::RPC::CGIStub)

# File lib/soap/rpc/cgistub.rb, line 153
  def set_fcgi_request(request)
    @fcgi = request
  end


__attr_proxy (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 27
      def __attr_proxy(symbol, assignable = false)
        name = symbol.to_s
        define_method(name) {
          @proxy.__send__(name)
        }
        if assignable
          aname = name + '='
          define_method(aname) { |rhs|
            @proxy.__send__(aname, rhs)
          }
        end
      end


__attr_proxy (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 40
      def __attr_proxy(symbol, assignable = false)
        name = symbol.to_s
        module_eval "def \#{name}\n@proxy.\#{name}\nend\n"
        if assignable
          module_eval "def \#{name}=(value)\n@proxy.\#{name} = value\nend\n"
        end
      end


inspect (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 74
  def inspect
    "#<#{self.class}:#{@proxy.inspect}>"
  end


httpproxy (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 78
  def httpproxy
    options["protocol.http.proxy"]
  end


httpproxy= (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 82
  def httpproxy=(httpproxy)
    options["protocol.http.proxy"] = httpproxy
  end


wiredump_dev (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 86
  def wiredump_dev
    options["protocol.http.wiredump_dev"]
  end


wiredump_dev= (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 90
  def wiredump_dev=(wiredump_dev)
    options["protocol.http.wiredump_dev"] = wiredump_dev
  end


mandatorycharset (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 94
  def mandatorycharset
    options["protocol.mandatorycharset"]
  end


mandatorycharset= (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 98
  def mandatorycharset=(mandatorycharset)
    options["protocol.mandatorycharset"] = mandatorycharset
  end


wiredump_file_base (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 102
  def wiredump_file_base
    options["protocol.wiredump_file_base"]
  end


wiredump_file_base= (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 106
  def wiredump_file_base=(wiredump_file_base)
    options["protocol.wiredump_file_base"] = wiredump_file_base
  end


new (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 110
  def initialize(endpoint_url, namespace = nil, soapaction = nil)
    @namespace = namespace
    @soapaction = soapaction
    @options = setup_options
    @wiredump_file_base = nil
    @proxy = Proxy.new(endpoint_url, @soapaction, @options)
  end


loadproperty (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 118
  def loadproperty(propertyname)
    unless options.loadproperty(propertyname)
      raise LoadError.new("No such property to load -- #{propertyname}")
    end
  end


add_rpc_method (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 124
  def add_rpc_method(name, *params)
    add_rpc_method_with_soapaction_as(name, name, @soapaction, *params)
  end


add_rpc_method_as (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 128
  def add_rpc_method_as(name, name_as, *params)
    add_rpc_method_with_soapaction_as(name, name_as, @soapaction, *params)
  end


add_rpc_method_with_soapaction (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 132
  def add_rpc_method_with_soapaction(name, soapaction, *params)
    add_rpc_method_with_soapaction_as(name, name, soapaction, *params)
  end


add_rpc_method_with_soapaction_as (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 136
  def add_rpc_method_with_soapaction_as(name, name_as, soapaction, *params)
    param_def = SOAPMethod.create_rpc_param_def(params)
    qname = XSD::QName.new(@namespace, name_as)
    @proxy.add_rpc_method(qname, soapaction, name, param_def)
    add_rpc_method_interface(name, param_def)
  end


add_document_method (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 149
  def add_document_method(name, soapaction, req_qname, res_qname)
    param_def = SOAPMethod.create_doc_param_def(req_qname, res_qname)
    @proxy.add_document_method(soapaction, name, param_def)
    add_document_method_interface(name, param_def)
  end


add_rpc_operation (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 155
  def add_rpc_operation(qname, soapaction, name, param_def, opt = {})
    @proxy.add_rpc_operation(qname, soapaction, name, param_def, opt)
    add_rpc_method_interface(name, param_def)
  end


add_document_operation (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 160
  def add_document_operation(soapaction, name, param_def, opt = {})
    @proxy.add_document_operation(soapaction, name, param_def, opt)
    add_document_method_interface(name, param_def)
  end


invoke (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 165
  def invoke(headers, body)
    if headers and !headers.is_a?(SOAPHeader)
      headers = create_header(headers)
    end
    set_wiredump_file_base(body.elename.name)
    env = @proxy.invoke(headers, body)
    if env.nil?
      return nil, nil
    else
      return env.header, env.body
    end
  end


call (SOAP::RPC::Driver)

# File lib/soap/rpc/driver.rb, line 178
  def call(name, *params)
    set_wiredump_file_base(name)
    @proxy.call(name, *params)
  end


new (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 23
  def initialize(config)
    super(config[:SOAPHTTPServerApplicationName] || self.class.name)
    @default_namespace = config[:SOAPDefaultNamespace]
    @webrick_config = config.dup
    self.level = Logger::Severity::ERROR # keep silent by default
    @webrick_config[:Logger] ||= @log
    @log = @webrick_config[:Logger]     # sync logger of App and HTTPServer
    @router = ::SOAP::RPC::Router.new(self.class.name)
    @soaplet = ::SOAP::RPC::SOAPlet.new(@router)
    on_init
    @server = WEBrick::HTTPServer.new(@webrick_config)
    @server.mount('/', @soaplet)
  end


on_init (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 37
  def on_init
    # do extra initialization in a derived class if needed.
  end


status (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 41
  def status
    @server.status if @server
  end


shutdown (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 45
  def shutdown
    @server.shutdown if @server
  end


mapping_registry (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 49
  def mapping_registry
    @router.mapping_registry
  end


mapping_registry= (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 53
  def mapping_registry=(mapping_registry)
    @router.mapping_registry = mapping_registry
  end


generate_explicit_type (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 57
  def generate_explicit_type
    @router.generate_explicit_type
  end


generate_explicit_type= (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 61
  def generate_explicit_type=(generate_explicit_type)
    @router.generate_explicit_type = generate_explicit_type
  end


add_rpc_request_servant (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 67
  def add_rpc_request_servant(factory, namespace = @default_namespace)
    @router.add_rpc_request_servant(factory, namespace)
  end


add_rpc_servant (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 71
  def add_rpc_servant(obj, namespace = @default_namespace)
    @router.add_rpc_servant(obj, namespace)
  end


add_request_headerhandler (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 75
  def add_request_headerhandler(factory)
    @router.add_request_headerhandler(factory)
  end


add_headerhandler (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 79
  def add_headerhandler(obj)
    @router.add_headerhandler(obj)
  end


add_rpc_method (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 86
  def add_rpc_method(obj, name, *param)
    add_rpc_method_as(obj, name, name, *param)
  end


add_rpc_method_as (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 91
  def add_rpc_method_as(obj, name, name_as, *param)
    qname = XSD::QName.new(@default_namespace, name_as)
    soapaction = nil
    param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param)
    @router.add_rpc_operation(obj, qname, soapaction, name, param_def)
  end


add_document_method (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 99
  def add_document_method(obj, soapaction, name, req_qnames, res_qnames)
    param_def = SOAPMethod.create_doc_param_def(req_qnames, res_qnames)
    @router.add_document_operation(obj, soapaction, name, param_def)
  end


add_rpc_operation (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 104
  def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
    @router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt)
  end


add_rpc_request_operation (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 108
  def add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {})
    @router.add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt)
  end


add_document_operation (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 112
  def add_document_operation(receiver, soapaction, name, param_def, opt = {})
    @router.add_document_operation(receiver, soapaction, name, param_def, opt)
  end


add_document_request_operation (SOAP::RPC::HTTPServer)

# File lib/soap/rpc/httpserver.rb, line 116
  def add_document_request_operation(factory, soapaction, name, param_def, opt = {})
    @router.add_document_request_operation(factory, soapaction, name, param_def, opt)
  end


new (SOAP::RPC::Proxy::Operation)

# File lib/soap/rpc/proxy.rb, line 282
    def initialize(soapaction, param_def, opt)
      @soapaction = soapaction
      @request_style = opt[:request_style]
      @response_style = opt[:response_style]
      @request_use = opt[:request_use]
      @response_use = opt[:response_use]
      # set nil(unqualified) by default
      @elementformdefault = opt[:elementformdefault]
      @attributeformdefault = opt[:attributeformdefault]
      check_style(@request_style)
      check_style(@response_style)
      check_use(@request_use)
      check_use(@response_use)
      if @request_style == :rpc
        @rpc_request_qname = opt[:request_qname]
        if @rpc_request_qname.nil?
          raise MethodDefinitionError.new("rpc_request_qname must be given")
        end
        @rpc_method_factory =
          RPC::SOAPMethodRequest.new(@rpc_request_qname, param_def, @soapaction)
      else
        @doc_request_qnames = []
        @doc_request_qualified = []
        @doc_response_qnames = []
        @doc_response_qualified = []
        param_def.each do |inout, paramname, typeinfo, eleinfo|
          klass_not_used, nsdef, namedef = typeinfo
          qualified = eleinfo
          if namedef.nil?
            raise MethodDefinitionError.new("qname must be given")
          end
          case inout
          when SOAPMethod::IN
            @doc_request_qnames << XSD::QName.new(nsdef, namedef)
            @doc_request_qualified << qualified
          when SOAPMethod::OUT
            @doc_response_qnames << XSD::QName.new(nsdef, namedef)
            @doc_response_qualified << qualified
          else
            raise MethodDefinitionError.new(
              "illegal inout definition for document style: #{inout}")
          end
        end
      end
    end


request_default_encodingstyle (SOAP::RPC::Proxy::Operation)

# File lib/soap/rpc/proxy.rb, line 328
    def request_default_encodingstyle
      (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end


response_default_encodingstyle (SOAP::RPC::Proxy::Operation)

# File lib/soap/rpc/proxy.rb, line 332
    def response_default_encodingstyle
      (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end


request_body (SOAP::RPC::Proxy::Operation)

# File lib/soap/rpc/proxy.rb, line 336
    def request_body(values, mapping_registry, literal_mapping_registry, opt)
      if @request_style == :rpc
        request_rpc(values, mapping_registry, literal_mapping_registry, opt)
      else
        request_doc(values, mapping_registry, literal_mapping_registry, opt)
      end
    end


response_obj (SOAP::RPC::Proxy::Operation)

# File lib/soap/rpc/proxy.rb, line 344
    def response_obj(body, mapping_registry, literal_mapping_registry, opt)
      if @response_style == :rpc
        response_rpc(body, mapping_registry, literal_mapping_registry, opt)
      else
        response_doc(body, mapping_registry, literal_mapping_registry, opt)
      end
    end


raise_fault (SOAP::RPC::Proxy::Operation)

# File lib/soap/rpc/proxy.rb, line 352
    def raise_fault(e, mapping_registry, literal_mapping_registry)
      if @response_style == :rpc
        Mapping.fault2exception(e, mapping_registry)
      else
        Mapping.fault2exception(e, literal_mapping_registry)
      end
    end


new (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 40
  def initialize(endpoint_url, soapaction, options)
    @endpoint_url = endpoint_url
    @soapaction = soapaction
    @options = options
    @streamhandler = HTTPStreamHandler.new(
      @options["protocol.http"] ||= ::SOAP::Property.new)
    @operation = {}
    @mandatorycharset = nil
    @allow_unqualified_element = true
    @default_encodingstyle = nil
    @generate_explicit_type = true
    @headerhandler = Header::HandlerSet.new
    @mapping_registry = nil
    @literal_mapping_registry = ::SOAP::Mapping::WSDLLiteralRegistry.new
  end


inspect (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 56
  def inspect
    "#<#{self.class}:#{@endpoint_url}>"
  end


endpoint_url (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 60
  def endpoint_url
    @endpoint_url
  end


endpoint_url= (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 64
  def endpoint_url=(endpoint_url)
    @endpoint_url = endpoint_url
    reset_stream
  end


reset_stream (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 69
  def reset_stream
    @streamhandler.reset(@endpoint_url)
  end


set_wiredump_file_base (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 73
  def set_wiredump_file_base(wiredump_file_base)
    @streamhandler.wiredump_file_base = wiredump_file_base
  end


test_loopback_response (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 77
  def test_loopback_response
    @streamhandler.test_loopback_response
  end


add_rpc_operation (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 81
  def add_rpc_operation(qname, soapaction, name, param_def, opt = {})
    opt[:request_qname] = qname
    opt[:request_style] ||= :rpc
    opt[:response_style] ||= :rpc
    opt[:request_use] ||= :encoded
    opt[:response_use] ||= :encoded
    @operation[name] = Operation.new(soapaction, param_def, opt)
  end


add_document_operation (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 90
  def add_document_operation(soapaction, name, param_def, opt = {})
    opt[:request_style] ||= :document
    opt[:response_style] ||= :document
    opt[:request_use] ||= :literal
    opt[:response_use] ||= :literal
    # default values of these values are unqualified in XML Schema.
    # set true for backward compatibility.
    unless opt.key?(:elementformdefault)
      opt[:elementformdefault] = true
    end
    unless opt.key?(:attributeformdefault)
      opt[:attributeformdefault] = true
    end
    @operation[name] = Operation.new(soapaction, param_def, opt)
  end


invoke (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 111
  def invoke(req_header, req_body, opt = nil)
    opt ||= create_encoding_opt
    route(req_header, req_body, opt, opt)
  end


call (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 116
  def call(name, *params)
    unless op_info = @operation[name]
      raise MethodDefinitionError, "method: #{name} not defined"
    end
    mapping_opt = create_mapping_opt
    req_header = create_request_header
    req_body = SOAPBody.new(
      op_info.request_body(params, @mapping_registry,
        @literal_mapping_registry, mapping_opt)
    )
    reqopt = create_encoding_opt(
      :soapaction => op_info.soapaction || @soapaction,
      :envelopenamespace => @options["soap.envelope.requestnamespace"],
      :default_encodingstyle =>
        @default_encodingstyle || op_info.request_default_encodingstyle,
      :elementformdefault => op_info.elementformdefault,
      :attributeformdefault => op_info.attributeformdefault
    )
    resopt = create_encoding_opt(
      :envelopenamespace => @options["soap.envelope.responsenamespace"],
      :default_encodingstyle =>
        @default_encodingstyle || op_info.response_default_encodingstyle,
      :elementformdefault => op_info.elementformdefault,
      :attributeformdefault => op_info.attributeformdefault
    )
    env = route(req_header, req_body, reqopt, resopt)
    raise EmptyResponseError unless env
    receive_headers(env.header)
    begin
      check_fault(env.body)
    rescue ::SOAP::FaultError => e
      op_info.raise_fault(e, @mapping_registry, @literal_mapping_registry)
    end
    op_info.response_obj(env.body, @mapping_registry,
      @literal_mapping_registry, mapping_opt)
  end


route (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 153
  def route(req_header, req_body, reqopt, resopt)
    req_env = ::SOAP::SOAPEnvelope.new(req_header, req_body)
    unless reqopt[:envelopenamespace].nil?
      set_envelopenamespace(req_env, reqopt[:envelopenamespace])
    end
    reqopt[:external_content] = nil
    conn_data = marshal(req_env, reqopt)
    if ext = reqopt[:external_content]
      mime = MIMEMessage.new
      ext.each do |k, v|
        mime.add_attachment(v.data)
      end
      mime.add_part(conn_data.send_string + "\r\n")
      mime.close
      conn_data.send_string = mime.content_str
      conn_data.send_contenttype = mime.headers['content-type'].str
    end
    conn_data = @streamhandler.send(@endpoint_url, conn_data,
      reqopt[:soapaction])
    if conn_data.receive_string.empty?
      return nil
    end
    unmarshal(conn_data, resopt)
  end


check_fault (SOAP::RPC::Proxy)

# File lib/soap/rpc/proxy.rb, line 178
  def check_fault(body)
    if body.fault
      raise SOAP::FaultError.new(body.fault)
    end
  end


new (SOAP::RPC::Router::ApplicationScopeOperation)

# File lib/soap/rpc/router.rb, line 563
    def initialize(soapaction, receiver, name, param_def, opt)
      super(soapaction, name, param_def, opt)
      @receiver = receiver
    end


new (SOAP::RPC::Router::Operation)

# File lib/soap/rpc/router.rb, line 342
    def initialize(soapaction, name, param_def, opt)
      @soapaction = soapaction
      @name = name
      @request_style = opt[:request_style]
      @response_style = opt[:response_style]
      @request_use = opt[:request_use]
      @response_use = opt[:response_use]
      check_style(@request_style)
      check_style(@response_style)
      check_use(@request_use)
      check_use(@response_use)
      if @response_style == :rpc
        request_qname = opt[:request_qname] or raise
        @rpc_method_factory =
          RPC::SOAPMethodRequest.new(request_qname, param_def, @soapaction)
        @rpc_response_qname = opt[:response_qname]
      else
        @doc_request_qnames = []
        @doc_request_qualified = []
        @doc_response_qnames = []
        @doc_response_qualified = []
        param_def.each do |inout, paramname, typeinfo, eleinfo|
          klass, nsdef, namedef = typeinfo
          qualified = eleinfo
          case inout
          when SOAPMethod::IN
            @doc_request_qnames << XSD::QName.new(nsdef, namedef)
            @doc_request_qualified << qualified
          when SOAPMethod::OUT
            @doc_response_qnames << XSD::QName.new(nsdef, namedef)
            @doc_response_qualified << qualified
          else
            raise ArgumentError.new(
              "illegal inout definition for document style: #{inout}")
          end
        end
      end
    end


request_default_encodingstyle (SOAP::RPC::Router::Operation)

# File lib/soap/rpc/router.rb, line 381
    def request_default_encodingstyle
      (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end


response_default_encodingstyle (SOAP::RPC::Router::Operation)

# File lib/soap/rpc/router.rb, line 385
    def response_default_encodingstyle
      (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace
    end


call (SOAP::RPC::Router::Operation)

# File lib/soap/rpc/router.rb, line 389
    def call(body, mapping_registry, literal_mapping_registry, opt)
      if @request_style == :rpc
        values = request_rpc(body, mapping_registry, literal_mapping_registry,
          opt)
      else
        values = request_document(body, mapping_registry,
          literal_mapping_registry, opt)
      end
      result = receiver.method(@name.intern).call(*values)
      return result if result.is_a?(SOAPFault)
      if @response_style == :rpc
        response_rpc(result, mapping_registry, literal_mapping_registry, opt)
      else
        response_doc(result, mapping_registry, literal_mapping_registry, opt)
      end
    end


new (SOAP::RPC::Router::RequestScopeOperation)

# File lib/soap/rpc/router.rb, line 576
    def initialize(soapaction, receiver_factory, name, param_def, opt)
      super(soapaction, name, param_def, opt)
      unless receiver_factory.respond_to?(:create)
        raise TypeError.new("factory must respond to 'create'")
      end
      @receiver_factory = receiver_factory
    end


new (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 33
  def initialize(actor)
    @actor = actor
    @mapping_registry = nil
    @headerhandler = Header::HandlerSet.new
    @literal_mapping_registry = ::SOAP::Mapping::WSDLLiteralRegistry.new
    @generate_explicit_type = true
    @external_ces = nil
    @operation_by_soapaction = {}
    @operation_by_qname = {}
    @headerhandlerfactory = []
  end


add_request_headerhandler (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 48
  def add_request_headerhandler(factory)
    unless factory.respond_to?(:create)
      raise TypeError.new("factory must respond to 'create'")
    end
    @headerhandlerfactory << factory
  end


add_headerhandler (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 55
  def add_headerhandler(handler)
    @headerhandler.add(handler)
  end


add_rpc_request_servant (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 62
  def add_rpc_request_servant(factory, namespace)
    unless factory.respond_to?(:create)
      raise TypeError.new("factory must respond to 'create'")
    end
    obj = factory.create        # a dummy instance for introspection
    ::SOAP::RPC.defined_methods(obj).each do |name|
      begin
        qname = XSD::QName.new(namespace, name)
        param_def = ::SOAP::RPC::SOAPMethod.derive_rpc_param_def(obj, name)
        opt = create_styleuse_option(:rpc, :encoded)
        add_rpc_request_operation(factory, qname, nil, name, param_def, opt)
      rescue SOAP::RPC::MethodDefinitionError => e
        p e if $DEBUG
      end
    end
  end


add_rpc_servant (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 79
  def add_rpc_servant(obj, namespace)
    ::SOAP::RPC.defined_methods(obj).each do |name|
      begin
        qname = XSD::QName.new(namespace, name)
        param_def = ::SOAP::RPC::SOAPMethod.derive_rpc_param_def(obj, name)
        opt = create_styleuse_option(:rpc, :encoded)
        add_rpc_operation(obj, qname, nil, name, param_def, opt)
      rescue SOAP::RPC::MethodDefinitionError => e
        p e if $DEBUG
      end
    end
  end


add_rpc_operation (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 96
  def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
    ensure_styleuse_option(opt, :rpc, :encoded)
    opt[:request_qname] = qname
    op = ApplicationScopeOperation.new(soapaction, receiver, name, param_def,
      opt)
    if opt[:request_style] != :rpc
      raise RPCRoutingError.new("illegal request_style given")
    end
    assign_operation(soapaction, qname, op)
  end


add_rpc_request_operation (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 109
  def add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {})
    ensure_styleuse_option(opt, :rpc, :encoded)
    opt[:request_qname] = qname
    op = RequestScopeOperation.new(soapaction, factory, name, param_def, opt)
    if opt[:request_style] != :rpc
      raise RPCRoutingError.new("illegal request_style given")
    end
    assign_operation(soapaction, qname, op)
  end


add_document_operation (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 119
  def add_document_operation(receiver, soapaction, name, param_def, opt = {})
    #
    # adopt workaround for doc/lit wrapper method
    # (you should consider to simply use rpc/lit service)
    #
    #unless soapaction
    #  raise RPCRoutingError.new("soapaction is a must for document method")
    #end
    ensure_styleuse_option(opt, :document, :literal)
    op = ApplicationScopeOperation.new(soapaction, receiver, name, param_def,
      opt)
    if opt[:request_style] != :document
      raise RPCRoutingError.new("illegal request_style given")
    end
    assign_operation(soapaction, first_input_part_qname(param_def), op)
  end


add_document_request_operation (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 137
  def add_document_request_operation(factory, soapaction, name, param_def, opt = {})
    #
    # adopt workaround for doc/lit wrapper method
    # (you should consider to simply use rpc/lit service)
    #
    #unless soapaction
    #  raise RPCRoutingError.new("soapaction is a must for document method")
    #end
    ensure_styleuse_option(opt, :document, :literal)
    op = RequestScopeOperation.new(soapaction, receiver, name, param_def, opt)
    if opt[:request_style] != :document
      raise RPCRoutingError.new("illegal request_style given")
    end
    assign_operation(soapaction, first_input_part_qname(param_def), op)
  end


route (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 153
  def route(conn_data)
    # we cannot set request_default_encodingsyle before parsing the content.
    env = unmarshal(conn_data)
    if env.nil?
      raise ArgumentError.new("illegal SOAP marshal format")
    end
    op = lookup_operation(conn_data.soapaction, env.body)
    headerhandler = @headerhandler.dup
    @headerhandlerfactory.each do |f|
      headerhandler.add(f.create)
    end
    receive_headers(headerhandler, env.header)
    soap_response = default_encodingstyle = nil
    begin
      soap_response =
        op.call(env.body, @mapping_registry, @literal_mapping_registry,
          create_mapping_opt)
      default_encodingstyle = op.response_default_encodingstyle
    rescue Exception
      soap_response = fault($!)
      default_encodingstyle = nil
    end
    conn_data.is_fault = true if soap_response.is_a?(SOAPFault)
    header = call_headers(headerhandler)
    body = SOAPBody.new(soap_response)
    env = SOAPEnvelope.new(header, body)
    marshal(conn_data, env, default_encodingstyle)
  end


create_fault_response (SOAP::RPC::Router)

# File lib/soap/rpc/router.rb, line 183
  def create_fault_response(e)
    env = SOAPEnvelope.new(SOAPHeader.new, SOAPBody.new(fault(e)))
    opt = {}
    opt[:external_content] = nil
    response_string = Processor.marshal(env, opt)
    conn_data = StreamHandler::ConnectionData.new(response_string)
    conn_data.is_fault = true
    if ext = opt[:external_content]
      mimeize(conn_data, ext)
    end
    conn_data
  end


new (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 45
  def initialize(router = nil)
    @router = router || ::SOAP::RPC::Router.new(self.class.name)
    @options = {}
    @config = {}
  end


app_scope_router (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 52
  def app_scope_router
    @router
  end


add_servant (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 57
  def add_servant(obj, namespace)
    @router.add_rpc_servant(obj, namespace)
  end


allow_content_encoding_gzip= (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 61
  def allow_content_encoding_gzip=(allow)
    @options[:allow_content_encoding_gzip] = allow
  end


get_instance (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 68
  def get_instance(config, *options)
    @config = config
    self
  end


require_path_info? (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 73
  def require_path_info?
    false
  end


do_GET (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 77
  def do_GET(req, res)
    res.header['Allow'] = 'POST'
    raise WEBrick::HTTPStatus::MethodNotAllowed, "GET request not allowed"
  end


do_POST (SOAP::RPC::SOAPlet)

# File lib/soap/rpc/soaplet.rb, line 82
  def do_POST(req, res)
    logger.debug { "SOAP request: " + req.body } if logger
    begin
      conn_data = ::SOAP::StreamHandler::ConnectionData.new
      setup_req(conn_data, req)
      @router.external_ces = @options[:external_ces]
      conn_data = @router.route(conn_data)
      setup_res(conn_data, req, res)
    rescue Exception => e
      conn_data = @router.create_fault_response(e)
      res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR
      res.body = conn_data.send_string
      res['content-type'] = conn_data.send_contenttype || "text/xml"
    end
    if res.body.is_a?(IO)
      res.chunked = true
      logger.debug { "SOAP response: (chunked response not logged)" } if logger
    else
      logger.debug { "SOAP response: " + res.body } if logger
    end
  end


new (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 83
  def initialize(qname, param_def = nil)
    super(nil)
    @elename = qname
    @encodingstyle = nil

    @param_def = param_def

    @signature = []
    @inparam_names = []
    @inoutparam_names = []
    @outparam_names = []

    @inparam = {}
    @outparam = {}
    @retval_name = nil
    @retval_class_name = nil

    init_param(@param_def) if @param_def
  end


have_outparam? (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 103
  def have_outparam?
    @outparam_names.size > 0
  end


input_params (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 107
  def input_params
    collect_params(IN, INOUT)
  end


output_params (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 111
  def output_params
    collect_params(OUT, INOUT)
  end


set_param (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 115
  def set_param(params)
    params.each do |param, data|
      @inparam[param] = data
      data.elename.name = param
      data.parent = self
    end
  end


set_outparam (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 123
  def set_outparam(params)
    params.each do |param, data|
      @outparam[param] = data
      data.elename.name = param
    end
  end


param_count (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 130
  def SOAPMethod.param_count(param_def, *type)
    count = 0
    param_def.each do |io_type, name, param_type|
      if type.include?(io_type)
        count += 1
      end
    end
    count
  end


derive_rpc_param_def (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 140
  def SOAPMethod.derive_rpc_param_def(obj, name, *param)
    if param.size == 1 and param[0].is_a?(Array)
      return param[0]
    end
    if param.empty?
      method = obj.method(name)
      param_names = (1..method.arity.abs).collect { |i| "p#{i}" }
    else
      param_names = param
    end
    create_rpc_param_def(param_names)
  end


create_rpc_param_def (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 153
  def SOAPMethod.create_rpc_param_def(param_names)
    param_def = []
    param_names.each do |param_name|
      param_def.push([IN, param_name, nil])
    end
    param_def.push([RETVAL, 'return', nil])
    param_def
  end


create_doc_param_def (SOAP::RPC::SOAPMethod)

# File lib/soap/rpc/element.rb, line 162
  def SOAPMethod.create_doc_param_def(req_qnames, res_qnames)
    req_qnames = [req_qnames] if req_qnames.is_a?(XSD::QName)
    res_qnames = [res_qnames] if res_qnames.is_a?(XSD::QName)
    param_def = []
    req_qnames.each do |qname|
      param_def << [IN, qname.name, [nil, qname.namespace, qname.name]]
    end
    res_qnames.each do |qname|
      param_def << [OUT, qname.name, [nil, qname.namespace, qname.name]]
    end
    param_def
  end


create_request (SOAP::RPC::SOAPMethodRequest)

# File lib/soap/rpc/element.rb, line 221
  def SOAPMethodRequest.create_request(qname, *params)
    param_def = []
    param_value = []
    i = 0
    params.each do |param|
      param_name = "p#{i}"
      i += 1
      param_def << [IN, param_name, nil]
      param_value << [param_name, param]
    end
    param_def << [RETVAL, 'return', nil]
    o = new(qname, param_def)
    o.set_param(param_value)
    o
  end


new (SOAP::RPC::SOAPMethodRequest)

# File lib/soap/rpc/element.rb, line 237
  def initialize(qname, param_def = nil, soapaction = nil)
    check_elename(qname)
    super(qname, param_def)
    @soapaction = soapaction
  end


each (SOAP::RPC::SOAPMethodRequest)

# File lib/soap/rpc/element.rb, line 243
  def each
    input_params.each do |name|
      unless @inparam[name]
        raise ParameterError.new("parameter: #{name} was not given")
      end
      yield(name, @inparam[name])
    end
  end


dup (SOAP::RPC::SOAPMethodRequest)

# File lib/soap/rpc/element.rb, line 252
  def dup
    req = self.class.new(@elename.dup, @param_def, @soapaction)
    req.encodingstyle = @encodingstyle
    req
  end


create_method_response (SOAP::RPC::SOAPMethodRequest)

# File lib/soap/rpc/element.rb, line 258
  def create_method_response(response_name = nil)
    response_name ||=
      XSD::QName.new(@elename.namespace, @elename.name + 'Response')
    SOAPMethodResponse.new(response_name, @param_def)
  end


new (SOAP::RPC::SOAPMethodResponse)

# File lib/soap/rpc/element.rb, line 277
  def initialize(qname, param_def = nil)
    super(qname, param_def)
    @retval = nil
  end


retval= (SOAP::RPC::SOAPMethodResponse)

# File lib/soap/rpc/element.rb, line 282
  def retval=(retval)
    @retval = retval
    @retval.elename = @retval.elename.dup_name(@retval_name || 'return')
    retval.parent = self
    retval
  end


each (SOAP::RPC::SOAPMethodResponse)

# File lib/soap/rpc/element.rb, line 289
  def each
    if @retval_name and !@retval.is_a?(SOAPVoid)
      yield(@retval_name, @retval)
    end

    output_params.each do |name|
      unless @outparam[name]
        raise ParameterError.new("parameter: #{name} was not given")
      end
      yield(name, @outparam[name])
    end
  end


new (SOAP::RPC::SOAPVoid)

# File lib/soap/rpc/element.rb, line 315
  def initialize()
    @elename = Name
    @id = nil
    @precedents = []
    @parent = nil
  end


new (SOAP::RPC::StandaloneServer)

# File lib/soap/rpc/standaloneServer.rb, line 17
  def initialize(appname, default_namespace, host = "0.0.0.0", port = 8080)
    @appname = appname
    @default_namespace = default_namespace
    @host = host
    @port = port
    super(create_config)
  end


defined_methods (SOAP::RPC)

# File lib/soap/rpc/rpc.rb, line 15
  def self.defined_methods(obj)
    if obj.is_a?(Module)
      obj.methods - Module.methods
    else
      obj.methods - Object.instance_methods(true)
    end
  end


new (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 707
  def initialize(type = nil, rank = 1, arytype = nil)
    super()
    @type = type || ValueArrayName
    @rank = rank
    @data = Array.new
    @sparse = false
    @offset = Array.new(rank, 0)
    @size = Array.new(rank, 0)
    @size_fixed = false
    @position = nil
    @arytype = arytype
  end


offset= (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 720
  def offset=(var)
    @offset = var
    @sparse = true
  end


add (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 725
  def add(value)
    self[*(@offset)] = value
  end


[] (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 729
  def [](*idxary)
    if idxary.size != @rank
      raise ArgumentError.new("given #{idxary.size} params does not match rank: #{@rank}")
    end

    retrieve(idxary)
  end


[]= (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 737
  def []=(*idxary)
    value = idxary.slice!(-1)

    if idxary.size != @rank
      raise ArgumentError.new("given #{idxary.size} params(#{idxary})" +
        " does not match rank: #{@rank}")
    end

    idx = 0
    while idx < idxary.size
      if idxary[idx] + 1 > @size[idx]
        @size[idx] = idxary[idx] + 1
      end
      idx += 1
    end

    data = retrieve(idxary[0, idxary.size - 1])
    data[idxary.last] = value

    if value.is_a?(SOAPType)
      value.elename = ITEM_NAME
      # Sync type
      unless @type.name
        @type = XSD::QName.new(value.type.namespace,
          SOAPArray.create_arytype(value.type.name, @rank))
      end
      value.type ||= @type
    end

    @offset = idxary
    value.parent = self if value.respond_to?(:parent=)
    offsetnext
  end


each (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 771
  def each
    @data.each do |data|
      yield(data)
    end
  end


to_a (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 777
  def to_a
    @data.dup
  end


replace (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 781
  def replace
    @data = deep_map(@data) do |ele|
      yield(ele)
    end
  end


deep_map (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 787
  def deep_map(ary, &block)
    ary.collect do |ele|
      if ele.is_a?(Array)
        deep_map(ele, &block)
      else
        new_obj = block.call(ele)
        new_obj.elename = ITEM_NAME
        new_obj
      end
    end
  end


include? (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 799
  def include?(var)
    traverse_data(@data) do |v, *rank|
      if v.is_a?(SOAPBasetype) && v.data == var
        return true
      end
    end
    false
  end


traverse (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 808
  def traverse
    traverse_data(@data) do |v, *rank|
      unless @sparse
       yield(v)
      else
       yield(v, *rank) if v && !v.is_a?(SOAPNil)
      end
    end
  end


soap2array (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 818
  def soap2array(ary)
    traverse_data(@data) do |v, *position|
      iteary = ary
      rank = 1
      while rank < position.size
        idx = position[rank - 1]
        if iteary[idx].nil?
          iteary = iteary[idx] = Array.new
        else
          iteary = iteary[idx]
        end
        rank += 1
      end
      if block_given?
        iteary[position.last] = yield(v)
      else
        iteary[position.last] = v
      end
    end
  end


position (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 839
  def position
    @position
  end


decode (SOAP::SOAPArray)

# File lib/soap/baseData.rb, line 903
  def self.decode(elename, type, arytype)
    typestr, nofary = parse_type(arytype.name)
    rank = nofary.count(',') + 1
    plain_arytype = XSD::QName.new(arytype.namespace, typestr)
    o = SOAPArray.new(type, rank, plain_arytype)
    size = []
    nofary.split(',').each do |s|
      if s.empty?
        size.clear
        break
      else
        size << s.to_i
      end
    end
    unless size.empty?
      o.size = size
      o.size_fixed = true
    end
    o.elename = elename
    o
  end


new (SOAP::SOAPAttachment)

# File lib/soap/attachment.rb, line 19
  def initialize(value)
    super()
    @data = value
  end


new (SOAP::SOAPBase64)

# File lib/soap/baseData.rb, line 304
  def initialize(value = nil)
    super(value)
    @type = Type
  end


as_xsd (SOAP::SOAPBase64)

# File lib/soap/baseData.rb, line 309
  def as_xsd
    @type = XSD::XSDBase64Binary::Type
  end


new (SOAP::SOAPBasetype)

# File lib/soap/baseData.rb, line 84
  def initialize(*arg)
    super
  end


new (SOAP::SOAPBody)

# File lib/soap/element.rb, line 98
  def initialize(data = nil, is_fault = false)
    super(nil)
    @elename = EleBodyName
    @encodingstyle = nil
    if data
      if data.respond_to?(:elename)
        add(data.elename.name, data)
      else
        data.to_a.each do |datum|
          add(datum.elename.name, datum)
        end
      end
    end
    @is_fault = is_fault
  end


encode (SOAP::SOAPBody)

# File lib/soap/element.rb, line 114
  def encode(generator, ns, attrs = {})
    name = ns.name(@elename)
    generator.encode_tag(name, attrs)
    if @is_fault
      yield(@data)
    else
      @data.each do |data|
        yield(data)
      end
    end
    generator.encode_tag_end(name, true)
  end


root_node (SOAP::SOAPBody)

# File lib/soap/element.rb, line 127
  def root_node
    @data.each do |node|
      if node.root == 1
        return node
      end
    end
    # No specified root...
    @data.each do |node|
      if node.root != 0
        return node
      end
    end

    raise Parser::FormatDecodeError.new('no root element')
  end


request (SOAP::SOAPBody)

# File lib/soap/rpc/element.rb, line 18
  def request
    root_node
  end


response (SOAP::SOAPBody)

# File lib/soap/rpc/element.rb, line 22
  def response
    root = root_node
    if !@is_fault
      if root.nil?
        nil
      elsif root.is_a?(SOAPBasetype)
        root
      else
        # Initial element is [retval].
        root[0]
      end
    else
      root
    end
  end


outparams (SOAP::SOAPBody)

# File lib/soap/rpc/element.rb, line 38
  def outparams
    root = root_node
    if !@is_fault and !root.nil? and !root.is_a?(SOAPBasetype)
      op = root[1..-1]
      op = nil if op && op.empty?
      op
    else
      nil
    end
  end


fault (SOAP::SOAPBody)

# File lib/soap/rpc/element.rb, line 49
  def fault
    if @is_fault
      self['fault']
    else
      nil
    end
  end


fault= (SOAP::SOAPBody)

# File lib/soap/rpc/element.rb, line 57
  def fault=(fault)
    @is_fault = true
    add_member('fault', fault)
  end


new (SOAP::SOAPCompoundtype)

# File lib/soap/baseData.rb, line 97
  def initialize(*arg)
    super
  end


new (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 521
  def initialize(elename, text = nil)
    if !elename.is_a?(XSD::QName)
      elename = XSD::QName.new(nil, elename)
    end
    @encodingstyle = LiteralNamespace
    @elename = elename
    @id = nil
    @precedents = []
    @root = false
    @parent = nil
    @position = nil
    @extraattr = {}

    @qualified = nil

    @array = []
    @data = []
    @text = text
  end


inspect (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 541
  def inspect
    sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename)
  end


add (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 550
  def add(value)
    add_member(value.elename.name, value)
  end


[] (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 554
  def [](idx)
    if @array.include?(idx)
      @data[@array.index(idx)]
    else
      nil
    end
  end


[]= (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 562
  def []=(idx, data)
    if @array.include?(idx)
      data.parent = self if data.respond_to?(:parent=)
      @data[@array.index(idx)] = data
    else
      add(data)
    end
  end


key? (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 571
  def key?(name)
    @array.include?(name)
  end


members (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 575
  def members
    @array
  end


to_obj (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 579
  def to_obj
    if members.empty?
      @text
    else
      hash = {}
      proptype = {}
      each do |k, v|
        value = v.respond_to?(:to_obj) ? v.to_obj : v.to_s
        case proptype[k]
        when :single
          hash[k] = [hash[k], value]
          proptype[k] = :multi
        when :multi
          hash[k] << value
        else
          hash[k] = value
          proptype[k] = :single
        end
      end
      hash
    end
  end


each (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 602
  def each
    idx = 0
    while idx < @array.length
      yield(@array[idx], @data[idx])
      idx += 1
    end
  end


decode (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 610
  def self.decode(elename)
    o = SOAPElement.new(elename)
    o
  end


from_obj (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 615
  def self.from_obj(obj, namespace = nil)
    o = SOAPElement.new(nil)
    case obj
    when nil
      o.text = nil
    when Hash
      obj.each do |elename, value|
        if value.is_a?(Array)
          value.each do |subvalue|
            child = from_obj(subvalue, namespace)
            child.elename = to_elename(elename, namespace)
            o.add(child)
          end
        else
          child = from_obj(value, namespace)
          child.elename = to_elename(elename, namespace)
          o.add(child)
        end
      end
    else
      o.text = obj.to_s
    end
    o
  end


to_elename (SOAP::SOAPElement)

# File lib/soap/baseData.rb, line 640
  def self.to_elename(obj, namespace = nil)
    if obj.is_a?(XSD::QName)
      obj
    elsif /\A(.+):([^:]+)\z/ =~ obj.to_s
      XSD::QName.new($1, $2)
    else
      XSD::QName.new(namespace, obj.to_s)
    end
  end


new (SOAP::SOAPEnvelope)

# File lib/soap/element.rb, line 219
  def initialize(header = nil, body = nil)
    super()
    @type = nil
    @elename = EleEnvelopeName
    @encodingstyle = nil
    @header = header
    @body = body
    @external_content = {}
    header.parent = self if header
    body.parent = self if body
  end


header= (SOAP::SOAPEnvelope)

# File lib/soap/element.rb, line 231
  def header=(header)
    header.parent = self
    @header = header
  end


body= (SOAP::SOAPEnvelope)

# File lib/soap/element.rb, line 236
  def body=(body)
    body.parent = self
    @body = body
  end


encode (SOAP::SOAPEnvelope)

# File lib/soap/element.rb, line 241
  def encode(generator, ns, attrs = {})
    SOAPGenerator.assign_ns(attrs, ns, elename.namespace, SOAPNamespaceTag)
    name = ns.name(@elename)
    generator.encode_tag(name, attrs)

    yield(@header) if @header and @header.length > 0
    yield(@body)

    generator.encode_tag_end(name, true)
  end


to_ary (SOAP::SOAPEnvelope)

# File lib/soap/element.rb, line 252
  def to_ary
    [header, body]
  end


new (SOAP::SOAPExternalReference)

# File lib/soap/baseData.rb, line 179
  def initialize
    super()
    @type = XSD::QName::EMPTY
  end


referred (SOAP::SOAPExternalReference)

# File lib/soap/baseData.rb, line 184
  def referred
    rootnode.external_content[external_contentid] = self
  end


refidstr (SOAP::SOAPExternalReference)

# File lib/soap/baseData.rb, line 188
  def refidstr
    'cid:' + external_contentid
  end


faultcode (SOAP::SOAPFault)

# File lib/soap/element.rb, line 27
  def faultcode
    self['faultcode']
  end


faultstring (SOAP::SOAPFault)

# File lib/soap/element.rb, line 31
  def faultstring
    self['faultstring']
  end


faultactor (SOAP::SOAPFault)

# File lib/soap/element.rb, line 35
  def faultactor
    self['faultactor']
  end


detail (SOAP::SOAPFault)

# File lib/soap/element.rb, line 39
  def detail
    self['detail']
  end


faultcode= (SOAP::SOAPFault)

# File lib/soap/element.rb, line 43
  def faultcode=(rhs)
    self['faultcode'] = rhs
  end


faultstring= (SOAP::SOAPFault)

# File lib/soap/element.rb, line 47
  def faultstring=(rhs)
    self['faultstring'] = rhs
  end


faultactor= (SOAP::SOAPFault)

# File lib/soap/element.rb, line 51
  def faultactor=(rhs)
    self['faultactor'] = rhs
  end


detail= (SOAP::SOAPFault)

# File lib/soap/element.rb, line 55
  def detail=(rhs)
    self['detail'] = rhs
  end


new (SOAP::SOAPFault)

# File lib/soap/element.rb, line 59
  def initialize(faultcode = nil, faultstring = nil, faultactor = nil, detail = nil)
    super(EleFaultName)
    @elename = EleFaultName
    @encodingstyle = EncodingNamespace

    if faultcode
      self.faultcode = faultcode
      self.faultstring = faultstring
      self.faultactor = faultactor
      self.detail = detail
      self.faultcode.elename = EleFaultCodeName if self.faultcode
      self.faultstring.elename = EleFaultStringName if self.faultstring
      self.faultactor.elename = EleFaultActorName if self.faultactor
      self.detail.elename = EleFaultDetailName if self.detail
    end
    faultcode.parent = self if faultcode
    faultstring.parent = self if faultstring
    faultactor.parent = self if faultactor
    detail.parent = self if detail
  end


encode (SOAP::SOAPFault)

# File lib/soap/element.rb, line 80
  def encode(generator, ns, attrs = {})
    SOAPGenerator.assign_ns(attrs, ns, EnvelopeNamespace)
    SOAPGenerator.assign_ns(attrs, ns, EncodingNamespace)
    attrs[ns.name(AttrEncodingStyleName)] = EncodingNamespace
    name = ns.name(@elename)
    generator.encode_tag(name, attrs)
    yield(self.faultcode)
    yield(self.faultstring)
    yield(self.faultactor)
    yield(self.detail) if self.detail
    generator.encode_tag_end(name, true)
  end


new (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 33
  def initialize(opt = {})
    @reftarget = nil
    @handlers = {}
    @charset = opt[:charset] || XSD::Charset.xml_encoding_label
    @default_encodingstyle = opt[:default_encodingstyle] || EncodingNamespace
    @generate_explicit_type =
      opt.key?(:generate_explicit_type) ? opt[:generate_explicit_type] : true
    @elementformdefault = opt[:elementformdefault]
    @attributeformdefault = opt[:attributeformdefault]
    @use_numeric_character_reference = opt[:use_numeric_character_reference]
    @indentstr = opt[:no_indent] ? '' : '  '
    @buf = @indent = @curr = nil
  end


generate (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 47
  def generate(obj, io = nil)
    @buf = io || ''
    @indent = ''

    prologue
    @handlers.each do |uri, handler|
      handler.encode_prologue
    end

    ns = XSD::NS.new
    @buf << xmldecl
    encode_data(ns, obj, nil)

    @handlers.each do |uri, handler|
      handler.encode_epilogue
    end
    epilogue

    @buf
  end


encode_data (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 68
  def encode_data(ns, obj, parent)
    if obj.is_a?(SOAPEnvelopeElement)
      encode_element(ns, obj, parent)
      return
    end
    if @reftarget && !obj.precedents.empty?
      add_reftarget(obj.elename.name, obj)
      ref = SOAPReference.new(obj)
      ref.elename = ref.elename.dup_name(obj.elename.name)
      obj.precedents.clear      # Avoid cyclic delay.
      obj.encodingstyle = parent.encodingstyle
      # SOAPReference is encoded here.
      obj = ref
    end
    encodingstyle = obj.encodingstyle
    # Children's encodingstyle is derived from its parent.
    encodingstyle ||= parent.encodingstyle if parent
    obj.encodingstyle = encodingstyle
    handler = find_handler(encodingstyle || @default_encodingstyle)
    unless handler
      raise FormatEncodeError.new("Unknown encodingStyle: #{ encodingstyle }.")
    end
    if !obj.elename.name
      raise FormatEncodeError.new("Element name not defined: #{ obj }.")
    end
    handler.encode_data(self, ns, obj, parent)
    handler.encode_data_end(self, ns, obj, parent)
  end


add_reftarget (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 97
  def add_reftarget(name, node)
    unless @reftarget
      raise FormatEncodeError.new("Reftarget is not defined.")
    end
    @reftarget.add(name, node)
  end


encode_child (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 104
  def encode_child(ns, child, parent)
    indent_backup, @indent = @indent, @indent + @indentstr
    encode_data(ns.clone_ns, child, parent)
    @indent = indent_backup
  end


encode_element (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 110
  def encode_element(ns, obj, parent)
    attrs = {}
    if obj.is_a?(SOAPBody)
      @reftarget = obj
      obj.encode(self, ns, attrs) do |child|
        indent_backup, @indent = @indent, @indent + @indentstr
        encode_data(ns.clone_ns, child, obj)
        @indent = indent_backup
      end
      @reftarget = nil
    else
      if obj.is_a?(SOAPEnvelope)
        # xsi:nil="true" can appear even if dumping without explicit type.
        SOAPGenerator.assign_ns(attrs, ns,
          XSD::InstanceNamespace, XSINamespaceTag)
        if @generate_explicit_type
          SOAPGenerator.assign_ns(attrs, ns, XSD::Namespace, XSDNamespaceTag)
        end
      end
      obj.encode(self, ns, attrs) do |child|
        indent_backup, @indent = @indent, @indent + @indentstr
        encode_data(ns.clone_ns, child, obj)
        @indent = indent_backup
      end
    end
  end


encode_name (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 137
  def encode_name(ns, data, attrs)
    if element_local?(data)
      data.elename.name
    else
      if element_qualified?(data)
        SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace, '')
      else
        SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace)
      end
      ns.name(data.elename)
    end
  end


encode_name_end (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 150
  def encode_name_end(ns, data)
    if element_local?(data)
      data.elename.name
    else
      ns.name(data.elename)
    end
  end


encode_tag (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 158
  def encode_tag(elename, attrs = nil)
    if !attrs or attrs.empty?
      @buf << "\n#{ @indent }<#{ elename }>"
    elsif attrs.size == 1
      key, value = attrs.shift
      @buf << %Q[\n#{ @indent }<#{ elename } #{ key }="#{ value }">]
    else
      @buf << "\n#{ @indent }<#{ elename } " <<
        attrs.collect { |key, value|
          %Q[#{ key }="#{ value }"]
        }.join("\n#{ @indent }#{ @indentstr * 2 }") <<
        '>'
    end
  end


encode_tag_end (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 173
  def encode_tag_end(elename, cr = nil)
    if cr
      @buf << "\n#{ @indent }</#{ elename }>"
    else
      @buf << "</#{ elename }>"
    end
  end


encode_rawstring (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 181
  def encode_rawstring(str)
    @buf << str
  end


encode_string (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 194
  def encode_string(str)
    if @use_numeric_character_reference and !XSD::Charset.is_us_ascii(str)
      str.gsub!(EncodeCharRegexp) { |c| EncodeMap[c] }
      @buf << str.unpack("U*").collect { |c|
        if c == 0x9 or c == 0xa or c == 0xd or (c >= 0x20 and c <= 0x7f)
          c.chr
        else
          sprintf("&#x%x;", c)
        end
      }.join
    else
      @buf << str.gsub(EncodeCharRegexp) { |c| EncodeMap[c] }
    end
  end


element_local? (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 209
  def element_local?(element)
    element.elename.namespace.nil?
  end


element_qualified? (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 213
  def element_qualified?(element)
    if element.respond_to?(:qualified)
      if element.qualified.nil?
        @elementformdefault
      else
        element.qualified
      end
    else
      @elementformdefault
    end
  end


assign_ns (SOAP::SOAPGenerator)

# File lib/soap/generator.rb, line 225
  def self.assign_ns(attrs, ns, namespace, tag = nil)
    if namespace.nil?
      raise FormatEncodeError.new("empty namespace")
    end
    unless ns.assigned?(namespace)
      tag = ns.assign(namespace, tag)
      if tag == ''
        attr = 'xmlns'
      else
        attr = "xmlns:#{tag}"
      end
      attrs[attr] = namespace
    end
  end


new (SOAP::SOAPHeader)

# File lib/soap/element.rb, line 182
  def initialize
    super(nil)
    @elename = EleHeaderName
    @encodingstyle = nil
  end


encode (SOAP::SOAPHeader)

# File lib/soap/element.rb, line 188
  def encode(generator, ns, attrs = {})
    name = ns.name(@elename)
    generator.encode_tag(name, attrs)
    @data.each do |data|
      yield(data)
    end
    generator.encode_tag_end(name, true)
  end


add (SOAP::SOAPHeader)

# File lib/soap/element.rb, line 197
  def add(name, value)
    mu = (value.extraattr[AttrMustUnderstandName] == '1')
    encstyle = value.extraattr[AttrEncodingStyleName]
    item = SOAPHeaderItem.new(value, mu, encstyle)
    super(name, item)
  end


length (SOAP::SOAPHeader)

# File lib/soap/element.rb, line 204
  def length
    @data.length
  end


new (SOAP::SOAPHeaderItem)

# File lib/soap/element.rb, line 155
  def initialize(element, mustunderstand = true, encodingstyle = nil)
    super()
    @type = nil
    @element = element
    @mustunderstand = mustunderstand
    @encodingstyle = encodingstyle
    element.parent = self if element
  end


encode (SOAP::SOAPHeaderItem)

# File lib/soap/element.rb, line 164
  def encode(generator, ns, attrs = {})
    attrs.each do |key, value|
      @element.extraattr[key] = value
    end
    @element.extraattr[ns.name(AttrMustUnderstandName)] =
      (@mustunderstand ? '1' : '0')
    if @encodingstyle
      @element.extraattr[ns.name(AttrEncodingStyleName)] = @encodingstyle
    end
    @element.encodingstyle = @encodingstyle if !@element.encodingstyle
    yield(@element)
  end


decode (SOAP::SOAPModuleUtils)

# File lib/soap/baseData.rb, line 24
  def decode(elename)
    d = self.new
    d.elename = elename
    d
  end


new (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 115
  def initialize(obj = nil)
    super()
    @type = XSD::QName::EMPTY
    @refid = nil
    @obj = nil
    __setobj__(obj) if obj
  end


__getobj__ (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 123
  def __getobj__
    @obj
  end


__setobj__ (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 127
  def __setobj__(obj)
    @obj = obj
    @refid = @obj.id || SOAPReference.create_refid(@obj)
    @obj.id = @refid unless @obj.id
    @obj.precedents << self
    # Copies NSDBase information
    @obj.type = @type unless @obj.type
  end


method_missing (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 144
  def method_missing(msg_id, *params)
    if @obj
      @obj.send(msg_id, *params)
    else
      nil
    end
  end


refidstr (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 152
  def refidstr
    '#' + @refid
  end


create_refid (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 156
  def self.create_refid(obj)
    'id' + obj.__id__.to_s
  end


decode (SOAP::SOAPReference)

# File lib/soap/baseData.rb, line 160
  def self.decode(elename, refidstr)
    if /\A#(.*)\z/ =~ refidstr
      refid = $1
    elsif /\Acid:(.*)\z/ =~ refidstr
      refid = $1
    else
      raise ArgumentError.new("illegal refid #{refidstr}")
    end
    d = super(elename)
    d.refid = refid
    d
  end


new (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 400
  def initialize(type = nil)
    super()
    @type = type || XSD::QName::EMPTY
    @array = []
    @data = []
  end


to_s (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 407
  def to_s()
    str = ''
    self.each do |key, data|
      str << "#{key}: #{data}\n"
    end
    str
  end


add (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 415
  def add(name, value)
    add_member(name, value)
  end


[] (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 419
  def [](idx)
    if idx.is_a?(Range)
      @data[idx]
    elsif idx.is_a?(Integer)
      if (idx > @array.size)
        raise ArrayIndexOutOfBoundsError.new('In ' << @type.name)
      end
      @data[idx]
    else
      if @array.include?(idx)
        @data[@array.index(idx)]
      else
        nil
      end
    end
  end


[]= (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 436
  def []=(idx, data)
    if @array.include?(idx)
      data.parent = self if data.respond_to?(:parent=)
      @data[@array.index(idx)] = data
    else
      add(idx, data)
    end
  end


key? (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 445
  def key?(name)
    @array.include?(name)
  end


members (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 449
  def members
    @array
  end


to_obj (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 453
  def to_obj
    hash = {}
    proptype = {}
    each do |k, v|
      value = v.respond_to?(:to_obj) ? v.to_obj : v.to_s
      case proptype[k]
      when :single
        hash[k] = [hash[k], value]
        proptype[k] = :multi
      when :multi
        hash[k] << value
      else
        hash[k] = value
        proptype[k] = :single
      end
    end
    hash
  end


each (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 472
  def each
    idx = 0
    while idx < @array.length
      yield(@array[idx], @data[idx])
      idx += 1
    end
  end


replace (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 480
  def replace
    members.each do |member|
      self[member] = yield(self[member])
    end
  end


decode (SOAP::SOAPStruct)

# File lib/soap/baseData.rb, line 486
  def self.decode(elename, type)
    s = SOAPStruct.new(type)
    s.elename = elename
    s
  end


new (SOAP::SOAPType)

# File lib/soap/baseData.rb, line 46
  def initialize(*arg)
    super
    @encodingstyle = nil
    @elename = XSD::QName::EMPTY
    @id = nil
    @precedents = []
    @root = false
    @parent = nil
    @position = nil
    @definedtype = nil
    @extraattr = {}
  end


inspect (SOAP::SOAPType)

# File lib/soap/baseData.rb, line 59
  def inspect
    if self.is_a?(XSD::NSDBase)
      sprintf("#<%s:0x%x %s %s>", self.class.name, __id__, self.elename, self.type)
    else
      sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename)
    end
  end


rootnode (SOAP::SOAPType)

# File lib/soap/baseData.rb, line 67
  def rootnode
    node = self
    while node = node.parent
      break if SOAPEnvelope === node
    end
    node
  end


new (SOAP::StreamHandler::ConnectionData)

# File lib/soap/streamHandler.rb, line 33
    def initialize(send_string = nil)
      @send_string = send_string
      @send_contenttype = nil
      @receive_string = nil
      @receive_contenttype = nil
      @is_fault = false
      @soapaction = nil
    end


parse_media_type (SOAP::StreamHandler)

# File lib/soap/streamHandler.rb, line 43
  def self.parse_media_type(str)
    if /^#{ MediaType }(?:\s*;\s*charset=([^"]+|"[^"]+"))?$/i !~ str
      return nil
    end
    charset = $1
    charset.gsub!(/"/, '') if charset
    charset || 'us-ascii'
  end


create_media_type (SOAP::StreamHandler)

# File lib/soap/streamHandler.rb, line 52
  def self.create_media_type(charset)
    "#{ MediaType }; charset=#{ charset }"
  end


new (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 268
    def initialize(host, wsdl, port, logdev)
      @host = host
      @wsdl = wsdl
      @port = port
      @logdev = logdev
      @soapaction = nil
      @options = setup_options
      @default_encodingstyle = nil
      @allow_unqualified_element = nil
      @generate_explicit_type = false
      @mapping_registry = nil           # for rpc unmarshal
      @wsdl_mapping_registry = nil      # for rpc marshal
      @wiredump_file_base = nil
      @mandatorycharset = nil
      @wsdl_elements = @wsdl.collect_elements
      @wsdl_types = @wsdl.collect_complextypes + @wsdl.collect_simpletypes
      @rpc_decode_typemap = @wsdl_types +
        @wsdl.soap_rpc_complextypes(port.find_binding)
      @wsdl_mapping_registry = Mapping::WSDLEncodedRegistry.new(
        @rpc_decode_typemap)
      @doc_mapper = Mapping::WSDLLiteralRegistry.new(
        @wsdl_types, @wsdl_elements)
      endpoint_url = @port.soap_address.location
      # Convert a map which key is QName, to a Hash which key is String.
      @operation = {}
      @port.inputoperation_map.each do |op_name, op_info|
        orgname = op_name.name
        name = XSD::CodeGen::GenSupport.safemethodname(orgname)
        @operation[name] = @operation[orgname] = op_info
        add_method_interface(op_info)
      end
      @proxy = ::SOAP::RPC::Proxy.new(endpoint_url, @soapaction, @options)
    end


inspect (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 302
    def inspect
      "#<#{self.class}:#{@proxy.inspect}>"
    end


endpoint_url (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 306
    def endpoint_url
      @proxy.endpoint_url
    end


endpoint_url= (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 310
    def endpoint_url=(endpoint_url)
      @proxy.endpoint_url = endpoint_url
    end


headerhandler (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 314
    def headerhandler
      @proxy.headerhandler
    end


streamhandler (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 318
    def streamhandler
      @proxy.streamhandler
    end


test_loopback_response (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 322
    def test_loopback_response
      @proxy.test_loopback_response
    end


reset_stream (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 326
    def reset_stream
      @proxy.reset_stream
    end


rpc_call (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 330
    def rpc_call(name, *values)
      set_wiredump_file_base(name)
      unless op_info = @operation[name]
        raise RuntimeError, "method: #{name} not defined"
      end
      req_header = create_request_header
      req_body = create_request_body(op_info, *values)
      reqopt = create_options({
        :soapaction => op_info.soapaction || @soapaction})
      resopt = create_options({
        :decode_typemap => @rpc_decode_typemap})
      env = @proxy.route(req_header, req_body, reqopt, resopt)
      raise EmptyResponseError unless env
      receive_headers(env.header)
      begin
        @proxy.check_fault(env.body)
      rescue ::SOAP::FaultError => e
        Mapping.fault2exception(e)
      end
      ret = env.body.response ?
        Mapping.soap2obj(env.body.response, @mapping_registry) : nil
      if env.body.outparams
        outparams = env.body.outparams.collect { |outparam|
          Mapping.soap2obj(outparam)
        }
        return [ret].concat(outparams)
      else
        return ret
      end
    end


document_send (SOAP::WSDLDriver::Servant__)

# File lib/soap/wsdlDriver.rb, line 363
    def document_send(name, header_obj, body_obj)
      set_wiredump_file_base(name)
      unless op_info = @operation[name]
        raise RuntimeError, "method: #{name} not defined"
      end
      req_header = header_obj ? header_from_obj(header_obj, op_info) : nil
      req_body = body_from_obj(body_obj, op_info)
      opt = create_options({
        :soapaction => op_info.soapaction || @soapaction,
        :decode_typemap => @wsdl_types})
      env = @proxy.invoke(req_header, req_body, opt)
      raise EmptyResponseError unless env
      if env.body.fault
        raise ::SOAP::FaultError.new(env.body.fault)
      end
      res_body_obj = env.body.response ?
        Mapping.soap2obj(env.body.response, @mapping_registry) : nil
      return env.header, res_body_obj
    end


__attr_proxy (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 164
      def __attr_proxy(symbol, assignable = false)
        name = symbol.to_s
        define_method(name) {
          @servant.__send__(name)
        }
        if assignable
          aname = name + '='
          define_method(aname) { |rhs|
            @servant.__send__(aname, rhs)
          }
        end
      end


__attr_proxy (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 177
      def __attr_proxy(symbol, assignable = false)
        name = symbol.to_s
        module_eval "def \#{name}\n@servant.\#{name}\nend\n"
        if assignable
          module_eval "def \#{name}=(value)\n@servant.\#{name} = value\nend\n"
        end
      end


httpproxy (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 208
  def httpproxy
    @servant.options["protocol.http.proxy"]
  end


httpproxy= (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 212
  def httpproxy=(httpproxy)
    @servant.options["protocol.http.proxy"] = httpproxy
  end


wiredump_dev (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 216
  def wiredump_dev
    @servant.options["protocol.http.wiredump_dev"]
  end


wiredump_dev= (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 220
  def wiredump_dev=(wiredump_dev)
    @servant.options["protocol.http.wiredump_dev"] = wiredump_dev
  end


mandatorycharset (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 224
  def mandatorycharset
    @servant.options["protocol.mandatorycharset"]
  end


mandatorycharset= (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 228
  def mandatorycharset=(mandatorycharset)
    @servant.options["protocol.mandatorycharset"] = mandatorycharset
  end


wiredump_file_base (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 232
  def wiredump_file_base
    @servant.options["protocol.wiredump_file_base"]
  end


wiredump_file_base= (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 236
  def wiredump_file_base=(wiredump_file_base)
    @servant.options["protocol.wiredump_file_base"] = wiredump_file_base
  end


new (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 240
  def initialize(wsdl, port, logdev)
    @servant = Servant__.new(self, wsdl, port, logdev)
  end


inspect (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 244
  def inspect
    "#<#{self.class}:#{@servant.port.name}>"
  end


reset_stream (SOAP::WSDLDriver)

# File lib/soap/wsdlDriver.rb, line 248
  def reset_stream
    @servant.reset_stream
  end


new (SOAP::WSDLDriverFactory)

# File lib/soap/wsdlDriver.rb, line 27
  def initialize(wsdl)
    @wsdl = import(wsdl)
    @methoddefcreator = WSDL::SOAP::MethodDefCreator.new(@wsdl)
  end


inspect (SOAP::WSDLDriverFactory)

# File lib/soap/wsdlDriver.rb, line 32
  def inspect
    "#<#{self.class}:#{@wsdl.name}>"
  end


create_rpc_driver (SOAP::WSDLDriverFactory)

# File lib/soap/wsdlDriver.rb, line 36
  def create_rpc_driver(servicename = nil, portname = nil)
    port = find_port(servicename, portname)
    drv = SOAP::RPC::Driver.new(port.soap_address.location)
    init_driver(drv, port)
    add_operation(drv, port)
    drv
  end


create_driver (SOAP::WSDLDriverFactory)

# File lib/soap/wsdlDriver.rb, line 45
  def create_driver(servicename = nil, portname = nil)
    warn("WSDLDriverFactory#create_driver is depricated.  Use create_rpc_driver instead.")
    port = find_port(servicename, portname)
    WSDLDriver.new(@wsdl, port, nil)
  end


new (SOAP)

# File lib/soap/netHttpClient.rb, line 33
  def initialize(proxy = nil, agent = nil)
    @proxy = proxy ? URI.parse(proxy) : nil
    @agent = agent
    @debug_dev = nil
    @session_manager = SessionManager.new
    @no_proxy = @ssl_config = @protocol_version = nil
    @connect_timeout = @send_timeout = @receive_timeout = nil
  end


test_loopback_response (SOAP)

# File lib/soap/netHttpClient.rb, line 42
  def test_loopback_response
    raise NotImplementedError.new("not supported for now")
  end


proxy= (SOAP)

# File lib/soap/netHttpClient.rb, line 46
  def proxy=(proxy)
    if proxy.nil?
      @proxy = nil
    else
      if proxy.is_a?(URI)
        @proxy = proxy
      else
        @proxy = URI.parse(proxy)
      end
      if @proxy.scheme == nil or @proxy.scheme.downcase != 'http' or
          @proxy.host == nil or @proxy.port == nil
        raise ArgumentError.new("unsupported proxy `#{proxy}'")
      end
    end
    reset_all
    @proxy
  end


set_basic_auth (SOAP)

# File lib/soap/netHttpClient.rb, line 64
  def set_basic_auth(uri, user_id, passwd)
    # net/http does not handle url.
    @basic_auth = [user_id, passwd]
    raise NotImplementedError.new("basic_auth is not supported under soap4r + net/http.")
  end


set_cookie_store (SOAP)

# File lib/soap/netHttpClient.rb, line 70
  def set_cookie_store(filename)
    raise NotImplementedError.new
  end


save_cookie_store (SOAP)

# File lib/soap/netHttpClient.rb, line 74
  def save_cookie_store(filename)
    raise NotImplementedError.new
  end


reset (SOAP)

# File lib/soap/netHttpClient.rb, line 78
  def reset(url)
    # no persistent connection.  ignored.
  end


reset_all (SOAP)

# File lib/soap/netHttpClient.rb, line 82
  def reset_all
    # no persistent connection.  ignored.
  end


post (SOAP)

# File lib/soap/netHttpClient.rb, line 86
  def post(url, req_body, header = {})
    unless url.is_a?(URI)
      url = URI.parse(url)
    end
    extra = header.dup
    extra['User-Agent'] = @agent if @agent
    res = start(url) { |http|
      http.post(url.request_uri, req_body, extra)
    }
    Response.new(res)
  end


get_content (SOAP)

# File lib/soap/netHttpClient.rb, line 98
  def get_content(url, header = {})
    unless url.is_a?(URI)
      url = URI.parse(url)
    end
    extra = header.dup
    extra['User-Agent'] = @agent if @agent
    res = start(url) { |http|
        http.get(url.request_uri, extra)
      }
    res.body
  end


connect (Socket)

/*
 * call-seq:
 *      socket.connect(server_sockaddr) => 0
 *
 * Requests a connection to be made on the given +server_sockaddr+. Returns 0 if
 * successful, otherwise an exception is raised.
 *
 * === Parameter
 * * +server_sockaddr+ - the +struct+ sockaddr contained in a string
 *
 * === Example:
 *      # Pull down Google's web page
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
 *      socket.connect( sockaddr )
 *      socket.write( "GET / HTTP/1.0\r\n\r\n" )
 *      results = socket.read
 *
 * === Unix-based Exceptions
 * On unix-based systems the following system exceptions may be raised if
 * the call to _connect_ fails:
 * * Errno::EACCES - search permission is denied for a component of the prefix
 *   path or write access to the +socket+ is denided
 * * Errno::EADDRINUSE - the _sockaddr_ is already in use
 * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
 *   local machine
 * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
 *   the address family of the specified +socket+
 * * Errno::EALREADY - a connection is already in progress for the specified
 *   socket
 * * Errno::EBADF - the +socket+ is not a valid file descriptor
 * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
 *   refused the connection request
 * * Errno::ECONNRESET - the remote host reset the connection request
 * * Errno::EFAULT - the _sockaddr_ cannot be accessed
 * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably
 *   because the host is down or a remote router cannot reach it)
 * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the
 *   connection cnanot be immediately established; the connection will be
 *   established asynchronously
 * * Errno::EINTR - the attempt to establish the connection was interrupted by
 *   delivery of a signal that was caught; the connection will be established
 *   asynchronously
 * * Errno::EISCONN - the specified +socket+ is already connected
 * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid
 *   length for the address family or there is an invalid family in _sockaddr_
 * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
 *   PATH_MAX
 * * Errno::ENETDOWN - the local interface used to reach the destination is down
 * * Errno::ENETUNREACH - no route to the network is present
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOSR - there were insufficient STREAMS resources available to
 *   complete the operation
 * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
 * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected
 * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket
 *   bound to the specified peer address
 * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
 *   was made.
 *
 * On unix-based systems if the address family of the calling +socket+ is
 * AF_UNIX the follow exceptions may be raised if the call to _connect_
 * fails:
 * * Errno::EIO - an i/o error occured while reading from or writing to the
 *   file system
 * * Errno::ELOOP - too many symbolic links were encountered in translating
 *   the pathname in _sockaddr_
 * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
 *   characters, or an entired pathname exceeded PATH_MAX characters
 * * Errno::ENOENT - a component of the pathname does not name an existing file
 *   or the pathname is an empty string
 * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
 *   is not a directory
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _connect_ fails:
 * * Errno::ENETDOWN - the network is down
 * * Errno::EADDRINUSE - the socket's local address is already in use
 * * Errno::EINTR - the socket was cancelled
 * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider
 *   is still processing a callback function. Or a nonblocking connect call is
 *   in progress on the +socket+.
 * * Errno::EALREADY - see Errno::EINVAL
 * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as
 *   ADDR_ANY TODO check ADDRANY TO INADDR_ANY
 * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with
 *   with this +socket+
 * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
 *   refused the connection request
 * * Errno::EFAULT - the socket's internal address or address length parameter
 *   is too small or is not a valid part of the user space address
 * * Errno::EINVAL - the +socket+ is a listening socket
 * * Errno::EISCONN - the +socket+ is already connected
 * * Errno::ENETUNREACH - the network cannot be reached from this host at this time
 * * Errno::EHOSTUNREACH - no route to the network is present
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
 * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
 *   was made.
 * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the
 *   connection cannot be completed immediately
 * * Errno::EACCES - the attempt to connect the datagram socket to the
 *   broadcast address failed
 *
 * === See
 * * connect manual pages on unix-based systems
 * * connect function in Microsoft's Winsock functions reference
 */
static VALUE
sock_connect(sock, addr)
    VALUE sock, addr;
{
    OpenFile *fptr;
    int fd;

    StringValue(addr);
    addr = rb_str_new4(addr);
    GetOpenFile(sock, fptr);
    fd = fileno(fptr->f);
    if (ruby_connect(fd, (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len, 0) < 0) {
        rb_sys_fail("connect(2)");
    }

    return INT2FIX(0);
}


connect_nonblock (Socket)

/*
 * call-seq:
 *      socket.connect_nonblock(server_sockaddr) => 0
 *
 * Requests a connection to be made on the given +server_sockaddr+ after
 * O_NONBLOCK is set for the underlying file descriptor.
 * Returns 0 if successful, otherwise an exception is raised.
 *
 * === Parameter
 * * +server_sockaddr+ - the +struct+ sockaddr contained in a string
 *
 * === Example:
 *      # Pull down Google's web page
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 *      sockaddr = Socket.sockaddr_in(80, 'www.google.com')
 *      begin
 *        socket.connect_nonblock(sockaddr)
 *      rescue Errno::EINPROGRESS
 *        IO.select(nil, [socket])
 *        begin
 *          socket.connect_nonblock(sockaddr)
 *        rescue Errno::EISCONN
 *        end
 *      end
 *      socket.write("GET / HTTP/1.0\r\n\r\n")
 *      results = socket.read
 *
 * Refer to Socket#connect for the exceptions that may be thrown if the call
 * to _connect_nonblock_ fails.
 *
 * Socket#connect_nonblock may raise any error corresponding to connect(2) failure,
 * including Errno::EINPROGRESS.
 *
 * === See
 * * Socket#connect
 */
static VALUE
sock_connect_nonblock(sock, addr)
    VALUE sock, addr;
{
    OpenFile *fptr;
    int n;

    StringValue(addr);
    addr = rb_str_new4(addr);
    GetOpenFile(sock, fptr);
    rb_io_set_nonblock(fptr);
    n = connect(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len);
    if (n < 0) {
        rb_sys_fail("connect(2)");
    }

    return INT2FIX(n);
}


bind (Socket)

/*
 * call-seq:
 *      socket.bind(server_sockaddr) => 0
 *
 * Binds to the given +struct+ sockaddr.
 *
 * === Parameter
 * * +server_sockaddr+ - the +struct+ sockaddr contained in a string
 *
 * === Example
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *
 * === Unix-based Exceptions
 * On unix-based based systems the following system exceptions may be raised if
 * the call to _bind_ fails:
 * * Errno::EACCES - the specified _sockaddr_ is protected and the current
 *   user does not have permission to bind to it
 * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use
 * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
 *   local machine
 * * Errno::EAFNOSUPPORT - the specified _sockaddr_ isnot a valid address for
 *   the family of the calling +socket+
 * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor
 * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed
 * * Errno::EINVAL - the +socket+ is already bound to an address, and the
 *   protocol does not support binding to the new _sockaddr_ or the +socket+
 *   has been shut down.
 * * Errno::EINVAL - the address length is not a valid length for the address
 *   family
 * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
 *   PATH_MAX
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOSR - there were insufficient STREAMS resources available to
 *   complete the operation
 * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
 * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support
 *   binding to an address
 *
 * On unix-based based systems if the address family of the calling +socket+ is
 * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_
 * fails:
 * * Errno::EACCES - search permission is denied for a component of the prefix
 *   path or write access to the +socket+ is denided
 * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer
 * * Errno::EISDIR - same as Errno::EDESTADDRREQ
 * * Errno::EIO - an i/o error occurred
 * * Errno::ELOOP - too many symbolic links were encountered in translating
 *   the pathname in _sockaddr_
 * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
 *   characters, or an entired pathname exceeded PATH_MAX characters
 * * Errno::ENOENT - a component of the pathname does not name an existing file
 *   or the pathname is an empty string
 * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
 *   is not a directory
 * * Errno::EROFS - the name would reside on a read only filesystem
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _bind_ fails:
 * * Errno::ENETDOWN-- the network is down
 * * Errno::EACCES - the attempt to connect the datagram socket to the
 *   broadcast address failed
 * * Errno::EADDRINUSE - the socket's local address is already in use
 * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this
 *   computer
 * * Errno::EFAULT - the socket's internal address or address length parameter
 *   is too small or is not a valid part of the user space addressed
 * * Errno::EINVAL - the +socket+ is already bound to an address
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
 *
 * === See
 * * bind manual pages on unix-based systems
 * * bind function in Microsoft's Winsock functions reference
 */
static VALUE
sock_bind(sock, addr)
    VALUE sock, addr;
{
    OpenFile *fptr;

    StringValue(addr);
    GetOpenFile(sock, fptr);
    if (bind(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len) < 0)
        rb_sys_fail("bind(2)");

    return INT2FIX(0);
}


listen (Socket)

/*
 * call-seq:
 *      socket.listen( int ) => 0
 *
 * Listens for connections, using the specified +int+ as the backlog. A call
 * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
 * SOCK_SEQPACKET.
 *
 * === Parameter
 * * +backlog+ - the maximum length of the queue for pending connections.
 *
 * === Example 1
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *      socket.listen( 5 )
 *
 * === Example 2 (listening on an arbitary port, unix-based systems only):
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      socket.listen( 1 )
 *
 * === Unix-based Exceptions
 * On unix based systems the above will work because a new +sockaddr+ struct
 * is created on the address ADDR_ANY, for an arbitrary port number as handed
 * off by the kernel. It will not work on Windows, because Windows requires that
 * the +socket+ is bound by calling _bind_ before it can _listen_.
 *
 * If the _backlog_ amount exceeds the implementation-dependent maximum
 * queue length, the implementation's maximum queue length will be used.
 *
 * On unix-based based systems the following system exceptions may be raised if the
 * call to _listen_ fails:
 * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
 * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
 *   the protocol does not support listening on an unbound socket
 * * Errno::EINVAL - the _socket_ is already connected
 * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
 * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
 * * Errno::EACCES - the calling process does not have approriate privileges
 * * Errno::EINVAL - the _socket_ has been shut down
 * * Errno::ENOBUFS - insufficient resources are available in the system to
 *   complete the call
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _listen_ fails:
 * * Errno::ENETDOWN - the network is down
 * * Errno::EADDRINUSE - the socket's local address is already in use. This
 *   usually occurs during the execution of _bind_ but could be delayed
 *   if the call to _bind_ was to a partially wildcard address (involving
 *   ADDR_ANY) and if a specific address needs to be commmitted at the
 *   time of the call to _listen_
 * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
 *   service provider is still processing a callback function
 * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
 * * Errno::EISCONN - the +socket+ is already connected
 * * Errno::EMFILE - no more socket descriptors are available
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOTSOC - +socket+ is not a socket
 * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
 *   the _listen_ method
 *
 * === See
 * * listen manual pages on unix-based systems
 * * listen function in Microsoft's Winsock functions reference
 */
static VALUE
sock_listen(sock, log)
    VALUE sock, log;
{
    OpenFile *fptr;
    int backlog;

    rb_secure(4);
    backlog = NUM2INT(log);
    GetOpenFile(sock, fptr);
    if (listen(fileno(fptr->f), backlog) < 0)
        rb_sys_fail("listen(2)");

    return INT2FIX(0);
}


accept (Socket)

/*
 * call-seq:
 *      socket.accept => [ socket, string ]
 *
 * Accepts an incoming connection returning an array containing a new
 * Socket object and a string holding the +struct+ sockaddr information about
 * the caller.
 *
 * === Example
 *      # In one script, start this first
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *      socket.listen( 5 )
 *      client, client_sockaddr = socket.accept
 *      puts "The client said, '#{client.readline.chomp}'"
 *      client.puts "Hello from script one!"
 *      socket.close
 *
 *      # In another script, start this second
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.connect( sockaddr )
 *      socket.puts "Hello from script 2."
 *      puts "The server said, '#{socket.readline.chomp}'"
 *      socket.close
 *
 * === Unix-based Exceptions
 * On unix-based based systems the following system exceptions may be raised if the
 * call to _accept_ fails:
 * * Errno::EAGAIN - O_NONBLOCK is set for the +socket+ file descriptor and no
 *   connections are parent to be accepted
 * * Errno::EWOULDBLOCK - same as Errno::EAGAIN
 * * Errno::EBADF - the +socket+ is not a valid file descriptor
 * * Errno::ECONNABORTED - a connection has been aborted
 * * Errno::EFAULT - the socket's internal address or address length parameter
 *   cannot be access or written
 * * Errno::EINTR - the _accept_ method was interrupted by a signal that was
 *   caught before a valid connection arrived
 * * Errno::EINVAL - the +socket+ is not accepting connections
 * * Errno::EMFILE - OPEN_MAX file descriptors are currently open in the calling
 *   process
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOMEM - there was insufficient memory available to complete the
 *   operation
 * * Errno::ENOSR - there was insufficient STREAMS resources available to
 *   complete the operation
 * * Errno::ENFILE - the maximum number of file descriptors in the system are
 *   already open
 * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
 * * Errno::EOPNOTSUPP - the socket type for the calling +socket+ does not
 *   support accept connections
 * * Errno::EPROTO - a protocol error has occurred
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _accept_ fails:
 * * Errno::ECONNRESET - an incoming connection was indicated, but was
 *   terminated by the remote peer prior to accepting the connection
 * * Errno::EFAULT - the socket's internal address or address length parameter
 *   is too small or is not a valid part of the user space address
 * * Errno::EINVAL - the _listen_ method was not invoked prior to calling _accept_
 * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
 *   the service provider is still processing a callback function
 * * Errno::EMFILE - the queue is not empty, upong etry to _accept_ and there are
 *   no socket descriptors available
 * * Errno::ENETDOWN - the network is down
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOTSOCK - +socket+ is not a socket
 * * Errno::EOPNOTSUPP - +socket+ is not a type that supports connection-oriented
 *   service.
 * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and no connections are
 *   present to be accepted
 *
 * === See
 * * accept manual pages on unix-based systems
 * * accept function in Microsoft's Winsock functions reference
 */
static VALUE
sock_accept(sock)
    VALUE sock;
{
    OpenFile *fptr;
    VALUE sock2;
    char buf[1024];
    socklen_t len = sizeof buf;

    GetOpenFile(sock, fptr);
    sock2 = s_accept(rb_cSocket,fileno(fptr->f),(struct sockaddr*)buf,&len);

    return rb_assoc_new(sock2, rb_str_new(buf, len));
}


accept_nonblock (Socket)

/*
 * call-seq:
 *    socket.accept_nonblock => [client_socket, client_sockaddr]
 *
 * Accepts an incoming connection using accept(2) after
 * O_NONBLOCK is set for the underlying file descriptor.
 * It returns an array containg the accpeted socket
 * for the incoming connection, _client_socket_,
 * and a string that contains the +struct+ sockaddr information
 * about the caller, _client_sockaddr_.
 *
 * === Example
 *      # In one script, start this first
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
 *      socket.bind(sockaddr)
 *      socket.listen(5)
 *      begin
 *        client_socket, client_sockaddr = socket.accept_nonblock
 *      rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
 *        IO.select([socket])
 *        retry
 *      end
 *      puts "The client said, '#{client_socket.readline.chomp}'"
 *      client_socket.puts "Hello from script one!"
 *      socket.close
 *
 *      # In another script, start this second
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
 *      socket.connect(sockaddr)
 *      socket.puts "Hello from script 2."
 *      puts "The server said, '#{socket.readline.chomp}'"
 *      socket.close
 *
 * Refer to Socket#accept for the exceptions that may be thrown if the call
 * to _accept_nonblock_ fails.
 *
 * Socket#accept_nonblock may raise any error corresponding to accept(2) failure,
 * including Errno::EAGAIN.
 *
 * === See
 * * Socket#accept
 */
static VALUE
sock_accept_nonblock(sock)
    VALUE sock;
{
    OpenFile *fptr;
    VALUE sock2;
    char buf[1024];
    socklen_t len = sizeof buf;

    GetOpenFile(sock, fptr);
    sock2 = s_accept_nonblock(rb_cSocket, fptr, (struct sockaddr *)buf, &len);
    return rb_assoc_new(sock2, rb_str_new(buf, len));
}


sysaccept (Socket)

/*
 * call-seq:
 *      socket.sysaccept => [client_socket_fd, client_sockaddr]
 *
 * Accepts an incoming connection returnings an array containg the (integer)
 * file descriptor for the incoming connection, _client_socket_fd_,
 * and a string that contains the +struct+ sockaddr information
 * about the caller, _client_sockaddr_.
 *
 * === Example
 *      # In one script, start this first
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *      socket.listen( 5 )
 *      client_fd, client_sockaddr = socket.sysaccept
 *      client_socket = Socket.for_fd( client_fd )
 *      puts "The client said, '#{client_socket.readline.chomp}'"
 *      client_socket.puts "Hello from script one!"
 *      socket.close
 *
 *      # In another script, start this second
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.connect( sockaddr )
 *      socket.puts "Hello from script 2."
 *      puts "The server said, '#{socket.readline.chomp}'"
 *      socket.close
 *
 * Refer to Socket#accept for the exceptions that may be thrown if the call
 * to _sysaccept_ fails.
 *
 * === See
 * * Socket#accept
 */
static VALUE
sock_sysaccept(sock)
    VALUE sock;
{
    OpenFile *fptr;
    VALUE sock2;
    char buf[1024];
    socklen_t len = sizeof buf;

    GetOpenFile(sock, fptr);
    sock2 = s_accept(0,fileno(fptr->f),(struct sockaddr*)buf,&len);

    return rb_assoc_new(sock2, rb_str_new(buf, len));
}


recvfrom (Socket)

/*
 * call-seq:
 *      socket.recvfrom(maxlen) => [mesg, sender_sockaddr]
 *      socket.recvfrom(maxlen, flags) => [mesg, sender_sockaddr]
 *
 * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more
 * of the +MSG_+ options. The first element of the results, _mesg_, is the data
 * received. The second element, _sender_sockaddr_, contains protocol-specific information
 * on the sender.
 *
 * === Parameters
 * * +maxlen+ - the number of bytes to receive from the socket
 * * +flags+ - zero or more of the +MSG_+ options
 *
 * === Example
 *      # In one file, start this first
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *      socket.listen( 5 )
 *      client, client_sockaddr = socket.accept
 *      data = client.recvfrom( 20 )[0].chomp
 *      puts "I only received 20 bytes '#{data}'"
 *      sleep 1
 *      socket.close
 *
 *      # In another file, start this second
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.connect( sockaddr )
 *      socket.puts "Watch this get cut short!"
 *      socket.close
 *
 * === Unix-based Exceptions
 * On unix-based based systems the following system exceptions may be raised if the
 * call to _recvfrom_ fails:
 * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no
 *   data is waiting to be received; or MSG_OOB is set and no out-of-band data
 *   is available and either the +socket+ file descriptor is marked as
 *   O_NONBLOCK or the +socket+ does not support blocking to wait for
 *   out-of-band-data
 * * Errno::EWOULDBLOCK - see Errno::EAGAIN
 * * Errno::EBADF - the +socket+ is not a valid file descriptor
 * * Errno::ECONNRESET - a connection was forcibly closed by a peer
 * * Errno::EFAULT - the socket's internal buffer, address or address length
 *   cannot be accessed or written
 * * Errno::EINTR - a signal interupted _recvfrom_ before any data was available
 * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
 * * Errno::EIO - an i/o error occurred while reading from or writing to the
 *   filesystem
 * * Errno::ENOBUFS - insufficient resources were available in the system to
 *   perform the operation
 * * Errno::ENOMEM - insufficient memory was available to fulfill the request
 * * Errno::ENOSR - there were insufficient STREAMS resources available to
 *   complete the operation
 * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that
 *   is not connected
 * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
 * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
 * * Errno::ETIMEDOUT - the connection timed out during connection establishment
 *   or due to a transmission timeout on an active connection
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _recvfrom_ fails:
 * * Errno::ENETDOWN - the network is down
 * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not
 *   part of the user address space, or the internal fromlen parameter is
 *   too small to accomodate the peer address
 * * Errno::EINTR - the (blocking) call was cancelled by an internal call to
 *   the WinSock function WSACancelBlockingCall
 * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
 *   the service provider is still processing a callback function
 * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an
 *   unknown flag was specified, or MSG_OOB was specified for a socket with
 *   SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal
 *   len parameter on +socket+ was zero or negative
 * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is
 *   not permitted with a connected socket on a socket that is connetion
 *   oriented or connectionless.
 * * Errno::ENETRESET - the connection has been broken due to the keep-alive
 *   activity detecting a failure while the operation was in progress.
 * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style
 *   such as type SOCK_STREAM. OOB data is not supported in the communication
 *   domain associated with +socket+, or +socket+ is unidirectional and
 *   supports only send operations
 * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to
 *   call _recvfrom_ on a socket after _shutdown_ has been invoked.
 * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a  call to
 *   _recvfrom_ would block.
 * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer
 *   and was truncated.
 * * Errno::ETIMEDOUT - the connection has been dropped, because of a network
 *   failure or because the system on the other end went down without
 *   notice
 * * Errno::ECONNRESET - the virtual circuit was reset by the remote side
 *   executing a hard or abortive close. The application should close the
 *   socket; it is no longer usable. On a UDP-datagram socket this error
 *   indicates a previous send operation resulted in an ICMP Port Unreachable
 *   message.
 */
static VALUE
sock_recvfrom(argc, argv, sock)
    int argc;
    VALUE *argv;
    VALUE sock;
{
    return s_recvfrom(sock, argc, argv, RECV_SOCKET);
}


recvfrom_nonblock (Socket)

/*
 * call-seq:
 *      socket.recvfrom_nonblock(maxlen) => [mesg, sender_sockaddr]
 *      socket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_sockaddr]
 *
 * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
 * O_NONBLOCK is set for the underlying file descriptor.
 * _flags_ is zero or more of the +MSG_+ options.
 * The first element of the results, _mesg_, is the data received.
 * The second element, _sender_sockaddr_, contains protocol-specific information
 * on the sender.
 *
 * When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns
 * an empty string as data.
 * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
 *
 * === Parameters
 * * +maxlen+ - the number of bytes to receive from the socket
 * * +flags+ - zero or more of the +MSG_+ options
 *
 * === Example
 *      # In one file, start this first
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
 *      socket.bind(sockaddr)
 *      socket.listen(5)
 *      client, client_sockaddr = socket.accept
 *      begin
 *        pair = client.recvfrom_nonblock(20)
 *      rescue Errno::EAGAIN
 *        IO.select([client])
 *        retry
 *      end
 *      data = pair[0].chomp
 *      puts "I only received 20 bytes '#{data}'"
 *      sleep 1
 *      socket.close
 *
 *      # In another file, start this second
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
 *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
 *      socket.connect(sockaddr)
 *      socket.puts "Watch this get cut short!"
 *      socket.close
 *
 * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
 * to _recvfrom_nonblock_ fails.
 *
 * Socket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
 * including Errno::EAGAIN.
 *
 * === See
 * * Socket#recvfrom
 */
static VALUE
sock_recvfrom_nonblock(int argc, VALUE *argv, VALUE sock)
{
    return s_recvfrom_nonblock(sock, argc, argv, RECV_SOCKET);
}


gethostbyname (Socket)

/*
 * Document-method: gethostbyname
 * call-seq: Socket.gethostbyname(host) => hostent
 *
 * Resolve +host+ and return name and address information for it, similarly to
 * gethostbyname(3). +host+ can be a domain name or the presentation format of
 * an address.
 *
 * Returns an array of information similar to that found in a +struct hostent+:
 *   - cannonical name: the cannonical name for host in the DNS, or a
 *     string representing the address
 *   - aliases: an array of aliases for the canonical name, there may be no aliases
 *   - address family: usually one of Socket::AF_INET or Socket::AF_INET6
 *   - address: a string, the binary value of the +struct sockaddr+ for this name, in
 *     the indicated address family
 *   - ...: if there are multiple addresses for this host,  a series of
 *     strings/+struct sockaddr+s may follow, not all necessarily in the same
 *     address family. Note that the fact that they may not be all in the same
 *     address family is a departure from the behaviour of gethostbyname(3).
 *
 * Note: I believe that the fact that the multiple addresses returned are not
 * necessarily in the same address family may be a bug, since if this function
 * actually called gethostbyname(3), ALL the addresses returned in the trailing
 * address list (h_addr_list from struct hostent) would be of the same address
 * family!  Examples from my system, OS X 10.3:
 *
 *   ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"]
 *     and
 *   ["ensemble.local", [], 30, "\376\200\000\004\000\000\000\000\002\003\223\377\376\255\010\214", "\300\250{\232" ]
 *
 * Similar information can be returned by Socket.getaddrinfo if called as:
 *
 *    Socket.getaddrinfo(+host+, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)
 *
 * == Examples
 *
 *   Socket.gethostbyname "example.com"
 *   => ["example.com", [], 2, "\300\000\"\246"]
 *
 * This name has no DNS aliases, and a single IPv4 address.
 *
 *   Socket.gethostbyname "smtp.telus.net"
 *   => ["smtp.svc.telus.net", ["smtp.telus.net"], 2, "\307\271\334\371"]
 *
 * This name is an an alias so the canonical name is returned, as well as the
 * alias and a single IPv4 address.
 *
 *   Socket.gethostbyname "localhost"
 *   => ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"]
 *
 * This machine has no aliases, returns an IPv6 address, and has an additional IPv4 address.
 *
 * +host+ can also be an IP address in presentation format, in which case a
 * reverse lookup is done on the address:
 *
 *   Socket.gethostbyname("127.0.0.1")
 *   => ["localhost", [], 2, "\177\000\000\001"]
 *
 *   Socket.gethostbyname("192.0.34.166")
 *   => ["www.example.com", [], 2, "\300\000\"\246"]
 *
 *
 * == See
 * See: Socket.getaddrinfo
 */
static VALUE
sock_s_gethostbyname(obj, host)
    VALUE obj, host;
{
    rb_secure(3);
    return make_hostent(host, sock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), sock_sockaddr);
}


getservbyname (Socket)

/*
 * Document-method: getservbyname
 * call-seq: Socket.getservbyname(name, proto="tcp") => port
 *
 * +name+ is a service name ("ftp", "telnet", ...) and proto is a protocol name
 * ("udp", "tcp", ...). '/etc/services' (or your system's equivalent) is
 * searched for a service for +name+ and +proto+, and the port number is
 * returned.
 *
 * Note that unlike Socket.getaddrinfo, +proto+ may not be specified using the
 * Socket::SOCK_* constants, a string must must be used.
 */
static VALUE
sock_s_getservbyaname(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE service, proto;
    struct servent *sp;
    int port;

    rb_scan_args(argc, argv, "11", &service, &proto);
    if (NIL_P(proto)) proto = rb_str_new2("tcp");
    StringValue(service);
    StringValue(proto);

    sp = getservbyname(StringValueCStr(service),  StringValueCStr(proto));
    if (sp) {
        port = ntohs(sp->s_port);
    }
    else {
        char *s = RSTRING(service)->ptr;
        char *end;

        port = strtoul(s, &end, 0);
        if (*end != '\0') {
            rb_raise(rb_eSocket, "no such service %s/%s", s, RSTRING(proto)->ptr);
        }
    }
    return INT2FIX(port);
}


getaddrinfo (Socket)

/*
 * Document-method: getaddrinfo
 * call-seq: Socket.getaddrinfo(host, service, family=nil, socktype=nil, protocol=nil, flags=nil) => addrinfo
 *
 * Return address information for +host+ and +port+. The remaining arguments
 * are hints that limit the address information returned.
 *
 * This method corresponds closely to the POSIX.1g getaddrinfo() definition.
 *
 * === Parameters
 * - +host+ is a host name or an address string (dotted decimal for IPv4, or a hex string
 *   for IPv6) for which to return information. A nil is also allowed, its meaning
 *   depends on +flags+, see below.
 * - +service+ is a service name ("http", "ssh", ...), or
 *   a port number (80, 22, ...), see Socket.getservbyname for more
 *   information. A nil is also allowed, meaning zero.
 * - +family+ limits the output to a specific address family, one of the
 *   Socket::AF_* constants. Socket::AF_INET (IPv4) and Socket::AF_INET6 (IPv6)
 *   are the most commonly used families. You will usually pass either nil or
 *   Socket::AF_UNSPEC, allowing the IPv6 information to be returned first if
 *   +host+ is reachable via IPv6, and IPv4 information otherwise.  The two
 *   strings "AF_INET" or "AF_INET6" are also allowed, they are converted to
 *   their respective Socket::AF_* constants.
 * - +socktype+ limits the output to a specific type of socket, one of the
 *   Socket::SOCK_* constants. Socket::SOCK_STREAM (for TCP) and
 *   Socket::SOCK_DGRAM (for UDP) are the most commonly used socket types. If
 *   nil, then information for all types of sockets supported by +service+ will
 *   be returned. You will usually know what type of socket you intend to
 *   create, and should pass that socket type in.
 * - +protocol+ limits the output to a specific protocol numpber, one of the
 *   Socket::IPPROTO_* constants. It is usually implied by the socket type
 *   (Socket::SOCK_STREAM => Socket::IPPROTO_TCP, ...), if you pass other than
 *   nil you already know what this is for.
 * - +flags+ is one of the Socket::AI_* constants. They mean:
 *   - Socket::AI_PASSIVE: when set, if +host+ is nil the 'any' address will be
 *     returned, Socket::INADDR_ANY or 0 for IPv4, "0::0" or "::" for IPv6.  This
 *     address is suitable for use by servers that will bind their socket and do
 *     a passive listen, thus the name of the flag. Otherwise the local or
 *     loopback address will be returned, this is "127.0.0.1" for IPv4 and "::1'
 *     for IPv6.
 *   - ...
 *
 *
 * === Returns
 *
 * Returns an array of arrays, where each subarray contains:
 * - address family, a string like "AF_INET" or "AF_INET6"
 * - port number, the port number for +service+
 * - host name, either a canonical name for +host+, or it's address in presentation
 *   format if the address could not be looked up.
 * - host IP, the address of +host+ in presentation format
 * - address family, as a numeric value (one of the Socket::AF_* constants).
 * - socket type, as a numeric value (one of the Socket::SOCK_* constants).
 * - protocol number, as a numeric value (one of the Socket::IPPROTO_* constants).
 *
 * The first four values are identical to what is commonly returned as an
 * address array, see IPSocket for more information.
 *
 * === Examples
 *
 * Not all input combinations are valid, and while there are many combinations,
 * only a few cases are common.
 *
 * A typical client will call getaddrinfo with the +host+ and +service+ it
 * wants to connect to. It knows that it will attempt to connect with either
 * TCP or UDP, and specifies +socktype+ accordingly. It loops through all
 * returned addresses, and try to connect to them in turn:
 *
 *   addrinfo = Socket::getaddrinfo('www.example.com', 'www', nil, Socket::SOCK_STREAM)
 *   addrinfo.each do |af, port, name, addr|
 *     begin
 *       sock = TCPSocket.new(addr, port)
 *       # ...
 *       exit 1
 *     rescue
 *     end
 *   end
 *
 * With UDP you don't know if connect suceeded, but if communication fails,
 * the next address can be tried.
 *
 * A typical server will call getaddrinfo with a +host+ of nil, the +service+
 * it listens to, and a +flags+ of Socket::AI_PASSIVE. It will listen for
 * connections on the first returned address:
 *   addrinfo = Socket::getaddrinfo(nil, 'www', nil, Socket::SOCK_STREAM, nil, Socket::AI_PASSIVE)
 *   af, port, name, addr = addrinfo.first
 *   sock = TCPServer(addr, port)
 *   while( client = s.accept )
 *     # ...
 *   end
 */
static VALUE
sock_s_getaddrinfo(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE host, port, family, socktype, protocol, flags, ret;
    char hbuf[1024], pbuf[1024];
    char *hptr, *pptr, *ap;
    struct addrinfo hints, *res;
    int error;

    host = port = family = socktype = protocol = flags = Qnil;
    rb_scan_args(argc, argv, "24", &host, &port, &family, &socktype, &protocol, &flags);
    if (NIL_P(host)) {
        hptr = NULL;
    }
    else {
        strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
        hbuf[sizeof(hbuf) - 1] = '\0';
        hptr = hbuf;
    }
    if (NIL_P(port)) {
        pptr = NULL;
    }
    else if (FIXNUM_P(port)) {
        snprintf(pbuf, sizeof(pbuf), "%ld", FIX2LONG(port));
        pptr = pbuf;
    }
    else {
        strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
        pbuf[sizeof(pbuf) - 1] = '\0';
        pptr = pbuf;
    }

    MEMZERO(&hints, struct addrinfo, 1);
    if (NIL_P(family)) {
        hints.ai_family = PF_UNSPEC;
    }
    else if (FIXNUM_P(family)) {
        hints.ai_family = FIX2INT(family);
    }
    else if ((ap = StringValuePtr(family)) != 0) {
        if (strcmp(ap, "AF_INET") == 0) {
            hints.ai_family = PF_INET;
        }
#ifdef INET6
        else if (strcmp(ap, "AF_INET6") == 0) {
            hints.ai_family = PF_INET6;
        }
#endif
    }

    if (!NIL_P(socktype)) {
        hints.ai_socktype = NUM2INT(socktype);
    }
    if (!NIL_P(protocol)) {
        hints.ai_protocol = NUM2INT(protocol);
    }
    if (!NIL_P(flags)) {
        hints.ai_flags = NUM2INT(flags);
    }
    error = getaddrinfo(hptr, pptr, &hints, &res);
    if (error) {
        rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error));
    }

    ret = make_addrinfo(res);
    freeaddrinfo(res);
    return ret;
}


new (SOCKSSocket)

# File lib/resolv-replace.rb, line 59
  def initialize(host, serv)
    original_resolv_initialize(IPSocket.getaddress(host), port)
  end


unpack (String)

/*
 *  call-seq:
 *     str.unpack(format)   => anArray
 *
 *  Decodes <i>str</i> (which may contain binary data) according to the
 *  format string, returning an array of each value extracted. The
 *  format string consists of a sequence of single-character directives,
 *  summarized in the table at the end of this entry.
 *  Each directive may be followed
 *  by a number, indicating the number of times to repeat with this
 *  directive. An asterisk (``<code>*</code>'') will use up all
 *  remaining elements. The directives <code>sSiIlL</code> may each be
 *  followed by an underscore (``<code>_</code>'') to use the underlying
 *  platform's native size for the specified type; otherwise, it uses a
 *  platform-independent consistent size. Spaces are ignored in the
 *  format string. See also <code>Array#pack</code>.
 *
 *     "abc \0\0abc \0\0".unpack('A6Z6')   #=> ["abc", "abc "]
 *     "abc \0\0".unpack('a3a3')           #=> ["abc", " \000\000"]
 *     "abc \0abc \0".unpack('Z*Z*')       #=> ["abc ", "abc "]
 *     "aa".unpack('b8B8')                 #=> ["10000110", "01100001"]
 *     "aaa".unpack('h2H2c')               #=> ["16", "61", 97]
 *     "\xfe\xff\xfe\xff".unpack('sS')     #=> [-2, 65534]
 *     "now=20is".unpack('M*')             #=> ["now is"]
 *     "whole".unpack('xax2aX2aX1aX2a')    #=> ["h", "e", "l", "l", "o"]
 *
 *  This table summarizes the various formats and the Ruby classes
 *  returned by each.
 *
 *     Format | Returns | Function
 *     -------+---------+-----------------------------------------
 *       A    | String  | with trailing nulls and spaces removed
 *     -------+---------+-----------------------------------------
 *       a    | String  | string
 *     -------+---------+-----------------------------------------
 *       B    | String  | extract bits from each character (msb first)
 *     -------+---------+-----------------------------------------
 *       b    | String  | extract bits from each character (lsb first)
 *     -------+---------+-----------------------------------------
 *       C    | Fixnum  | extract a character as an unsigned integer
 *     -------+---------+-----------------------------------------
 *       c    | Fixnum  | extract a character as an integer
 *     -------+---------+-----------------------------------------
 *       d,D  | Float   | treat sizeof(double) characters as
 *            |         | a native double
 *     -------+---------+-----------------------------------------
 *       E    | Float   | treat sizeof(double) characters as
 *            |         | a double in little-endian byte order
 *     -------+---------+-----------------------------------------
 *       e    | Float   | treat sizeof(float) characters as
 *            |         | a float in little-endian byte order
 *     -------+---------+-----------------------------------------
 *       f,F  | Float   | treat sizeof(float) characters as
 *            |         | a native float
 *     -------+---------+-----------------------------------------
 *       G    | Float   | treat sizeof(double) characters as
 *            |         | a double in network byte order
 *     -------+---------+-----------------------------------------
 *       g    | Float   | treat sizeof(float) characters as a
 *            |         | float in network byte order
 *     -------+---------+-----------------------------------------
 *       H    | String  | extract hex nibbles from each character
 *            |         | (most significant first)
 *     -------+---------+-----------------------------------------
 *       h    | String  | extract hex nibbles from each character
 *            |         | (least significant first)
 *     -------+---------+-----------------------------------------
 *       I    | Integer | treat sizeof(int) (modified by _)
 *            |         | successive characters as an unsigned
 *            |         | native integer
 *     -------+---------+-----------------------------------------
 *       i    | Integer | treat sizeof(int) (modified by _)
 *            |         | successive characters as a signed
 *            |         | native integer
 *     -------+---------+-----------------------------------------
 *       L    | Integer | treat four (modified by _) successive
 *            |         | characters as an unsigned native
 *            |         | long integer
 *     -------+---------+-----------------------------------------
 *       l    | Integer | treat four (modified by _) successive
 *            |         | characters as a signed native
 *            |         | long integer
 *     -------+---------+-----------------------------------------
 *       M    | String  | quoted-printable
 *     -------+---------+-----------------------------------------
 *       m    | String  | base64-encoded
 *     -------+---------+-----------------------------------------
 *       N    | Integer | treat four characters as an unsigned
 *            |         | long in network byte order
 *     -------+---------+-----------------------------------------
 *       n    | Fixnum  | treat two characters as an unsigned
 *            |         | short in network byte order
 *     -------+---------+-----------------------------------------
 *       P    | String  | treat sizeof(char *) characters as a
 *            |         | pointer, and  return \emph{len} characters
 *            |         | from the referenced location
 *     -------+---------+-----------------------------------------
 *       p    | String  | treat sizeof(char *) characters as a
 *            |         | pointer to a  null-terminated string
 *     -------+---------+-----------------------------------------
 *       Q    | Integer | treat 8 characters as an unsigned
 *            |         | quad word (64 bits)
 *     -------+---------+-----------------------------------------
 *       q    | Integer | treat 8 characters as a signed
 *            |         | quad word (64 bits)
 *     -------+---------+-----------------------------------------
 *       S    | Fixnum  | treat two (different if _ used)
 *            |         | successive characters as an unsigned
 *            |         | short in native byte order
 *     -------+---------+-----------------------------------------
 *       s    | Fixnum  | Treat two (different if _ used)
 *            |         | successive characters as a signed short
 *            |         | in native byte order
 *     -------+---------+-----------------------------------------
 *       U    | Integer | UTF-8 characters as unsigned integers
 *     -------+---------+-----------------------------------------
 *       u    | String  | UU-encoded
 *     -------+---------+-----------------------------------------
 *       V    | Fixnum  | treat four characters as an unsigned
 *            |         | long in little-endian byte order
 *     -------+---------+-----------------------------------------
 *       v    | Fixnum  | treat two characters as an unsigned
 *            |         | short in little-endian byte order
 *     -------+---------+-----------------------------------------
 *       w    | Integer | BER-compressed integer (see Array.pack)
 *     -------+---------+-----------------------------------------
 *       X    | ---     | skip backward one character
 *     -------+---------+-----------------------------------------
 *       x    | ---     | skip forward one character
 *     -------+---------+-----------------------------------------
 *       Z    | String  | with trailing nulls removed
 *            |         | upto first null with *
 *     -------+---------+-----------------------------------------
 *       @    | ---     | skip to the offset given by the
 *            |         | length argument
 *     -------+---------+-----------------------------------------
 */

static VALUE
pack_unpack(str, fmt)
    VALUE str, fmt;
{
    static char *hexdigits = "0123456789abcdef0123456789ABCDEFx";
    char *s, *send;
    char *p, *pend;
    VALUE ary;
    char type;
    long len;
    int tmp, star;
#ifdef NATINT_PACK
    int natint;                 /* native integer */
#endif

    StringValue(str);
    StringValue(fmt);
    s = RSTRING(str)->ptr;
    send = s + RSTRING(str)->len;
    p = RSTRING(fmt)->ptr;
    pend = p + RSTRING(fmt)->len;

    ary = rb_ary_new();
    while (p < pend) {
        type = *p++;
#ifdef NATINT_PACK
        natint = 0;
#endif

        if (ISSPACE(type)) continue;
        if (type == '#') {
            while ((p < pend) && (*p != '\n')) {
                p++;
            }
            continue;
        }
        star = 0;
        if (*p == '_' || *p == '!') {
            char *natstr = "sSiIlL";

            if (strchr(natstr, type)) {
#ifdef NATINT_PACK
                natint = 1;
#endif
                p++;
            }
            else {
                rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
            }
        }
        if (p >= pend)
            len = 1;
        else if (*p == '*') {
            star = 1;
            len = send - s;
            p++;
        }
        else if (ISDIGIT(*p)) {
            len = strtoul(p, (char**)&p, 10);
        }
        else {
            len = (type != '@');
        }

        switch (type) {
          case '%':
            rb_raise(rb_eArgError, "%% is not supported");
            break;

          case 'A':
            if (len > send - s) len = send - s;
            {
                long end = len;
                char *t = s + len - 1;

                while (t >= s) {
                    if (*t != ' ' && *t != '\0') break;
                    t--; len--;
                }
                rb_ary_push(ary, infected_str_new(s, len, str));
                s += end;
            }
            break;

          case 'Z':
            {
                char *t = s;

                if (len > send-s) len = send-s;
                while (t < s+len && *t) t++;
                rb_ary_push(ary, infected_str_new(s, t-s, str));
                if (t < send) t++;
                s = star ? t : s+len;
            }
            break;

          case 'a':
            if (len > send - s) len = send - s;
            rb_ary_push(ary, infected_str_new(s, len, str));
            s += len;
            break;

          case 'b':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 8)
                    len = (send - s) * 8;
                bits = 0;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                for (i=0; i<len; i++) {
                    if (i & 7) bits >>= 1;
                    else bits = *s++;
                    *t++ = (bits & 1) ? '1' : '0';
                }
            }
            break;

          case 'B':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 8)
                    len = (send - s) * 8;
                bits = 0;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                for (i=0; i<len; i++) {
                    if (i & 7) bits <<= 1;
                    else bits = *s++;
                    *t++ = (bits & 128) ? '1' : '0';
                }
            }
            break;

          case 'h':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 2)
                    len = (send - s) * 2;
                bits = 0;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                for (i=0; i<len; i++) {
                    if (i & 1)
                        bits >>= 4;
                    else
                        bits = *s++;
                    *t++ = hexdigits[bits & 15];
                }
            }
            break;

          case 'H':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 2)
                    len = (send - s) * 2;
                bits = 0;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                for (i=0; i<len; i++) {
                    if (i & 1)
                        bits <<= 4;
                    else
                        bits = *s++;
                    *t++ = hexdigits[(bits >> 4) & 15];
                }
            }
            break;

          case 'c':
            PACK_LENGTH_ADJUST(char,sizeof(char));
            while (len-- > 0) {
                int c = *s++;
                if (c > (char)127) c-=256;
                rb_ary_push(ary, INT2FIX(c));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'C':
            PACK_LENGTH_ADJUST(unsigned char,sizeof(unsigned char));
            while (len-- > 0) {
                unsigned char c = *s++;
                rb_ary_push(ary, INT2FIX(c));
            }
            PACK_ITEM_ADJUST();
            break;

          case 's':
            PACK_LENGTH_ADJUST(short,2);
            while (len-- > 0) {
                short tmp = 0;
                memcpy(OFF16(&tmp), s, NATINT_LEN(short,2));
                EXTEND16(tmp);
                s += NATINT_LEN(short,2);
                rb_ary_push(ary, INT2FIX(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'S':
            PACK_LENGTH_ADJUST(unsigned short,2);
            while (len-- > 0) {
                unsigned short tmp = 0;
                memcpy(OFF16(&tmp), s, NATINT_LEN(unsigned short,2));
                s += NATINT_LEN(unsigned short,2);
                rb_ary_push(ary, INT2FIX(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'i':
            PACK_LENGTH_ADJUST(int,sizeof(int));
            while (len-- > 0) {
                int tmp;
                memcpy(&tmp, s, sizeof(int));
                s += sizeof(int);
                rb_ary_push(ary, INT2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'I':
            PACK_LENGTH_ADJUST(unsigned int,sizeof(unsigned int));
            while (len-- > 0) {
                unsigned int tmp;
                memcpy(&tmp, s, sizeof(unsigned int));
                s += sizeof(unsigned int);
                rb_ary_push(ary, UINT2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'l':
            PACK_LENGTH_ADJUST(long,4);
            while (len-- > 0) {
                long tmp = 0;
                memcpy(OFF32(&tmp), s, NATINT_LEN(long,4));
                EXTEND32(tmp);
                s += NATINT_LEN(long,4);
                rb_ary_push(ary, LONG2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'L':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(OFF32(&tmp), s, NATINT_LEN(unsigned long,4));
                s += NATINT_LEN(unsigned long,4);
                rb_ary_push(ary, ULONG2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'q':
            PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
            while (len-- > 0) {
                char *tmp = (char*)s;
                s += QUAD_SIZE;
                rb_ary_push(ary, rb_quad_unpack(tmp, 1));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'Q':
            PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
            while (len-- > 0) {
                char *tmp = (char*)s;
                s += QUAD_SIZE;
                rb_ary_push(ary, rb_quad_unpack(tmp, 0));
            }
            break;

          case 'n':
            PACK_LENGTH_ADJUST(unsigned short,2);
            while (len-- > 0) {
                unsigned short tmp = 0;
                memcpy(OFF16B(&tmp), s, NATINT_LEN(unsigned short,2));
                s += NATINT_LEN(unsigned short,2);
                rb_ary_push(ary, UINT2NUM(ntohs(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'N':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(OFF32B(&tmp), s, NATINT_LEN(unsigned long,4));
                s += NATINT_LEN(unsigned long,4);
                rb_ary_push(ary, ULONG2NUM(ntohl(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'v':
            PACK_LENGTH_ADJUST(unsigned short,2);
            while (len-- > 0) {
                unsigned short tmp = 0;
                memcpy(OFF16(&tmp), s, NATINT_LEN(unsigned short,2));
                s += NATINT_LEN(unsigned short,2);
                rb_ary_push(ary, UINT2NUM(vtohs(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'V':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(OFF32(&tmp), s, NATINT_LEN(long,4));
                s += NATINT_LEN(long,4);
                rb_ary_push(ary, ULONG2NUM(vtohl(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'f':
          case 'F':
            PACK_LENGTH_ADJUST(float,sizeof(float));
            while (len-- > 0) {
                float tmp;
                memcpy(&tmp, s, sizeof(float));
                s += sizeof(float);
                rb_ary_push(ary, rb_float_new((double)tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'e':
            PACK_LENGTH_ADJUST(float,sizeof(float));
            while (len-- > 0) {
                float tmp;
                FLOAT_CONVWITH(ftmp);

                memcpy(&tmp, s, sizeof(float));
                s += sizeof(float);
                tmp = VTOHF(tmp,ftmp);
                rb_ary_push(ary, rb_float_new((double)tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'E':
            PACK_LENGTH_ADJUST(double,sizeof(double));
            while (len-- > 0) {
                double tmp;
                DOUBLE_CONVWITH(dtmp);

                memcpy(&tmp, s, sizeof(double));
                s += sizeof(double);
                tmp = VTOHD(tmp,dtmp);
                rb_ary_push(ary, rb_float_new(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'D':
          case 'd':
            PACK_LENGTH_ADJUST(double,sizeof(double));
            while (len-- > 0) {
                double tmp;
                memcpy(&tmp, s, sizeof(double));
                s += sizeof(double);
                rb_ary_push(ary, rb_float_new(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'g':
            PACK_LENGTH_ADJUST(float,sizeof(float));
            while (len-- > 0) {
                float tmp;
                FLOAT_CONVWITH(ftmp;)

                memcpy(&tmp, s, sizeof(float));
                s += sizeof(float);
                tmp = NTOHF(tmp,ftmp);
                rb_ary_push(ary, rb_float_new((double)tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'G':
            PACK_LENGTH_ADJUST(double,sizeof(double));
            while (len-- > 0) {
                double tmp;
                DOUBLE_CONVWITH(dtmp);

                memcpy(&tmp, s, sizeof(double));
                s += sizeof(double);
                tmp = NTOHD(tmp,dtmp);
                rb_ary_push(ary, rb_float_new(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'U':
            if (len > send - s) len = send - s;
            while (len > 0 && s < send) {
                long alen = send - s;
                unsigned long l;

                l = utf8_to_uv(s, &alen);
                s += alen; len--;
                rb_ary_push(ary, ULONG2NUM(l));
            }
            break;

          case 'u':
            {
                VALUE buf = infected_str_new(0, (send - s)*3/4, str);
                char *ptr = RSTRING(buf)->ptr;
                long total = 0;

                while (s < send && *s > ' ' && *s < 'a') {
                    long a,b,c,d;
                    char hunk[4];

                    hunk[3] = '\0';
                    len = (*s++ - ' ') & 077;
                    total += len;
                    if (total > RSTRING(buf)->len) {
                        len -= total - RSTRING(buf)->len;
                        total = RSTRING(buf)->len;
                    }

                    while (len > 0) {
                        long mlen = len > 3 ? 3 : len;

                        if (s < send && *s >= ' ')
                            a = (*s++ - ' ') & 077;
                        else
                            a = 0;
                        if (s < send && *s >= ' ')
                            b = (*s++ - ' ') & 077;
                        else
                            b = 0;
                        if (s < send && *s >= ' ')
                            c = (*s++ - ' ') & 077;
                        else
                            c = 0;
                        if (s < send && *s >= ' ')
                            d = (*s++ - ' ') & 077;
                        else
                            d = 0;
                        hunk[0] = a << 2 | b >> 4;
                        hunk[1] = b << 4 | c >> 2;
                        hunk[2] = c << 6 | d;
                        memcpy(ptr, hunk, mlen);
                        ptr += mlen;
                        len -= mlen;
                    }
                    if (*s == '\r') s++;
                    if (*s == '\n') s++;
                    else if (s < send && (s+1 == send || s[1] == '\n'))
                        s += 2;      /* possible checksum byte */
                }

                RSTRING(buf)->ptr[total] = '\0';
                RSTRING(buf)->len = total;
                rb_ary_push(ary, buf);
            }
            break;

          case 'm':
            {
                VALUE buf = infected_str_new(0, (send - s)*3/4, str);
                char *ptr = RSTRING(buf)->ptr;
                int a = -1,b = -1,c = 0,d;
                static int first = 1;
                static int b64_xtable[256];

                if (first) {
                    int i;
                    first = 0;

                    for (i = 0; i < 256; i++) {
                        b64_xtable[i] = -1;
                    }
                    for (i = 0; i < 64; i++) {
                        b64_xtable[(int)b64_table[i]] = i;
                    }
                }
                while (s < send) {
                    a = b = c = d = -1;
                    while((a = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { s++; }
                    if( s >= send ) break;
                    s++;
                    while((b = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { s++; }
                    if( s >= send ) break;
                    s++;
                    while((c = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { if( *s == '=' ) break; s++; }
                    if( *s == '=' || s >= send ) break;
                    s++;
                    while((d = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { if( *s == '=' ) break; s++; }
                    if( *s == '=' || s >= send ) break;
                    s++;
                    *ptr++ = a << 2 | b >> 4;
                    *ptr++ = b << 4 | c >> 2;
                    *ptr++ = c << 6 | d;
                }
                if (a != -1 && b != -1) {
                    if (c == -1 && *s == '=')
                        *ptr++ = a << 2 | b >> 4;
                    else if (c != -1 && *s == '=') {
                        *ptr++ = a << 2 | b >> 4;
                        *ptr++ = b << 4 | c >> 2;
                    }
                }
                *ptr = '\0';
                RSTRING(buf)->len = ptr - RSTRING(buf)->ptr;
                rb_ary_push(ary, buf);
            }
            break;

          case 'M':
            {
                VALUE buf = infected_str_new(0, send - s, str);
                char *ptr = RSTRING(buf)->ptr;
                int c1, c2;

                while (s < send) {
                    if (*s == '=') {
                        if (++s == send) break;
                       if (s+1 < send && *s == '\r' && *(s+1) == '\n')
                         s++;
                        if (*s != '\n') {
                            if ((c1 = hex2num(*s)) == -1) break;
                            if (++s == send) break;
                            if ((c2 = hex2num(*s)) == -1) break;
                            *ptr++ = c1 << 4 | c2;
                        }
                    }
                    else {
                        *ptr++ = *s;
                    }
                    s++;
                }
                *ptr = '\0';
                RSTRING(buf)->len = ptr - RSTRING(buf)->ptr;
                rb_ary_push(ary, buf);
            }
            break;

          case '@':
            if (len > RSTRING(str)->len)
                rb_raise(rb_eArgError, "@ outside of string");
            s = RSTRING(str)->ptr + len;
            break;

          case 'X':
            if (len > s - RSTRING(str)->ptr)
                rb_raise(rb_eArgError, "X outside of string");
            s -= len;
            break;

          case 'x':
            if (len > send - s)
                rb_raise(rb_eArgError, "x outside of string");
            s += len;
            break;

          case 'P':
            if (sizeof(char *) <= send - s) {
                char *t;
                VALUE tmp;

                memcpy(&t, s, sizeof(char *));
                s += sizeof(char *);

                if (t) {
                    VALUE a, *p, *pend;

                    if (!(a = rb_str_associated(str))) {
                        rb_raise(rb_eArgError, "no associated pointer");
                    }
                    p = RARRAY(a)->ptr;
                    pend = p + RARRAY(a)->len;
                    while (p < pend) {
                        if (TYPE(*p) == T_STRING && RSTRING(*p)->ptr == t) {
                            if (len < RSTRING(*p)->len) {
                                tmp = rb_tainted_str_new(t, len);
                                rb_str_associate(tmp, a);
                            }
                            else {
                                tmp = *p;
                            }
                            break;
                        }
                        p++;
                    }
                    if (p == pend) {
                        rb_raise(rb_eArgError, "non associated pointer");
                    }
                }
                else {
                    tmp = Qnil;
                }
                rb_ary_push(ary, tmp);
            }
            break;

          case 'p':
            if (len > (send - s) / sizeof(char *))
                len = (send - s) / sizeof(char *);
            while (len-- > 0) {
                if (send - s < sizeof(char *))
                    break;
                else {
                    VALUE tmp;
                    char *t;

                    memcpy(&t, s, sizeof(char *));
                    s += sizeof(char *);

                    if (t) {
                        VALUE a, *p, *pend;

                        if (!(a = rb_str_associated(str))) {
                            rb_raise(rb_eArgError, "no associated pointer");
                        }
                        p = RARRAY(a)->ptr;
                        pend = p + RARRAY(a)->len;
                        while (p < pend) {
                            if (TYPE(*p) == T_STRING && RSTRING(*p)->ptr == t) {
                                tmp = *p;
                                break;
                            }
                            p++;
                        }
                        if (p == pend) {
                            rb_raise(rb_eArgError, "non associated pointer");
                        }
                    }
                    else {
                        tmp = Qnil;
                    }
                    rb_ary_push(ary, tmp);
                }
            }
            break;

          case 'w':
            {
                unsigned long ul = 0;
                unsigned long ulmask = 0xfeUL << ((sizeof(unsigned long) - 1) * 8);

                while (len > 0 && s < send) {
                    ul <<= 7;
                    ul |= (*s & 0x7f);
                    if (!(*s++ & 0x80)) {
                        rb_ary_push(ary, ULONG2NUM(ul));
                        len--;
                        ul = 0;
                    }
                    else if (ul & ulmask) {
                        VALUE big = rb_uint2big(ul);
                        VALUE big128 = rb_uint2big(128);
                        while (s < send) {
                            big = rb_big_mul(big, big128);
                            big = rb_big_plus(big, rb_uint2big(*s & 0x7f));
                            if (!(*s++ & 0x80)) {
                                rb_ary_push(ary, big);
                                len--;
                                ul = 0;
                                break;
                            }
                        }
                    }
                }
            }
            break;

          default:
            break;
        }
    }

    return ary;
}


new (String)

/*
 *  call-seq:
 *     String.new(str="")   => new_str
 *
 *  Returns a new string object containing a copy of <i>str</i>.
 */

static VALUE
rb_str_init(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE orig;

    if (rb_scan_args(argc, argv, "01", &orig) == 1)
        rb_str_replace(str, orig);
    return str;
}


initialize_copy (String)

/*
 *  call-seq:
 *     str.replace(other_str)   => str
 *
 *  Replaces the contents and taintedness of <i>str</i> with the corresponding
 *  values in <i>other_str</i>.
 *
 *     s = "hello"         #=> "hello"
 *     s.replace "world"   #=> "world"
 */

static VALUE
rb_str_replace(str, str2)
    VALUE str, str2;
{
    if (str == str2) return str;

    StringValue(str2);
    if (FL_TEST(str2, ELTS_SHARED)) {
        if (str_independent(str)) {
            free(RSTRING(str)->ptr);
        }
        RSTRING(str)->len = RSTRING(str2)->len;
        RSTRING(str)->ptr = RSTRING(str2)->ptr;
        FL_SET(str, ELTS_SHARED);
        FL_UNSET(str, STR_ASSOC);
        RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
    }
    else {
        rb_str_modify(str);
        rb_str_resize(str, RSTRING(str2)->len);
        memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len);
        if (FL_TEST(str2, STR_ASSOC)) {
            FL_SET(str, STR_ASSOC);
            RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
        }
    }

    OBJ_INFECT(str, str2);
    return str;
}


<=> (String)

/*
 *  call-seq:
 *     str <=> other_str   => -1, 0, +1
 *
 *  Comparison---Returns -1 if <i>other_str</i> is less than, 0 if
 *  <i>other_str</i> is equal to, and +1 if <i>other_str</i> is greater than
 *  <i>str</i>. If the strings are of different lengths, and the strings are
 *  equal when compared up to the shortest length, then the longer string is
 *  considered greater than the shorter one. If the variable <code>$=</code> is
 *  <code>false</code>, the comparison is based on comparing the binary values
 *  of each character in the string. In older versions of Ruby, setting
 *  <code>$=</code> allowed case-insensitive comparisons; this is now deprecated
 *  in favor of using <code>String#casecmp</code>.
 *
 *  <code><=></code> is the basis for the methods <code><</code>,
 *  <code><=</code>, <code>></code>, <code>>=</code>, and <code>between?</code>,
 *  included from module <code>Comparable</code>.  The method
 *  <code>String#==</code> does not use <code>Comparable#==</code>.
 *
 *     "abcdef" <=> "abcde"     #=> 1
 *     "abcdef" <=> "abcdef"    #=> 0
 *     "abcdef" <=> "abcdefg"   #=> -1
 *     "abcdef" <=> "ABCDEF"    #=> 1
 */

static VALUE
rb_str_cmp_m(str1, str2)
    VALUE str1, str2;
{
    long result;

    if (TYPE(str2) != T_STRING) {
        if (!rb_respond_to(str2, rb_intern("to_str"))) {
            return Qnil;
        }
        else if (!rb_respond_to(str2, rb_intern("<=>"))) {
            return Qnil;
        }
        else {
            VALUE tmp = rb_funcall(str2, rb_intern("<=>"), 1, str1);

            if (NIL_P(tmp)) return Qnil;
            if (!FIXNUM_P(tmp)) {
                return rb_funcall(LONG2FIX(0), '-', 1, tmp);
            }
            result = -FIX2LONG(tmp);
        }
    }
    else {
        result = rb_str_cmp(str1, str2);
    }
    return LONG2NUM(result);
}


== (String)

/*
 *  call-seq:
 *     str == obj   => true or false
 *
 *  Equality---If <i>obj</i> is not a <code>String</code>, returns
 *  <code>false</code>. Otherwise, returns <code>true</code> if <i>str</i>
 *  <code><=></code> <i>obj</i> returns zero.
 */

static VALUE
rb_str_equal(str1, str2)
    VALUE str1, str2;
{
    if (str1 == str2) return Qtrue;
    if (TYPE(str2) != T_STRING) {
        if (!rb_respond_to(str2, rb_intern("to_str"))) {
            return Qfalse;
        }
        return rb_equal(str2, str1);
    }
    if (RSTRING(str1)->len == RSTRING(str2)->len &&
        rb_str_cmp(str1, str2) == 0) {
        return Qtrue;
    }
    return Qfalse;
}


eql? (String)

/*
 * call-seq:
 *   str.eql?(other)   => true or false
 *
 * Two strings are equal if the have the same length and content.
 */

static VALUE
rb_str_eql(str1, str2)
    VALUE str1, str2;
{
    if (TYPE(str2) != T_STRING || RSTRING(str1)->len != RSTRING(str2)->len)
        return Qfalse;

    if (memcmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr,
               lesser(RSTRING(str1)->len, RSTRING(str2)->len)) == 0)
        return Qtrue;

    return Qfalse;
}


hash (String)

/*
 * call-seq:
 *    str.hash   => fixnum
 *
 * Return a hash based on the string's length and content.
 */

static VALUE
rb_str_hash_m(str)
    VALUE str;
{
    int key = rb_str_hash(str);
    return INT2FIX(key);
}


casecmp (String)

/*
 *  call-seq:
 *     str.casecmp(other_str)   => -1, 0, +1
 *
 *  Case-insensitive version of <code>String#<=></code>.
 *
 *     "abcdef".casecmp("abcde")     #=> 1
 *     "aBcDeF".casecmp("abcdef")    #=> 0
 *     "abcdef".casecmp("abcdefg")   #=> -1
 *     "abcdef".casecmp("ABCDEF")    #=> 0
 */

static VALUE
rb_str_casecmp(str1, str2)
    VALUE str1, str2;
{
    long len;
    int retval;

    StringValue(str2);
    len = lesser(RSTRING(str1)->len, RSTRING(str2)->len);
    retval = rb_memcicmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr, len);
    if (retval == 0) {
        if (RSTRING(str1)->len == RSTRING(str2)->len) return INT2FIX(0);
        if (RSTRING(str1)->len > RSTRING(str2)->len) return INT2FIX(1);
        return INT2FIX(-1);
    }
    if (retval == 0) return INT2FIX(0);
    if (retval > 0) return INT2FIX(1);
    return INT2FIX(-1);
}


+ (String)

/*
 *  call-seq:
 *     str + other_str   => new_str
 *
 *  Concatenation---Returns a new <code>String</code> containing
 *  <i>other_str</i> concatenated to <i>str</i>.
 *
 *     "Hello from " + self.to_s   #=> "Hello from main"
 */

VALUE
rb_str_plus(str1, str2)
    VALUE str1, str2;
{
    VALUE str3;

    StringValue(str2);
    str3 = rb_str_new(0, RSTRING(str1)->len+RSTRING(str2)->len);
    memcpy(RSTRING(str3)->ptr, RSTRING(str1)->ptr, RSTRING(str1)->len);
    memcpy(RSTRING(str3)->ptr + RSTRING(str1)->len,
           RSTRING(str2)->ptr, RSTRING(str2)->len);
    RSTRING(str3)->ptr[RSTRING(str3)->len] = '\0';

    if (OBJ_TAINTED(str1) || OBJ_TAINTED(str2))
        OBJ_TAINT(str3);
    return str3;
}


* (String)

/*
 *  call-seq:
 *     str * integer   => new_str
 *
 *  Copy---Returns a new <code>String</code> containing <i>integer</i> copies of
 *  the receiver.
 *
 *     "Ho! " * 3   #=> "Ho! Ho! Ho! "
 */

VALUE
rb_str_times(str, times)
    VALUE str;
    VALUE times;
{
    VALUE str2;
    long i, len;

    len = NUM2LONG(times);
    if (len < 0) {
        rb_raise(rb_eArgError, "negative argument");
    }
    if (len && LONG_MAX/len <  RSTRING(str)->len) {
        rb_raise(rb_eArgError, "argument too big");
    }

    str2 = rb_str_new5(str,0, len *= RSTRING(str)->len);
    for (i = 0; i < len; i += RSTRING(str)->len) {
        memcpy(RSTRING(str2)->ptr + i,
               RSTRING(str)->ptr, RSTRING(str)->len);
    }
    RSTRING(str2)->ptr[RSTRING(str2)->len] = '\0';

    OBJ_INFECT(str2, str);

    return str2;
}


% (String)

/*
 *  call-seq:
 *     str % arg   => new_str
 *
 *  Format---Uses <i>str</i> as a format specification, and returns the result
 *  of applying it to <i>arg</i>. If the format specification contains more than
 *  one substitution, then <i>arg</i> must be an <code>Array</code> containing
 *  the values to be substituted. See <code>Kernel::sprintf</code> for details
 *  of the format string.
 *
 *     "%05d" % 123                       #=> "00123"
 *     "%-5s: %08x" % [ "ID", self.id ]   #=> "ID   : 200e14d6"
 */

static VALUE
rb_str_format(str, arg)
    VALUE str, arg;
{
    VALUE *argv;

    if (TYPE(arg) == T_ARRAY) {
        argv = ALLOCA_N(VALUE, RARRAY(arg)->len + 1);
        argv[0] = str;
        MEMCPY(argv+1, RARRAY(arg)->ptr, VALUE, RARRAY(arg)->len);
        return rb_f_sprintf(RARRAY(arg)->len+1, argv);
    }

    argv = ALLOCA_N(VALUE, 2);
    argv[0] = str;
    argv[1] = arg;
    return rb_f_sprintf(2, argv);
}


[] (String)

/*
 *  call-seq:
 *     str[fixnum]                 => fixnum or nil
 *     str[fixnum, fixnum]         => new_str or nil
 *     str[range]                  => new_str or nil
 *     str[regexp]                 => new_str or nil
 *     str[regexp, fixnum]         => new_str or nil
 *     str[other_str]              => new_str or nil
 *     str.slice(fixnum)           => fixnum or nil
 *     str.slice(fixnum, fixnum)   => new_str or nil
 *     str.slice(range)            => new_str or nil
 *     str.slice(regexp)           => new_str or nil
 *     str.slice(regexp, fixnum)   => new_str or nil
 *     str.slice(other_str)        => new_str or nil
 *
 *  Element Reference---If passed a single <code>Fixnum</code>, returns the code
 *  of the character at that position. If passed two <code>Fixnum</code>
 *  objects, returns a substring starting at the offset given by the first, and
 *  a length given by the second. If given a range, a substring containing
 *  characters at offsets given by the range is returned. In all three cases, if
 *  an offset is negative, it is counted from the end of <i>str</i>. Returns
 *  <code>nil</code> if the initial offset falls outside the string, the length
 *  is negative, or the beginning of the range is greater than the end.
 *
 *  If a <code>Regexp</code> is supplied, the matching portion of <i>str</i> is
 *  returned. If a numeric parameter follows the regular expression, that
 *  component of the <code>MatchData</code> is returned instead. If a
 *  <code>String</code> is given, that string is returned if it occurs in
 *  <i>str</i>. In both cases, <code>nil</code> is returned if there is no
 *  match.
 *
 *     a = "hello there"
 *     a[1]                   #=> 101
 *     a[1,3]                 #=> "ell"
 *     a[1..3]                #=> "ell"
 *     a[-3,2]                #=> "er"
 *     a[-4..-2]              #=> "her"
 *     a[12..-1]              #=> nil
 *     a[-2..-4]              #=> ""
 *     a[/[aeiou](.)\1/]      #=> "ell"
 *     a[/[aeiou](.)\1/, 0]   #=> "ell"
 *     a[/[aeiou](.)\1/, 1]   #=> "l"
 *     a[/[aeiou](.)\1/, 2]   #=> nil
 *     a["lo"]                #=> "lo"
 *     a["bye"]               #=> nil
 */

static VALUE
rb_str_aref_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    if (argc == 2) {
        if (TYPE(argv[0]) == T_REGEXP) {
            return rb_str_subpat(str, argv[0], NUM2INT(argv[1]));
        }
        return rb_str_substr(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]));
    }
    if (argc != 1) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    return rb_str_aref(str, argv[0]);
}


[]= (String)

/*
 *  call-seq:
 *     str[fixnum] = fixnum
 *     str[fixnum] = new_str
 *     str[fixnum, fixnum] = new_str
 *     str[range] = aString
 *     str[regexp] = new_str
 *     str[regexp, fixnum] = new_str
 *     str[other_str] = new_str
 *
 *  Element Assignment---Replaces some or all of the content of <i>str</i>. The
 *  portion of the string affected is determined using the same criteria as
 *  <code>String#[]</code>. If the replacement string is not the same length as
 *  the text it is replacing, the string will be adjusted accordingly. If the
 *  regular expression or string is used as the index doesn't match a position
 *  in the string, <code>IndexError</code> is raised. If the regular expression
 *  form is used, the optional second <code>Fixnum</code> allows you to specify
 *  which portion of the match to replace (effectively using the
 *  <code>MatchData</code> indexing rules. The forms that take a
 *  <code>Fixnum</code> will raise an <code>IndexError</code> if the value is
 *  out of range; the <code>Range</code> form will raise a
 *  <code>RangeError</code>, and the <code>Regexp</code> and <code>String</code>
 *  forms will silently ignore the assignment.
 */

static VALUE
rb_str_aset_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    if (argc == 3) {
        if (TYPE(argv[0]) == T_REGEXP) {
            rb_str_subpat_set(str, argv[0], NUM2INT(argv[1]), argv[2]);
        }
        else {
            rb_str_splice(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
        }
        return argv[2];
    }
    if (argc != 2) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc);
    }
    return rb_str_aset(str, argv[0], argv[1]);
}


insert (String)

/*
 *  call-seq:
 *     str.insert(index, other_str)   => str
 *
 *  Inserts <i>other_str</i> before the character at the given
 *  <i>index</i>, modifying <i>str</i>. Negative indices count from the
 *  end of the string, and insert <em>after</em> the given character.
 *  The intent is insert <i>aString</i> so that it starts at the given
 *  <i>index</i>.
 *
 *     "abcd".insert(0, 'X')    #=> "Xabcd"
 *     "abcd".insert(3, 'X')    #=> "abcXd"
 *     "abcd".insert(4, 'X')    #=> "abcdX"
 *     "abcd".insert(-3, 'X')   #=> "abXcd"
 *     "abcd".insert(-1, 'X')   #=> "abcdX"
 */

static VALUE
rb_str_insert(str, idx, str2)
    VALUE str, idx, str2;
{
    long pos = NUM2LONG(idx);

    if (pos == -1) {
        pos = RSTRING(str)->len;
    }
    else if (pos < 0) {
        pos++;
    }
    rb_str_splice(str, pos, 0, str2);
    return str;
}


length (String)

/*
 *  call-seq:
 *     str.length   => integer
 *
 *  Returns the length of <i>str</i>.
 */

static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}


size (String)

/*
 *  call-seq:
 *     str.length   => integer
 *
 *  Returns the length of <i>str</i>.
 */

static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}


empty? (String)

/*
 *  call-seq:
 *     str.empty?   => true or false
 *
 *  Returns <code>true</code> if <i>str</i> has a length of zero.
 *
 *     "hello".empty?   #=> false
 *     "".empty?        #=> true
 */

static VALUE
rb_str_empty(str)
    VALUE str;
{
    if (RSTRING(str)->len == 0)
        return Qtrue;
    return Qfalse;
}


=~ (String)

/*
 *  call-seq:
 *     str =~ obj   => fixnum or nil
 *
 *  Match---If <i>obj</i> is a <code>Regexp</code>, use it as a pattern to match
 *  against <i>str</i>,and returns the position the match starts, or
 *  <code>nil</code> if there is no match. Otherwise, invokes
 *  <i>obj.=~</i>, passing <i>str</i> as an argument. The default
 *  <code>=~</code> in <code>Object</code> returns <code>false</code>.
 *
 *     "cat o' 9 tails" =~ /\d/   #=> 7
 *     "cat o' 9 tails" =~ 9      #=> false
 */

static VALUE
rb_str_match(x, y)
    VALUE x, y;
{
    switch (TYPE(y)) {
      case T_STRING:
        rb_raise(rb_eTypeError, "type mismatch: String given");

      case T_REGEXP:
        return rb_reg_match(y, x);

      default:
        return rb_funcall(y, rb_intern("=~"), 1, x);
    }
}


match (String)

/*
 *  call-seq:
 *     str.match(pattern)   => matchdata or nil
 *
 *  Converts <i>pattern</i> to a <code>Regexp</code> (if it isn't already one),
 *  then invokes its <code>match</code> method on <i>str</i>.
 *
 *     'hello'.match('(.)\1')      #=> #<MatchData:0x401b3d30>
 *     'hello'.match('(.)\1')[0]   #=> "ll"
 *     'hello'.match(/(.)\1/)[0]   #=> "ll"
 *     'hello'.match('xx')         #=> nil
 */

static VALUE
rb_str_match_m(str, re)
    VALUE str, re;
{
    return rb_funcall(get_pat(re, 0), rb_intern("match"), 1, str);
}


succ (String)

/*
 *  call-seq:
 *     str.succ   => new_str
 *     str.next   => new_str
 *
 *  Returns the successor to <i>str</i>. The successor is calculated by
 *  incrementing characters starting from the rightmost alphanumeric (or
 *  the rightmost character if there are no alphanumerics) in the
 *  string. Incrementing a digit always results in another digit, and
 *  incrementing a letter results in another letter of the same case.
 *  Incrementing nonalphanumerics uses the underlying character set's
 *  collating sequence.
 *
 *  If the increment generates a ``carry,'' the character to the left of
 *  it is incremented. This process repeats until there is no carry,
 *  adding an additional character if necessary.
 *
 *     "abcd".succ        #=> "abce"
 *     "THX1138".succ     #=> "THX1139"
 *     "<<koala>>".succ   #=> "<<koalb>>"
 *     "1999zzz".succ     #=> "2000aaa"
 *     "ZZZ9999".succ     #=> "AAAA0000"
 *     "***".succ         #=> "**+"
 */

static VALUE
rb_str_succ(orig)
    VALUE orig;
{
    VALUE str;
    char *sbeg, *s;
    int c = -1;
    long n = 0;

    str = rb_str_new5(orig, RSTRING(orig)->ptr, RSTRING(orig)->len);
    OBJ_INFECT(str, orig);
    if (RSTRING(str)->len == 0) return str;

    sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;

    while (sbeg <= s) {
        if (ISALNUM(*s)) {
            if ((c = succ_char(s)) == 0) break;
            n = s - sbeg;
        }
        s--;
    }
    if (c == -1) {              /* str contains no alnum */
        sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
        c = '\001';
        while (sbeg <= s) {
            if ((*s += 1) != 0) break;
            s--;
        }
    }
    if (s < sbeg) {
        RESIZE_CAPA(str, RSTRING(str)->len + 1);
        s = RSTRING(str)->ptr + n;
        memmove(s+1, s, RSTRING(str)->len - n);
        *s = c;
        RSTRING(str)->len += 1;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
    }

    return str;
}


succ! (String)

/*
 *  call-seq:
 *     str.succ!   => str
 *     str.next!   => str
 *
 *  Equivalent to <code>String#succ</code>, but modifies the receiver in
 *  place.
 */

static VALUE
rb_str_succ_bang(str)
    VALUE str;
{
    rb_str_shared_replace(str, rb_str_succ(str));

    return str;
}


next (String)

/*
 *  call-seq:
 *     str.succ   => new_str
 *     str.next   => new_str
 *
 *  Returns the successor to <i>str</i>. The successor is calculated by
 *  incrementing characters starting from the rightmost alphanumeric (or
 *  the rightmost character if there are no alphanumerics) in the
 *  string. Incrementing a digit always results in another digit, and
 *  incrementing a letter results in another letter of the same case.
 *  Incrementing nonalphanumerics uses the underlying character set's
 *  collating sequence.
 *
 *  If the increment generates a ``carry,'' the character to the left of
 *  it is incremented. This process repeats until there is no carry,
 *  adding an additional character if necessary.
 *
 *     "abcd".succ        #=> "abce"
 *     "THX1138".succ     #=> "THX1139"
 *     "<<koala>>".succ   #=> "<<koalb>>"
 *     "1999zzz".succ     #=> "2000aaa"
 *     "ZZZ9999".succ     #=> "AAAA0000"
 *     "***".succ         #=> "**+"
 */

static VALUE
rb_str_succ(orig)
    VALUE orig;
{
    VALUE str;
    char *sbeg, *s;
    int c = -1;
    long n = 0;

    str = rb_str_new5(orig, RSTRING(orig)->ptr, RSTRING(orig)->len);
    OBJ_INFECT(str, orig);
    if (RSTRING(str)->len == 0) return str;

    sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;

    while (sbeg <= s) {
        if (ISALNUM(*s)) {
            if ((c = succ_char(s)) == 0) break;
            n = s - sbeg;
        }
        s--;
    }
    if (c == -1) {              /* str contains no alnum */
        sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
        c = '\001';
        while (sbeg <= s) {
            if ((*s += 1) != 0) break;
            s--;
        }
    }
    if (s < sbeg) {
        RESIZE_CAPA(str, RSTRING(str)->len + 1);
        s = RSTRING(str)->ptr + n;
        memmove(s+1, s, RSTRING(str)->len - n);
        *s = c;
        RSTRING(str)->len += 1;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
    }

    return str;
}


next! (String)

/*
 *  call-seq:
 *     str.succ!   => str
 *     str.next!   => str
 *
 *  Equivalent to <code>String#succ</code>, but modifies the receiver in
 *  place.
 */

static VALUE
rb_str_succ_bang(str)
    VALUE str;
{
    rb_str_shared_replace(str, rb_str_succ(str));

    return str;
}


upto (String)

/*
 *  call-seq:
 *     str.upto(other_str) {|s| block }   => str
 *
 *  Iterates through successive values, starting at <i>str</i> and
 *  ending at <i>other_str</i> inclusive, passing each value in turn to
 *  the block. The <code>String#succ</code> method is used to generate
 *  each value.
 *
 *     "a8".upto("b6") {|s| print s, ' ' }
 *     for s in "a8".."b6"
 *       print s, ' '
 *     end
 *
 *  <em>produces:</em>
 *
 *     a8 a9 b0 b1 b2 b3 b4 b5 b6
 *     a8 a9 b0 b1 b2 b3 b4 b5 b6
 */

static VALUE
rb_str_upto_m(beg, end)
    VALUE beg, end;
{
    return rb_str_upto(beg, end, Qfalse);
}


index (String)

/*
 *  call-seq:
 *     str.index(substring [, offset])   => fixnum or nil
 *     str.index(fixnum [, offset])      => fixnum or nil
 *     str.index(regexp [, offset])      => fixnum or nil
 *
 *  Returns the index of the first occurrence of the given <i>substring</i>,
 *  character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>str</i>. Returns
 *  <code>nil</code> if not found. If the second parameter is present, it
 *  specifies the position in the string to begin the search.
 *
 *     "hello".index('e')             #=> 1
 *     "hello".index('lo')            #=> 3
 *     "hello".index('a')             #=> nil
 *     "hello".index(101)             #=> 1
 *     "hello".index(/[aeiou]/, -3)   #=> 4
 */

static VALUE
rb_str_index_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE sub;
    VALUE initpos;
    long pos;

    if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
        pos = NUM2LONG(initpos);
    }
    else {
        pos = 0;
    }
    if (pos < 0) {
        pos += RSTRING(str)->len;
        if (pos < 0) {
            if (TYPE(sub) == T_REGEXP) {
                rb_backref_set(Qnil);
            }
            return Qnil;
        }
    }

    switch (TYPE(sub)) {
      case T_REGEXP:
        pos = rb_reg_adjust_startpos(sub, str, pos, 0);
        pos = rb_reg_search(sub, str, pos, 0);
        break;

      case T_FIXNUM:
      {
          int c = FIX2INT(sub);
          long len = RSTRING(str)->len;
          unsigned char *p = (unsigned char*)RSTRING(str)->ptr;

          for (;pos<len;pos++) {
              if (p[pos] == c) return LONG2NUM(pos);
          }
          return Qnil;
      }

      default: {
          VALUE tmp;

          tmp = rb_check_string_type(sub);
          if (NIL_P(tmp)) {
              rb_raise(rb_eTypeError, "type mismatch: %s given",
                       rb_obj_classname(sub));
          }
          sub = tmp;
      }
        /* fall through */
      case T_STRING:
        pos = rb_str_index(str, sub, pos);
        break;
    }

    if (pos == -1) return Qnil;
    return LONG2NUM(pos);
}


rindex (String)

/*
 *  call-seq:
 *     str.rindex(substring [, fixnum])   => fixnum or nil
 *     str.rindex(fixnum [, fixnum])   => fixnum or nil
 *     str.rindex(regexp [, fixnum])   => fixnum or nil
 *
 *  Returns the index of the last occurrence of the given <i>substring</i>,
 *  character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>str</i>. Returns
 *  <code>nil</code> if not found. If the second parameter is present, it
 *  specifies the position in the string to end the search---characters beyond
 *  this point will not be considered.
 *
 *     "hello".rindex('e')             #=> 1
 *     "hello".rindex('l')             #=> 3
 *     "hello".rindex('a')             #=> nil
 *     "hello".rindex(101)             #=> 1
 *     "hello".rindex(/[aeiou]/, -2)   #=> 1
 */

static VALUE
rb_str_rindex_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE sub;
    VALUE position;
    long pos;

    if (rb_scan_args(argc, argv, "11", &sub, &position) == 2) {
        pos = NUM2LONG(position);
        if (pos < 0) {
            pos += RSTRING(str)->len;
            if (pos < 0) {
                if (TYPE(sub) == T_REGEXP) {
                    rb_backref_set(Qnil);
                }
                return Qnil;
            }
        }
        if (pos > RSTRING(str)->len) pos = RSTRING(str)->len;
    }
    else {
        pos = RSTRING(str)->len;
    }

    switch (TYPE(sub)) {
      case T_REGEXP:
        if (RREGEXP(sub)->len) {
            pos = rb_reg_adjust_startpos(sub, str, pos, 1);
            pos = rb_reg_search(sub, str, pos, 1);
        }
        if (pos >= 0) return LONG2NUM(pos);
        break;

      case T_STRING:
        pos = rb_str_rindex(str, sub, pos);
        if (pos >= 0) return LONG2NUM(pos);
        break;

      case T_FIXNUM:
      {
          int c = FIX2INT(sub);
          unsigned char *p = (unsigned char*)RSTRING(str)->ptr + pos;
          unsigned char *pbeg = (unsigned char*)RSTRING(str)->ptr;

          if (pos == RSTRING(str)->len) {
              if (pos == 0) return Qnil;
              --p;
          }
          while (pbeg <= p) {
              if (*p == c) return LONG2NUM((char*)p - RSTRING(str)->ptr);
              p--;
          }
          return Qnil;
      }

      default:
        rb_raise(rb_eTypeError, "type mismatch: %s given",
                 rb_obj_classname(sub));
    }
    return Qnil;
}


replace (String)

/*
 *  call-seq:
 *     str.replace(other_str)   => str
 *
 *  Replaces the contents and taintedness of <i>str</i> with the corresponding
 *  values in <i>other_str</i>.
 *
 *     s = "hello"         #=> "hello"
 *     s.replace "world"   #=> "world"
 */

static VALUE
rb_str_replace(str, str2)
    VALUE str, str2;
{
    if (str == str2) return str;

    StringValue(str2);
    if (FL_TEST(str2, ELTS_SHARED)) {
        if (str_independent(str)) {
            free(RSTRING(str)->ptr);
        }
        RSTRING(str)->len = RSTRING(str2)->len;
        RSTRING(str)->ptr = RSTRING(str2)->ptr;
        FL_SET(str, ELTS_SHARED);
        FL_UNSET(str, STR_ASSOC);
        RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
    }
    else {
        rb_str_modify(str);
        rb_str_resize(str, RSTRING(str2)->len);
        memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len);
        if (FL_TEST(str2, STR_ASSOC)) {
            FL_SET(str, STR_ASSOC);
            RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
        }
    }

    OBJ_INFECT(str, str2);
    return str;
}


to_i (String)

/*
 *  call-seq:
 *     str.to_i(base=10)   => integer
 *
 *  Returns the result of interpreting leading characters in <i>str</i> as an
 *  integer base <i>base</i> (2, 8, 10, or 16). Extraneous characters past the
 *  end of a valid number are ignored. If there is not a valid number at the
 *  start of <i>str</i>, <code>0</code> is returned. This method never raises an
 *  exception.
 *
 *     "12345".to_i             #=> 12345
 *     "99 red balloons".to_i   #=> 99
 *     "0a".to_i                #=> 0
 *     "0a".to_i(16)            #=> 10
 *     "hello".to_i             #=> 0
 *     "1100101".to_i(2)        #=> 101
 *     "1100101".to_i(8)        #=> 294977
 *     "1100101".to_i(10)       #=> 1100101
 *     "1100101".to_i(16)       #=> 17826049
 */

static VALUE
rb_str_to_i(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE b;
    int base;

    rb_scan_args(argc, argv, "01", &b);
    if (argc == 0) base = 10;
    else base = NUM2INT(b);

    if (base < 0) {
        rb_raise(rb_eArgError, "illegal radix %d", base);
    }
    return rb_str_to_inum(str, base, Qfalse);
}


to_f (String)

/*
 *  call-seq:
 *     str.to_f   => float
 *
 *  Returns the result of interpreting leading characters in <i>str</i> as a
 *  floating point number. Extraneous characters past the end of a valid number
 *  are ignored. If there is not a valid number at the start of <i>str</i>,
 *  <code>0.0</code> is returned. This method never raises an exception.
 *
 *     "123.45e1".to_f        #=> 1234.5
 *     "45.67 degrees".to_f   #=> 45.67
 *     "thx1138".to_f         #=> 0.0
 */

static VALUE
rb_str_to_f(str)
    VALUE str;
{
    return rb_float_new(rb_str_to_dbl(str, Qfalse));
}


to_s (String)

/*
 *  call-seq:
 *     str.to_s     => str
 *     str.to_str   => str
 *
 *  Returns the receiver.
 */

static VALUE
rb_str_to_s(str)
    VALUE str;
{
    if (rb_obj_class(str) != rb_cString) {
        VALUE dup = str_alloc(rb_cString);
        rb_str_replace(dup, str);
        return dup;
    }
    return str;
}


to_str (String)

/*
 *  call-seq:
 *     str.to_s     => str
 *     str.to_str   => str
 *
 *  Returns the receiver.
 */

static VALUE
rb_str_to_s(str)
    VALUE str;
{
    if (rb_obj_class(str) != rb_cString) {
        VALUE dup = str_alloc(rb_cString);
        rb_str_replace(dup, str);
        return dup;
    }
    return str;
}


inspect (String)

/*
 * call-seq:
 *   str.inspect   => string
 *
 * Returns a printable version of _str_, with special characters
 * escaped.
 *
 *    str = "hello"
 *    str[3] = 8
 *    str.inspect       #=> "hel\010o"
 */

VALUE
rb_str_inspect(str)
    VALUE str;
{
    char *p, *pend;
    VALUE result = rb_str_buf_new2("\"");
    char s[5];

    p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
    while (p < pend) {
        char c = *p++;
        if (ismbchar(c) && p < pend) {
            int len = mbclen(c);
            rb_str_buf_cat(result, p - 1, len);
            p += len - 1;
        }
        else if (c == '"'|| c == '\\' || (c == '#' && IS_EVSTR(p, pend))) {
            s[0] = '\\'; s[1] = c;
            rb_str_buf_cat(result, s, 2);
        }
        else if (ISPRINT(c)) {
            s[0] = c;
            rb_str_buf_cat(result, s, 1);
        }
        else if (c == '\n') {
            s[0] = '\\'; s[1] = 'n';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\r') {
            s[0] = '\\'; s[1] = 'r';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\t') {
            s[0] = '\\'; s[1] = 't';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\f') {
            s[0] = '\\'; s[1] = 'f';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\013') {
            s[0] = '\\'; s[1] = 'v';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\010') {
            s[0] = '\\'; s[1] = 'b';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\007') {
            s[0] = '\\'; s[1] = 'a';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == 033) {
            s[0] = '\\'; s[1] = 'e';
            rb_str_buf_cat(result, s, 2);
        }
        else {
            sprintf(s, "\\%03o", c & 0377);
            rb_str_buf_cat2(result, s);
        }
    }
    rb_str_buf_cat2(result, "\"");

    OBJ_INFECT(result, str);
    return result;
}


dump (String)

/*
 *  call-seq:
 *     str.dump   => new_str
 *
 *  Produces a version of <i>str</i> with all nonprinting characters replaced by
 *  <code>\nnn</code> notation and all special characters escaped.
 */

VALUE
rb_str_dump(str)
    VALUE str;
{
    long len;
    char *p, *pend;
    char *q, *qend;
    VALUE result;

    len = 2;                    /* "" */
    p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
    while (p < pend) {
        char c = *p++;
        switch (c) {
          case '"':  case '\\':
          case '\n': case '\r':
          case '\t': case '\f':
          case '\013': case '\010': case '\007': case '\033':
            len += 2;
            break;

          case '#':
            len += IS_EVSTR(p, pend) ? 2 : 1;
            break;

          default:
            if (ISPRINT(c)) {
                len++;
            }
            else {
                len += 4;             /* \nnn */
            }
            break;
        }
    }

    result = rb_str_new5(str, 0, len);
    p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
    q = RSTRING(result)->ptr; qend = q + len;

    *q++ = '"';
    while (p < pend) {
        char c = *p++;

        if (c == '"' || c == '\\') {
            *q++ = '\\';
            *q++ = c;
        }
        else if (c == '#') {
            if (IS_EVSTR(p, pend)) *q++ = '\\';
            *q++ = '#';
        }
        else if (ISPRINT(c)) {
            *q++ = c;
        }
        else if (c == '\n') {
            *q++ = '\\';
            *q++ = 'n';
        }
        else if (c == '\r') {
            *q++ = '\\';
            *q++ = 'r';
        }
        else if (c == '\t') {
            *q++ = '\\';
            *q++ = 't';
        }
        else if (c == '\f') {
            *q++ = '\\';
            *q++ = 'f';
        }
        else if (c == '\013') {
            *q++ = '\\';
            *q++ = 'v';
        }
        else if (c == '\010') {
            *q++ = '\\';
            *q++ = 'b';
        }
        else if (c == '\007') {
            *q++ = '\\';
            *q++ = 'a';
        }
        else if (c == '\033') {
            *q++ = '\\';
            *q++ = 'e';
        }
        else {
            *q++ = '\\';
            sprintf(q, "%03o", c&0xff);
            q += 3;
        }
    }
    *q++ = '"';

    OBJ_INFECT(result, str);
    return result;
}


upcase (String)

/*
 *  call-seq:
 *     str.upcase   => new_str
 *
 *  Returns a copy of <i>str</i> with all lowercase letters replaced with their
 *  uppercase counterparts. The operation is locale insensitive---only
 *  characters ``a'' to ``z'' are affected.
 *
 *     "hEllO".upcase   #=> "HELLO"
 */

static VALUE
rb_str_upcase(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_upcase_bang(str);
    return str;
}


downcase (String)

/*
 *  call-seq:
 *     str.downcase   => new_str
 *
 *  Returns a copy of <i>str</i> with all uppercase letters replaced with their
 *  lowercase counterparts. The operation is locale insensitive---only
 *  characters ``A'' to ``Z'' are affected.
 *
 *     "hEllO".downcase   #=> "hello"
 */

static VALUE
rb_str_downcase(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_downcase_bang(str);
    return str;
}


capitalize (String)

/*
 *  call-seq:
 *     str.capitalize   => new_str
 *
 *  Returns a copy of <i>str</i> with the first character converted to uppercase
 *  and the remainder to lowercase.
 *
 *     "hello".capitalize    #=> "Hello"
 *     "HELLO".capitalize    #=> "Hello"
 *     "123ABC".capitalize   #=> "123abc"
 */

static VALUE
rb_str_capitalize(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_capitalize_bang(str);
    return str;
}


swapcase (String)

/*
 *  call-seq:
 *     str.swapcase   => new_str
 *
 *  Returns a copy of <i>str</i> with uppercase alphabetic characters converted
 *  to lowercase and lowercase characters converted to uppercase.
 *
 *     "Hello".swapcase          #=> "hELLO"
 *     "cYbEr_PuNk11".swapcase   #=> "CyBeR_pUnK11"
 */

static VALUE
rb_str_swapcase(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_swapcase_bang(str);
    return str;
}


upcase! (String)

/*
 *  call-seq:
 *     str.upcase!   => str or nil
 *
 *  Upcases the contents of <i>str</i>, returning <code>nil</code> if no changes
 *  were made.
 */

static VALUE
rb_str_upcase_bang(str)
    VALUE str;
{
    char *s, *send;
    int modify = 0;

    rb_str_modify(str);
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    while (s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISLOWER(*s)) {
            *s = toupper(*s);
            modify = 1;
        }
        s++;
    }

    if (modify) return str;
    return Qnil;
}


downcase! (String)

/*
 *  call-seq:
 *     str.downcase!   => str or nil
 *
 *  Downcases the contents of <i>str</i>, returning <code>nil</code> if no
 *  changes were made.
 */

static VALUE
rb_str_downcase_bang(str)
    VALUE str;
{
    char *s, *send;
    int modify = 0;

    rb_str_modify(str);
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    while (s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISUPPER(*s)) {
            *s = tolower(*s);
            modify = 1;
        }
        s++;
    }

    if (modify) return str;
    return Qnil;
}


capitalize! (String)

/*
 *  call-seq:
 *     str.capitalize!   => str or nil
 *
 *  Modifies <i>str</i> by converting the first character to uppercase and the
 *  remainder to lowercase. Returns <code>nil</code> if no changes are made.
 *
 *     a = "hello"
 *     a.capitalize!   #=> "Hello"
 *     a               #=> "Hello"
 *     a.capitalize!   #=> nil
 */

static VALUE
rb_str_capitalize_bang(str)
    VALUE str;
{
    char *s, *send;
    int modify = 0;

    rb_str_modify(str);
    if (RSTRING(str)->len == 0 || !RSTRING(str)->ptr) return Qnil;
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    if (ISLOWER(*s)) {
        *s = toupper(*s);
        modify = 1;
    }
    while (++s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISUPPER(*s)) {
            *s = tolower(*s);
            modify = 1;
        }
    }
    if (modify) return str;
    return Qnil;
}


swapcase! (String)

/*
 *  call-seq:
 *     str.swapcase!   => str or nil
 *
 *  Equivalent to <code>String#swapcase</code>, but modifies the receiver in
 *  place, returning <i>str</i>, or <code>nil</code> if no changes were made.
 */

static VALUE
rb_str_swapcase_bang(str)
    VALUE str;
{
    char *s, *send;
    int modify = 0;

    rb_str_modify(str);
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    while (s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISUPPER(*s)) {
            *s = tolower(*s);
            modify = 1;
        }
        else if (ISLOWER(*s)) {
            *s = toupper(*s);
            modify = 1;
        }
        s++;
    }

    if (modify) return str;
    return Qnil;
}


hex (String)

/*
 *  call-seq:
 *     str.hex   => integer
 *
 *  Treats leading characters from <i>str</i> as a string of hexadecimal digits
 *  (with an optional sign and an optional <code>0x</code>) and returns the
 *  corresponding number. Zero is returned on error.
 *
 *     "0x0a".hex     #=> 10
 *     "-1234".hex    #=> -4660
 *     "0".hex        #=> 0
 *     "wombat".hex   #=> 0
 */

static VALUE
rb_str_hex(str)
    VALUE str;
{
    return rb_str_to_inum(str, 16, Qfalse);
}


oct (String)

/*
 *  call-seq:
 *     str.oct   => integer
 *
 *  Treats leading characters of <i>str</i> as a string of octal digits (with an
 *  optional sign) and returns the corresponding number.  Returns 0 if the
 *  conversion fails.
 *
 *     "123".oct       #=> 83
 *     "-377".oct      #=> -255
 *     "bad".oct       #=> 0
 *     "0377bad".oct   #=> 255
 */

static VALUE
rb_str_oct(str)
    VALUE str;
{
    return rb_str_to_inum(str, -8, Qfalse);
}


split (String)

/*
 *  call-seq:
 *     str.split(pattern=$;, [limit])   => anArray
 *
 *  Divides <i>str</i> into substrings based on a delimiter, returning an array
 *  of these substrings.
 *
 *  If <i>pattern</i> is a <code>String</code>, then its contents are used as
 *  the delimiter when splitting <i>str</i>. If <i>pattern</i> is a single
 *  space, <i>str</i> is split on whitespace, with leading whitespace and runs
 *  of contiguous whitespace characters ignored.
 *
 *  If <i>pattern</i> is a <code>Regexp</code>, <i>str</i> is divided where the
 *  pattern matches. Whenever the pattern matches a zero-length string,
 *  <i>str</i> is split into individual characters.
 *
 *  If <i>pattern</i> is omitted, the value of <code>$;</code> is used.  If
 *  <code>$;</code> is <code>nil</code> (which is the default), <i>str</i> is
 *  split on whitespace as if ` ' were specified.
 *
 *  If the <i>limit</i> parameter is omitted, trailing null fields are
 *  suppressed. If <i>limit</i> is a positive number, at most that number of
 *  fields will be returned (if <i>limit</i> is <code>1</code>, the entire
 *  string is returned as the only entry in an array). If negative, there is no
 *  limit to the number of fields returned, and trailing null fields are not
 *  suppressed.
 *
 *     " now's  the time".split        #=> ["now's", "the", "time"]
 *     " now's  the time".split(' ')   #=> ["now's", "the", "time"]
 *     " now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
 *     "1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
 *     "hello".split(//)               #=> ["h", "e", "l", "l", "o"]
 *     "hello".split(//, 3)            #=> ["h", "e", "llo"]
 *     "hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]
 *
 *     "mellow yellow".split("ello")   #=> ["m", "w y", "w"]
 *     "1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
 *     "1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
 *     "1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]
 */

static VALUE
rb_str_split_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE spat;
    VALUE limit;
    int awk_split = Qfalse;
    long beg, end, i = 0;
    int lim = 0;
    VALUE result, tmp;

    if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) {
        lim = NUM2INT(limit);
        if (lim <= 0) limit = Qnil;
        else if (lim == 1) {
            if (RSTRING(str)->len == 0)
                return rb_ary_new2(0);
            return rb_ary_new3(1, str);
        }
        i = 1;
    }

    if (NIL_P(spat)) {
        if (!NIL_P(rb_fs)) {
            spat = rb_fs;
            goto fs_set;
        }
        awk_split = Qtrue;
    }
    else {
      fs_set:
        if (TYPE(spat) == T_STRING && RSTRING(spat)->len == 1) {
            if (RSTRING(spat)->ptr[0] == ' ') {
                awk_split = Qtrue;
            }
            else {
                spat = rb_reg_regcomp(rb_reg_quote(spat));
            }
        }
        else {
            spat = get_pat(spat, 1);
        }
    }

    result = rb_ary_new();
    beg = 0;
    if (awk_split) {
        char *ptr = RSTRING(str)->ptr;
        long len = RSTRING(str)->len;
        char *eptr = ptr + len;
        int skip = 1;

        for (end = beg = 0; ptr<eptr; ptr++) {
            if (skip) {
                if (ISSPACE(*ptr)) {
                    beg++;
                }
                else {
                    end = beg+1;
                    skip = 0;
                    if (!NIL_P(limit) && lim <= i) break;
                }
            }
            else {
                if (ISSPACE(*ptr)) {
                    rb_ary_push(result, rb_str_substr(str, beg, end-beg));
                    skip = 1;
                    beg = end + 1;
                    if (!NIL_P(limit)) ++i;
                }
                else {
                    end++;
                }
            }
        }
    }
    else {
        long start = beg;
        long idx;
        int last_null = 0;
        struct re_registers *regs;

        while ((end = rb_reg_search(spat, str, start, 0)) >= 0) {
            regs = RMATCH(rb_backref_get())->regs;
            if (start == end && BEG(0) == END(0)) {
                if (!RSTRING(str)->ptr) {
                    rb_ary_push(result, rb_str_new("", 0));
                    break;
                }
                else if (last_null == 1) {
                    rb_ary_push(result, rb_str_substr(str, beg, mbclen2(RSTRING(str)->ptr[beg],spat)));
                    beg = start;
                }
                else {
                    start += mbclen2(RSTRING(str)->ptr[start],spat);
                    last_null = 1;
                    continue;
                }
            }
            else {
                rb_ary_push(result, rb_str_substr(str, beg, end-beg));
                beg = start = END(0);
            }
            last_null = 0;

            for (idx=1; idx < regs->num_regs; idx++) {
                if (BEG(idx) == -1) continue;
                if (BEG(idx) == END(idx))
                    tmp = rb_str_new5(str, 0, 0);
                else
                    tmp = rb_str_substr(str, BEG(idx), END(idx)-BEG(idx));
                rb_ary_push(result, tmp);
            }
            if (!NIL_P(limit) && lim <= ++i) break;
        }
    }
    if (RSTRING(str)->len > 0 && (!NIL_P(limit) || RSTRING(str)->len > beg || lim < 0)) {
        if (RSTRING(str)->len == beg)
            tmp = rb_str_new5(str, 0, 0);
        else
            tmp = rb_str_substr(str, beg, RSTRING(str)->len-beg);
        rb_ary_push(result, tmp);
    }
    if (NIL_P(limit) && lim == 0) {
        while (RARRAY(result)->len > 0 &&
               RSTRING(RARRAY(result)->ptr[RARRAY(result)->len-1])->len == 0)
            rb_ary_pop(result);
    }

    return result;
}


reverse (String)

/*
 *  call-seq:
 *     str.reverse   => new_str
 *
 *  Returns a new string with the characters from <i>str</i> in reverse order.
 *
 *     "stressed".reverse   #=> "desserts"
 */

static VALUE
rb_str_reverse(str)
    VALUE str;
{
    VALUE obj;
    char *s, *e, *p;

    if (RSTRING(str)->len <= 1) return rb_str_dup(str);

    obj = rb_str_new5(str, 0, RSTRING(str)->len);
    s = RSTRING(str)->ptr; e = s + RSTRING(str)->len - 1;
    p = RSTRING(obj)->ptr;

    while (e >= s) {
        *p++ = *e--;
    }
    OBJ_INFECT(obj, str);

    return obj;
}


reverse! (String)

/*
 *  call-seq:
 *     str.reverse!   => str
 *
 *  Reverses <i>str</i> in place.
 */

static VALUE
rb_str_reverse_bang(str)
    VALUE str;
{
    char *s, *e;
    char c;

    if (RSTRING(str)->len > 1) {
        rb_str_modify(str);
        s = RSTRING(str)->ptr;
        e = s + RSTRING(str)->len - 1;
        while (s < e) {
            c = *s;
            *s++ = *e;
            *e-- = c;
        }
    }
    return str;
}


concat (String)

/*
 *  call-seq:
 *     str << fixnum        => str
 *     str.concat(fixnum)   => str
 *     str << obj           => str
 *     str.concat(obj)      => str
 *
 *  Append---Concatenates the given object to <i>str</i>. If the object is a
 *  <code>Fixnum</code> between 0 and 255, it is converted to a character before
 *  concatenation.
 *
 *     a = "hello "
 *     a << "world"   #=> "hello world"
 *     a.concat(33)   #=> "hello world!"
 */

VALUE
rb_str_concat(str1, str2)
    VALUE str1, str2;
{
    if (FIXNUM_P(str2)) {
        int i = FIX2INT(str2);
        if (0 <= i && i <= 0xff) { /* byte */
            char c = i;
            return rb_str_cat(str1, &c, 1);
        }
    }
    str1 = rb_str_append(str1, str2);

    return str1;
}


<< (String)

/*
 *  call-seq:
 *     str << fixnum        => str
 *     str.concat(fixnum)   => str
 *     str << obj           => str
 *     str.concat(obj)      => str
 *
 *  Append---Concatenates the given object to <i>str</i>. If the object is a
 *  <code>Fixnum</code> between 0 and 255, it is converted to a character before
 *  concatenation.
 *
 *     a = "hello "
 *     a << "world"   #=> "hello world"
 *     a.concat(33)   #=> "hello world!"
 */

VALUE
rb_str_concat(str1, str2)
    VALUE str1, str2;
{
    if (FIXNUM_P(str2)) {
        int i = FIX2INT(str2);
        if (0 <= i && i <= 0xff) { /* byte */
            char c = i;
            return rb_str_cat(str1, &c, 1);
        }
    }
    str1 = rb_str_append(str1, str2);

    return str1;
}


crypt (String)

/*
 *  call-seq:
 *     str.crypt(other_str)   => new_str
 *
 *  Applies a one-way cryptographic hash to <i>str</i> by invoking the standard
 *  library function <code>crypt</code>. The argument is the salt string, which
 *  should be two characters long, each character drawn from
 *  <code>[a-zA-Z0-9./]</code>.
 */

static VALUE
rb_str_crypt(str, salt)
    VALUE str, salt;
{
    extern char *crypt();
    VALUE result;
    char *s;

    StringValue(salt);
    if (RSTRING(salt)->len < 2)
        rb_raise(rb_eArgError, "salt too short(need >=2 bytes)");

    if (RSTRING(str)->ptr) s = RSTRING(str)->ptr;
    else s = "";
    result = rb_str_new2(crypt(s, RSTRING(salt)->ptr));
    OBJ_INFECT(result, str);
    OBJ_INFECT(result, salt);
    return result;
}


intern (String)

/*
 *  call-seq:
 *     str.intern   => symbol
 *     str.to_sym   => symbol
 *
 *  Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
 *  symbol if it did not previously exist. See <code>Symbol#id2name</code>.
 *
 *     "Koala".intern         #=> :Koala
 *     s = 'cat'.to_sym       #=> :cat
 *     s == :cat              #=> true
 *     s = '@cat'.to_sym      #=> :@cat
 *     s == :@cat             #=> true
 *
 *  This can also be used to create symbols that cannot be represented using the
 *  <code>:xxx</code> notation.
 *
 *     'cat and dog'.to_sym   #=> :"cat and dog"
 */

VALUE
rb_str_intern(s)
    VALUE s;
{
    volatile VALUE str = s;
    ID id;

    if (!RSTRING(str)->ptr || RSTRING(str)->len == 0) {
        rb_raise(rb_eArgError, "interning empty string");
    }
    if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len)
        rb_raise(rb_eArgError, "symbol string may not contain `\\0'");
    if (OBJ_TAINTED(str) && rb_safe_level() >= 1 && !rb_sym_interned_p(str)) {
        rb_raise(rb_eSecurityError, "Insecure: can't intern tainted string");
    }
    id = rb_intern(RSTRING(str)->ptr);
    return ID2SYM(id);
}


to_sym (String)

/*
 *  call-seq:
 *     str.intern   => symbol
 *     str.to_sym   => symbol
 *
 *  Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
 *  symbol if it did not previously exist. See <code>Symbol#id2name</code>.
 *
 *     "Koala".intern         #=> :Koala
 *     s = 'cat'.to_sym       #=> :cat
 *     s == :cat              #=> true
 *     s = '@cat'.to_sym      #=> :@cat
 *     s == :@cat             #=> true
 *
 *  This can also be used to create symbols that cannot be represented using the
 *  <code>:xxx</code> notation.
 *
 *     'cat and dog'.to_sym   #=> :"cat and dog"
 */

VALUE
rb_str_intern(s)
    VALUE s;
{
    volatile VALUE str = s;
    ID id;

    if (!RSTRING(str)->ptr || RSTRING(str)->len == 0) {
        rb_raise(rb_eArgError, "interning empty string");
    }
    if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len)
        rb_raise(rb_eArgError, "symbol string may not contain `\\0'");
    if (OBJ_TAINTED(str) && rb_safe_level() >= 1 && !rb_sym_interned_p(str)) {
        rb_raise(rb_eSecurityError, "Insecure: can't intern tainted string");
    }
    id = rb_intern(RSTRING(str)->ptr);
    return ID2SYM(id);
}


include? (String)

/*
 *  call-seq:
 *     str.include? other_str   => true or false
 *     str.include? fixnum      => true or false
 *
 *  Returns <code>true</code> if <i>str</i> contains the given string or
 *  character.
 *
 *     "hello".include? "lo"   #=> true
 *     "hello".include? "ol"   #=> false
 *     "hello".include? ?h     #=> true
 */

static VALUE
rb_str_include(str, arg)
    VALUE str, arg;
{
    long i;

    if (FIXNUM_P(arg)) {
        if (memchr(RSTRING(str)->ptr, FIX2INT(arg), RSTRING(str)->len))
            return Qtrue;
        return Qfalse;
    }

    StringValue(arg);
    i = rb_str_index(str, arg, 0);

    if (i == -1) return Qfalse;
    return Qtrue;
}


scan (String)

/*
 *  call-seq:
 *     str.scan(pattern)                         => array
 *     str.scan(pattern) {|match, ...| block }   => str
 *
 *  Both forms iterate through <i>str</i>, matching the pattern (which may be a
 *  <code>Regexp</code> or a <code>String</code>). For each match, a result is
 *  generated and either added to the result array or passed to the block. If
 *  the pattern contains no groups, each individual result consists of the
 *  matched string, <code>$&</code>.  If the pattern contains groups, each
 *  individual result is itself an array containing one entry per group.
 *
 *     a = "cruel world"
 *     a.scan(/\w+/)        #=> ["cruel", "world"]
 *     a.scan(/.../)        #=> ["cru", "el ", "wor"]
 *     a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
 *     a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]
 *
 *  And the block form:
 *
 *     a.scan(/\w+/) {|w| print "<<#{w}>> " }
 *     print "\n"
 *     a.scan(/(.)(.)/) {|x,y| print y, x }
 *     print "\n"
 *
 *  <em>produces:</em>
 *
 *     <<cruel>> <<world>>
 *     rceu lowlr
 */

static VALUE
rb_str_scan(str, pat)
    VALUE str, pat;
{
    VALUE result;
    long start = 0;
    VALUE match = Qnil;
    char *p = RSTRING(str)->ptr; long len = RSTRING(str)->len;

    pat = get_pat(pat, 1);
    if (!rb_block_given_p()) {
        VALUE ary = rb_ary_new();

        while (!NIL_P(result = scan_once(str, pat, &start))) {
            match = rb_backref_get();
            rb_ary_push(ary, result);
        }
        rb_backref_set(match);
        return ary;
    }

    while (!NIL_P(result = scan_once(str, pat, &start))) {
        match = rb_backref_get();
        rb_match_busy(match);
        rb_yield(result);
        str_mod_check(str, p, len);
        rb_backref_set(match); /* restore $~ value */
    }
    rb_backref_set(match);
    return str;
}


ljust (String)

/*
 *  call-seq:
 *     str.ljust(integer, padstr=' ')   => new_str
 *
 *  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
 *  <code>String</code> of length <i>integer</i> with <i>str</i> left justified
 *  and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
 *
 *     "hello".ljust(4)            #=> "hello"
 *     "hello".ljust(20)           #=> "hello               "
 *     "hello".ljust(20, '1234')   #=> "hello123412341234123"
 */

static VALUE
rb_str_ljust(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return rb_str_justify(argc, argv, str, 'l');
}


rjust (String)

/*
 *  call-seq:
 *     str.rjust(integer, padstr=' ')   => new_str
 *
 *  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
 *  <code>String</code> of length <i>integer</i> with <i>str</i> right justified
 *  and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
 *
 *     "hello".rjust(4)            #=> "hello"
 *     "hello".rjust(20)           #=> "               hello"
 *     "hello".rjust(20, '1234')   #=> "123412341234123hello"
 */

static VALUE
rb_str_rjust(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return rb_str_justify(argc, argv, str, 'r');
}


center (String)

/*
 *  call-seq:
 *     str.center(integer, padstr)   => new_str
 *
 *  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
 *  <code>String</code> of length <i>integer</i> with <i>str</i> centered and
 *  padded with <i>padstr</i>; otherwise, returns <i>str</i>.
 *
 *     "hello".center(4)         #=> "hello"
 *     "hello".center(20)        #=> "       hello        "
 *     "hello".center(20, '123') #=> "1231231hello12312312"
 */

static VALUE
rb_str_center(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return rb_str_justify(argc, argv, str, 'c');
}


sub (String)

/*
 *  call-seq:
 *     str.sub(pattern, replacement)         => new_str
 *     str.sub(pattern) {|match| block }     => new_str
 *
 *  Returns a copy of <i>str</i> with the <em>first</em> occurrence of
 *  <i>pattern</i> replaced with either <i>replacement</i> or the value of the
 *  block. The <i>pattern</i> will typically be a <code>Regexp</code>; if it is
 *  a <code>String</code> then no regular expression metacharacters will be
 *  interpreted (that is <code>/\d/</code> will match a digit, but
 *  <code>'\d'</code> will match a backslash followed by a 'd').
 *
 *  If the method call specifies <i>replacement</i>, special variables such as
 *  <code>$&</code> will not be useful, as substitution into the string occurs
 *  before the pattern match starts. However, the sequences <code>\1</code>,
 *  <code>\2</code>, etc., may be used.
 *
 *  In the block form, the current match string is passed in as a parameter, and
 *  variables such as <code>$1</code>, <code>$2</code>, <code>$`</code>,
 *  <code>$&</code>, and <code>$'</code> will be set appropriately. The value
 *  returned by the block will be substituted for the match on each call.
 *
 *  The result inherits any tainting in the original string or any supplied
 *  replacement string.
 *
 *     "hello".sub(/[aeiou]/, '*')               #=> "h*llo"
 *     "hello".sub(/([aeiou])/, '<\1>')          #=> "h<e>llo"
 *     "hello".sub(/./) {|s| s[0].to_s + ' ' }   #=> "104 ello"
 */

static VALUE
rb_str_sub(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_sub_bang(argc, argv, str);
    return str;
}


gsub (String)

/*
 *  call-seq:
 *     str.gsub(pattern, replacement)       => new_str
 *     str.gsub(pattern) {|match| block }   => new_str
 *
 *  Returns a copy of <i>str</i> with <em>all</em> occurrences of <i>pattern</i>
 *  replaced with either <i>replacement</i> or the value of the block. The
 *  <i>pattern</i> will typically be a <code>Regexp</code>; if it is a
 *  <code>String</code> then no regular expression metacharacters will be
 *  interpreted (that is <code>/\d/</code> will match a digit, but
 *  <code>'\d'</code> will match a backslash followed by a 'd').
 *
 *  If a string is used as the replacement, special variables from the match
 *  (such as <code>$&</code> and <code>$1</code>) cannot be substituted into it,
 *  as substitution into the string occurs before the pattern match
 *  starts. However, the sequences <code>\1</code>, <code>\2</code>, and so on
 *  may be used to interpolate successive groups in the match.
 *
 *  In the block form, the current match string is passed in as a parameter, and
 *  variables such as <code>$1</code>, <code>$2</code>, <code>$`</code>,
 *  <code>$&</code>, and <code>$'</code> will be set appropriately. The value
 *  returned by the block will be substituted for the match on each call.
 *
 *  The result inherits any tainting in the original string or any supplied
 *  replacement string.
 *
 *     "hello".gsub(/[aeiou]/, '*')              #=> "h*ll*"
 *     "hello".gsub(/([aeiou])/, '<\1>')         #=> "h<e>ll<o>"
 *     "hello".gsub(/./) {|s| s[0].to_s + ' '}   #=> "104 101 108 108 111 "
 */

static VALUE
rb_str_gsub(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return str_gsub(argc, argv, str, 0);
}


chop (String)

/*
 *  call-seq:
 *     str.chop   => new_str
 *
 *  Returns a new <code>String</code> with the last character removed.  If the
 *  string ends with <code>\r\n</code>, both characters are removed. Applying
 *  <code>chop</code> to an empty string returns an empty
 *  string. <code>String#chomp</code> is often a safer alternative, as it leaves
 *  the string unchanged if it doesn't end in a record separator.
 *
 *     "string\r\n".chop   #=> "string"
 *     "string\n\r".chop   #=> "string\n"
 *     "string\n".chop     #=> "string"
 *     "string".chop       #=> "strin"
 *     "x".chop.chop       #=> ""
 */

static VALUE
rb_str_chop(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_chop_bang(str);
    return str;
}


chomp (String)

/*
 *  call-seq:
 *     str.chomp(separator=$/)   => new_str
 *
 *  Returns a new <code>String</code> with the given record separator removed
 *  from the end of <i>str</i> (if present). If <code>$/</code> has not been
 *  changed from the default Ruby record separator, then <code>chomp</code> also
 *  removes carriage return characters (that is it will remove <code>\n</code>,
 *  <code>\r</code>, and <code>\r\n</code>).
 *
 *     "hello".chomp            #=> "hello"
 *     "hello\n".chomp          #=> "hello"
 *     "hello\r\n".chomp        #=> "hello"
 *     "hello\n\r".chomp        #=> "hello\n"
 *     "hello\r".chomp          #=> "hello"
 *     "hello \n there".chomp   #=> "hello \n there"
 *     "hello".chomp("llo")     #=> "he"
 */

static VALUE
rb_str_chomp(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_chomp_bang(argc, argv, str);
    return str;
}


strip (String)

/*
 *  call-seq:
 *     str.strip   => new_str
 *
 *  Returns a copy of <i>str</i> with leading and trailing whitespace removed.
 *
 *     "    hello    ".strip   #=> "hello"
 *     "\tgoodbye\r\n".strip   #=> "goodbye"
 */

static VALUE
rb_str_strip(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}


lstrip (String)

/*
 *  call-seq:
 *     str.lstrip   => new_str
 *
 *  Returns a copy of <i>str</i> with leading whitespace removed. See also
 *  <code>String#rstrip</code> and <code>String#strip</code>.
 *
 *     "  hello  ".lstrip   #=> "hello  "
 *     "hello".lstrip       #=> "hello"
 */

static VALUE
rb_str_lstrip(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_lstrip_bang(str);
    return str;
}


rstrip (String)

/*
 *  call-seq:
 *     str.rstrip   => new_str
 *
 *  Returns a copy of <i>str</i> with trailing whitespace removed. See also
 *  <code>String#lstrip</code> and <code>String#strip</code>.
 *
 *     "  hello  ".rstrip   #=> "  hello"
 *     "hello".rstrip       #=> "hello"
 */

static VALUE
rb_str_rstrip(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_rstrip_bang(str);
    return str;
}


sub! (String)

/*
 *  call-seq:
 *     str.sub!(pattern, replacement)          => str or nil
 *     str.sub!(pattern) {|match| block }      => str or nil
 *
 *  Performs the substitutions of <code>String#sub</code> in place,
 *  returning <i>str</i>, or <code>nil</code> if no substitutions were
 *  performed.
 */

static VALUE
rb_str_sub_bang(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE pat, repl, match;
    struct re_registers *regs;
    int iter = 0;
    int tainted = 0;
    long plen;

    if (argc == 1 && rb_block_given_p()) {
        iter = 1;
    }
    else if (argc == 2) {
        repl = argv[1];
        StringValue(repl);
        if (OBJ_TAINTED(repl)) tainted = 1;
    }
    else {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc);
    }

    pat = get_pat(argv[0], 1);
    if (rb_reg_search(pat, str, 0, 0) >= 0) {
        match = rb_backref_get();
        regs = RMATCH(match)->regs;

        if (iter) {
            char *p = RSTRING(str)->ptr; long len = RSTRING(str)->len;

            rb_match_busy(match);
            repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
            str_mod_check(str, p, len);
            str_frozen_check(str);
            rb_backref_set(match);
        }
        else {
            repl = rb_reg_regsub(repl, str, regs);
        }
        rb_str_modify(str);
        if (OBJ_TAINTED(repl)) tainted = 1;
        plen = END(0) - BEG(0);
        if (RSTRING(repl)->len > plen) {
            RESIZE_CAPA(str, RSTRING(str)->len + RSTRING(repl)->len - plen);
        }
        if (RSTRING(repl)->len != plen) {
            memmove(RSTRING(str)->ptr + BEG(0) + RSTRING(repl)->len,
                    RSTRING(str)->ptr + BEG(0) + plen,
                    RSTRING(str)->len - BEG(0) - plen);
        }
        memcpy(RSTRING(str)->ptr + BEG(0),
               RSTRING(repl)->ptr, RSTRING(repl)->len);
        RSTRING(str)->len += RSTRING(repl)->len - plen;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        if (tainted) OBJ_TAINT(str);

        return str;
    }
    return Qnil;
}


gsub! (String)

/*
 *  call-seq:
 *     str.gsub!(pattern, replacement)        => str or nil
 *     str.gsub!(pattern) {|match| block }    => str or nil
 *
 *  Performs the substitutions of <code>String#gsub</code> in place, returning
 *  <i>str</i>, or <code>nil</code> if no substitutions were performed.
 */

static VALUE
rb_str_gsub_bang(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return str_gsub(argc, argv, str, 1);
}


chop! (String)

/*
 *  call-seq:
 *     str.chop!   => str or nil
 *
 *  Processes <i>str</i> as for <code>String#chop</code>, returning <i>str</i>,
 *  or <code>nil</code> if <i>str</i> is the empty string.  See also
 *  <code>String#chomp!</code>.
 */

static VALUE
rb_str_chop_bang(str)
    VALUE str;
{
    if (RSTRING(str)->len > 0) {
        rb_str_modify(str);
        RSTRING(str)->len--;
        if (RSTRING(str)->ptr[RSTRING(str)->len] == '\n') {
            if (RSTRING(str)->len > 0 &&
                RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
                RSTRING(str)->len--;
            }
        }
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        return str;
    }
    return Qnil;
}


chomp! (String)

/*
 *  call-seq:
 *     str.chomp!(separator=$/)   => str or nil
 *
 *  Modifies <i>str</i> in place as described for <code>String#chomp</code>,
 *  returning <i>str</i>, or <code>nil</code> if no modifications were made.
 */

static VALUE
rb_str_chomp_bang(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE rs;
    int newline;
    char *p;
    long len, rslen;

    if (rb_scan_args(argc, argv, "01", &rs) == 0) {
        len = RSTRING(str)->len;
        if (len == 0) return Qnil;
        p = RSTRING(str)->ptr;
        rs = rb_rs;
        if (rs == rb_default_rs) {
          smart_chomp:
            rb_str_modify(str);
            if (RSTRING(str)->ptr[len-1] == '\n') {
                RSTRING(str)->len--;
                if (RSTRING(str)->len > 0 &&
                    RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
                    RSTRING(str)->len--;
                }
            }
            else if (RSTRING(str)->ptr[len-1] == '\r') {
                RSTRING(str)->len--;
            }
            else {
                return Qnil;
            }
            RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
            return str;
        }
    }
    if (NIL_P(rs)) return Qnil;
    StringValue(rs);
    len = RSTRING(str)->len;
    if (len == 0) return Qnil;
    p = RSTRING(str)->ptr;
    rslen = RSTRING(rs)->len;
    if (rslen == 0) {
        while (len>0 && p[len-1] == '\n') {
            len--;
            if (len>0 && p[len-1] == '\r')
                len--;
        }
        if (len < RSTRING(str)->len) {
            rb_str_modify(str);
            RSTRING(str)->len = len;
            RSTRING(str)->ptr[len] = '\0';
            return str;
        }
        return Qnil;
    }
    if (rslen > len) return Qnil;
    newline = RSTRING(rs)->ptr[rslen-1];
    if (rslen == 1 && newline == '\n')
        goto smart_chomp;

    if (p[len-1] == newline &&
        (rslen <= 1 ||
         rb_memcmp(RSTRING(rs)->ptr, p+len-rslen, rslen) == 0)) {
        rb_str_modify(str);
        RSTRING(str)->len -= rslen;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        return str;
    }
    return Qnil;
}


strip! (String)

/*
 *  call-seq:
 *     str.strip!   => str or nil
 *
 *  Removes leading and trailing whitespace from <i>str</i>. Returns
 *  <code>nil</code> if <i>str</i> was not altered.
 */

static VALUE
rb_str_strip_bang(str)
    VALUE str;
{
    VALUE l = rb_str_lstrip_bang(str);
    VALUE r = rb_str_rstrip_bang(str);

    if (NIL_P(l) && NIL_P(r)) return Qnil;
    return str;
}


lstrip! (String)

/*
 *  call-seq:
 *     str.lstrip!   => self or nil
 *
 *  Removes leading whitespace from <i>str</i>, returning <code>nil</code> if no
 *  change was made. See also <code>String#rstrip!</code> and
 *  <code>String#strip!</code>.
 *
 *     "  hello  ".lstrip   #=> "hello  "
 *     "hello".lstrip!      #=> nil
 */

static VALUE
rb_str_lstrip_bang(str)
    VALUE str;
{
    char *s, *t, *e;

    s = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    e = t = s + RSTRING(str)->len;
    /* remove spaces at head */
    while (s < t && ISSPACE(*s)) s++;

    if (s > RSTRING(str)->ptr) {
        rb_str_modify(str);
        RSTRING(str)->len = t-s;
        memmove(RSTRING(str)->ptr, s, RSTRING(str)->len);
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        return str;
    }
    return Qnil;
}


rstrip! (String)

/*
 *  call-seq:
 *     str.rstrip!   => self or nil
 *
 *  Removes trailing whitespace from <i>str</i>, returning <code>nil</code> if
 *  no change was made. See also <code>String#lstrip!</code> and
 *  <code>String#strip!</code>.
 *
 *     "  hello  ".rstrip   #=> "  hello"
 *     "hello".rstrip!      #=> nil
 */

static VALUE
rb_str_rstrip_bang(str)
    VALUE str;
{
    char *s, *t, *e;

    s = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    e = t = s + RSTRING(str)->len;

    /* remove trailing '\0's */
    while (s < t && t[-1] == '\0') t--;

    /* remove trailing spaces */
    while (s < t && ISSPACE(*(t-1))) t--;

    if (t < e) {
        rb_str_modify(str);
        RSTRING(str)->len = t-s;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        return str;
    }
    return Qnil;
}


tr (String)

/*
 *  call-seq:
 *     str.tr(from_str, to_str)   => new_str
 *
 *  Returns a copy of <i>str</i> with the characters in <i>from_str</i> replaced
 *  by the corresponding characters in <i>to_str</i>. If <i>to_str</i> is
 *  shorter than <i>from_str</i>, it is padded with its last character. Both
 *  strings may use the c1--c2 notation to denote ranges of characters, and
 *  <i>from_str</i> may start with a <code>^</code>, which denotes all
 *  characters except those listed.
 *
 *     "hello".tr('aeiou', '*')    #=> "h*ll*"
 *     "hello".tr('^aeiou', '*')   #=> "*e**o"
 *     "hello".tr('el', 'ip')      #=> "hippo"
 *     "hello".tr('a-y', 'b-z')    #=> "ifmmp"
 */

static VALUE
rb_str_tr(str, src, repl)
    VALUE str, src, repl;
{
    str = rb_str_dup(str);
    tr_trans(str, src, repl, 0);
    return str;
}


tr_s (String)

/*
 *  call-seq:
 *     str.tr_s(from_str, to_str)   => new_str
 *
 *  Processes a copy of <i>str</i> as described under <code>String#tr</code>,
 *  then removes duplicate characters in regions that were affected by the
 *  translation.
 *
 *     "hello".tr_s('l', 'r')     #=> "hero"
 *     "hello".tr_s('el', '*')    #=> "h*o"
 *     "hello".tr_s('el', 'hx')   #=> "hhxo"
 */

static VALUE
rb_str_tr_s(str, src, repl)
    VALUE str, src, repl;
{
    str = rb_str_dup(str);
    tr_trans(str, src, repl, 1);
    return str;
}


delete (String)

/*
 *  call-seq:
 *     str.delete([other_str]+)   => new_str
 *
 *  Returns a copy of <i>str</i> with all characters in the intersection of its
 *  arguments deleted. Uses the same rules for building the set of characters as
 *  <code>String#count</code>.
 *
 *     "hello".delete "l","lo"        #=> "heo"
 *     "hello".delete "lo"            #=> "he"
 *     "hello".delete "aeiou", "^e"   #=> "hell"
 *     "hello".delete "ej-m"          #=> "ho"
 */

static VALUE
rb_str_delete(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_delete_bang(argc, argv, str);
    return str;
}


squeeze (String)

/*
 *  call-seq:
 *     str.squeeze([other_str]*)    => new_str
 *
 *  Builds a set of characters from the <i>other_str</i> parameter(s) using the
 *  procedure described for <code>String#count</code>. Returns a new string
 *  where runs of the same character that occur in this set are replaced by a
 *  single character. If no arguments are given, all runs of identical
 *  characters are replaced by a single character.
 *
 *     "yellow moon".squeeze                  #=> "yelow mon"
 *     "  now   is  the".squeeze(" ")         #=> " now is the"
 *     "putters shoot balls".squeeze("m-z")   #=> "puters shot balls"
 */

static VALUE
rb_str_squeeze(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_squeeze_bang(argc, argv, str);
    return str;
}


count (String)

/*
 *  call-seq:
 *     str.count([other_str]+)   => fixnum
 *
 *  Each <i>other_str</i> parameter defines a set of characters to count.  The
 *  intersection of these sets defines the characters to count in
 *  <i>str</i>. Any <i>other_str</i> that starts with a caret (^) is
 *  negated. The sequence c1--c2 means all characters between c1 and c2.
 *
 *     a = "hello world"
 *     a.count "lo"            #=> 5
 *     a.count "lo", "o"       #=> 2
 *     a.count "hello", "^l"   #=> 4
 *     a.count "ej-m"          #=> 4
 */

static VALUE
rb_str_count(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    char table[256];
    char *s, *send;
    int init = 1;
    int i;

    if (argc < 1) {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    for (i=0; i<argc; i++) {
        VALUE s = argv[i];

        StringValue(s);
        tr_setup_table(s, table, init);
        init = 0;
    }

    s = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return INT2FIX(0);
    send = s + RSTRING(str)->len;
    i = 0;
    while (s < send) {
        if (table[*s++ & 0xff]) {
            i++;
        }
    }
    return INT2NUM(i);
}


tr! (String)

/*
 *  call-seq:
 *     str.tr!(from_str, to_str)   => str or nil
 *
 *  Translates <i>str</i> in place, using the same rules as
 *  <code>String#tr</code>. Returns <i>str</i>, or <code>nil</code> if no
 *  changes were made.
 */

static VALUE
rb_str_tr_bang(str, src, repl)
    VALUE str, src, repl;
{
    return tr_trans(str, src, repl, 0);
}


tr_s! (String)

/*
 *  call-seq:
 *     str.tr_s!(from_str, to_str)   => str or nil
 *
 *  Performs <code>String#tr_s</code> processing on <i>str</i> in place,
 *  returning <i>str</i>, or <code>nil</code> if no changes were made.
 */

static VALUE
rb_str_tr_s_bang(str, src, repl)
    VALUE str, src, repl;
{
    return tr_trans(str, src, repl, 1);
}


delete! (String)

/*
 *  call-seq:
 *     str.delete!([other_str]+>)   => str or nil
 *
 *  Performs a <code>delete</code> operation in place, returning <i>str</i>, or
 *  <code>nil</code> if <i>str</i> was not modified.
 */

static VALUE
rb_str_delete_bang(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    char *s, *send, *t;
    char squeez[256];
    int modify = 0;
    int init = 1;
    int i;

    if (argc < 1) {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    for (i=0; i<argc; i++) {
        VALUE s = argv[i];

        StringValue(s);
        tr_setup_table(s, squeez, init);
        init = 0;
    }

    rb_str_modify(str);
    s = t = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    send = s + RSTRING(str)->len;
    while (s < send) {
        if (squeez[*s & 0xff])
            modify = 1;
        else
            *t++ = *s;
        s++;
    }
    *t = '\0';
    RSTRING(str)->len = t - RSTRING(str)->ptr;

    if (modify) return str;
    return Qnil;
}


squeeze! (String)

/*
 *  call-seq:
 *     str.squeeze!([other_str]*)   => str or nil
 *
 *  Squeezes <i>str</i> in place, returning either <i>str</i>, or
 *  <code>nil</code> if no changes were made.
 */

static VALUE
rb_str_squeeze_bang(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    char squeez[256];
    char *s, *send, *t;
    int c, save, modify = 0;
    int init = 1;
    int i;

    if (argc == 0) {
        for (i=0; i<256; i++) {
            squeez[i] = 1;
        }
    }
    else {
        for (i=0; i<argc; i++) {
            VALUE s = argv[i];

            StringValue(s);
            tr_setup_table(s, squeez, init);
            init = 0;
        }
    }

    rb_str_modify(str);
    s = t = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    send = s + RSTRING(str)->len;
    save = -1;
    while (s < send) {
        c = *s++ & 0xff;
        if (c != save || !squeez[c]) {
            *t++ = save = c;
        }
    }
    *t = '\0';
    if (t - RSTRING(str)->ptr != RSTRING(str)->len) {
        RSTRING(str)->len = t - RSTRING(str)->ptr;
        modify = 1;
    }

    if (modify) return str;
    return Qnil;
}


each_line (String)

/*
 *  call-seq:
 *     str.each(separator=$/) {|substr| block }        => str
 *     str.each_line(separator=$/) {|substr| block }   => str
 *
 *  Splits <i>str</i> using the supplied parameter as the record separator
 *  (<code>$/</code> by default), passing each substring in turn to the supplied
 *  block. If a zero-length record separator is supplied, the string is split on
 *  <code>\n</code> characters, except that multiple successive newlines are
 *  appended together.
 *
 *     print "Example one\n"
 *     "hello\nworld".each {|s| p s}
 *     print "Example two\n"
 *     "hello\nworld".each('l') {|s| p s}
 *     print "Example three\n"
 *     "hello\n\n\nworld".each('') {|s| p s}
 *
 *  <em>produces:</em>
 *
 *     Example one
 *     "hello\n"
 *     "world"
 *     Example two
 *     "hel"
 *     "l"
 *     "o\nworl"
 *     "d"
 *     Example three
 *     "hello\n\n\n"
 *     "world"
 */

static VALUE
rb_str_each_line(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE rs;
    int newline;
    char *p = RSTRING(str)->ptr, *pend = p + RSTRING(str)->len, *s;
    char *ptr = p;
    long len = RSTRING(str)->len, rslen;
    VALUE line;

    if (rb_scan_args(argc, argv, "01", &rs) == 0) {
        rs = rb_rs;
    }

    if (NIL_P(rs)) {
        rb_yield(str);
        return str;
    }
    StringValue(rs);
    rslen = RSTRING(rs)->len;
    if (rslen == 0) {
        newline = '\n';
    }
    else {
        newline = RSTRING(rs)->ptr[rslen-1];
    }

    for (s = p, p += rslen; p < pend; p++) {
        if (rslen == 0 && *p == '\n') {
            if (*++p != '\n') continue;
            while (*p == '\n') p++;
        }
        if (RSTRING(str)->ptr < p && p[-1] == newline &&
            (rslen <= 1 ||
             rb_memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) {
            line = rb_str_new5(str, s, p - s);
            OBJ_INFECT(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p;
        }
    }

    if (s != pend) {
        if (p > pend) p = pend;
        line = rb_str_new5(str, s, p - s);
        OBJ_INFECT(line, str);
        rb_yield(line);
    }

    return str;
}


each (String)

/*
 *  call-seq:
 *     str.each(separator=$/) {|substr| block }        => str
 *     str.each_line(separator=$/) {|substr| block }   => str
 *
 *  Splits <i>str</i> using the supplied parameter as the record separator
 *  (<code>$/</code> by default), passing each substring in turn to the supplied
 *  block. If a zero-length record separator is supplied, the string is split on
 *  <code>\n</code> characters, except that multiple successive newlines are
 *  appended together.
 *
 *     print "Example one\n"
 *     "hello\nworld".each {|s| p s}
 *     print "Example two\n"
 *     "hello\nworld".each('l') {|s| p s}
 *     print "Example three\n"
 *     "hello\n\n\nworld".each('') {|s| p s}
 *
 *  <em>produces:</em>
 *
 *     Example one
 *     "hello\n"
 *     "world"
 *     Example two
 *     "hel"
 *     "l"
 *     "o\nworl"
 *     "d"
 *     Example three
 *     "hello\n\n\n"
 *     "world"
 */

static VALUE
rb_str_each_line(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE rs;
    int newline;
    char *p = RSTRING(str)->ptr, *pend = p + RSTRING(str)->len, *s;
    char *ptr = p;
    long len = RSTRING(str)->len, rslen;
    VALUE line;

    if (rb_scan_args(argc, argv, "01", &rs) == 0) {
        rs = rb_rs;
    }

    if (NIL_P(rs)) {
        rb_yield(str);
        return str;
    }
    StringValue(rs);
    rslen = RSTRING(rs)->len;
    if (rslen == 0) {
        newline = '\n';
    }
    else {
        newline = RSTRING(rs)->ptr[rslen-1];
    }

    for (s = p, p += rslen; p < pend; p++) {
        if (rslen == 0 && *p == '\n') {
            if (*++p != '\n') continue;
            while (*p == '\n') p++;
        }
        if (RSTRING(str)->ptr < p && p[-1] == newline &&
            (rslen <= 1 ||
             rb_memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) {
            line = rb_str_new5(str, s, p - s);
            OBJ_INFECT(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p;
        }
    }

    if (s != pend) {
        if (p > pend) p = pend;
        line = rb_str_new5(str, s, p - s);
        OBJ_INFECT(line, str);
        rb_yield(line);
    }

    return str;
}


each_byte (String)

/*
 *  call-seq:
 *     str.each_byte {|fixnum| block }    => str
 *
 *  Passes each byte in <i>str</i> to the given block.
 *
 *     "hello".each_byte {|c| print c, ' ' }
 *
 *  <em>produces:</em>
 *
 *     104 101 108 108 111
 */

static VALUE
rb_str_each_byte(str)
    VALUE str;
{
    long i;

    for (i=0; i<RSTRING(str)->len; i++) {
        rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff));
    }
    return str;
}


sum (String)

/*
 *  call-seq:
 *     str.sum(n=16)   => integer
 *
 *  Returns a basic <em>n</em>-bit checksum of the characters in <i>str</i>,
 *  where <em>n</em> is the optional <code>Fixnum</code> parameter, defaulting
 *  to 16. The result is simply the sum of the binary value of each character in
 *  <i>str</i> modulo <code>2n - 1</code>. This is not a particularly good
 *  checksum.
 */

static VALUE
rb_str_sum(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE vbits;
    int bits;
    char *ptr, *p, *pend;
    long len;

    if (rb_scan_args(argc, argv, "01", &vbits) == 0) {
        bits = 16;
    }
    else bits = NUM2INT(vbits);

    ptr = p = RSTRING(str)->ptr;
    len = RSTRING(str)->len;
    pend = p + len;
    if (bits >= sizeof(long)*CHAR_BIT) {
        VALUE sum = INT2FIX(0);

        while (p < pend) {
            str_mod_check(str, ptr, len);
            sum = rb_funcall(sum, '+', 1, INT2FIX((unsigned char)*p));
            p++;
        }
        if (bits != 0) {
            VALUE mod;

            mod = rb_funcall(INT2FIX(1), rb_intern("<<"), 1, INT2FIX(bits));
            mod = rb_funcall(mod, '-', 1, INT2FIX(1));
            sum = rb_funcall(sum, '&', 1, mod);
        }
        return sum;
    }
    else {
       unsigned long sum = 0;

        while (p < pend) {
            str_mod_check(str, ptr, len);
            sum += (unsigned char)*p;
            p++;
        }
        if (bits != 0) {
           sum &= (((unsigned long)1)<<bits)-1;
        }
        return rb_int2inum(sum);
    }
}


slice (String)

/*
 *  call-seq:
 *     str[fixnum]                 => fixnum or nil
 *     str[fixnum, fixnum]         => new_str or nil
 *     str[range]                  => new_str or nil
 *     str[regexp]                 => new_str or nil
 *     str[regexp, fixnum]         => new_str or nil
 *     str[other_str]              => new_str or nil
 *     str.slice(fixnum)           => fixnum or nil
 *     str.slice(fixnum, fixnum)   => new_str or nil
 *     str.slice(range)            => new_str or nil
 *     str.slice(regexp)           => new_str or nil
 *     str.slice(regexp, fixnum)   => new_str or nil
 *     str.slice(other_str)        => new_str or nil
 *
 *  Element Reference---If passed a single <code>Fixnum</code>, returns the code
 *  of the character at that position. If passed two <code>Fixnum</code>
 *  objects, returns a substring starting at the offset given by the first, and
 *  a length given by the second. If given a range, a substring containing
 *  characters at offsets given by the range is returned. In all three cases, if
 *  an offset is negative, it is counted from the end of <i>str</i>. Returns
 *  <code>nil</code> if the initial offset falls outside the string, the length
 *  is negative, or the beginning of the range is greater than the end.
 *
 *  If a <code>Regexp</code> is supplied, the matching portion of <i>str</i> is
 *  returned. If a numeric parameter follows the regular expression, that
 *  component of the <code>MatchData</code> is returned instead. If a
 *  <code>String</code> is given, that string is returned if it occurs in
 *  <i>str</i>. In both cases, <code>nil</code> is returned if there is no
 *  match.
 *
 *     a = "hello there"
 *     a[1]                   #=> 101
 *     a[1,3]                 #=> "ell"
 *     a[1..3]                #=> "ell"
 *     a[-3,2]                #=> "er"
 *     a[-4..-2]              #=> "her"
 *     a[12..-1]              #=> nil
 *     a[-2..-4]              #=> ""
 *     a[/[aeiou](.)\1/]      #=> "ell"
 *     a[/[aeiou](.)\1/, 0]   #=> "ell"
 *     a[/[aeiou](.)\1/, 1]   #=> "l"
 *     a[/[aeiou](.)\1/, 2]   #=> nil
 *     a["lo"]                #=> "lo"
 *     a["bye"]               #=> nil
 */

static VALUE
rb_str_aref_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    if (argc == 2) {
        if (TYPE(argv[0]) == T_REGEXP) {
            return rb_str_subpat(str, argv[0], NUM2INT(argv[1]));
        }
        return rb_str_substr(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]));
    }
    if (argc != 1) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    return rb_str_aref(str, argv[0]);
}


slice! (String)

/*
 *  call-seq:
 *     str.slice!(fixnum)           => fixnum or nil
 *     str.slice!(fixnum, fixnum)   => new_str or nil
 *     str.slice!(range)            => new_str or nil
 *     str.slice!(regexp)           => new_str or nil
 *     str.slice!(other_str)        => new_str or nil
 *
 *  Deletes the specified portion from <i>str</i>, and returns the portion
 *  deleted. The forms that take a <code>Fixnum</code> will raise an
 *  <code>IndexError</code> if the value is out of range; the <code>Range</code>
 *  form will raise a <code>RangeError</code>, and the <code>Regexp</code> and
 *  <code>String</code> forms will silently ignore the assignment.
 *
 *     string = "this is a string"
 *     string.slice!(2)        #=> 105
 *     string.slice!(3..6)     #=> " is "
 *     string.slice!(/s.*t/)   #=> "sa st"
 *     string.slice!("r")      #=> "r"
 *     string                  #=> "thing"
 */

static VALUE
rb_str_slice_bang(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE result;
    VALUE buf[3];
    int i;

    if (argc < 1 || 2 < argc) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    for (i=0; i<argc; i++) {
        buf[i] = argv[i];
    }
    buf[i] = rb_str_new(0,0);
    result = rb_str_aref_m(argc, buf, str);
    if (!NIL_P(result)) {
        rb_str_aset_m(argc+1, buf, str);
    }
    return result;
}


mbchar? (String)

# File lib/jcode.rb, line 46
  def mbchar?
    case $KCODE[0]
    when ?s, ?S
      self =~ RE_SJIS
    when ?e, ?E
      self =~ RE_EUC
    when ?u, ?U
      self =~ RE_UTF8
    else
      nil
    end
  end


end_regexp (String)

# File lib/jcode.rb, line 59
  def end_regexp
    case $KCODE[0]
    when ?s, ?S
      /#{PATTERN_SJIS}$/on
    when ?e, ?E
      /#{PATTERN_EUC}$/on
    when ?u, ?U
      /#{PATTERN_UTF8}$/on
    else
      /.$/on
    end
  end


succ! (String)

# File lib/jcode.rb, line 78
  def succ!
    reg = end_regexp
    if  $KCODE != 'NONE' && self =~ reg
      succ_table = SUCC[$KCODE[0,1].downcase]
      begin
        self[-1] += succ_table[self[-1]]
        self[-2] += 1 if self[-1] == 0
      end while self !~ reg
      self
    else
      original_succ!
    end
  end


succ (String)

# File lib/jcode.rb, line 92
  def succ
    str = self.dup
    str.succ! or str
  end


tr! (String)

# File lib/jcode.rb, line 133
  def tr!(from, to)
    return nil if from == ""
    return self.delete!(from) if to == ""

    pattern = TrPatternCache[from] ||= /[#{_regex_quote(from)}]/
    if from[0] == ?^
      last = /.$/.match(to)[0]
      self.gsub!(pattern, last)
    else
      h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to)
      self.gsub!(pattern) do |c| h[c] end
    end
  end


tr (String)

# File lib/jcode.rb, line 147
  def tr(from, to)
    (str = self.dup).tr!(from, to) or str
  end


delete! (String)

# File lib/jcode.rb, line 151
  def delete!(del)
    return nil if del == ""
    self.gsub!(DeletePatternCache[del] ||= /[#{_regex_quote(del)}]+/, '')
  end


delete (String)

# File lib/jcode.rb, line 156
  def delete(del)
    (str = self.dup).delete!(del) or str
  end


squeeze! (String)

# File lib/jcode.rb, line 160
  def squeeze!(del=nil)
    return nil if del == ""
    pattern =
      if del
        SqueezePatternCache[del] ||= /([#{_regex_quote(del)}])\1+/
      else
        /(.|\n)\1+/
      end
    self.gsub!(pattern, '\1')
  end


squeeze (String)

# File lib/jcode.rb, line 171
  def squeeze(del=nil)
    (str = self.dup).squeeze!(del) or str
  end


tr_s! (String)

# File lib/jcode.rb, line 175
  def tr_s!(from, to)
    return self.delete!(from) if to.length == 0

    pattern = SqueezePatternCache[from] ||= /([#{_regex_quote(from)}])\1*/
    if from[0] == ?^
      last = /.$/.match(to)[0]
      self.gsub!(pattern, last)
    else
      h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to)
      self.gsub!(pattern) do h[$1] end
    end
  end


tr_s (String)

# File lib/jcode.rb, line 188
  def tr_s(from, to)
    (str = self.dup).tr_s!(from,to) or str
  end


chop! (String)

# File lib/jcode.rb, line 192
  def chop!
    self.gsub!(/(?:.|\r?\n)\z/, '')
  end


chop (String)

# File lib/jcode.rb, line 196
  def chop
    (str = self.dup).chop! or str
  end


jlength (String)

# File lib/jcode.rb, line 200
  def jlength
    self.gsub(/[^\Wa-zA-Z_\d]/, ' ').length
  end


jcount (String)

# File lib/jcode.rb, line 205
  def jcount(str)
    self.delete("^#{str}").jlength
  end


each_char (String)

# File lib/jcode.rb, line 209
  def each_char
    if block_given?
      scan(/./m) do |x|
        yield x
      end
    else
      scan(/./m)
    end
  end


quote (String)

# File lib/mkmf.rb, line 132
  def quote
    /\s/ =~ self ? "\"#{self}\"" : self
  end


scanf (String)

# File lib/scanf.rb, line 670
  def scanf(fstr,&b)
    if b
      block_scanf(fstr,&b)
    else
      fs =
        if fstr.is_a? Scanf::FormatString
          fstr
        else
          Scanf::FormatString.new(fstr)
        end
      fs.match(self)
    end
  end


block_scanf (String)

# File lib/scanf.rb, line 684
  def block_scanf(fstr,&b)
    fs = Scanf::FormatString.new(fstr)
    str = self.dup
    final = []
    begin
      current = str.scanf(fs)
      final.push(yield(current)) unless current.empty?
      str = fs.string_left
    end until current.empty? || str.empty?
    return final
  end


is_complex_yaml? (String)

# File lib/yaml/rubytypes.rb, line 142
    def is_complex_yaml?
        to_yaml_style or not to_yaml_properties.empty? or self =~ /\n.+/
    end


is_binary_data? (String)

# File lib/yaml/rubytypes.rb, line 145
    def is_binary_data?
        ( self.count( "^ -~", "^\r\n" ) / self.size > 0.3 || self.count( "\x00" ) > 0 ) unless empty?
    end


yaml_new (String)

# File lib/yaml/rubytypes.rb, line 148
    def String.yaml_new( klass, tag, val )
        val = val.unpack("m")[0] if tag == "tag:yaml.org,2002:binary"
        val = { 'str' => val } if String === val
        if Hash === val
            s = klass.allocate
            # Thank you, NaHi
            String.instance_method(:initialize).
                  bind(s).
                  call( val.delete( 'str' ) )
            val.each { |k,v| s.instance_variable_set( k, v ) }
            s
        else
            raise YAML::TypeError, "Invalid String: " + val.inspect
        end
    end


to_yaml (String)

# File lib/yaml/rubytypes.rb, line 163
        def to_yaml( opts = {} )
                YAML::quick_emit( is_complex_yaml? ? object_id : nil, opts ) do |out|
            if is_binary_data?
                out.scalar( "tag:yaml.org,2002:binary", [self].pack("m"), :literal )
            elsif to_yaml_properties.empty?
                out.scalar( taguri, self, self =~ /^:/ ? :quote2 : to_yaml_style )
            else
                out.map( taguri, to_yaml_style ) do |map|
                    map.add( 'str', "#{self}" )
                    to_yaml_properties.each do |m|
                        map.add( m, instance_variable_get( m ) )
                    end
                end
            end
        end
        end


kconv (String)

# File ext/nkf/lib/kconv.rb, line 277
  def kconv(out_code, in_code=Kconv::AUTO)
    Kconv::kconv(self, out_code, in_code)
  end


tojis (String)

# File ext/nkf/lib/kconv.rb, line 294
  def tojis; Kconv.tojis(self) end


toeuc (String)

# File ext/nkf/lib/kconv.rb, line 305
  def toeuc; Kconv.toeuc(self) end


tosjis (String)

# File ext/nkf/lib/kconv.rb, line 316
  def tosjis; Kconv.tosjis(self) end


toutf8 (String)

# File ext/nkf/lib/kconv.rb, line 327
  def toutf8; Kconv.toutf8(self) end


toutf16 (String)

# File ext/nkf/lib/kconv.rb, line 338
  def toutf16; Kconv.toutf16(self) end


iseuc (String)

# File ext/nkf/lib/kconv.rb, line 350
  def iseuc;    Kconv.iseuc(self) end


issjis (String)

# File ext/nkf/lib/kconv.rb, line 358
  def issjis;   Kconv.issjis(self) end


isutf8 (String)

# File ext/nkf/lib/kconv.rb, line 366
  def isutf8;   Kconv.isutf8(self) end


new (StringIO)

# File lib/yaml/stringio.rb, line 9
        def initialize(string="")
            @string=string
            @pos=0
            @eof=(string.size==0)
        end


pos (StringIO)

# File lib/yaml/stringio.rb, line 14
        def pos
            @pos
        end


eof (StringIO)

# File lib/yaml/stringio.rb, line 17
        def eof
            @eof
        end


readline (StringIO)

# File lib/yaml/stringio.rb, line 21
        def readline(rs=$/)
            if @eof
                raise EOFError
            else
                if p = @string[@pos..-1]=~rs
                    line = @string[@pos,p+1]
                else
                    line = @string[@pos..-1]
                end
                @pos+=line.size
                @eof =true if @pos==@string.size
                $_ = line
            end
        end


rewind (StringIO)

# File lib/yaml/stringio.rb, line 35
        def rewind
            seek(0,0)
        end


seek (StringIO)

# File lib/yaml/stringio.rb, line 38
        def seek(offset,whence)
            case whence
            when 0
                @pos=offset
            when 1
                @pos+=offset
            when 2
                @pos=@string.size+offset
            end
            @eof=(@pos>=@string.size)
            0
        end


open (StringIO)

/*
 * call-seq: StringIO.open(string=""[, mode]) {|strio| ...}
 *
 * Equivalent to StringIO.new except that when it is called with a block, it
 * yields with the new instance and closes it, and returns the result which
 * returned from the block.
 */
static VALUE
strio_s_open(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE obj = rb_class_new_instance(argc, argv, klass);
    if (!rb_block_given_p()) return obj;
    return rb_ensure(rb_yield, obj, strio_finalize, obj);
}


new (StringIO)

/*
 * call-seq: StringIO.new(string=""[, mode])
 *
 * Creates new StringIO instance from with _string_ and _mode_.
 */
static VALUE
strio_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct StringIO *ptr = check_strio(self);

    if (!ptr) {
        DATA_PTR(self) = ptr = strio_alloc();
    }
    rb_call_super(0, 0);
    strio_init(argc, argv, ptr);
    return self;
}


reopen (StringIO)

/*
 * call-seq:
 *   strio.reopen(other_StrIO)     -> strio
 *   strio.reopen(string, mode)    -> strio
 *
 * Reinitializes *strio* with the given <i>other_StrIO</i> or _string_
 * and _mode_ (see StringIO#new).
 */
static VALUE
strio_reopen(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    if (!OBJ_TAINTED(self)) rb_secure(4);
    if (argc == 1 && TYPE(*argv) != T_STRING) {
        return strio_copy(self, *argv);
    }
    strio_init(argc, argv, StringIO(self));
    return self;
}


string (StringIO)

/*
 * call-seq: strio.string     -> string
 *
 * Returns underlying String object, the subject of IO.
 */
static VALUE
strio_get_string(self)
    VALUE self;
{
    return StringIO(self)->string;
}


string= (StringIO)

/*
 * call-seq:
 *   strio.string = string  -> string
 *
 * Changes underlying String object, the subject of IO.
 */
static VALUE
strio_set_string(self, string)
    VALUE self, string;
{
    struct StringIO *ptr = StringIO(self);

    if (!OBJ_TAINTED(self)) rb_secure(4);
    ptr->flags &= ~FMODE_READWRITE;
    StringValue(string);
    ptr->flags = OBJ_FROZEN(string) ? FMODE_READABLE : FMODE_READWRITE;
    ptr->pos = 0;
    ptr->lineno = 0;
    return ptr->string = string;
}


lineno (StringIO)

/*
 * call-seq:
 *   strio.lineno    -> integer
 *
 * Returns the current line number in *strio*. The stringio must be
 * opened for reading. +lineno+ counts the number of times  +gets+ is
 * called, rather than the number of newlines  encountered. The two
 * values will differ if +gets+ is  called with a separator other than
 * newline.  See also the  <code>$.</code> variable.
 */
static VALUE
strio_get_lineno(self)
    VALUE self;
{
    return LONG2NUM(StringIO(self)->lineno);
}


lineno= (StringIO)

/*
 * call-seq:
 *   strio.lineno = integer    -> integer
 *
 * Manually sets the current line number to the given value.
 * <code>$.</code> is updated only on the next read.
 */
static VALUE
strio_set_lineno(self, lineno)
    VALUE self, lineno;
{
    StringIO(self)->lineno = NUM2LONG(lineno);
    return lineno;
}


binmode (StringIO)

/*
 * Returns *strio* itself.  Just for compatibility to IO.
 */
static VALUE
strio_self(self)
    VALUE self;
{
    StringIO(self);
    return self;
}


close (StringIO)

/*
 * call-seq:
 *   strio.close  -> nil
 *
 * Closes strio.  The *strio* is unavailable for any further data
 * operations; an +IOError+ is raised if such an attempt is made.
 */
static VALUE
strio_close(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    if (CLOSED(ptr)) {
        rb_raise(rb_eIOError, "closed stream");
    }
    ptr->flags &= ~FMODE_READWRITE;
    return Qnil;
}


close_read (StringIO)

/*
 * call-seq:
 *   strio.close_read    -> nil
 *
 * Closes the read end of a StringIO.  Will raise an +IOError+ if the
 * *strio* is not readable.
 */
static VALUE
strio_close_read(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    if (!READABLE(ptr)) {
        rb_raise(rb_eIOError, "closing non-duplex IO for reading");
    }
    ptr->flags &= ~FMODE_READABLE;
    return Qnil;
}


close_write (StringIO)

/*
 * call-seq:
 *   strio.close_write    -> nil
 *
 * Closes the write end of a StringIO.  Will raise an  +IOError+ if the
 * *strio* is not writeable.
 */
static VALUE
strio_close_write(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    if (!WRITABLE(ptr)) {
        rb_raise(rb_eIOError, "closing non-duplex IO for writing");
    }
    ptr->flags &= ~FMODE_WRITABLE;
    return Qnil;
}


closed? (StringIO)

/*
 * call-seq:
 *   strio.closed?    -> true or false
 *
 * Returns +true+ if *strio* is completely closed, +false+ otherwise.
 */
static VALUE
strio_closed(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    if (!CLOSED(ptr)) return Qfalse;
    return Qtrue;
}


closed_read? (StringIO)

/*
 * call-seq:
 *   strio.closed_read?    -> true or false
 *
 * Returns +true+ if *strio* is not readable, +false+ otherwise.
 */
static VALUE
strio_closed_read(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    if (READABLE(ptr)) return Qfalse;
    return Qtrue;
}


closed_write? (StringIO)

/*
 * call-seq:
 *   strio.closed_write?    -> true or false
 *
 * Returns +true+ if *strio* is not writable, +false+ otherwise.
 */
static VALUE
strio_closed_write(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    if (WRITABLE(ptr)) return Qfalse;
    return Qtrue;
}


eof (StringIO)

/*
 * call-seq:
 *   strio.eof     -> true or false
 *   strio.eof?    -> true or false
 *
 * Returns true if *strio* is at end of file. The stringio must be
 * opened for reading or an +IOError+ will be raised.
 */
static VALUE
strio_eof(self)
    VALUE self;
{
    struct StringIO *ptr = readable(StringIO(self));
    if (ptr->pos < RSTRING(ptr->string)->len) return Qfalse;
    return Qtrue;
}


eof? (StringIO)

/*
 * call-seq:
 *   strio.eof     -> true or false
 *   strio.eof?    -> true or false
 *
 * Returns true if *strio* is at end of file. The stringio must be
 * opened for reading or an +IOError+ will be raised.
 */
static VALUE
strio_eof(self)
    VALUE self;
{
    struct StringIO *ptr = readable(StringIO(self));
    if (ptr->pos < RSTRING(ptr->string)->len) return Qfalse;
    return Qtrue;
}


fcntl (StringIO)

/*
 * Raises NotImplementedError.
 */
static VALUE
strio_unimpl(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    StringIO(self);
    rb_notimplement();
    return Qnil;                /* not reached */
}


flush (StringIO)

/*
 * Returns *strio* itself.  Just for compatibility to IO.
 */
static VALUE
strio_self(self)
    VALUE self;
{
    StringIO(self);
    return self;
}


fsync (StringIO)

/*
 * Returns 0.  Just for compatibility to IO.
 */
static VALUE
strio_0(self)
    VALUE self;
{
    StringIO(self);
    return INT2FIX(0);
}


pos (StringIO)

/*
 * call-seq:
 *   strio.pos     -> integer
 *   strio.tell    -> integer
 *
 * Returns the current offset (in bytes) of *strio*.
 */
static VALUE
strio_get_pos(self)
    VALUE self;
{
    return LONG2NUM(StringIO(self)->pos);
}


pos= (StringIO)

/*
 * call-seq:
 *   strio.pos = integer    -> integer
 *
 * Seeks to the given position (in bytes) in *strio*.
 */
static VALUE
strio_set_pos(self, pos)
    VALUE self;
    VALUE pos;
{
    struct StringIO *ptr = StringIO(self);
    long p = NUM2LONG(pos);
    if (p < 0) {
        error_inval(0);
    }
    ptr->pos = p;
    ptr->flags &= ~STRIO_EOF;
    return pos;
}


rewind (StringIO)

/*
 * call-seq:
 *   strio.rewind    -> 0
 *
 * Positions *strio* to the beginning of input, resetting
 * +lineno+ to zero.
 */
static VALUE
strio_rewind(self)
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    ptr->pos = 0;
    ptr->lineno = 0;
    ptr->flags &= ~STRIO_EOF;
    return INT2FIX(0);
}


seek (StringIO)

/*
 * call-seq:
 *   strio.seek(amount, whence=SEEK_SET) -> 0
 *
 * Seeks to a given offset _amount_ in the stream according to
 * the value of _whence_ (see IO#seek).
 */
static VALUE
strio_seek(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE whence;
    struct StringIO *ptr = StringIO(self);
    long offset;

    rb_scan_args(argc, argv, "11", NULL, &whence);
    offset = NUM2LONG(argv[0]);
    switch (NIL_P(whence) ? 0 : NUM2LONG(whence)) {
      case 0:
        break;
      case 1:
        offset += ptr->pos;
        break;
      case 2:
        offset += RSTRING(ptr->string)->len;
        break;
      default:
        rb_raise(rb_eArgError, "invalid whence %ld", NUM2LONG(whence));
    }
    if (offset < 0) {
        error_inval(0);
    }
    ptr->pos = offset;
    ptr->flags &= ~STRIO_EOF;
    return INT2FIX(0);
}


sync (StringIO)

/*
 * call-seq:
 *   strio.sync    -> true
 *
 * Returns +true+ always.
 */
static VALUE
strio_get_sync(self)
    VALUE self;
{
    StringIO(self);
    return Qtrue;
}


sync= (StringIO)

/*
 * Returns the argument unchanged.  Just for compatibility to IO.
 */
static VALUE
strio_first(self, arg)
    VALUE self, arg;
{
    StringIO(self);
    return arg;
}


tell (StringIO)

/*
 * call-seq:
 *   strio.pos     -> integer
 *   strio.tell    -> integer
 *
 * Returns the current offset (in bytes) of *strio*.
 */
static VALUE
strio_get_pos(self)
    VALUE self;
{
    return LONG2NUM(StringIO(self)->pos);
}


path (StringIO)

/*
 * Returns +nil+.  Just for compatibility to IO.
 */
static VALUE
strio_nil(self)
    VALUE self;
{
    StringIO(self);
    return Qnil;
}


each (StringIO)

/*
 * call-seq:
 *   strio.each(sep_string=$/)      {|line| block }  -> strio
 *   strio.each_line(sep_string=$/) {|line| block }  -> strio
 *
 * See IO#each.
 */
static VALUE
strio_each(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    VALUE line;

    while (!NIL_P(line = strio_getline(argc, argv, readable(ptr)))) {
        rb_yield(line);
    }
    return self;
}


each_byte (StringIO)

/*
 * call-seq:
 *   strio.each_byte {|byte| block }  -> strio
 *
 * See IO#each_byte.
 */
static VALUE
strio_each_byte(self)
    VALUE self;
{
    struct StringIO *ptr = readable(StringIO(self));
    while (ptr->pos < RSTRING(ptr->string)->len) {
        char c = RSTRING(ptr->string)->ptr[ptr->pos++];
        rb_yield(CHR2FIX(c));
    }
    return Qnil;
}


each_line (StringIO)

/*
 * call-seq:
 *   strio.each(sep_string=$/)      {|line| block }  -> strio
 *   strio.each_line(sep_string=$/) {|line| block }  -> strio
 *
 * See IO#each.
 */
static VALUE
strio_each(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    VALUE line;

    while (!NIL_P(line = strio_getline(argc, argv, readable(ptr)))) {
        rb_yield(line);
    }
    return self;
}


getc (StringIO)

/*
 * call-seq:
 *   strio.getc   -> fixnum or nil
 *
 * See IO#getc.
 */
static VALUE
strio_getc(self)
    VALUE self;
{
    struct StringIO *ptr = readable(StringIO(self));
    int c;
    if (ptr->pos >= RSTRING(ptr->string)->len) {
        ptr->flags |= STRIO_EOF;
        return Qnil;
    }
    c = RSTRING(ptr->string)->ptr[ptr->pos++];
    return CHR2FIX(c);
}


ungetc (StringIO)

/*
 * call-seq:
 *   strio.ungetc(integer)   -> nil
 *
 * Pushes back one character (passed as a parameter) onto *strio*
 * such that a subsequent buffered read will return it.  Pushing back
 * behind the beginning of the buffer string is not possible.  Nothing
 * will be done if such an attempt is made.
 * In other case, there is no limitation for multiple pushbacks.
 */
static VALUE
strio_ungetc(self, ch)
    VALUE self, ch;
{
    struct StringIO *ptr = readable(StringIO(self));
    int cc = NUM2INT(ch);
    long len, pos = ptr->pos;

    if (cc != EOF && pos > 0) {
        if ((len = RSTRING(ptr->string)->len) < pos-- ||
            (unsigned char)RSTRING(ptr->string)->ptr[pos] !=
            (unsigned char)cc) {
            strio_extend(ptr, pos, 1);
            RSTRING(ptr->string)->ptr[pos] = cc;
            OBJ_INFECT(ptr->string, self);
        }
        --ptr->pos;
        ptr->flags &= ~STRIO_EOF;
    }
    return Qnil;
}


readchar (StringIO)

/*
 * call-seq:
 *   strio.readchar   -> fixnum
 *
 * See IO#readchar.
 */
static VALUE
strio_readchar(self)
    VALUE self;
{
    VALUE c = strio_getc(self);
    if (NIL_P(c)) rb_eof_error();
    return c;
}


gets (StringIO)

/*
 * call-seq:
 *   strio.gets(sep_string=$/)   -> string or nil
 *
 * See IO#gets.
 */
static VALUE
strio_gets(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE str = strio_getline(argc, argv, readable(StringIO(self)));

    rb_lastline_set(str);
    return str;
}


readline (StringIO)

/*
 * call-seq:
 *   strio.readline(sep_string=$/)   -> string
 *
 * See IO#readline.
 */
static VALUE
strio_readline(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE line = strio_getline(argc, argv, readable(StringIO(self)));
    if (NIL_P(line)) rb_eof_error();
    return line;
}


readlines (StringIO)

/*
 * call-seq:
 *   strio.readlines(sep_string=$/)  ->   array
 *
 * See IO#readlines.
 */
static VALUE
strio_readlines(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct StringIO *ptr = StringIO(self);
    VALUE ary = rb_ary_new(), line;
    while (!NIL_P(line = strio_getline(argc, argv, readable(ptr)))) {
        rb_ary_push(ary, line);
    }
    return ary;
}


read (StringIO)

/*
 * call-seq:
 *   strio.read([length [, buffer]])    -> string, buffer, or nil
 *
 * See IO#read.
 */
static VALUE
strio_read(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct StringIO *ptr = readable(StringIO(self));
    VALUE str = Qnil;
    long len, olen;

    switch (argc) {
      case 2:
        str = argv[1];
        StringValue(str);
        rb_str_modify(str);
      case 1:
        if (!NIL_P(argv[0])) {
            len = olen = NUM2LONG(argv[0]);
            if (len < 0) {
                rb_raise(rb_eArgError, "negative length %ld given", len);
            }
            if (len > 0 && ptr->pos >= RSTRING(ptr->string)->len) {
                ptr->flags |= STRIO_EOF;
                if (!NIL_P(str)) rb_str_resize(str, 0);
                return Qnil;
            }
            else if (ptr->flags & STRIO_EOF) {
                if (!NIL_P(str)) rb_str_resize(str, 0);
                return Qnil;
            }
            break;
        }
        /* fall through */
      case 0:
        olen = -1;
        len = RSTRING(ptr->string)->len;
        if (len <= ptr->pos) {
            ptr->flags |= STRIO_EOF;
            if (NIL_P(str)) {
                str = rb_str_new(0, 0);
            }
            else {
                rb_str_resize(str, 0);
            }
            return str;
        }
        else {
            len -= ptr->pos;
        }
        break;
      default:
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
    }
    if (NIL_P(str)) {
        str = rb_str_substr(ptr->string, ptr->pos, len);
    }
    else {
        long rest = RSTRING(ptr->string)->len - ptr->pos;
        if (len > rest) len = rest;
        rb_str_resize(str, len);
        MEMCPY(RSTRING(str)->ptr, RSTRING(ptr->string)->ptr + ptr->pos, char, len);
    }
    if (NIL_P(str)) {
        if (!(ptr->flags & STRIO_EOF)) str = rb_str_new(0, 0);
        len = 0;
    }
    else {
        ptr->pos += len = RSTRING(str)->len;
    }
    if (olen < 0 || olen > len) ptr->flags |= STRIO_EOF;
    return str;
}


sysread (StringIO)

/*
 * call-seq:
 *   strio.sysread(integer[, outbuf])    -> string
 *
 * Similar to #read, but raises +EOFError+ at end of string instead of
 * returning +nil+, as well as IO#sysread does.
 */
static VALUE
strio_sysread(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE val = strio_read(argc, argv, self);
    if (NIL_P(val) || RSTRING(val)->len == 0) {
        rb_eof_error();
    }
    return val;
}


write (StringIO)

/*
 * call-seq:
 *   strio.write(string)    -> integer
 *   strio.syswrite(string) -> integer
 *
 * Appends the given string to the underlying buffer string of *strio*.
 * The stream must be opened for writing.  If the argument is not a
 * string, it will be converted to a string using <code>to_s</code>.
 * Returns the number of bytes written.  See IO#write.
 */
static VALUE
strio_write(self, str)
    VALUE self, str;
{
    struct StringIO *ptr = writable(StringIO(self));
    long len, olen;

    if (TYPE(str) != T_STRING)
        str = rb_obj_as_string(str);
    len = RSTRING(str)->len;
    if (!len) return INT2FIX(0);
    check_modifiable(ptr);
    olen = RSTRING(ptr->string)->len;
    if (ptr->flags & FMODE_APPEND) {
        ptr->pos = olen;
    }
    if (ptr->pos == olen) {
        rb_str_cat(ptr->string, RSTRING(str)->ptr, len);
    }
    else {
        strio_extend(ptr, ptr->pos, len);
        rb_str_update(ptr->string, ptr->pos, len, str);
    }
    OBJ_INFECT(ptr->string, self);
    ptr->pos += len;
    return LONG2NUM(len);
}


putc (StringIO)

/*
 * call-seq:
 *   strio.putc(obj)    -> obj
 *
 * See IO#putc.
 */
static VALUE
strio_putc(self, ch)
    VALUE self, ch;
{
    struct StringIO *ptr = writable(StringIO(self));
    int c = NUM2CHR(ch);
    long olen;

    check_modifiable(ptr);
    olen = RSTRING(ptr->string)->len;
    if (ptr->flags & FMODE_APPEND) {
        ptr->pos = olen;
    }
    strio_extend(ptr, ptr->pos, 1);
    RSTRING(ptr->string)->ptr[ptr->pos++] = c;
    OBJ_INFECT(ptr->string, self);
    return ch;
}


syswrite (StringIO)

/*
 * call-seq:
 *   strio.write(string)    -> integer
 *   strio.syswrite(string) -> integer
 *
 * Appends the given string to the underlying buffer string of *strio*.
 * The stream must be opened for writing.  If the argument is not a
 * string, it will be converted to a string using <code>to_s</code>.
 * Returns the number of bytes written.  See IO#write.
 */
static VALUE
strio_write(self, str)
    VALUE self, str;
{
    struct StringIO *ptr = writable(StringIO(self));
    long len, olen;

    if (TYPE(str) != T_STRING)
        str = rb_obj_as_string(str);
    len = RSTRING(str)->len;
    if (!len) return INT2FIX(0);
    check_modifiable(ptr);
    olen = RSTRING(ptr->string)->len;
    if (ptr->flags & FMODE_APPEND) {
        ptr->pos = olen;
    }
    if (ptr->pos == olen) {
        rb_str_cat(ptr->string, RSTRING(str)->ptr, len);
    }
    else {
        strio_extend(ptr, ptr->pos, len);
        rb_str_update(ptr->string, ptr->pos, len, str);
    }
    OBJ_INFECT(ptr->string, self);
    ptr->pos += len;
    return LONG2NUM(len);
}


isatty (StringIO)

/*
 * Returns +false+.  Just for compatibility to IO.
 */
static VALUE
strio_false(self)
    VALUE self;
{
    StringIO(self);
    return Qfalse;
}


tty? (StringIO)

/*
 * Returns +false+.  Just for compatibility to IO.
 */
static VALUE
strio_false(self)
    VALUE self;
{
    StringIO(self);
    return Qfalse;
}


pid (StringIO)

/*
 * Returns +nil+.  Just for compatibility to IO.
 */
static VALUE
strio_nil(self)
    VALUE self;
{
    StringIO(self);
    return Qnil;
}


fileno (StringIO)

/*
 * Returns +nil+.  Just for compatibility to IO.
 */
static VALUE
strio_nil(self)
    VALUE self;
{
    StringIO(self);
    return Qnil;
}


size (StringIO)

/*
 * call-seq:
 *   strio.size   -> integer
 *
 * Returns the size of the buffer string.
 */
static VALUE
strio_size(self)
    VALUE self;
{
    VALUE string = StringIO(self)->string;
    if (NIL_P(string)) {
        rb_raise(rb_eIOError, "not opened");
    }
    return ULONG2NUM(RSTRING(string)->len);
}


length (StringIO)

/*
 * call-seq:
 *   strio.size   -> integer
 *
 * Returns the size of the buffer string.
 */
static VALUE
strio_size(self)
    VALUE self;
{
    VALUE string = StringIO(self)->string;
    if (NIL_P(string)) {
        rb_raise(rb_eIOError, "not opened");
    }
    return ULONG2NUM(RSTRING(string)->len);
}


truncate (StringIO)

/*
 * call-seq:
 *   strio.truncate(integer)    -> 0
 *
 * Truncates the buffer string to at most _integer_ bytes. The *strio*
 * must be opened for writing.
 */
static VALUE
strio_truncate(self, len)
    VALUE self, len;
{
    VALUE string = writable(StringIO(self))->string;
    long l = NUM2LONG(len);
    long plen = RSTRING(string)->len;
    if (l < 0) {
        error_inval("negative legnth");
    }
    rb_str_resize(string, l);
    if (plen < l) {
        MEMZERO(RSTRING(string)->ptr + plen, char, l - plen);
    }
    return len;
}


new (StringScanner)

/*
 * call-seq: StringScanner.new(string, dup = false)
 *
 * Creates a new StringScanner object to scan over the given +string+.
 * +dup+ argument is obsolete and not used now.
 */
static VALUE
strscan_initialize(int argc, VALUE *argv, VALUE self)
{
    struct strscanner *p;
    VALUE str, need_dup;

    Data_Get_Struct(self, struct strscanner, p);
    rb_scan_args(argc, argv, "11", &str, &need_dup);
    StringValue(str);
    p->str = str;

    return self;
}


initialize_copy (StringScanner)

/*
 * call-seq:
 *   dup
 *   clone
 *
 * Duplicates a StringScanner object.
 */
static VALUE
strscan_init_copy(VALUE vself, VALUE vorig)
{
    struct strscanner *self, *orig;

    Data_Get_Struct(vself, struct strscanner, self);
    check_strscan(vorig);
    Data_Get_Struct(vorig, struct strscanner, orig);
    if (self != orig) {
        self->flags = orig->flags;
        self->str = orig->str;
        self->prev = orig->prev;
        self->curr = orig->curr;
        re_copy_registers(&self->regs, &orig->regs);
    }
    return vself;
}


must_C_version (StringScanner)

/*
 * call-seq: StringScanner.must_C_version
 *
 * This method is defined for backward compatibility.
 */
static VALUE
strscan_s_mustc(VALUE self)
{
    return self;
}


reset (StringScanner)

/*
 * Reset the scan pointer (index 0) and clear matching data.
 */
static VALUE
strscan_reset(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    p->curr = 0;
    CLEAR_MATCH_STATUS(p);
    return self;
}


terminate (StringScanner)

/*
 * call-seq:
 *   terminate
 *   clear
 *
 * Set the scan pointer to the end of the string and clear matching data.
 */
static VALUE
strscan_terminate(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    p->curr = S_LEN(p);
    CLEAR_MATCH_STATUS(p);
    return self;
}


clear (StringScanner)

/*
 * Equivalent to #terminate.
 * This method is obsolete; use #terminate instead.
 */
static VALUE
strscan_clear(VALUE self)
{
    rb_warning("StringScanner#clear is obsolete; use #terminate instead");
    return strscan_terminate(self);
}


string (StringScanner)

/*
 * Returns the string being scanned.
 */
static VALUE
strscan_get_string(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return p->str;
}


string= (StringScanner)

/*
 * call-seq: string=(str)
 *
 * Changes the string being scanned to +str+ and resets the scanner.
 * Returns +str+.
 */
static VALUE
strscan_set_string(VALUE self, VALUE str)
{
    struct strscanner *p;

    Data_Get_Struct(self, struct strscanner, p);
    StringValue(str);
    p->str = rb_str_dup(str);
    rb_obj_freeze(p->str);
    p->curr = 0;
    CLEAR_MATCH_STATUS(p);
    return str;
}


concat (StringScanner)

/*
 * call-seq:
 *   concat(str)
 *   <<(str)
 *
 * Appends +str+ to the string being scanned.
 * This method does not affect scan pointer.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.scan(/Fri /)
 *   s << " +1000 GMT"
 *   s.string            # -> "Fri Dec 12 1975 14:39 +1000 GMT"
 *   s.scan(/Dec/)       # -> "Dec"
 */
static VALUE
strscan_concat(VALUE self, VALUE str)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    StringValue(str);
    rb_str_append(p->str, str);
    return self;
}


<< (StringScanner)

/*
 * call-seq:
 *   concat(str)
 *   <<(str)
 *
 * Appends +str+ to the string being scanned.
 * This method does not affect scan pointer.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.scan(/Fri /)
 *   s << " +1000 GMT"
 *   s.string            # -> "Fri Dec 12 1975 14:39 +1000 GMT"
 *   s.scan(/Dec/)       # -> "Dec"
 */
static VALUE
strscan_concat(VALUE self, VALUE str)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    StringValue(str);
    rb_str_append(p->str, str);
    return self;
}


pos (StringScanner)

/*
 * Returns the position of the scan pointer.  In the 'reset' position, this
 * value is zero.  In the 'terminated' position (i.e. the string is exhausted),
 * this value is the length of the string.
 *
 * In short, it's a 0-based index into the string.
 *
 *   s = StringScanner.new('test string')
 *   s.pos               # -> 0
 *   s.scan_until /str/  # -> "test str"
 *   s.pos               # -> 8
 *   s.terminate         # -> #<StringScanner fin>
 *   s.pos               # -> 11
 */
static VALUE
strscan_get_pos(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return INT2FIX(p->curr);
}


pos= (StringScanner)

/*
 * call-seq: pos=(n)
 *
 * Modify the scan pointer.
 *
 *   s = StringScanner.new('test string')
 *   s.pos = 7            # -> 7
 *   s.rest               # -> "ring"
 */
static VALUE
strscan_set_pos(VALUE self, VALUE v)
{
    struct strscanner *p;
    long i;

    GET_SCANNER(self, p);
    i = NUM2INT(v);
    if (i < 0) i += S_LEN(p);
    if (i < 0) rb_raise(rb_eRangeError, "index out of range");
    if (i > S_LEN(p)) rb_raise(rb_eRangeError, "index out of range");
    p->curr = i;
    return INT2NUM(i);
}


pointer (StringScanner)

/*
 * Returns the position of the scan pointer.  In the 'reset' position, this
 * value is zero.  In the 'terminated' position (i.e. the string is exhausted),
 * this value is the length of the string.
 *
 * In short, it's a 0-based index into the string.
 *
 *   s = StringScanner.new('test string')
 *   s.pos               # -> 0
 *   s.scan_until /str/  # -> "test str"
 *   s.pos               # -> 8
 *   s.terminate         # -> #<StringScanner fin>
 *   s.pos               # -> 11
 */
static VALUE
strscan_get_pos(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return INT2FIX(p->curr);
}


pointer= (StringScanner)

/*
 * call-seq: pos=(n)
 *
 * Modify the scan pointer.
 *
 *   s = StringScanner.new('test string')
 *   s.pos = 7            # -> 7
 *   s.rest               # -> "ring"
 */
static VALUE
strscan_set_pos(VALUE self, VALUE v)
{
    struct strscanner *p;
    long i;

    GET_SCANNER(self, p);
    i = NUM2INT(v);
    if (i < 0) i += S_LEN(p);
    if (i < 0) rb_raise(rb_eRangeError, "index out of range");
    if (i > S_LEN(p)) rb_raise(rb_eRangeError, "index out of range");
    p->curr = i;
    return INT2NUM(i);
}


scan (StringScanner)

/*
 * call-seq: scan(pattern) => String
 *
 * Tries to match with +pattern+ at the current position. If there's a match,
 * the scanner advances the "scan pointer" and returns the matched string.
 * Otherwise, the scanner returns +nil+.
 *
 *   s = StringScanner.new('test string')
 *   p s.scan(/\w+/)   # -> "test"
 *   p s.scan(/\w+/)   # -> nil
 *   p s.scan(/\s+/)   # -> " "
 *   p s.scan(/\w+/)   # -> "string"
 *   p s.scan(/./)     # -> nil
 *
 */
static VALUE
strscan_scan(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 1, 1, 1);
}


skip (StringScanner)

/*
 * call-seq: skip(pattern)
 *
 * Attempts to skip over the given +pattern+ beginning with the scan pointer.
 * If it matches, the scan pointer is advanced to the end of the match, and the
 * length of the match is returned.  Otherwise, +nil+ is returned.
 *
 * It's similar to #scan, but without returning the matched string.
 *
 *   s = StringScanner.new('test string')
 *   p s.skip(/\w+/)   # -> 4
 *   p s.skip(/\w+/)   # -> nil
 *   p s.skip(/\s+/)   # -> 1
 *   p s.skip(/\w+/)   # -> 6
 *   p s.skip(/./)     # -> nil
 *
 */
static VALUE
strscan_skip(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 1, 0, 1);
}


match? (StringScanner)

/*
 * call-seq: match?(pattern)
 *
 * Tests whether the given +pattern+ is matched from the current scan pointer.
 * Returns the length of the match, or +nil+.  The scan pointer is not advanced.
 *
 *   s = StringScanner.new('test string')
 *   p s.match?(/\w+/)   # -> 4
 *   p s.match?(/\w+/)   # -> 4
 *   p s.match?(/\s+/)   # -> nil
 */
static VALUE
strscan_match_p(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 0, 0, 1);
}


check (StringScanner)

/*
 * call-seq: check(pattern)
 *
 * This returns the value that #scan would return, without advancing the scan
 * pointer.  The match register is affected, though.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.check /Fri/               # -> "Fri"
 *   s.pos                       # -> 0
 *   s.matched                   # -> "Fri"
 *   s.check /12/                # -> nil
 *   s.matched                   # -> nil
 *
 * Mnemonic: it "checks" to see whether a #scan will return a value.
 */
static VALUE
strscan_check(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 0, 1, 1);
}


scan_full (StringScanner)

/*
 * call-seq: scan_full(pattern, return_string_p, advance_pointer_p)
 *
 * Tests whether the given +pattern+ is matched from the current scan pointer.
 * Returns the matched string if +return_string_p+ is true.
 * Advances the scan pointer if +advance_pointer_p+ is true.
 * The match register is affected.
 *
 * "full" means "#scan with full parameters".
 */
static VALUE
strscan_scan_full(VALUE self, VALUE re, VALUE s, VALUE f)
{
    return strscan_do_scan(self, re, RTEST(s), RTEST(f), 1);
}


scan_until (StringScanner)

/*
 * call-seq: scan_until(pattern)
 *
 * Scans the string _until_ the +pattern+ is matched.  Returns the substring up
 * to and including the end of the match, advancing the scan pointer to that
 * location. If there is no match, +nil+ is returned.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.scan_until(/1/)        # -> "Fri Dec 1"
 *   s.pre_match              # -> "Fri Dec "
 *   s.scan_until(/XYZ/)      # -> nil
 */
static VALUE
strscan_scan_until(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 1, 1, 0);
}


skip_until (StringScanner)

/*
 * call-seq: skip_until(pattern)
 *
 * Advances the scan pointer until +pattern+ is matched and consumed.  Returns
 * the number of bytes advanced, or +nil+ if no match was found.
 *
 * Look ahead to match +pattern+, and advance the scan pointer to the _end_
 * of the match.  Return the number of characters advanced, or +nil+ if the
 * match was unsuccessful.
 *
 * It's similar to #scan_until, but without returning the intervening string.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.skip_until /12/           # -> 10
 *   s                           #
 */
static VALUE
strscan_skip_until(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 1, 0, 0);
}


exist? (StringScanner)

/*
 * call-seq: exist?(pattern)
 *
 * Looks _ahead_ to see if the +pattern+ exists _anywhere_ in the string,
 * without advancing the scan pointer.  This predicates whether a #scan_until
 * will return a value.
 *
 *   s = StringScanner.new('test string')
 *   s.exist? /s/            # -> 3
 *   s.scan /test/           # -> "test"
 *   s.exist? /s/            # -> 6
 *   s.exist? /e/            # -> nil
 */
static VALUE
strscan_exist_p(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 0, 0, 0);
}


check_until (StringScanner)

/*
 * call-seq: check_until(pattern)
 *
 * This returns the value that #scan_until would return, without advancing the
 * scan pointer.  The match register is affected, though.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.check_until /12/          # -> "Fri Dec 12"
 *   s.pos                       # -> 0
 *   s.matched                   # -> 12
 *
 * Mnemonic: it "checks" to see whether a #scan_until will return a value.
 */
static VALUE
strscan_check_until(VALUE self, VALUE re)
{
    return strscan_do_scan(self, re, 0, 1, 0);
}


search_full (StringScanner)

/*
 * call-seq: search_full(pattern, return_string_p, advance_pointer_p)
 *
 * Scans the string _until_ the +pattern+ is matched.
 * Returns the matched string if +return_string_p+ is true, otherwise
 * returns the number of bytes advanced.
 * Advances the scan pointer if +advance_pointer_p+, otherwise not.
 * This method does affect the match register.
 */
static VALUE
strscan_search_full(VALUE self, VALUE re, VALUE s, VALUE f)
{
    return strscan_do_scan(self, re, RTEST(s), RTEST(f), 0);
}


getch (StringScanner)

/*
 * Scans one character and returns it.
 * This method is multi-byte character sensitive.
 * See also #get_byte.
 *
 *   s = StringScanner.new('ab')
 *   s.getch           # => "a"
 *   s.getch           # => "b"
 *   s.getch           # => nil
 *
 *   $KCODE = 'EUC'
 *   s = StringScanner.new("\244\242")
 *   s.getch           # => "\244\242"   # Japanese hira-kana "A" in EUC-JP
 *   s.getch           # => nil
 */
static VALUE
strscan_getch(VALUE self)
{
    struct strscanner *p;
    long len;

    GET_SCANNER(self, p);
    CLEAR_MATCH_STATUS(p);
    if (EOS_P(p))
        return Qnil;
    len = mbclen(*CURPTR(p));
    if (p->curr + len > S_LEN(p)) {
        len = S_LEN(p) - p->curr;
    }
    p->prev = p->curr;
    p->curr += len;
    MATCHED(p);
    adjust_registers_to_matched(p);
    return extract_range(p, p->prev + p->regs.beg[0],
                            p->prev + p->regs.end[0]);
}


get_byte (StringScanner)

/*
 * Scans one byte and returns it.
 * This method is NOT multi-byte character sensitive.
 * See also #getch.
 *
 *   s = StringScanner.new('ab')
 *   s.get_byte         # => "a"
 *   s.get_byte         # => "b"
 *   s.get_byte         # => nil
 *
 *   s = StringScanner.new("\244\242")
 *   s.get_byte         # => "\244"
 *   s.get_byte         # => "\242"
 *   s.get_byte         # => nil
 */
static VALUE
strscan_get_byte(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    CLEAR_MATCH_STATUS(p);
    if (EOS_P(p)) {
        return Qnil;
    }
    p->prev = p->curr;
    p->curr++;
    MATCHED(p);
    adjust_registers_to_matched(p);
    return extract_range(p, p->prev + p->regs.beg[0],
                            p->prev + p->regs.end[0]);
}


getbyte (StringScanner)

/*
 * Equivalent to #get_byte.
 * This method is obsolete; use #get_byte instead.
 */
static VALUE
strscan_getbyte(VALUE self)
{
    rb_warning("StringScanner#getbyte is obsolete; use #get_byte instead");
    return strscan_get_byte(self);
}


peek (StringScanner)

/*
 * call-seq: peek(len)
 *
 * Extracts a string corresponding to <tt>string[pos,len]</tt>, without
 * advancing the scan pointer.
 *
 *   s = StringScanner.new('test string')
 *   s.peek(7)          # => "test st"
 *   s.peek(7)          # => "test st"
 *
 */
static VALUE
strscan_peek(VALUE self, VALUE vlen)
{
    struct strscanner *p;
    long len;

    GET_SCANNER(self, p);
    len = NUM2LONG(vlen);
    if (EOS_P(p)) {
        return infect(rb_str_new("", 0), p);
    }
    if (p->curr + len > S_LEN(p)) {
        len = S_LEN(p) - p->curr;
    }
    return extract_beg_len(p, p->curr, len);
}


peep (StringScanner)

/*
 * Equivalent to #peek.
 * This method is obsolete; use #peek instead.
 */
static VALUE
strscan_peep(VALUE self, VALUE vlen)
{
    rb_warning("StringScanner#peep is obsolete; use #peek instead");
    return strscan_peek(self, vlen);
}


unscan (StringScanner)

/*
 * Set the scan pointer to the previous position.  Only one previous position is
 * remembered, and it changes with each scanning operation.
 *
 *   s = StringScanner.new('test string')
 *   s.scan(/\w+/)        # => "test"
 *   s.unscan
 *   s.scan(/../)         # => "te"
 *   s.scan(/\d/)         # => nil
 *   s.unscan             # ScanError: unscan failed: previous match had failed
 */
static VALUE
strscan_unscan(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p)) {
        rb_raise(ScanError, "unscan failed: previous match had failed");
    }
    p->curr = p->prev;
    CLEAR_MATCH_STATUS(p);
    return self;
}


beginning_of_line? (StringScanner)

/*
 * Returns +true+ iff the scan pointer is at the beginning of the line.
 *
 *   s = StringScanner.new("test\ntest\n")
 *   s.bol?           # => true
 *   s.scan(/te/)
 *   s.bol?           # => false
 *   s.scan(/st\n/)
 *   s.bol?           # => true
 *   s.terminate
 *   s.bol?           # => true
 */
static VALUE
strscan_bol_p(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (CURPTR(p) > S_PEND(p)) return Qnil;
    if (p->curr == 0) return Qtrue;
    return (*(CURPTR(p) - 1) == '\n') ? Qtrue : Qfalse;
}


eos? (StringScanner)

/*
 * Returns +true+ if the scan pointer is at the end of the string.
 *
 *   s = StringScanner.new('test string')
 *   p s.eos?          # => false
 *   s.scan(/test/)
 *   p s.eos?          # => false
 *   s.terminate
 *   p s.eos?          # => true
 */
static VALUE
strscan_eos_p(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return EOS_P(p) ? Qtrue : Qfalse;
}


empty? (StringScanner)

/*
 * Equivalent to #eos?.
 * This method is obsolete, use #eos? instead.
 */
static VALUE
strscan_empty_p(VALUE self)
{
    rb_warning("StringScanner#empty? is obsolete; use #eos? instead");
    return strscan_eos_p(self);
}


rest? (StringScanner)

/*
 * Returns true iff there is more data in the string.  See #eos?.
 * This method is obsolete; use #eos? instead.
 *
 *   s = StringScanner.new('test string')
 *   s.eos?              # These two
 *   s.rest?             # are opposites.
 */
static VALUE
strscan_rest_p(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return EOS_P(p) ? Qfalse : Qtrue;
}


matched? (StringScanner)

/*
 * Returns +true+ iff the last match was successful.
 *
 *   s = StringScanner.new('test string')
 *   s.match?(/\w+/)     # => 4
 *   s.matched?          # => true
 *   s.match?(/\d+/)     # => nil
 *   s.matched?          # => false
 */
static VALUE
strscan_matched_p(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    return MATCHED_P(p) ? Qtrue : Qfalse;
}


matched (StringScanner)

/*
 * Returns the last matched string.
 *
 *   s = StringScanner.new('test string')
 *   s.match?(/\w+/)     # -> 4
 *   s.matched           # -> "test"
 */
static VALUE
strscan_matched(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p)) return Qnil;

    return extract_range(p, p->prev + p->regs.beg[0],
                            p->prev + p->regs.end[0]);
}


matched_size (StringScanner)

/*
 * Returns the size of the most recent match (see #matched), or +nil+ if there
 * was no recent match.
 *
 *   s = StringScanner.new('test string')
 *   s.check /\w+/           # -> "test"
 *   s.matched_size          # -> 4
 *   s.check /\d+/           # -> nil
 *   s.matched_size          # -> nil
 */
static VALUE
strscan_matched_size(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p)) return Qnil;

    return INT2NUM(p->regs.end[0] - p->regs.beg[0]);
}


matchedsize (StringScanner)

/*
 * Equivalent to #matched_size.
 * This method is obsolete; use #matched_size instead.
 */
static VALUE
strscan_matchedsize(VALUE self)
{
    rb_warning("StringScanner#matchedsize is obsolete; use #matched_size instead");
    return strscan_matched_size(self);
}


[] (StringScanner)

/*
 * call-seq: [](n)
 *
 * Return the n-th subgroup in the most recent match.
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.scan(/(\w+) (\w+) (\d+) /)       # -> "Fri Dec 12 "
 *   s[0]                               # -> "Fri Dec 12 "
 *   s[1]                               # -> "Fri"
 *   s[2]                               # -> "Dec"
 *   s[3]                               # -> "12"
 *   s.post_match                       # -> "1975 14:39"
 *   s.pre_match                        # -> ""
 */
static VALUE
strscan_aref(VALUE self, VALUE idx)
{
    struct strscanner *p;
    long i;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p))        return Qnil;

    i = NUM2LONG(idx);
    if (i < 0)
        i += p->regs.num_regs;
    if (i < 0)                 return Qnil;
    if (i >= p->regs.num_regs) return Qnil;
    if (p->regs.beg[i] == -1)  return Qnil;

    return extract_range(p, p->prev + p->regs.beg[i],
                            p->prev + p->regs.end[i]);
}


pre_match (StringScanner)

/*
 * Return the <i><b>pre</b>-match</i> (in the regular expression sense) of the last scan.
 *
 *   s = StringScanner.new('test string')
 *   s.scan(/\w+/)           # -> "test"
 *   s.scan(/\s+/)           # -> " "
 *   s.pre_match             # -> "test"
 *   s.post_match            # -> "string"
 */
static VALUE
strscan_pre_match(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p)) return Qnil;

    return extract_range(p, 0, p->prev + p->regs.beg[0]);
}


post_match (StringScanner)

/*
 * Return the <i><b>post</b>-match</i> (in the regular expression sense) of the last scan.
 *
 *   s = StringScanner.new('test string')
 *   s.scan(/\w+/)           # -> "test"
 *   s.scan(/\s+/)           # -> " "
 *   s.pre_match             # -> "test"
 *   s.post_match            # -> "string"
 */
static VALUE
strscan_post_match(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (! MATCHED_P(p)) return Qnil;

    return extract_range(p, p->prev + p->regs.end[0], S_LEN(p));
}


rest (StringScanner)

/*
 * Returns the "rest" of the string (i.e. everything after the scan pointer).
 * If there is no more data (eos? = true), it returns <tt>""</tt>.
 */
static VALUE
strscan_rest(VALUE self)
{
    struct strscanner *p;

    GET_SCANNER(self, p);
    if (EOS_P(p)) {
        return infect(rb_str_new("", 0), p);
    }
    return extract_range(p, p->curr, S_LEN(p));
}


rest_size (StringScanner)

/*
 * <tt>s.rest_size</tt> is equivalent to <tt>s.rest.size</tt>.
 */
static VALUE
strscan_rest_size(VALUE self)
{
    struct strscanner *p;
    long i;

    GET_SCANNER(self, p);
    if (EOS_P(p)) {
        return INT2FIX(0);
    }

    i = S_LEN(p) - p->curr;
    return INT2FIX(i);
}


restsize (StringScanner)

/*
 * <tt>s.restsize</tt> is equivalent to <tt>s.rest_size</tt>.
 * This method is obsolete; use #rest_size instead.
 */
static VALUE
strscan_restsize(VALUE self)
{
    rb_warning("StringScanner#restsize is obsolete; use #rest_size instead");
    return strscan_rest_size(self);
}


inspect (StringScanner)

/*
 * Returns a string that represents the StringScanner object, showing:
 * - the current position
 * - the size of the string
 * - the characters surrounding the scan pointer
 *
 *   s = StringScanner.new("Fri Dec 12 1975 14:39")
 *   s.inspect            # -> '#<StringScanner 0/21 @ "Fri D...">'
 *   s.scan_until /12/    # -> "Fri Dec 12"
 *   s.inspect            # -> '#<StringScanner 10/21 "...ec 12" @ " 1975...">'
 */
static VALUE
strscan_inspect(VALUE self)
{
    struct strscanner *p;
    char buf[BUFSIZE];
    long len;
    VALUE a, b;

    Data_Get_Struct(self, struct strscanner, p);
    if (NIL_P(p->str)) {
        len = snprintf(buf, BUFSIZE, "#<%s (uninitialized)>",
                       rb_class2name(CLASS_OF(self)));
        return infect(rb_str_new(buf, len), p);
    }
    if (EOS_P(p)) {
        len = snprintf(buf, BUFSIZE, "#<%s fin>",
                       rb_class2name(CLASS_OF(self)));
        return infect(rb_str_new(buf, len), p);
    }
    if (p->curr == 0) {
        b = inspect2(p);
        len = snprintf(buf, BUFSIZE, "#<%s %ld/%ld @ %s>",
                       rb_class2name(CLASS_OF(self)),
                       p->curr, S_LEN(p),
                       RSTRING(b)->ptr);
        return infect(rb_str_new(buf, len), p);
    }
    a = inspect1(p);
    b = inspect2(p);
    len = snprintf(buf, BUFSIZE, "#<%s %ld/%ld %s @ %s>",
                   rb_class2name(CLASS_OF(self)),
                   p->curr, S_LEN(p),
                   RSTRING(a)->ptr,
                   RSTRING(b)->ptr);
    return infect(rb_str_new(buf, len), p);
}


new (Struct)

/*
 *  call-seq:
 *     Struct.new( [aString] [, aSym]+> )    => StructClass
 *     StructClass.new(arg, ...)             => obj
 *     StructClass[arg, ...]                 => obj
 *
 *  Creates a new class, named by <i>aString</i>, containing accessor
 *  methods for the given symbols. If the name <i>aString</i> is
 *  omitted, an anonymous structure class will be created. Otherwise,
 *  the name of this struct will appear as a constant in class
 *  <code>Struct</code>, so it must be unique for all
 *  <code>Struct</code>s in the system and should start with a capital
 *  letter. Assigning a structure class to a constant effectively gives
 *  the class the name of the constant.
 *
 *  <code>Struct::new</code> returns a new <code>Class</code> object,
 *  which can then be used to create specific instances of the new
 *  structure. The number of actual parameters must be
 *  less than or equal to the number of attributes defined for this
 *  class; unset parameters default to \nil{}.  Passing too many
 *  parameters will raise an \E{ArgumentError}.
 *
 *  The remaining methods listed in this section (class and instance)
 *  are defined for this generated class.
 *
 *     # Create a structure with a name in Struct
 *     Struct.new("Customer", :name, :address)    #=> Struct::Customer
 *     Struct::Customer.new("Dave", "123 Main")   #=> #<Struct::Customer name="Dave", address="123 Main">
 *
 *     # Create a structure named by its constant
 *     Customer = Struct.new(:name, :address)     #=> Customer
 *     Customer.new("Dave", "123 Main")           #=> #<Customer name="Dave", address="123 Main">
 */

static VALUE
rb_struct_s_def(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE name, rest;
    long i;
    VALUE st;
    ID id;

    rb_scan_args(argc, argv, "1*", &name, &rest);
    for (i=0; i<RARRAY(rest)->len; i++) {
        id = rb_to_id(RARRAY(rest)->ptr[i]);
        RARRAY(rest)->ptr[i] = ID2SYM(id);
    }
    if (!NIL_P(name)) {
        VALUE tmp = rb_check_string_type(name);

        if (NIL_P(tmp)) {
            id = rb_to_id(name);
            rb_ary_unshift(rest, ID2SYM(id));
            name = Qnil;
        }
    }
    st = make_struct(name, rest, klass);
    if (rb_block_given_p()) {
        rb_mod_module_eval(0, 0, st);
    }

    return st;
}


new (Struct)

/*
 */

static VALUE
rb_struct_initialize(self, values)
    VALUE self, values;
{
    VALUE klass = rb_obj_class(self);
    VALUE size;
    long n;

    rb_struct_modify(self);
    size = rb_struct_iv_get(klass, "__size__");
    n = FIX2LONG(size);
    if (n < RARRAY(values)->len) {
        rb_raise(rb_eArgError, "struct size differs");
    }
    MEMCPY(RSTRUCT(self)->ptr, RARRAY(values)->ptr, VALUE, RARRAY(values)->len);
    if (n > RARRAY(values)->len) {
        rb_mem_clear(RSTRUCT(self)->ptr+RARRAY(values)->len,
                     n-RARRAY(values)->len);
    }
    return Qnil;
}


== (Struct)

/*
 *  call-seq:
 *     struct == other_struct     => true or false
 *
 *  Equality---Returns <code>true</code> if <i>other_struct</i> is
 *  equal to this one: they must be of the same class as generated by
 *  <code>Struct::new</code>, and the values of all instance variables
 *  must be equal (according to <code>Object#==</code>).
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe   = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     jane  = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
 *     joe == joejr   #=> true
 *     joe == jane    #=> false
 */

static VALUE
rb_struct_equal(s, s2)
    VALUE s, s2;
{
    long i;

    if (s == s2) return Qtrue;
    if (TYPE(s2) != T_STRUCT) return Qfalse;
    if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
    if (RSTRUCT(s)->len != RSTRUCT(s2)->len) {
        rb_bug("inconsistent struct"); /* should never happen */
    }

    for (i=0; i<RSTRUCT(s)->len; i++) {
        if (!rb_equal(RSTRUCT(s)->ptr[i], RSTRUCT(s2)->ptr[i])) return Qfalse;
    }
    return Qtrue;
}


eql? (Struct)

/*
 * code-seq:
 *   struct.eql?(other)   => true or false
 *
 * Two structures are equal if they are the same object, or if all their
 * fields are equal (using <code>eql?</code>).
 */

static VALUE
rb_struct_eql(s, s2)
    VALUE s, s2;
{
    long i;

    if (s == s2) return Qtrue;
    if (TYPE(s2) != T_STRUCT) return Qfalse;
    if (rb_obj_class(s) != rb_obj_class(s2)) return Qfalse;
    if (RSTRUCT(s)->len != RSTRUCT(s2)->len) {
        rb_bug("inconsistent struct"); /* should never happen */
    }

    for (i=0; i<RSTRUCT(s)->len; i++) {
        if (!rb_eql(RSTRUCT(s)->ptr[i], RSTRUCT(s2)->ptr[i])) return Qfalse;
    }
    return Qtrue;
}


hash (Struct)

/*
 * call-seq:
 *   struct.hash   => fixnum
 *
 * Return a hash value based on this struct's contents.
 */

static VALUE
rb_struct_hash(s)
    VALUE s;
{
    long i, h;
    VALUE n;

    h = rb_hash(rb_obj_class(s));
    for (i = 0; i < RSTRUCT(s)->len; i++) {
        h = (h << 1) | (h<0 ? 1 : 0);
        n = rb_hash(RSTRUCT(s)->ptr[i]);
        h ^= NUM2LONG(n);
    }
    return LONG2FIX(h);
}


to_s (Struct)

/*
 * call-seq:
 *   struct.to_s      => string
 *   struct.inspect   => string
 *
 * Describe the contents of this struct in a string.
 */

static VALUE
rb_struct_inspect(s)
    VALUE s;
{
    if (rb_inspecting_p(s)) {
        char *cname = rb_class2name(rb_obj_class(s));
        size_t len = strlen(cname) + 14;
        VALUE str = rb_str_new(0, len);

        snprintf(RSTRING(str)->ptr, len+1, "#<struct %s:...>", cname);
        RSTRING(str)->len = strlen(RSTRING(str)->ptr);
        return str;
    }
    return rb_protect_inspect(inspect_struct, s, 0);
}


inspect (Struct)

/*
 * call-seq:
 *   struct.to_s      => string
 *   struct.inspect   => string
 *
 * Describe the contents of this struct in a string.
 */

static VALUE
rb_struct_inspect(s)
    VALUE s;
{
    if (rb_inspecting_p(s)) {
        char *cname = rb_class2name(rb_obj_class(s));
        size_t len = strlen(cname) + 14;
        VALUE str = rb_str_new(0, len);

        snprintf(RSTRING(str)->ptr, len+1, "#<struct %s:...>", cname);
        RSTRING(str)->len = strlen(RSTRING(str)->ptr);
        return str;
    }
    return rb_protect_inspect(inspect_struct, s, 0);
}


to_a (Struct)

/*
 *  call-seq:
 *     struct.to_a     => array
 *     struct.values   => array
 *
 *  Returns the values for this instance as an array.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.to_a[1]   #=> "123 Maple, Anytown NC"
 */

static VALUE
rb_struct_to_a(s)
    VALUE s;
{
    return rb_ary_new4(RSTRUCT(s)->len, RSTRUCT(s)->ptr);
}


values (Struct)

/*
 *  call-seq:
 *     struct.to_a     => array
 *     struct.values   => array
 *
 *  Returns the values for this instance as an array.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.to_a[1]   #=> "123 Maple, Anytown NC"
 */

static VALUE
rb_struct_to_a(s)
    VALUE s;
{
    return rb_ary_new4(RSTRUCT(s)->len, RSTRUCT(s)->ptr);
}


size (Struct)

/*
 *  call-seq:
 *     struct.length    => fixnum
 *     struct.size      => fixnum
 *
 *  Returns the number of instance variables.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.length   #=> 3
 */

static VALUE
rb_struct_size(s)
    VALUE s;
{
    return LONG2FIX(RSTRUCT(s)->len);
}


length (Struct)

/*
 *  call-seq:
 *     struct.length    => fixnum
 *     struct.size      => fixnum
 *
 *  Returns the number of instance variables.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.length   #=> 3
 */

static VALUE
rb_struct_size(s)
    VALUE s;
{
    return LONG2FIX(RSTRUCT(s)->len);
}


each (Struct)

/*
 *  call-seq:
 *     struct.each {|obj| block }  => struct
 *
 *  Calls <i>block</i> once for each instance variable, passing the
 *  value as a parameter.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.each {|x| puts(x) }
 *
 *  <em>produces:</em>
 *
 *     Joe Smith
 *     123 Maple, Anytown NC
 *     12345
 */

static VALUE
rb_struct_each(s)
    VALUE s;
{
    long i;

    for (i=0; i<RSTRUCT(s)->len; i++) {
        rb_yield(RSTRUCT(s)->ptr[i]);
    }
    return s;
}


each_pair (Struct)

/*
 *  call-seq:
 *     struct.each_pair {|sym, obj| block }     => struct
 *
 *  Calls <i>block</i> once for each instance variable, passing the name
 *  (as a symbol) and the value as parameters.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.each_pair {|name, value| puts("#{name} => #{value}") }
 *
 *  <em>produces:</em>
 *
 *     name => Joe Smith
 *     address => 123 Maple, Anytown NC
 *     zip => 12345
 */

static VALUE
rb_struct_each_pair(s)
    VALUE s;
{
    VALUE members;
    long i;

    members = rb_struct_members(s);
    for (i=0; i<RSTRUCT(s)->len; i++) {
        rb_yield_values(2, rb_ary_entry(members, i), RSTRUCT(s)->ptr[i]);
    }
    return s;
}


[] (Struct)

/*
 *  call-seq:
 *     struct[symbol]    => anObject
 *     struct[fixnum]    => anObject
 *
 *  Attribute Reference---Returns the value of the instance variable
 *  named by <i>symbol</i>, or indexed (0..length-1) by
 *  <i>fixnum</i>. Will raise <code>NameError</code> if the named
 *  variable does not exist, or <code>IndexError</code> if the index is
 *  out of range.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *
 *     joe["name"]   #=> "Joe Smith"
 *     joe[:name]    #=> "Joe Smith"
 *     joe[0]        #=> "Joe Smith"
 */

VALUE
rb_struct_aref(s, idx)
    VALUE s, idx;
{
    long i;

    if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
        return rb_struct_aref_id(s, rb_to_id(idx));
    }

    i = NUM2LONG(idx);
    if (i < 0) i = RSTRUCT(s)->len + i;
    if (i < 0)
        rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
                 i, RSTRUCT(s)->len);
    if (RSTRUCT(s)->len <= i)
        rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
                 i, RSTRUCT(s)->len);
    return RSTRUCT(s)->ptr[i];
}


[]= (Struct)

/*
 *  call-seq:
 *     struct[symbol] = obj    => obj
 *     struct[fixnum] = obj    => obj
 *
 *  Attribute Assignment---Assigns to the instance variable named by
 *  <i>symbol</i> or <i>fixnum</i> the value <i>obj</i> and
 *  returns it. Will raise a <code>NameError</code> if the named
 *  variable does not exist, or an <code>IndexError</code> if the index
 *  is out of range.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *
 *     joe["name"] = "Luke"
 *     joe[:zip]   = "90210"
 *
 *     joe.name   #=> "Luke"
 *     joe.zip    #=> "90210"
 */

VALUE
rb_struct_aset(s, idx, val)
    VALUE s, idx, val;
{
    long i;

    if (TYPE(idx) == T_STRING || TYPE(idx) == T_SYMBOL) {
        return rb_struct_aset_id(s, rb_to_id(idx), val);
    }

    i = NUM2LONG(idx);
    if (i < 0) i = RSTRUCT(s)->len + i;
    if (i < 0) {
        rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
                 i, RSTRUCT(s)->len);
    }
    if (RSTRUCT(s)->len <= i) {
        rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
                 i, RSTRUCT(s)->len);
    }
    rb_struct_modify(s);
    return RSTRUCT(s)->ptr[i] = val;
}


select (Struct)

/*
 *  call-seq:
 *     struct.select {|i| block }    => array
 *
 *  Invokes the block passing in successive elements from
 *  <i>struct</i>, returning an array containing those elements
 *  for which the block returns a true value (equivalent to
 *  <code>Enumerable#select</code>).
 *
 *     Lots = Struct.new(:a, :b, :c, :d, :e, :f)
 *     l = Lots.new(11, 22, 33, 44, 55, 66)
 *     l.select {|v| (v % 2).zero? }   #=> [22, 44, 66]
 */

static VALUE
rb_struct_select(argc, argv, s)
    int argc;
    VALUE *argv;
    VALUE s;
{
    VALUE result;
    long i;

    if (argc > 0) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
    }
    result = rb_ary_new();
    for (i = 0; i < RSTRUCT(s)->len; i++) {
        if (RTEST(rb_yield(RSTRUCT(s)->ptr[i]))) {
            rb_ary_push(result, RSTRUCT(s)->ptr[i]);
        }
    }

    return result;
}


values_at (Struct)

/*
 * call-seq:
 *   struct.values_at(selector,... )  => an_array
 *
 *   Returns an array containing the elements in
 *   _self_ corresponding to the given selector(s). The selectors
 *   may be either integer indices or ranges.
 *   See also </code>.select<code>.
 *
 *      a = %w{ a b c d e f }
 *      a.values_at(1, 3, 5)
 *      a.values_at(1, 3, 5, 7)
 *      a.values_at(-1, -3, -5, -7)
 *      a.values_at(1..3, 2...5)
 */

static VALUE
rb_struct_values_at(argc, argv, s)
    int argc;
    VALUE *argv;
    VALUE s;
{
    return rb_values_at(s, RSTRUCT(s)->len, argc, argv, struct_entry);
}


members (Struct)

/*
 *  call-seq:
 *     struct.members    => array
 *
 *  Returns an array of strings representing the names of the instance
 *  variables.
 *
 *     Customer = Struct.new(:name, :address, :zip)
 *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
 *     joe.members   #=> ["name", "address", "zip"]
 */

static VALUE
rb_struct_members_m(obj)
    VALUE obj;
{
    return rb_struct_s_members_m(rb_obj_class(obj));
}


pretty_print (Struct)

# File lib/pp.rb, line 331
  def pretty_print(q)
    q.group(1, '#<struct ' + PP.mcall(self, Kernel, :class).name, '>') {
      q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
        q.breakable
        q.text member.to_s
        q.text '='
        q.group(1) {
          q.breakable ''
          q.pp self[member]
        }
      }
    }
  end


pretty_print_cycle (Struct)

# File lib/pp.rb, line 345
  def pretty_print_cycle(q)
    q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
  end


yaml_tag_class_name (Struct)

# File lib/yaml/rubytypes.rb, line 50
    def self.yaml_tag_class_name; self.name.gsub( "Struct::", "" ); end


yaml_tag_read_class (Struct)

# File lib/yaml/rubytypes.rb, line 51
    def self.yaml_tag_read_class( name ); "Struct::#{ name }"; end


yaml_new (Struct)

# File lib/yaml/rubytypes.rb, line 52
    def self.yaml_new( klass, tag, val )
        if Hash === val
            struct_type = nil

            #
            # Use existing Struct if it exists
            #
            props = {}
            val.delete_if { |k,v| props[k] = v if k =~ /^@/ }
            begin
                struct_name, struct_type = YAML.read_type_class( tag, Struct )
            rescue NameError
            end
            if not struct_type
                struct_def = [ tag.split( ':', 4 ).last ]
                struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) )
            end

            #
            # Set the Struct properties
            #
            st = YAML::object_maker( struct_type, {} )
            st.members.each do |m|
                st.send( "#{m}=", val[m] )
            end
            props.each do |k,v|
                st.instance_variable_set(k, v)
            end
            st
        else
            raise YAML::TypeError, "Invalid Ruby Struct: " + val.inspect
        end
    end


to_yaml (Struct)

# File lib/yaml/rubytypes.rb, line 85
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
                        #
                        # Basic struct is passed as a YAML map
                        #
            out.map( taguri, to_yaml_style ) do |map|
                                self.members.each do |m|
                    map.add( m, self[m] )
                end
                                self.to_yaml_properties.each do |m|
                    map.add( m, instance_variable_get( m ) )
                end
            end
        end
        end


all_symbols (Symbol)

/*
 *  call-seq:
 *     Symbol.all_symbols    => array
 *
 *  Returns an array of all the symbols currently in Ruby's symbol
 *  table.
 *
 *     Symbol.all_symbols.size    #=> 903
 *     Symbol.all_symbols[1,20]   #=> [:floor, :ARGV, :Binding, :symlink,
 *                                     :chown, :EOFError, :$;, :String,
 *                                     :LOCK_SH, :"setuid?", :$<,
 *                                     :default_proc, :compact, :extend,
 *                                     :Tms, :getwd, :$=, :ThreadGroup,
 *                                     :wait2, :$>]
 */

VALUE
rb_sym_all_symbols()
{
    VALUE ary = rb_ary_new2(sym_tbl->num_entries);

    st_foreach(sym_tbl, symbols_i, ary);
    return ary;
}


to_i (Symbol)

/*
 *  call-seq:
 *     sym.to_i      => fixnum
 *
 *  Returns an integer that is unique for each symbol within a
 *  particular execution of a program.
 *
 *     :fred.to_i           #=> 9809
 *     "fred".to_sym.to_i   #=> 9809
 */

static VALUE
sym_to_i(sym)
    VALUE sym;
{
    ID id = SYM2ID(sym);

    return LONG2FIX(id);
}


to_int (Symbol)

/* :nodoc: */

static VALUE
sym_to_int(sym)
    VALUE sym;
{
    rb_warning("treating Symbol as an integer");
    return sym_to_i(sym);
}


inspect (Symbol)

/*
 *  call-seq:
 *     sym.inspect    => string
 *
 *  Returns the representation of <i>sym</i> as a symbol literal.
 *
 *     :fred.inspect   #=> ":fred"
 */

static VALUE
sym_inspect(sym)
    VALUE sym;
{
    VALUE str;
    char *name;
    ID id = SYM2ID(sym);

    name = rb_id2name(id);
    str = rb_str_new(0, strlen(name)+1);
    RSTRING(str)->ptr[0] = ':';
    strcpy(RSTRING(str)->ptr+1, name);
    if (!rb_symname_p(name)) {
        str = rb_str_dump(str);
        strncpy(RSTRING(str)->ptr, ":\"", 2);
    }
    return str;
}


to_s (Symbol)

/*
 *  call-seq:
 *     sym.id2name   => string
 *     sym.to_s      => string
 *
 *  Returns the name or string corresponding to <i>sym</i>.
 *
 *     :fred.id2name   #=> "fred"
 */

static VALUE
sym_to_s(sym)
    VALUE sym;
{
    return rb_str_new2(rb_id2name(SYM2ID(sym)));
}


id2name (Symbol)

/*
 *  call-seq:
 *     sym.id2name   => string
 *     sym.to_s      => string
 *
 *  Returns the name or string corresponding to <i>sym</i>.
 *
 *     :fred.id2name   #=> "fred"
 */

static VALUE
sym_to_s(sym)
    VALUE sym;
{
    return rb_str_new2(rb_id2name(SYM2ID(sym)));
}


to_sym (Symbol)

/*
 * call-seq:
 *   sym.to_sym   => sym
 *
 * In general, <code>to_sym</code> returns the <code>Symbol</code> corresponding
 * to an object. As <i>sym</i> is already a symbol, <code>self</code> is returned
 * in this case.
 */

static VALUE
sym_to_sym(sym)
    VALUE sym;
{
    return sym;
}


=== (Symbol)

/*
 *  call-seq:
 *     obj == other        => true or false
 *     obj.equal?(other)   => true or false
 *     obj.eql?(other)     => true or false
 *
 *  Equality---At the <code>Object</code> level, <code>==</code> returns
 *  <code>true</code> only if <i>obj</i> and <i>other</i> are the
 *  same object. Typically, this method is overridden in descendent
 *  classes to provide class-specific meaning.
 *
 *  Unlike <code>==</code>, the <code>equal?</code> method should never be
 *  overridden by subclasses: it is used to determine object identity
 *  (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same
 *  object as <code>b</code>).
 *
 *  The <code>eql?</code> method returns <code>true</code> if
    <i>obj</i> and <i>anObject</i> have the
 *  same value. Used by <code>Hash</code> to test members for equality.
 *  For objects of class <code>Object</code>, <code>eql?</code> is
 *  synonymous with <code>==</code>. Subclasses normally continue this
 *  tradition, but there are exceptions. <code>Numeric</code> types, for
 *  example, perform type conversion across <code>==</code>, but not
 *  across <code>eql?</code>, so:
 *
 *     1 == 1.0     #=> true
 *     1.eql? 1.0   #=> false
 */

static VALUE
rb_obj_equal(obj1, obj2)
    VALUE obj1, obj2;
{
    if (obj1 == obj2) return Qtrue;
    return Qfalse;
}


dclone (Symbol)

# File lib/rexml/xpath_parser.rb, line 13
  def dclone ; self ; end


yaml_new (Symbol)

# File lib/yaml/rubytypes.rb, line 184
    def Symbol.yaml_new( klass, tag, val )
        if String === val
            val = YAML::load( val ) if val =~ /\A(["']).*\1\z/
            val.intern
        else
            raise YAML::TypeError, "Invalid Symbol: " + val.inspect
        end
    end


to_yaml (Symbol)

# File lib/yaml/rubytypes.rb, line 192
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( "tag:yaml.org,2002:str", self.inspect, :plain )
        end
        end


new (Sync)

# File lib/sync.rb, line 306
  def initialize
    super
  end


Fail (Sync_m::Err::LockModeFailer)

# File lib/sync.rb, line 69
      def LockModeFailer.Fail(mode)
        if mode.id2name
          mode = id2name
        end
        super(mode)
      end


Fail (Sync_m::Err::UnknownLocker)

# File lib/sync.rb, line 62
      def UnknownLocker.Fail(th)
        super(th.inspect)
      end


Fail (Sync_m::Err)

# File lib/sync.rb, line 56
    def Err.Fail(*opt)
      fail self, sprintf(self::Message, *opt)
    end


define_aliases (Sync_m)

# File lib/sync.rb, line 78
  def Sync_m.define_aliases(cl)
    cl.module_eval %q{
      alias locked? sync_locked?
      alias shared? sync_shared?
      alias exclusive? sync_exclusive?
      alias lock sync_lock
      alias unlock sync_unlock
      alias try_lock sync_try_lock
      alias synchronize sync_synchronize
    }
  end


append_features (Sync_m)

# File lib/sync.rb, line 90
  def Sync_m.append_features(cl)
    super
    unless cl.instance_of?(Module)
      # do nothing for Modules
      # make aliases and include the proper module.
      define_aliases(cl)
    end
  end


extend_object (Sync_m)

# File lib/sync.rb, line 99
  def Sync_m.extend_object(obj)
    super
    obj.sync_extended
  end


sync_extended (Sync_m)

# File lib/sync.rb, line 104
  def sync_extended
    unless (defined? locked? and
            defined? shared? and
            defined? exclusive? and
            defined? lock and
            defined? unlock and
            defined? try_lock and
            defined? synchronize)
      Sync_m.define_aliases(class<<self;self;end)
    end
    sync_initialize
  end


sync_locked? (Sync_m)

# File lib/sync.rb, line 118
  def sync_locked?
    sync_mode != UN
  end


sync_shared? (Sync_m)

# File lib/sync.rb, line 122
  def sync_shared?
    sync_mode == SH
  end


sync_exclusive? (Sync_m)

# File lib/sync.rb, line 126
  def sync_exclusive?
    sync_mode == EX
  end


sync_try_lock (Sync_m)

# File lib/sync.rb, line 131
  def sync_try_lock(mode = EX)
    return unlock if sync_mode == UN

    Thread.critical = true
    ret = sync_try_lock_sub(sync_mode)
    Thread.critical = false
    ret
  end


sync_lock (Sync_m)

# File lib/sync.rb, line 140
  def sync_lock(m = EX)
    return unlock if m == UN

    until (Thread.critical = true; sync_try_lock_sub(m))
      if sync_sh_locker[Thread.current]
        sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]]
        sync_sh_locker.delete(Thread.current)
      else
        sync_waiting.push Thread.current
      end
      Thread.stop
    end
    Thread.critical = false
    self
  end


sync_unlock (Sync_m)

# File lib/sync.rb, line 156
  def sync_unlock(m = EX)
    Thread.critical = true
    if sync_mode == UN
      Thread.critical = false
      Err::UnknownLocker.Fail(Thread.current)
    end

    m = sync_mode if m == EX and sync_mode == SH

    runnable = false
    case m
    when UN
      Thread.critical = false
      Err::UnknownLocker.Fail(Thread.current)

    when EX
      if sync_ex_locker == Thread.current
        if (self.sync_ex_count = sync_ex_count - 1) == 0
          self.sync_ex_locker = nil
          if sync_sh_locker.include?(Thread.current)
            self.sync_mode = SH
          else
            self.sync_mode = UN
          end
          runnable = true
        end
      else
        Err::UnknownLocker.Fail(Thread.current)
      end

    when SH
      if (count = sync_sh_locker[Thread.current]).nil?
        Err::UnknownLocker.Fail(Thread.current)
      else
        if (sync_sh_locker[Thread.current] = count - 1) == 0
          sync_sh_locker.delete(Thread.current)
          if sync_sh_locker.empty? and sync_ex_count == 0
            self.sync_mode = UN
            runnable = true
          end
        end
      end
    end

    if runnable
      if sync_upgrade_waiting.size > 0
        for k, v in sync_upgrade_waiting
          sync_sh_locker[k] = v
        end
        wait = sync_upgrade_waiting
        self.sync_upgrade_waiting = []
        Thread.critical = false

        for w, v in wait
          w.run
        end
      else
        wait = sync_waiting
        self.sync_waiting = []
        Thread.critical = false
        for w in wait
          w.run
        end
      end
    end

    Thread.critical = false
    self
  end


sync_synchronize (Sync_m)

# File lib/sync.rb, line 226
  def sync_synchronize(mode = EX)
    begin
      sync_lock(mode)
      yield
    ensure
      sync_unlock
    end
  end


new (Sync_m)

# File lib/sync.rb, line 254
  def initialize(*args)
    sync_initialize
    super
  end


new (SyncEnumerator)

# File lib/generator.rb, line 186
  def initialize(*enums)
    @gens = enums.map { |e| Generator.new(e) }
  end


size (SyncEnumerator)

# File lib/generator.rb, line 192
  def size
    @gens.size
  end


length (SyncEnumerator)

# File lib/generator.rb, line 198
  def length
    @gens.length
  end


end? (SyncEnumerator)

# File lib/generator.rb, line 205
  def end?(i = nil)
    if i.nil?
      @gens.detect { |g| g.end? } ? true : false
    else
      @gens[i].end?
    end
  end


each (SyncEnumerator)

# File lib/generator.rb, line 214
  def each
    @gens.each { |g| g.rewind }

    loop do
      count = 0

      ret = @gens.map { |g|
        if g.end?
          count += 1
          nil
        else
          g.next
        end
      }

      if count == @gens.size
        break
      end

      yield ret
    end

    self
  end


new (SystemCallError)

/*
 * call-seq:
 *   SystemCallError.new(msg, errno)  => system_call_error_subclass
 *
 * If _errno_ corresponds to a known system error code, constructs
 * the appropriate <code>Errno</code> class for that error, otherwise
 * constructs a generic <code>SystemCallError</code> object. The
 * error number is subsequently available via the <code>errno</code>
 * method.
 */

static VALUE
syserr_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
#if !defined(_WIN32) && !defined(__VMS)
    char *strerror();
#endif
    char *err;
    VALUE mesg, error;
    VALUE klass = rb_obj_class(self);

    if (klass == rb_eSystemCallError) {
        rb_scan_args(argc, argv, "11", &mesg, &error);
        if (argc == 1 && FIXNUM_P(mesg)) {
            error = mesg; mesg = Qnil;
        }
        if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &klass)) {
            /* change class */
            if (TYPE(self) != T_OBJECT) { /* insurance to avoid type crash */
                rb_raise(rb_eTypeError, "invalid instance type");
            }
            RBASIC(self)->klass = klass;
        }
    }
    else {
        rb_scan_args(argc, argv, "01", &mesg);
        error = rb_const_get(klass, rb_intern("Errno"));
    }
    if (!NIL_P(error)) err = strerror(NUM2LONG(error));
    else err = "unknown error";
    if (!NIL_P(mesg)) {
        VALUE str = mesg;
        size_t len;

        StringValue(str);
        len = strlen(err)+RSTRING(str)->len+3;
        mesg = rb_str_new(0, len);
        snprintf(RSTRING(mesg)->ptr, len+1, "%s - %.*s", err,
                (int)RSTRING(str)->len, RSTRING(str)->ptr);
        rb_str_resize(mesg, strlen(RSTRING(mesg)->ptr));
    }
    else {
        mesg = rb_str_new2(err);
    }
    rb_call_super(1, &mesg);
    rb_iv_set(self, "errno", error);
    return self;
}


errno (SystemCallError)

/*
 * call-seq:
 *   system_call_error.errno   => fixnum
 *
 * Return this SystemCallError's error number.
 */

static VALUE
syserr_errno(self)
    VALUE self;
{
    return rb_attr_get(self, rb_intern("errno"));
}


=== (SystemCallError)

/*
 * call-seq:
 *   system_call_error === other  => true or false
 *
 * Return +true+ if the receiver is a generic +SystemCallError+, or
 * if the error numbers _self_ and _other_ are the same.
 */

static VALUE
syserr_eqq(self, exc)
    VALUE self, exc;
{
    VALUE num, e;

    if (!rb_obj_is_kind_of(exc, rb_eSystemCallError)) return Qfalse;
    if (self == rb_eSystemCallError) return Qtrue;

    num = rb_attr_get(exc, rb_intern("errno"));
    if (NIL_P(num)) {
        VALUE klass = CLASS_OF(exc);

        while (TYPE(klass) == T_ICLASS || FL_TEST(klass, FL_SINGLETON)) {
            klass = (VALUE)RCLASS(klass)->super;
        }
        num = rb_const_get(klass, rb_intern("Errno"));
    }
    e = rb_const_get(self, rb_intern("Errno"));
    if (FIXNUM_P(num) ? num == e : rb_equal(num, e))
        return Qtrue;
    return Qfalse;
}


new (SystemExit)

/*
 * call-seq:
 *   SystemExit.new(status=0)   => system_exit
 *
 * Create a new +SystemExit+ exception with the given status.
 */

static VALUE
exit_initialize(argc, argv, exc)
    int argc;
    VALUE *argv;
    VALUE exc;
{
    VALUE status = INT2FIX(EXIT_SUCCESS);
    if (argc > 0 && FIXNUM_P(argv[0])) {
        status = *argv++;
        --argc;
    }
    rb_call_super(argc, argv);
    rb_iv_set(exc, "status", status);
    return exc;
}


status (SystemExit)

/*
 * call-seq:
 *   system_exit.status   => fixnum
 *
 * Return the status value associated with this system exit.
 */

static VALUE
exit_status(exc)
    VALUE exc;
{
    return rb_attr_get(exc, rb_intern("status"));
}


success? (SystemExit)

/*
 * call-seq:
 *   system_exit.success?  => true or false
 *
 * Returns +true+ if exiting successful, +false+ if not.
 */

static VALUE
exit_success_p(exc)
    VALUE exc;
{
    VALUE status = rb_attr_get(exc, rb_intern("status"));
    if (NIL_P(status)) return Qtrue;
    if (status == INT2FIX(EXIT_SUCCESS)) return Qtrue;
    return Qfalse;
}


accept_nonblock (TCPServer)

/*
 * call-seq:
 *      tcpserver.accept_nonblock => tcpsocket
 *
 * Accepts an incoming connection using accept(2) after
 * O_NONBLOCK is set for the underlying file descriptor.
 * It returns an accepted TCPSocket for the incoming connection.
 *
 * === Example
 *      require 'socket'
 *      serv = TCPServer.new(2202)
 *      begin
 *        sock = serv.accept_nonblock
 *      rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
 *        IO.select([serv])
 *        retry
 *      end
 *      # sock is an accepted socket.
 *
 * Refer to Socket#accept for the exceptions that may be thrown if the call
 * to TCPServer#accept_nonblock fails.
 *
 * TCPServer#accept_nonblock may raise any error corresponding to accept(2) failure,
 * including Errno::EAGAIN.
 *
 * === See
 * * TCPServer#accept
 * * Socket#accept
 */
static VALUE
tcp_accept_nonblock(sock)
    VALUE sock;
{
    OpenFile *fptr;
    struct sockaddr_storage from;
    socklen_t fromlen;

    GetOpenFile(sock, fptr);
    fromlen = sizeof(from);
    return s_accept_nonblock(rb_cTCPSocket, fptr,
                             (struct sockaddr *)&from, &fromlen);
}


listen (TCPServer)

/*
 * call-seq:
 *      socket.listen( int ) => 0
 *
 * Listens for connections, using the specified +int+ as the backlog. A call
 * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
 * SOCK_SEQPACKET.
 *
 * === Parameter
 * * +backlog+ - the maximum length of the queue for pending connections.
 *
 * === Example 1
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *      socket.listen( 5 )
 *
 * === Example 2 (listening on an arbitary port, unix-based systems only):
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      socket.listen( 1 )
 *
 * === Unix-based Exceptions
 * On unix based systems the above will work because a new +sockaddr+ struct
 * is created on the address ADDR_ANY, for an arbitrary port number as handed
 * off by the kernel. It will not work on Windows, because Windows requires that
 * the +socket+ is bound by calling _bind_ before it can _listen_.
 *
 * If the _backlog_ amount exceeds the implementation-dependent maximum
 * queue length, the implementation's maximum queue length will be used.
 *
 * On unix-based based systems the following system exceptions may be raised if the
 * call to _listen_ fails:
 * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
 * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
 *   the protocol does not support listening on an unbound socket
 * * Errno::EINVAL - the _socket_ is already connected
 * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
 * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
 * * Errno::EACCES - the calling process does not have approriate privileges
 * * Errno::EINVAL - the _socket_ has been shut down
 * * Errno::ENOBUFS - insufficient resources are available in the system to
 *   complete the call
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _listen_ fails:
 * * Errno::ENETDOWN - the network is down
 * * Errno::EADDRINUSE - the socket's local address is already in use. This
 *   usually occurs during the execution of _bind_ but could be delayed
 *   if the call to _bind_ was to a partially wildcard address (involving
 *   ADDR_ANY) and if a specific address needs to be commmitted at the
 *   time of the call to _listen_
 * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
 *   service provider is still processing a callback function
 * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
 * * Errno::EISCONN - the +socket+ is already connected
 * * Errno::EMFILE - no more socket descriptors are available
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOTSOC - +socket+ is not a socket
 * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
 *   the _listen_ method
 *
 * === See
 * * listen manual pages on unix-based systems
 * * listen function in Microsoft's Winsock functions reference
 */
static VALUE
sock_listen(sock, log)
    VALUE sock, log;
{
    OpenFile *fptr;
    int backlog;

    rb_secure(4);
    backlog = NUM2INT(log);
    GetOpenFile(sock, fptr);
    if (listen(fileno(fptr->f), backlog) < 0)
        rb_sys_fail("listen(2)");

    return INT2FIX(0);
}


new (TCPSocket)

# File lib/resolv-replace.rb, line 17
  def initialize(host, serv, *rest)
    rest[0] = IPSocket.getaddress(rest[0]) unless rest.empty?
    original_resolv_initialize(IPSocket.getaddress(host), serv, *rest)
  end


new (TCPSocket)

/*
 * call-seq:
 *    TCPSocket.new(remote_host, remote_port, local_host=nil, local_port=nil)
 *
 * Opens a TCP connection to +remote_host+ on +remote_port+.  If +local_host+
 * and +local_port+ are specified, then those parameters are used on the local
 * end to establish the connection.
 */
static VALUE
tcp_init(argc, argv, sock)
     int argc;
     VALUE *argv;
     VALUE sock;
{
    VALUE remote_host, remote_serv;
    VALUE local_host, local_serv;

    rb_scan_args(argc, argv, "22", &remote_host, &remote_serv,
                        &local_host, &local_serv);

    return init_inetsock(sock, remote_host, remote_serv,
                        local_host, local_serv, INET_CLIENT);
}


new (Tempfile)

# File lib/tempfile.rb, line 24
  def initialize(basename, tmpdir=Dir::tmpdir)
    if $SAFE > 0 and tmpdir.tainted?
      tmpdir = '/tmp'
    end

    lock = nil
    n = failure = 0

    begin
      Thread.critical = true

      begin
        tmpname = File.join(tmpdir, make_tmpname(basename, n))
        lock = tmpname + '.lock'
        n += 1
      end while @@cleanlist.include?(tmpname) or
        File.exist?(lock) or File.exist?(tmpname)

      Dir.mkdir(lock)
    rescue
      failure += 1
      retry if failure < MAX_TRY
      raise "cannot generate tempfile `%s'" % tmpname
    ensure
      Thread.critical = false
    end

    @data = [tmpname]
    @clean_proc = Tempfile.callback(@data)
    ObjectSpace.define_finalizer(self, @clean_proc)

    @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
    @tmpname = tmpname
    @@cleanlist << @tmpname
    @data[1] = @tmpfile
    @data[2] = @@cleanlist

    super(@tmpfile)

    # Now we have all the File/IO methods defined, you must not
    # carelessly put bare puts(), etc. after this.

    Dir.rmdir(lock)
  end


open (Tempfile)

# File lib/tempfile.rb, line 75
  def open
    @tmpfile.close if @tmpfile
    @tmpfile = File.open(@tmpname, 'r+')
    @data[1] = @tmpfile
    __setobj__(@tmpfile)
  end


close (Tempfile)

# File lib/tempfile.rb, line 93
  def close(unlink_now=false)
    if unlink_now
      close!
    else
      _close
    end
  end


close! (Tempfile)

# File lib/tempfile.rb, line 102
  def close!
    _close
    @clean_proc.call
    ObjectSpace.undefine_finalizer(self)
  end


unlink (Tempfile)

# File lib/tempfile.rb, line 112
  def unlink
    # keep this order for thread safeness
    begin
      File.unlink(@tmpname) if File.exist?(@tmpname)
      @@cleanlist.delete(@tmpname)
      @data = @tmpname = nil
      ObjectSpace.undefine_finalizer(self)
    rescue Errno::EACCES
      # may not be able to unlink on Windows; just ignore
    end
  end


path (Tempfile)

# File lib/tempfile.rb, line 126
  def path
    @tmpname
  end


size (Tempfile)

# File lib/tempfile.rb, line 132
  def size
    if @tmpfile
      @tmpfile.flush
      @tmpfile.stat.size
    else
      0
    end
  end


open (Tempfile)

# File lib/tempfile.rb, line 167
    def open(*args)
      tempfile = new(*args)

      if block_given?
        begin
          yield(tempfile)
        ensure
          tempfile.close
        end

        nil
      else
        tempfile
      end
    end


new (TemplatePage::Context)

# File lib/rdoc/template.rb, line 47
    def initialize
      @stack = []
    end


push (TemplatePage::Context)

# File lib/rdoc/template.rb, line 51
    def push(hash)
      @stack.push(hash)
    end


pop (TemplatePage::Context)

# File lib/rdoc/template.rb, line 55
    def pop
      @stack.pop
    end


find_scalar (TemplatePage::Context)

# File lib/rdoc/template.rb, line 62
    def find_scalar(key)
      @stack.reverse_each do |level|
        if val = level[key]
          return val unless val.kind_of? Array
        end
      end
      raise "Template error: can't find variable '#{key}'"
    end


lookup (TemplatePage::Context)

# File lib/rdoc/template.rb, line 73
    def lookup(key)
      @stack.reverse_each do |level|
        val = level[key]
        return val if val
      end
      nil
    end


new (TemplatePage::LineReader)

# File lib/rdoc/template.rb, line 87
    def initialize(lines)
      @lines = lines
    end


read (TemplatePage::LineReader)

# File lib/rdoc/template.rb, line 92
    def read
      @lines.shift
    end


read_up_to (TemplatePage::LineReader)

# File lib/rdoc/template.rb, line 98
    def read_up_to(pattern)
      res = []
      while line = read
        if pattern.match(line)
          return LineReader.new(res)
        else
          res << line
        end
      end
      raise "Missing end tag in template: #{pattern.source}"
    end


dup (TemplatePage::LineReader)

# File lib/rdoc/template.rb, line 112
    def dup
      LineReader.new(@lines.dup)
    end


new (TemplatePage)

# File lib/rdoc/template.rb, line 132
  def initialize(*templates)
    result = "!INCLUDE!"
    templates.each do |content|
      result.sub!(/!INCLUDE!/, content)
    end
    @lines = LineReader.new(result.split($/))
  end


write_html_on (TemplatePage)

# File lib/rdoc/template.rb, line 144
  def write_html_on(op, value_hash)
    @context = Context.new
    op << substitute_into(@lines, value_hash).tr("\000", '\\')
  end


substitute_into (TemplatePage)

# File lib/rdoc/template.rb, line 161
  def substitute_into(lines, values)
    @context.push(values)
    skip_to = nil
    result = []

    while line = lines.read

      case line

      when /^IF:(\w+)/
        lines.read_up_to(/^ENDIF:#$1/) unless @context.lookup($1)

    when /^IFNOT:(\w+)/
        lines.read_up_to(/^ENDIF:#$1/) if @context.lookup($1)

      when /^ENDIF:/
        ;

      when /^START:(\w+)/
        tag = $1
        body = lines.read_up_to(/^END:#{tag}/)
        inner_values = @context.lookup(tag)
        raise "unknown tag: #{tag}" unless inner_values
        raise "not array: #{tag}"   unless inner_values.kind_of?(Array)
        inner_values.each do |vals|
          result << substitute_into(body.dup, vals)
        end
      else
        result << expand_line(line.dup)
      end
    end

    @context.pop

    result.join("\n")
  end


expand_line (TemplatePage)

# File lib/rdoc/template.rb, line 201
  def expand_line(line)
    # Generate a cross reference if a reference is given,
    # otherwise just fill in the name part

    line.gsub!(/HREF:(\w+?):(\w+?):/) {
      ref = @context.lookup($1)
      name = @context.find_scalar($2)

      if ref and !ref.kind_of?(Array)
        "<a href=\"#{ref}\">#{name}</a>"
      else
        name
      end
    }

    # Substitute in values for %xxx% constructs.  This is made complex
    # because the replacement string may contain characters that are
    # meaningful to the regexp (like \1)

    line = line.gsub(/%([a-zA-Z]\w*)%/) {
      val = @context.find_scalar($1)
      val.tr('\\', "\000")
    }

    line
  rescue Exception => e
    $stderr.puts "Error in template: #{e}"
    $stderr.puts "Original line: #{line}"
    exit
  end


assert_block (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 45
      def assert_block(message="assert_block failed.") # :yields:
        _wrap_assertion do
          if (! yield)
            raise AssertionFailedError.new(message.to_s)
          end
        end
      end


assert (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 60
      def assert(boolean, message=nil)
        _wrap_assertion do
          assert_block("assert should not be called with a block.") { !block_given? }
          assert_block(build_message(message, "<?> is not true.", boolean)) { boolean }
        end
      end


assert_equal (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 78
      def assert_equal(expected, actual, message=nil)
        full_message = build_message(message, "<?> expected but was\n<?>.\n", expected, actual)
        assert_block(full_message) { expected == actual }
      end


assert_raise (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 111
      def assert_raise(*args)
        _wrap_assertion do
          if Module === args.last
            message = ""
          else
            message = args.pop
          end
          exceptions, modules = _check_exception_class(args)
          expected = args.size == 1 ? args.first : args
          actual_exception = nil
          full_message = build_message(message, "<?> exception expected but none was thrown.", expected)
          assert_block(full_message) do
            begin
              yield
            rescue Exception => actual_exception
              break
            end
            false
          end
          full_message = build_message(message, "<?> exception expected but was\n?", expected, actual_exception)
          assert_block(full_message) {_expected_exception?(actual_exception, exceptions, modules)}
          actual_exception
        end
      end


assert_raises (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 142
      def assert_raises(*args, &block)
        assert_raise(*args, &block)
      end


assert_instance_of (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 153
      def assert_instance_of(klass, object, message="")
        _wrap_assertion do
          assert_equal(Class, klass.class, "assert_instance_of takes a Class as its first argument")
          full_message = build_message(message, "<?> expected to be an instance of\n<?> but was\n<?>.\n", object, klass, object.class)
          assert_block(full_message){object.instance_of?(klass)}
        end
      end


assert_nil (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 173
      def assert_nil(object, message="")
        assert_equal(nil, object, message)
      end


assert_kind_of (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 184
      def assert_kind_of(klass, object, message="")
        _wrap_assertion do
          assert(klass.kind_of?(Module), "The first parameter to assert_kind_of should be a kind_of Module.")
          full_message = build_message(message, "<?>\nexpected to be kind_of\\?\n<?> but was\n<?>.", object, klass, object.class)
          assert_block(full_message){object.kind_of?(klass)}
        end
      end


assert_respond_to (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 199
      def assert_respond_to(object, method, message="")
        _wrap_assertion do
          full_message = build_message(nil, "<?>\ngiven as the method name argument to #assert_respond_to must be a Symbol or #respond_to\\?(:to_str).", method)

          assert_block(full_message) do
            method.kind_of?(Symbol) || method.respond_to?(:to_str)
          end
          full_message = build_message(message, "<?>\nof type <?>\nexpected to respond_to\\\\?<?>.\n", object, object.class, method)
          assert_block(full_message) { object.respond_to?(method) }
        end
      end


assert_match (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 223
      def assert_match(pattern, string, message="")
        _wrap_assertion do
          pattern = case(pattern)
            when String
              Regexp.new(Regexp.escape(pattern))
            else
              pattern
          end
          full_message = build_message(message, "<?> expected to be =~\n<?>.", string, pattern)
          assert_block(full_message) { string =~ pattern }
        end
      end


assert_same (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 245
      def assert_same(expected, actual, message="")
        full_message = build_message(message, "<?>\nwith id <?> expected to be equal\\\\? to\n<?>\nwith id <?>.\n", expected, expected.__id__, actual, actual.__id__)
        assert_block(full_message) { actual.equal?(expected) }
      end


assert_operator (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 265
      def assert_operator(object1, operator, object2, message="")
        _wrap_assertion do
          full_message = build_message(nil, "<?>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
          assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
          full_message = build_message(message, "<?> expected to be\n?\n<?>.\n", object1, AssertionMessage.literal(operator), object2)
          assert_block(full_message) { object1.__send__(operator, object2) }
        end
      end


assert_nothing_raised (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 288
      def assert_nothing_raised(*args)
        _wrap_assertion do
          if Module === args.last
            message = ""
          else
            message = args.pop
          end
          exceptions, modules = _check_exception_class(args)
          begin
            yield
          rescue Exception => e
            if ((args.empty? && !e.instance_of?(AssertionFailedError)) ||
                _expected_exception?(e, exceptions, modules))
              assert_block(build_message(message, "Exception raised:\n?", e)){false}
            else
              raise
            end
          end
          nil
        end
      end


flunk (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 317
      def flunk(message="Flunked")
        assert_block(build_message(message)){false}
      end


assert_not_same (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 328
      def assert_not_same(expected, actual, message="")
        full_message = build_message(message, "<?>\nwith id <?> expected to not be equal\\\\? to\n<?>\nwith id <?>.\n", expected, expected.__id__, actual, actual.__id__)
        assert_block(full_message) { !actual.equal?(expected) }
      end


assert_not_equal (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 346
      def assert_not_equal(expected, actual, message="")
        full_message = build_message(message, "<?> expected to be != to\n<?>.", expected, actual)
        assert_block(full_message) { expected != actual }
      end


assert_not_nil (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 358
      def assert_not_nil(object, message="")
        full_message = build_message(message, "<?> expected to not be nil.", object)
        assert_block(full_message){!object.nil?}
      end


assert_no_match (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 370
      def assert_no_match(regexp, string, message="")
        _wrap_assertion do
          assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.")
          full_message = build_message(message, "<?> expected to not match\n<?>.", regexp, string)
          assert_block(full_message) { regexp !~ string }
        end
      end


assert_throws (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 390
      def assert_throws(expected_symbol, message="", &proc)
        _wrap_assertion do
          assert_instance_of(Symbol, expected_symbol, "assert_throws expects the symbol that should be thrown for its first argument")
          assert_block("Should have passed a block to assert_throws."){block_given?}
          caught = true
          begin
            catch(expected_symbol) do
              proc.call
              caught = false
            end
            full_message = build_message(message, "<?> should have been thrown.", expected_symbol)
            assert_block(full_message){caught}
          rescue NameError, ThreadError => error
            if UncaughtThrow[error.class] !~ error.message
              raise error
            end
            full_message = build_message(message, "<?> expected to be thrown but\n<?> was thrown.", expected_symbol, $1.intern)
            flunk(full_message)
          end
        end
      end


assert_nothing_thrown (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 421
      def assert_nothing_thrown(message="", &proc)
        _wrap_assertion do
          assert(block_given?, "Should have passed a block to assert_nothing_thrown")
          begin
            proc.call
          rescue NameError, ThreadError => error
            if UncaughtThrow[error.class] !~ error.message
              raise error
            end
            full_message = build_message(message, "<?> was thrown when nothing was expected", $1.intern)
            flunk(full_message)
          end
          assert(true, "Expected nothing to be thrown")
        end
      end


assert_in_delta (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 445
      def assert_in_delta(expected_float, actual_float, delta, message="")
        _wrap_assertion do
          {expected_float => "first float", actual_float => "second float", delta => "delta"}.each do |float, name|
            assert_respond_to(float, :to_f, "The arguments must respond to to_f; the #{name} did not")
          end
          assert_operator(delta, :>=, 0.0, "The delta should not be negative")
          full_message = build_message(message, "<?> and\n<?> expected to be within\n<?> of each other.\n", expected_float, actual_float, delta)
          assert_block(full_message) { (expected_float.to_f - actual_float.to_f).abs <= delta.to_f }
        end
      end


assert_send (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 473
      def assert_send(send_array, message="")
        _wrap_assertion do
          assert_instance_of(Array, send_array, "assert_send requires an array of send information")
          assert(send_array.size >= 2, "assert_send requires at least a receiver and a message name")
          full_message = build_message(message, "<?> expected to respond to\n<?(?)> with a true value.\n", send_array[0], AssertionMessage.literal(send_array[1].to_s), send_array[2..-1])
          assert_block(full_message) { send_array[0].__send__(send_array[1], *send_array[2..-1]) }
        end
      end


build_message (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 491
      def build_message(head, template=nil, *arguments)
        template &&= template.chomp
        return AssertionMessage.new(head, template, arguments)
      end


use_pp= (Test::Unit::Assertions)

# File lib/test/unit/assertions.rb, line 525
      def self.use_pp=(value)
        AssertionMessage.use_pp = value
      end


run (Test::Unit::AutoRunner)

# File lib/test/unit/autorunner.rb, line 8
      def self.run(force_standalone=false, default_dir=nil, argv=ARGV, &block)
        r = new(force_standalone || standalone?, &block)
        r.base = default_dir
        r.process_args(argv)
        r.run
      end


standalone? (Test::Unit::AutoRunner)

# File lib/test/unit/autorunner.rb, line 15
      def self.standalone?
        return false unless("-e" == $0)
        ObjectSpace.each_object(Class) do |klass|
          return false if(klass < TestCase)
        end
        true
      end


new (Test::Unit::Collector::Dir)

# File lib/test/unit/collector/dir.rb, line 13
        def initialize(dir=::Dir, file=::File, object_space=::ObjectSpace, req=nil)
          super()
          @dir = dir
          @file = file
          @object_space = object_space
          @req = req
          @pattern = [/\btest_.*\.rb\Z/m]
          @exclude = []
        end


collect (Test::Unit::Collector::Dir)

# File lib/test/unit/collector/dir.rb, line 23
        def collect(*from)
          basedir = @base
          $:.push(basedir) if basedir
          if(from.empty?)
            recursive_collect('.', find_test_cases)
          elsif(from.size == 1)
            recursive_collect(from.first, find_test_cases)
          else
            suites = []
            from.each do |f|
              suite = recursive_collect(f, find_test_cases)
              suites << suite unless(suite.tests.empty?)
            end
            suite = TestSuite.new("[#{from.join(', ')}]")
            sort(suites).each{|s| suite << s}
            suite
          end
        ensure
          $:.delete_at($:.rindex(basedir)) if basedir
        end


find_test_cases (Test::Unit::Collector::Dir)

# File lib/test/unit/collector/dir.rb, line 44
        def find_test_cases(ignore=[])
          cases = []
          @object_space.each_object(Class) do |c|
            cases << c if(c < TestCase && !ignore.include?(c))
          end
          ignore.concat(cases)
          cases
        end


recursive_collect (Test::Unit::Collector::Dir)

# File lib/test/unit/collector/dir.rb, line 53
        def recursive_collect(name, already_gathered)
          sub_suites = []
          path = realdir(name)
          if @file.directory?(path)
            dir_name = name unless name == '.'
            @dir.entries(path).each do |e|
              next if(e == '.' || e == '..')
              e_name = dir_name ? @file.join(dir_name, e) : e
              if @file.directory?(realdir(e_name))
                next if /\ACVS\z/ =~ e
                sub_suite = recursive_collect(e_name, already_gathered)
                sub_suites << sub_suite unless(sub_suite.empty?)
              else
                next if /~\z/ =~ e_name or /\A\.\#/ =~ e
                if @pattern and !@pattern.empty?
                  next unless @pattern.any? {|pat| pat =~ e_name}
                end
                if @exclude and !@exclude.empty?
                  next if @exclude.any? {|pat| pat =~ e_name}
                end
                collect_file(e_name, sub_suites, already_gathered)
              end
            end
          else
            collect_file(name, sub_suites, already_gathered)
          end
          suite = TestSuite.new(@file.basename(name))
          sort(sub_suites).each{|s| suite << s}
          suite
        end


collect_file (Test::Unit::Collector::Dir)

# File lib/test/unit/collector/dir.rb, line 84
        def collect_file(name, suites, already_gathered)
          dir = @file.dirname(@file.expand_path(name, @base))
          $:.unshift(dir)
          if(@req)
            @req.require(name)
          else
            require(name)
          end
          find_test_cases(already_gathered).each{|t| add_suite(suites, t.suite)}
        ensure
          $:.delete_at($:.rindex(dir)) if(dir)
        end


realdir (Test::Unit::Collector::Dir)

# File lib/test/unit/collector/dir.rb, line 97
        def realdir(path)
          if @base
            @file.join(@base, path)
          else
            path
          end
        end


new (Test::Unit::Collector::ObjectSpace)

# File lib/test/unit/collector/objectspace.rb, line 15
        def initialize(source=::ObjectSpace)
          super()
          @source = source
        end


collect (Test::Unit::Collector::ObjectSpace)

# File lib/test/unit/collector/objectspace.rb, line 20
        def collect(name=NAME)
          suite = TestSuite.new(name)
          sub_suites = []
          @source.each_object(Class) do |klass|
            if(Test::Unit::TestCase > klass)
              add_suite(sub_suites, klass.suite)
            end
          end
          sort(sub_suites).each{|s| suite << s}
          suite
        end


new (Test::Unit::Collector)

# File lib/test/unit/collector.rb, line 4
      def initialize
        @filters = []
      end


filter= (Test::Unit::Collector)

# File lib/test/unit/collector.rb, line 8
      def filter=(filters)
        @filters = case(filters)
          when Proc
            [filters]
          when Array
            filters
        end
      end


add_suite (Test::Unit::Collector)

# File lib/test/unit/collector.rb, line 17
      def add_suite(destination, suite)
        to_delete = suite.tests.find_all{|t| !include?(t)}
        to_delete.each{|t| suite.delete(t)}
        destination << suite unless(suite.size == 0)
      end


include? (Test::Unit::Collector)

# File lib/test/unit/collector.rb, line 23
      def include?(test)
        return true if(@filters.empty?)
        @filters.each do |filter|
          result = filter[test]
          if(result.nil?)
            next
          elsif(!result)
            return false
          else
            return true
          end
        end
        true
      end


sort (Test::Unit::Collector)

# File lib/test/unit/collector.rb, line 38
      def sort(suites)
        suites.sort_by{|s| s.name}
      end


new (Test::Unit::Error)

# File lib/test/unit/error.rb, line 24
      def initialize(test_name, exception)
        @test_name = test_name
        @exception = exception
      end


single_character_display (Test::Unit::Error)

# File lib/test/unit/error.rb, line 30
      def single_character_display
        SINGLE_CHARACTER
      end


message (Test::Unit::Error)

# File lib/test/unit/error.rb, line 35
      def message
        "#{@exception.class.name}: #{@exception.message}"
      end


short_display (Test::Unit::Error)

# File lib/test/unit/error.rb, line 40
      def short_display
        "#@test_name: #{message.split("\n")[0]}"
      end


long_display (Test::Unit::Error)

# File lib/test/unit/error.rb, line 45
      def long_display
        backtrace = filter_backtrace(@exception.backtrace).join("\n    ")
        "Error:\n#@test_name:\n#{message}\n    #{backtrace}"
      end


to_s (Test::Unit::Error)

# File lib/test/unit/error.rb, line 51
      def to_s
        long_display
      end


new (Test::Unit::Failure)

# File lib/test/unit/failure.rb, line 19
      def initialize(test_name, location, message)
        @test_name = test_name
        @location = location
        @message = message
      end


single_character_display (Test::Unit::Failure)

# File lib/test/unit/failure.rb, line 26
      def single_character_display
        SINGLE_CHARACTER
      end


short_display (Test::Unit::Failure)

# File lib/test/unit/failure.rb, line 31
      def short_display
        "#@test_name: #{@message.split("\n")[0]}"
      end


long_display (Test::Unit::Failure)

# File lib/test/unit/failure.rb, line 36
      def long_display
        location_display = if(location.size == 1)
          location[0].sub(/\A(.+:\d+).*/, ' [\\1]')
        else
          "\n    [#{location.join("\n     ")}]"
        end
        "Failure:\n#@test_name#{location_display}:\n#@message"
      end


to_s (Test::Unit::Failure)

# File lib/test/unit/failure.rb, line 46
      def to_s
        long_display
      end


new (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 39
      def initialize(test_method_name)
        unless(respond_to?(test_method_name) and
               (method(test_method_name).arity == 0 ||
                method(test_method_name).arity == -1))
          throw :invalid_test
        end
        @method_name = test_method_name
        @test_passed = true
      end


suite (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 52
      def self.suite
        method_names = public_instance_methods(true)
        tests = method_names.delete_if {|method_name| method_name !~ /^test./}
        suite = TestSuite.new(name)
        tests.sort.each do
          |test|
          catch(:invalid_test) do
            suite << new(test)
          end
        end
        if (suite.empty?)
          catch(:invalid_test) do
            suite << new("default_test")
          end
        end
        return suite
      end


run (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 73
      def run(result)
        yield(STARTED, name)
        @_result = result
        begin
          setup
          __send__(@method_name)
        rescue AssertionFailedError => e
          add_failure(e.message, e.backtrace)
        rescue Exception
          raise if PASSTHROUGH_EXCEPTIONS.include? $!.class
          add_error($!)
        ensure
          begin
            teardown
          rescue AssertionFailedError => e
            add_failure(e.message, e.backtrace)
          rescue Exception
            raise if PASSTHROUGH_EXCEPTIONS.include? $!.class
            add_error($!)
          end
        end
        result.add_run
        yield(FINISHED, name)
      end


setup (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 100
      def setup
      end


teardown (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 105
      def teardown
      end


default_test (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 108
      def default_test
        flunk("No tests were specified")
      end


size (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 120
      def size
        1
      end


name (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 143
      def name
        "#{@method_name}(#{self.class.name})"
      end


to_s (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 148
      def to_s
        name
      end


== (Test::Unit::TestCase)

# File lib/test/unit/testcase.rb, line 153
      def ==(other)
        return false unless(other.kind_of?(self.class))
        return false unless(@method_name == other.method_name)
        self.class == other.class
      end


new (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 24
      def initialize
        @run_count, @assertion_count = 0, 0
        @failures, @errors = Array.new, Array.new
      end


add_run (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 30
      def add_run
        @run_count += 1
        notify_listeners(CHANGED, self)
      end


add_failure (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 36
      def add_failure(failure)
        @failures << failure
        notify_listeners(FAULT, failure)
        notify_listeners(CHANGED, self)
      end


add_error (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 43
      def add_error(error)
        @errors << error
        notify_listeners(FAULT, error)
        notify_listeners(CHANGED, self)
      end


add_assertion (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 50
      def add_assertion
        @assertion_count += 1
        notify_listeners(CHANGED, self)
      end


to_s (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 57
      def to_s
        "#{run_count} tests, #{assertion_count} assertions, #{failure_count} failures, #{error_count} errors"
      end


passed? (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 63
      def passed?
        return @failures.empty? && @errors.empty?
      end


failure_count (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 69
      def failure_count
        return @failures.size
      end


error_count (Test::Unit::TestResult)

# File lib/test/unit/testresult.rb, line 75
      def error_count
        return @errors.size
      end


new (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 24
      def initialize(name="Unnamed TestSuite")
        @name = name
        @tests = []
      end


run (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 31
      def run(result, &progress_block)
        yield(STARTED, name)
        @tests.each do |test|
          test.run(result, &progress_block)
        end
        yield(FINISHED, name)
      end


<< (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 40
      def <<(test)
        @tests << test
        self
      end


delete (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 45
      def delete(test)
        @tests.delete(test)
      end


size (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 52
      def size
        total_size = 0
        @tests.each { |test| total_size += test.size }
        total_size
      end


empty? (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 58
      def empty?
        tests.empty?
      end


to_s (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 64
      def to_s
        @name
      end


== (Test::Unit::TestSuite)

# File lib/test/unit/testsuite.rb, line 69
      def ==(other)
        return false unless(other.kind_of?(self.class))
        return false unless(@name == other.name)
        @tests == other.tests
      end


new (Test::Unit::UI::Console::TestRunner)

# File lib/test/unit/ui/console/testrunner.rb, line 25
          def initialize(suite, output_level=NORMAL, io=STDOUT)
            if (suite.respond_to?(:suite))
              @suite = suite.suite
            else
              @suite = suite
            end
            @output_level = output_level
            @io = io
            @already_outputted = false
            @faults = []
          end


start (Test::Unit::UI::Console::TestRunner)

# File lib/test/unit/ui/console/testrunner.rb, line 38
          def start
            setup_mediator
            attach_to_mediator
            return start_mediator
          end


new (Test::Unit::UI::Fox::FaultListItem)

# File lib/test/unit/ui/fox/testrunner.rb, line 256
          def initialize(fault)
            super(fault.short_display)
            @fault = fault
          end


new (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 32
          def initialize(suite, output_level = NORMAL)
            if (suite.respond_to?(:suite))
              @suite = suite.suite
            else
              @suite = suite
            end

            @result = nil
            @red = false
          end


start (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 44
          def start
            setup_ui
            setup_mediator
            attach_to_mediator
            start_ui
            @result
          end


setup_mediator (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 52
          def setup_mediator
            @mediator = TestRunnerMediator.new(@suite)
            suite_name = @suite.to_s
            if ( @suite.kind_of?(Module) )
              suite_name = @suite.name
            end
            @suite_name_entry.text = suite_name
          end


attach_to_mediator (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 61
          def attach_to_mediator
            @mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui))
            @mediator.add_listener(TestResult::FAULT, &method(:add_fault))
            @mediator.add_listener(TestResult::CHANGED, &method(:result_changed))
            @mediator.add_listener(TestRunnerMediator::STARTED, &method(:started))
            @mediator.add_listener(TestCase::STARTED, &method(:test_started))
            @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished))
          end


start_ui (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 70
          def start_ui
            @application.create
            @window.show(PLACEMENT_SCREEN)
            @application.addTimeout(1) do
              @mediator.run_suite
            end
            @application.run
          end


stop (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 79
          def stop
            @application.exit(0)
          end


reset_ui (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 83
          def reset_ui(count)
            @test_progress_bar.barColor = GREEN_STYLE
            @test_progress_bar.total = count
            @test_progress_bar.progress = 0
            @red = false

            @test_count_label.text = "0"
            @assertion_count_label.text = "0"
            @failure_count_label.text = "0"
            @error_count_label.text = "0"

            @fault_list.clearItems
          end


add_fault (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 97
          def add_fault(fault)
            if ( ! @red )
              @test_progress_bar.barColor = RED_STYLE
              @red = true
            end
            item = FaultListItem.new(fault)
            @fault_list.appendItem(item)
          end


show_fault (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 106
          def show_fault(fault)
            raw_show_fault(fault.long_display)
          end


raw_show_fault (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 110
          def raw_show_fault(string)
            @detail_text.setText(string)
          end


clear_fault (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 114
          def clear_fault
            raw_show_fault("")
          end


result_changed (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 118
          def result_changed(result)
            @test_progress_bar.progress = result.run_count

            @test_count_label.text = result.run_count.to_s
            @assertion_count_label.text = result.assertion_count.to_s
            @failure_count_label.text = result.failure_count.to_s
            @error_count_label.text = result.error_count.to_s

             # repaint now!
             @info_panel.repaint
             @application.flush
          end


started (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 131
          def started(result)
            @result = result
            output_status("Started...")
          end


test_started (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 136
          def test_started(test_name)
            output_status("Running #{test_name}...")
          end


finished (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 140
          def finished(elapsed_time)
            output_status("Finished in #{elapsed_time} seconds")
          end


output_status (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 144
          def output_status(string)
            @status_entry.text = string
            @status_entry.repaint
          end


setup_ui (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 149
          def setup_ui
            @application = create_application
            create_tooltip(@application)

            @window = create_window(@application)

            @status_entry = create_entry(@window)

            main_panel = create_main_panel(@window)

            suite_panel = create_suite_panel(main_panel)
            create_label(suite_panel, "Suite:")
            @suite_name_entry = create_entry(suite_panel)
            create_button(suite_panel, "&Run\tRun the current suite", proc { @mediator.run_suite })

            @test_progress_bar = create_progress_bar(main_panel)

            @info_panel = create_info_panel(main_panel)
            create_label(@info_panel, "Tests:")
            @test_count_label = create_label(@info_panel, "0")
            create_label(@info_panel, "Assertions:")
            @assertion_count_label = create_label(@info_panel, "0")
            create_label(@info_panel, "Failures:")
            @failure_count_label = create_label(@info_panel, "0")
            create_label(@info_panel, "Errors:")
            @error_count_label = create_label(@info_panel, "0")

            list_panel = create_list_panel(main_panel)
            @fault_list = create_fault_list(list_panel)

            detail_panel = create_detail_panel(main_panel)
            @detail_text = create_text(detail_panel)
          end


create_application (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 183
          def create_application
            app = FXApp.new("TestRunner", "Test::Unit")
            app.init([])
            app
          end


create_window (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 189
          def create_window(app)
            FXMainWindow.new(app, "Test::Unit TestRunner", nil, nil, DECOR_ALL, 0, 0, 450)
          end


create_tooltip (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 193
          def create_tooltip(app)
            FXTooltip.new(app)
          end


create_main_panel (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 197
          def create_main_panel(parent)
            panel = FXVerticalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y)
            panel.vSpacing = 10
            panel
          end


create_suite_panel (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 203
          def create_suite_panel(parent)
            FXHorizontalFrame.new(parent, LAYOUT_SIDE_LEFT | LAYOUT_FILL_X)
          end


create_button (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 207
          def create_button(parent, text, action)
            FXButton.new(parent, text).connect(SEL_COMMAND, &action)
          end


create_progress_bar (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 211
          def create_progress_bar(parent)
            FXProgressBar.new(parent, nil, 0, PROGRESSBAR_NORMAL | LAYOUT_FILL_X)
          end


create_info_panel (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 215
          def create_info_panel(parent)
            FXMatrix.new(parent, 1, MATRIX_BY_ROWS | LAYOUT_FILL_X)
          end


create_label (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 219
          def create_label(parent, text)
            FXLabel.new(parent, text, nil, JUSTIFY_CENTER_X | LAYOUT_FILL_COLUMN)
          end


create_list_panel (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 223
          def create_list_panel(parent)
            FXHorizontalFrame.new(parent, LAYOUT_FILL_X | FRAME_SUNKEN | FRAME_THICK)
          end


create_fault_list (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 227
          def create_fault_list(parent)
            list = FXList.new(parent, 10, nil, 0, LIST_SINGLESELECT | LAYOUT_FILL_X) #, 0, 0, 0, 150)
            list.connect(SEL_COMMAND) do |sender, sel, ptr|
              if sender.retrieveItem(sender.currentItem).selected?
                show_fault(sender.retrieveItem(sender.currentItem).fault)
              else
                clear_fault
              end
            end
            list
          end


create_detail_panel (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 239
          def create_detail_panel(parent)
            FXHorizontalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y | FRAME_SUNKEN | FRAME_THICK)
          end


create_text (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 243
          def create_text(parent)
            FXText.new(parent, nil, 0, TEXT_READONLY | LAYOUT_FILL_X | LAYOUT_FILL_Y)
          end


create_entry (Test::Unit::UI::Fox::TestRunner)

# File lib/test/unit/ui/fox/testrunner.rb, line 247
          def create_entry(parent)
            entry = FXTextField.new(parent, 30, nil, 0, TEXTFIELD_NORMAL | LAYOUT_SIDE_BOTTOM | LAYOUT_FILL_X)
            entry.disable
            entry
          end


set_text (Test::Unit::UI::GTK::EnhancedLabel)

# File lib/test/unit/ui/gtk/testrunner.rb, line 397
          def set_text(text)
            super(text.gsub(/\n\t/, "\n" + (" " * 4)))
          end


set_style (Test::Unit::UI::GTK::EnhancedProgressBar)

# File lib/test/unit/ui/gtk/testrunner.rb, line 389
          def set_style(style)
            super
            hide
            show
          end


new (Test::Unit::UI::GTK::FaultListItem)

# File lib/test/unit/ui/gtk/testrunner.rb, line 404
          def initialize(fault)
            super(fault.short_display)
            @fault = fault
          end


new (Test::Unit::UI::GTK::TestRunner)

# File lib/test/unit/ui/gtk/testrunner.rb, line 25
          def initialize(suite, output_level = NORMAL)
            if (suite.respond_to?(:suite))
              @suite = suite.suite
            else
              @suite = suite
            end
            @result = nil

            @runner = Thread.current
            @restart_signal = Class.new(Exception)
            @viewer = Thread.start do
              @runner.join rescue @runner.run
              Gtk.main
            end
            @viewer.join rescue nil # wait deadlock to handshake
          end


start (Test::Unit::UI::GTK::TestRunner)

# File lib/test/unit/ui/gtk/testrunner.rb, line 43
          def start
            setup_mediator
            setup_ui
            attach_to_mediator
            start_ui
            @result
          end


set_text (Test::Unit::UI::GTK2::EnhancedLabel)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 19
          def set_text(text)
            super(text.gsub(/\n\t/, "\n    "))
          end


new (Test::Unit::UI::GTK2::FaultList)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 25
          def initialize
            @faults = []
            @model = Gtk::ListStore.new(String, String)
            super(@model)
            column = Gtk::TreeViewColumn.new
            column.visible = false
            append_column(column)
            renderer = Gtk::CellRendererText.new
            column = Gtk::TreeViewColumn.new("Failures", renderer, {:text => 1})
            append_column(column)
            selection.mode = Gtk::SELECTION_SINGLE
            set_rules_hint(true)
            set_headers_visible(false)
          end


add_fault (Test::Unit::UI::GTK2::FaultList)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 40
          def add_fault(fault)
            @faults.push(fault)
            iter = @model.append
            iter.set_value(0, (@faults.length - 1).to_s)
            iter.set_value(1, fault.short_display)
          end


get_fault (Test::Unit::UI::GTK2::FaultList)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 47
          def get_fault(iter)
            @faults[iter.get_value(0).to_i]
          end


clear (Test::Unit::UI::GTK2::FaultList)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 51
          def clear
            model.clear
          end


progress_panel (Test::Unit::UI::GTK2::TestRunner)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 237
          def progress_panel
            lazy_initialize(:progress_panel) do
              @progress_panel = Gtk::HBox.new(false, 10)
              @progress_panel.border_width = 10
              @progress_panel.pack_start(test_progress_bar, true, true, 0)
            end
          end


run_button (Test::Unit::UI::GTK2::TestRunner)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 245
          def run_button
            lazy_initialize(:run_button) do
              @run_button = Gtk::Button.new("Run")
            end
          end


test_finished (Test::Unit::UI::GTK2::TestRunner)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 330
          def test_finished(result)
            test_progress_bar.fraction += 1.0 / @count
          end


start (Test::Unit::UI::GTK2::TestRunner)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 435
          def start
            setup_mediator
            setup_ui
            attach_to_mediator
            start_ui
            @result
          end


new (Test::Unit::UI::GTK2::TestRunner)

# File lib/test/unit/ui/gtk2/testrunner.rb, line 443
          def initialize(suite, output_level = NORMAL)
            if suite.respond_to?(:suite) then
              @suite = suite.suite
            else
              @suite = suite
            end
            @result = nil

            @runner = Thread.current
            @restart_signal = Class.new(Exception)
            @viewer = Thread.start do
              @runner.join rescue @runner.run
              Gtk.main
            end
            @viewer.join rescue nil # wait deadlock to handshake
          end


new (Test::Unit::UI::TestRunnerMediator)

# File lib/test/unit/ui/testrunnermediator.rb, line 26
        def initialize(suite)
          @suite = suite
        end


run_suite (Test::Unit::UI::TestRunnerMediator)

# File lib/test/unit/ui/testrunnermediator.rb, line 32
        def run_suite
          Unit.run = true
          begin_time = Time.now
          notify_listeners(RESET, @suite.size)
          result = create_result
          notify_listeners(STARTED, result)
          result_listener = result.add_listener(TestResult::CHANGED) do |updated_result|
            notify_listeners(TestResult::CHANGED, updated_result)
          end

          fault_listener = result.add_listener(TestResult::FAULT) do |fault|
            notify_listeners(TestResult::FAULT, fault)
          end

          @suite.run(result) do |channel, value|
            notify_listeners(channel, value)
          end

          result.remove_listener(TestResult::FAULT, fault_listener)
          result.remove_listener(TestResult::CHANGED, result_listener)
          end_time = Time.now
          elapsed_time = end_time - begin_time
          notify_listeners(FINISHED, elapsed_time) #"Finished in #{elapsed_time} seconds.")
          return result
        end


run (Test::Unit::UI::TestRunnerUtilities)

# File lib/test/unit/ui/testrunnerutilities.rb, line 28
        def run(suite, output_level=NORMAL)
          return new(suite, output_level).start
        end


start_command_line_test (Test::Unit::UI::TestRunnerUtilities)

# File lib/test/unit/ui/testrunnerutilities.rb, line 35
        def start_command_line_test
          if ARGV.empty?
            puts "You should supply the name of a test suite file to the runner"
            exit
          end
          require ARGV[0].gsub(/.+::/, '')
          new(eval(ARGV[0])).start
        end


new (Test::Unit::UI::Tk::TestRunner)

# File lib/test/unit/ui/tk/testrunner.rb, line 26
          def initialize(suite, output_level = NORMAL)
            if (suite.respond_to?(:suite))
              @suite = suite.suite
            else
              @suite = suite
            end
            @result = nil

            @red = false
            @fault_detail_list = []
            @runner = Thread.current
            @restart_signal = Class.new(Exception)
            @viewer = Thread.start do
              @runner.join rescue @runner.run
              ::Tk.mainloop
            end
            @viewer.join rescue nil # wait deadlock to handshake
          end


start (Test::Unit::UI::Tk::TestRunner)

# File lib/test/unit/ui/tk/testrunner.rb, line 46
          def start
            setup_ui
            setup_mediator
            attach_to_mediator
            start_ui
            @result
          end


filter_backtrace (Test::Unit::Util::BacktraceFilter)

# File lib/test/unit/util/backtracefilter.rb, line 9
        def filter_backtrace(backtrace, prefix=nil)
          return ["No backtrace"] unless(backtrace)
          split_p = if(prefix)
            prefix.split(TESTUNIT_FILE_SEPARATORS)
          else
            TESTUNIT_PREFIX
          end
          match = proc do |e|
            split_e = e.split(TESTUNIT_FILE_SEPARATORS)[0, split_p.size]
            next false unless(split_e[0..-2] == split_p[0..-2])
            split_e[-1].sub(TESTUNIT_RB_FILE, '') == split_p[-1]
          end
          return backtrace unless(backtrace.detect(&match))
          found_prefix = false
          new_backtrace = backtrace.reverse.reject do |e|
            if(match[e])
              found_prefix = true
              true
            elsif(found_prefix)
              false
            else
              true
            end
          end.reverse
          new_backtrace = (new_backtrace.empty? ? backtrace : new_backtrace)
          new_backtrace = new_backtrace.reject(&match)
          new_backtrace.empty? ? backtrace : new_backtrace
        end


add_listener (Test::Unit::Util::Observable)

# File lib/test/unit/util/observable.rb, line 31
        def add_listener(channel_name, listener_key=NOTHING, &listener) # :yields: value
          unless(block_given?)
            raise ArgumentError.new("No callback was passed as a listener")
          end

          key = listener_key
          if (listener_key == NOTHING)
            listener_key = listener
            key = ProcWrapper.new(listener)
          end

          channels[channel_name] ||= {}
          channels[channel_name][key] = listener
          return listener_key
        end


remove_listener (Test::Unit::Util::Observable)

# File lib/test/unit/util/observable.rb, line 51
        def remove_listener(channel_name, listener_key)
          channel = channels[channel_name]
          return nil unless (channel)
          key = listener_key
          if (listener_key.instance_of?(Proc))
            key = ProcWrapper.new(listener_key)
          end
          if (channel.has_key?(key))
            return channel.delete(key)
          end
          return nil
        end


notify_listeners (Test::Unit::Util::Observable)

# File lib/test/unit/util/observable.rb, line 74
        def notify_listeners(channel_name, *arguments)
          channel = channels[channel_name]
          return 0 unless (channel)
          listeners = channel.values
          listeners.each { |listener| listener.call(*arguments) }
          return listeners.size
        end


new (Test::Unit::Util::ProcWrapper)

# File lib/test/unit/util/procwrapper.rb, line 23
        def initialize(a_proc)
          @a_proc = a_proc
          @hash = a_proc.inspect.sub(/^(#<#{a_proc.class}:)/){''}.sub(/(>)$/){''}.hex
        end


hash (Test::Unit::Util::ProcWrapper)

# File lib/test/unit/util/procwrapper.rb, line 28
        def hash
          return @hash
        end


== (Test::Unit::Util::ProcWrapper)

# File lib/test/unit/util/procwrapper.rb, line 32
        def ==(other)
          case(other)
            when ProcWrapper
              return @a_proc == other.to_proc
            else
              return super
          end
        end


to_proc (Test::Unit::Util::ProcWrapper)

# File lib/test/unit/util/procwrapper.rb, line 42
        def to_proc
          return @a_proc
        end


run= (Test::Unit)

# File lib/test/unit.rb, line 265
    def self.run=(flag)
      @run = flag
    end


run? (Test::Unit)

# File lib/test/unit.rb, line 270
    def self.run?
      @run ||= false
    end


setup (TestMyExcel)

# File ext/win32ole/tests/testWIN32OLE.rb, line 333
  def setup
    @excel = MyExcel.new
    @excel.visible = true
  end


test_s_new (TestMyExcel)

# File ext/win32ole/tests/testWIN32OLE.rb, line 337
  def test_s_new
    assert_instance_of(MyExcel, @excel)
  end


test_s_connect (TestMyExcel)

# File ext/win32ole/tests/testWIN32OLE.rb, line 340
  def test_s_connect
    excel2 = MyExcel.connect
    assert_instance_of(MyExcel, excel2)
  end


setup (TestNIL2VT_EMPTY)

# File ext/win32ole/tests/testNIL2VTEMPTY.rb, line 8
  def setup
    fs = WIN32OLE.new('Scripting.FileSystemObject')
    @path = fs.GetFolder(".").path
  end


test_openSchema (TestNIL2VT_EMPTY)

# File ext/win32ole/tests/testNIL2VTEMPTY.rb, line 12
  def test_openSchema
    con = nil
    begin
      con = WIN32OLE.new('ADODB.Connection')
      con.connectionString = "Provider=MSDASQL;Extended Properties="
      con.connectionString +="\"DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=#{@path}\""
      con.open
    rescue
      con = nil
    end
    if con
      rs = con.openSchema(4, [nil,nil,"DUMMY", "TABLE"])
      assert(rs)
    end
  end


setup (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 10
  def setup
    @excel_app = WIN32OLE_TYPE.new(MS_EXCEL_TYPELIB, 'Application')
  end


test_s_new (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 13
  def test_s_new
    m = WIN32OLE_METHOD.new(@excel_app, 'Quit')
    assert_instance_of(WIN32OLE_METHOD, m)
    m =  WIN32OLE_METHOD.new(@excel_app, 'WorkbookOpen')
    assert_instance_of(WIN32OLE_METHOD, m)
    m =  WIN32OLE_METHOD.new(@excel_app, 'workbookopen')
    assert_instance_of(WIN32OLE_METHOD, m)
  end


test_name (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 21
  def test_name
    m = WIN32OLE_METHOD.new(@excel_app, 'Quit')
    assert_equal('Quit', m.name)
  end


test_to_s (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 25
  def test_to_s
    m = WIN32OLE_METHOD.new(@excel_app, 'Quit')
    assert_equal('Quit', "#{m}")
  end


test_return_type (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 29
  def test_return_type
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert_equal('Range', m.return_type)
    m = WIN32OLE_METHOD.new(@excel_app, 'ActivePrinter')
    assert_equal('BSTR', m.return_type)
  end


test_return_vtype (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 35
  def test_return_vtype
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert_equal(WIN32OLE::VARIANT::VT_PTR, m.return_vtype)
    m = WIN32OLE_METHOD.new(@excel_app, 'ActivePrinter')
    assert_equal(WIN32OLE::VARIANT::VT_BSTR, m.return_vtype)
  end


test_return_type_detail (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 41
  def test_return_type_detail
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert_equal(['PTR', 'USERDEFINED', 'Range'], m.return_type_detail)
    m = WIN32OLE_METHOD.new(@excel_app, 'ActivePrinter')
    assert_equal(['BSTR'], m.return_type_detail)
  end


test_invoke_kind (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 48
  def test_invoke_kind
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert_equal('PROPERTYGET', m.invoke_kind)
  end


test_visible (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 52
  def test_visible
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert(m.visible?)
    m = WIN32OLE_METHOD.new(@excel_app, 'AddRef')
    assert(!m.visible?)
  end


test_event (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 58
  def test_event
    m =  WIN32OLE_METHOD.new(@excel_app, 'WorkbookOpen')
    assert(m.event?)
    m =  WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert(!m.event?)
  end


test_event_interface (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 64
  def test_event_interface
    m = WIN32OLE_METHOD.new(@excel_app, 'WorkbookOpen')
    assert_equal('AppEvents', m.event_interface)
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert_nil(m.event_interface)
  end


test_helpstring (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 70
  def test_helpstring
    domdoc = WIN32OLE_TYPE.new(MS_XML_TYPELIB, 'DOMDocument')
    m =  WIN32OLE_METHOD.new(domdoc, 'abort')
    assert_equal('abort an asynchronous download', m.helpstring)
  end


test_helpfile (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 75
  def test_helpfile
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert_match(/VBAXL.*\.(HLP|CHM)$/i, m.helpfile)
  end


test_helpcontext (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 79
  def test_helpcontext
    m = WIN32OLE_METHOD.new(@excel_app, 'ActiveCell')
    assert(m.helpcontext > 0)
  end


test_offset_vtbl (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 83
  def test_offset_vtbl
    m = WIN32OLE_METHOD.new(@excel_app, 'QueryInterface')
    assert_equal(0, m.offset_vtbl)
  end


test_dispid (TestOLEMETHOD)

# File ext/win32ole/tests/testOLEMETHOD.rb, line 87
  def test_dispid
    tobj = WIN32OLE_TYPE.new('Microsoft Shell Controls And Automation', 'FolderItem2')
    method = WIN32OLE_METHOD.new(tobj, 'InvokeVerb')
    assert_equal(1610743824, method.dispid)
  end


test_name (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 10
  def test_name
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    sh = classes.find {|c| c.name == 'Worksheet'}
    saveas = sh.ole_methods.find {|m| m.name == 'SaveAs'}
    param_names = saveas.params.collect{|p| p.name}
    assert(param_names.size > 0)
    assert(param_names.include?('Filename'))
  end


test_to_s (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 18
  def test_to_s
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    sh = classes.find {|c| c.name == 'Worksheet'}
    saveas = sh.ole_methods.find {|m| m.name == 'SaveAs'}
    param_names = saveas.params.collect{|p| "#{p}"}
    assert(param_names.include?('Filename'))
  end


test_ole_type (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 25
  def test_ole_type
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert_equal('BSTR', f.params[0].ole_type)
    methods = classes.find {|c| c.name == 'Workbook'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert_equal('XlSaveAsAccessMode', f.params[6].ole_type)
  end


test_ole_type_detail (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 34
  def test_ole_type_detail
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert_equal(['BSTR'], f.params[0].ole_type_detail)
    methods = classes.find {|c| c.name == 'Workbook'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert_equal(['USERDEFINED', 'XlSaveAsAccessMode'], f.params[6].ole_type_detail)
  end


test_input (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 43
  def test_input
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert(f.params[0].input?)
  end


test_output (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 50
  def test_output
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert(!f.params[0].output?)
  end


test_optional (TestOLEPARAM)

# File ext/win32ole/tests/testOLEPARAM.rb, line 56
  def test_optional
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert(!f.params[0].optional?)
    methods = classes.find {|c| c.name == 'Workbook'}.ole_methods
    f = methods.find {|m| m.name == 'SaveAs'}
    assert(f.params[0].optional?)
  end


test_s_new (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 10
  def test_s_new
    type = WIN32OLE_TYPE.new(MS_EXCEL_TYPELIB, 'Application')
    assert_instance_of(WIN32OLE_TYPE, type)
  end


test_s_ole_classes (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 14
  def test_s_ole_classes
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    assert(classes.size > 0)
  end


test_s_typelibs (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 18
  def test_s_typelibs
    libs = WIN32OLE_TYPE.typelibs
    assert(libs.include?(MS_EXCEL_TYPELIB))
    assert(libs.include?(MS_XML_TYPELIB))
  end


test_s_progids (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 23
  def test_s_progids
    progids = WIN32OLE_TYPE.progids
    assert(progids.include?('Excel.Application'))
  end


test_name (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 27
  def test_name
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    class_names = classes.collect{|c|
      c.name
    }
    assert(class_names.include?('Application'))
  end


test_class_to_s (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 35
  def test_class_to_s
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    class_names = classes.collect{|c|
      "#{c}"
    }
    assert(class_names.include?('Application'))
  end


test_ole_type (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 43
  def test_ole_type
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    app = classes.find {|c| c.name == 'Application'}
    assert_equal('Class', app.ole_type)
    app = classes.find {|c| c.name == '_Application'}
    assert_equal('Dispatch', app.ole_type)
  end


test_typekind (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 50
  def test_typekind
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    app = classes.find {|c| c.name == 'Application'}
    assert_equal(5, app.typekind)
  end


test_visible (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 55
  def test_visible
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    app = classes.find {|c| c.name == 'Application'}
    assert(app.visible?)
    app = classes.find {|c| c.name == 'IAppEvents'}
    assert(!app.visible?)
  end


test_src_type (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 62
  def test_src_type
    classes = WIN32OLE_TYPE.ole_classes(MS_XML_TYPELIB)
    domnode = classes.find {|c| c.name == 'DOMNodeType'}
    assert_equal('tagDOMNodeType', domnode.src_type)
  end


test_helpstring (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 67
  def test_helpstring
    classes = WIN32OLE_TYPE.ole_classes(MS_XML_TYPELIB)
    domdoc = classes.find {|c| c.name == 'DOMDocument'}
    assert_equal('W3C-DOM XML Document', domdoc.helpstring)
  end


test_variables (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 72
  def test_variables
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    xlchart = classes.find {|c| c.name == 'XlChartType'}
    assert(xlchart.variables.size > 0)
  end


test_ole_methods (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 77
  def test_ole_methods
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    worksheet = classes.find {|c| c.name == 'Worksheet'}
    assert(worksheet.ole_methods.size > 0)
  end


test_helpfile (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 82
  def test_helpfile
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    worksheet = classes.find {|c| c.name == 'Worksheet'}
    assert_match(/VBAXL.*\.(CHM|HLP)$/, worksheet.helpfile)
  end


test_helpcontext (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 87
  def test_helpcontext
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    worksheet = classes.find {|c| c.name == 'Worksheet'}
    assert_equal(131088, worksheet.helpcontext)
  end


test_to_s (TestOLETYPE)

# File ext/win32ole/tests/testOLETYPE.rb, line 92
  def test_to_s
    type = WIN32OLE_TYPE.new(MS_EXCEL_TYPELIB, 'Application')
    assert_equal("Application", "#{type}");
  end


test_name (TestOLEVARIABLE)

# File ext/win32ole/tests/testOLEVARIABLE.rb, line 10
  def test_name
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    chart = classes.find {|c| c.name == 'XlChartType'}
    var_names = chart.variables.collect {|m| m.name}
    assert(var_names.size > 0)
    assert(var_names.include?('xl3DColumn'))
  end


test_to_s (TestOLEVARIABLE)

# File ext/win32ole/tests/testOLEVARIABLE.rb, line 17
  def test_to_s
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    chart = classes.find {|c| c.name == 'XlChartType'}
    var_names = chart.variables.collect {|m| "#{m}"}
    assert(var_names.size > 0)
    assert(var_names.include?('xl3DColumn'))
  end


test_ole_type (TestOLEVARIABLE)

# File ext/win32ole/tests/testOLEVARIABLE.rb, line 24
  def test_ole_type
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    chart = classes.find {|c| c.name == 'XlChartType'}
    var = chart.variables.find {|m| m.name == 'xl3DColumn'}
    assert_equal('INT', var.ole_type)
  end


test_ole_type_detail (TestOLEVARIABLE)

# File ext/win32ole/tests/testOLEVARIABLE.rb, line 30
  def test_ole_type_detail
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    chart = classes.find {|c| c.name == 'XlChartType'}
    var = chart.variables.find {|m| m.name == 'xl3DColumn'}
    assert_equal(['INT'], var.ole_type_detail)
  end


test_value (TestOLEVARIABLE)

# File ext/win32ole/tests/testOLEVARIABLE.rb, line 37
  def test_value
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    chart = classes.find {|c| c.name == 'XlChartType'}
    var = chart.variables.find {|m| m.name == 'xl3DColumn'}
    assert_equal(-4100, var.value)
  end


test_visible (TestOLEVARIABLE)

# File ext/win32ole/tests/testOLEVARIABLE.rb, line 43
  def test_visible
    classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
    chart = classes.find {|c| c.name == 'XlChartType'}
    var = chart.variables.find {|m| m.name == 'xl3DColumn'}
    assert(var.visible?)
  end


setup (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 23
  def setup
    @excel = WIN32OLE.new("Excel.Application")
    @excel.visible = true
  end


test_s_new (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 27
  def test_s_new
    assert_instance_of(WIN32OLE, @excel)
  end


test_s_new_DCOM (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 30
  def test_s_new_DCOM
    rexcel = WIN32OLE.new("Excel.Application", "localhost")
    assert_instance_of(WIN32OLE, rexcel)
    rexcel.visible = true
    rexcel.quit
  end


test_s_new_from_clsid (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 36
  def test_s_new_from_clsid
    excel = WIN32OLE.new("{00024500-0000-0000-C000-000000000046}")
    assert_instance_of(WIN32OLE, excel)
    excel.quit
    exc = assert_exception(WIN32OLERuntimeError) {
      WIN32OLE.new("{000}")
    }
    assert_match(/unknown OLE server: `\{000\}'/, exc.message)
  end


test_s_connect (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 45
  def test_s_connect
    excel2 = WIN32OLE.connect('Excel.Application')
    assert_instance_of(WIN32OLE, excel2)
  end


test_s_const_load (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 50
  def test_s_const_load
    assert(!defined?(EXCEL_CONST::XlTop))
    WIN32OLE.const_load(@excel, EXCEL_CONST)
    assert_equal(-4160, EXCEL_CONST::XlTop)

    assert(!defined?(CONST1::XlTop))
    WIN32OLE.const_load(MS_EXCEL_TYPELIB, CONST1)
    assert_equal(-4160, CONST1::XlTop)
  end


test_s_codepage (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 60
  def test_s_codepage
    assert_equal(WIN32OLE::CP_ACP, WIN32OLE.codepage)
  end


test_s_codepage_set (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 64
  def test_s_codepage_set
    WIN32OLE.codepage = WIN32OLE::CP_UTF8
    assert_equal(WIN32OLE::CP_UTF8, WIN32OLE.codepage)
    WIN32OLE.codepage = WIN32OLE::CP_ACP
  end


test_const_CP_ACP (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 70
  def test_const_CP_ACP
    assert_equal(0, WIN32OLE::CP_ACP)
  end


test_const_CP_OEMCP (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 74
  def test_const_CP_OEMCP
    assert_equal(1, WIN32OLE::CP_OEMCP)
  end


test_const_CP_MACCP (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 78
  def test_const_CP_MACCP
    assert_equal(2, WIN32OLE::CP_MACCP)
  end


test_const_CP_THREAD_ACP (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 82
  def test_const_CP_THREAD_ACP
    assert_equal(3, WIN32OLE::CP_THREAD_ACP)
  end


test_const_CP_SYMBOL (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 86
  def test_const_CP_SYMBOL
    assert_equal(42, WIN32OLE::CP_SYMBOL)
  end


test_const_CP_UTF7 (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 90
  def test_const_CP_UTF7
    assert_equal(65000, WIN32OLE::CP_UTF7)
  end


test_const_CP_UTF8 (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 94
  def test_const_CP_UTF8
    assert_equal(65001, WIN32OLE::CP_UTF8)
  end


test_s_codepage_changed (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 98
  def test_s_codepage_changed
    book = @excel.workbooks.add
    sheet = book.worksheets(1)
    begin
      WIN32OLE.codepage = WIN32OLE::CP_UTF8
      sheet.range("A1").value = [0x3042].pack("U*")
      val = sheet.range("A1").value
      assert_equal("\343\201\202", val)
      WIN32OLE.codepage = WIN32OLE::CP_ACP
      val = sheet.range("A1").value
      assert_equal("\202\240", val)
    ensure
      book.saved = true
    end
  end


test_get_win32ole_object (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 114
  def test_get_win32ole_object
    workbooks = @excel.Workbooks;
    assert_instance_of(WIN32OLE, workbooks)
  end


test_each (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 118
  def test_each
    workbooks = @excel.Workbooks
    assert_no_exception {
      i = 0;
      workbooks.each do |workbook|
        print i += 1
      end
    }
    workbooks.add
    workbooks.add
    i = 0
    workbooks.each do |workbook|
      i+=1
    end
    assert_equal(2, i)
    workbooks.each do |workbook|
      workbook.saved = true
    end
  end


test_setproperty_bracket (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 137
  def test_setproperty_bracket
    book = @excel.workbooks.add
    sheet = book.worksheets(1)
    begin
      sheet.range("A1")['Value'] = 10
      assert_equal(10, sheet.range("A1").value)
      sheet['Cells', 1, 2] = 10
      assert_equal(10, sheet.range("B1").value)
      assert_equal(10, sheet['Cells', 1, 2].value)
    ensure
      book.saved = true
    end
  end


test_convert_bignum (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 150
  def test_convert_bignum
    book = @excel.workbooks.add
    sheet = book.worksheets(1)
    begin
      sheet.range("A1").value = 999999999
      sheet.range("A2").value = 9999999999
      sheet.range("A3").value = "=A1*10 + 9"
      assert_equal(9999999999, sheet.range("A2").value)
      assert_equal(9999999999, sheet.range("A3").value)

    ensure
      book.saved = true
    end
  end


test_ole_invoke_with_named_arg (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 165
  def test_ole_invoke_with_named_arg
    book = @excel.workbooks.add
    sheets = book.worksheets
    sheet = book.worksheets(1)
    num = sheets.count
    begin
      sheets.add({'count' => 2, 'after'=>sheet})
      assert_equal(2, sheets.count - num);
    ensure
      book.saved = true
    end
  end


test_ole_invoke_with_named_arg_last (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 178
  def test_ole_invoke_with_named_arg_last
    book = @excel.workbooks.add
    sheets = book.worksheets
    sheet = book.worksheets(1)
    num = sheets.count
    begin
      sheets.add(sheet, {'count' => 2})
      assert_equal(2, sheets.count - num);
    ensure
      book.saved = true
    end
  end


test_setproperty (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 191
  def test_setproperty
    @excel.setproperty('Visible', false)
    assert_equal(false, @excel.Visible)
    @excel.setproperty('Visible', true)
    assert_equal(true, @excel.Visible)
    book = @excel.workbooks.add
    sheet = book.worksheets(1)
    begin
      sheet.setproperty('Cells', 1, 2, 10)
      assert_equal(10, sheet.range("B1").value)
    ensure
      book.saved = true
    end
  end


test_no_exist_property (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 205
  def test_no_exist_property
    isok = false
    begin
      @excel.unknown_prop = 1
    rescue WIN32OLERuntimeError
      isok = true
    end
    assert(isok)

    isok = false
    begin
      @excel['unknown_prop'] = 2
    rescue WIN32OLERuntimeError
      isok = true
    end
    assert(isok)
  end


test_setproperty_with_equal (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 223
  def test_setproperty_with_equal
    book = @excel.workbooks.add
    sheet = book.worksheets(1)
    begin
      sheet.range("B1").value = 10
      assert_equal(10, sheet.range("B1").value)
      sheet.range("C1:D1").value = [11, 12]
      assert_equal(11, sheet.range("C1").value)
      assert_equal(12, sheet.range("D1").value)
    ensure
      book.saved = true
    end
  end


test_invoke (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 236
  def test_invoke
    workbooks = @excel.invoke( 'workbooks' )
    assert_instance_of(WIN32OLE, workbooks)
    book = workbooks.invoke( 'add' )
    assert_instance_of(WIN32OLE, book)
  end


test_ole_methods (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 242
  def test_ole_methods
    methods = @excel.ole_methods
    method_names = methods.collect{|m| m.name}
    assert(method_names.include?("Quit"))
  end


test_ole_func_methods (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 247
  def test_ole_func_methods
    methods = @excel.ole_func_methods
    assert(methods.size > 0)
    method_names = methods.collect{|m| m.name}
    assert(method_names.include?("Quit"))
  end


test_ole_put_methods (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 253
  def test_ole_put_methods
    methods = @excel.ole_put_methods
    assert(methods.size > 0)
    method_names = methods.collect{|m| m.name}
    assert(method_names.include?("Visible"))
  end


test_ole_get_methods (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 259
  def test_ole_get_methods
    methods = @excel.ole_get_methods
    assert(methods.size > 0)
    method_names = methods.collect{|m| m.name}
    assert(method_names.include?("Visible"))
  end


test_ole_method_help (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 265
  def test_ole_method_help
    quit_info = @excel.ole_method_help("Quit")
    assert_equal(0, quit_info.size_params)
    assert_equal(0, quit_info.size_opt_params)

    workbooks = @excel.Workbooks
    add_info = workbooks.ole_method_help("Add")
    assert_equal(1, add_info.size_params)
    assert_equal(1, add_info.size_opt_params)
    assert(add_info.params[0].input?)
    assert(add_info.params[0].optional?)
    assert_equal('VARIANT', add_info.params[0].ole_type)
  end


teardown (TestWin32OLE)

# File ext/win32ole/tests/testWIN32OLE.rb, line 278
  def teardown
    @excel.quit
    @excel = nil
    GC.start
  end


setup (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 5
  def setup
    @excel = WIN32OLE.new("Excel.Application")
    @excel.visible = true
    @event = ""
    @event2 = ""
  end


test_on_event (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 11
  def test_on_event
    book = @excel.workbooks.Add
    value = ""
    begin
      ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
      ev.on_event('SheetChange'){|arg1, arg2|
        begin
          value = arg1.value
        rescue
          value = $!.message
        end
      }
      book.Worksheets(1).Range("A1").value = "OK"
    ensure
      book.saved = true
    end
    assert_equal("OK", value)
  end


handler1 (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 30
  def handler1
    @event += "handler1"
  end


handler2 (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 33
  def handler2
    @event += "handler2"
  end


handler3 (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 37
  def handler3
    @event += "handler3"
  end


test_on_event2 (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 41
  def test_on_event2
    book = @excel.workbooks.Add
    begin
      ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
      ev.on_event('SheetChange'){|arg1, arg2|
        handler1
      }
      ev.on_event('SheetChange'){|arg1, arg2|
        handler2
      }
      book.Worksheets(1).Range("A1").value = "OK"
    ensure
      book.saved = true
    end
    assert_equal("handler2", @event)
  end


test_on_event3 (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 58
  def test_on_event3
    book = @excel.workbooks.Add
    begin
      ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
      ev.on_event{ handler1 }
      ev.on_event{ handler2 }
      book.Worksheets(1).Range("A1").value = "OK"
    ensure
      book.saved = true
    end
    assert_equal("handler2", @event)
  end


test_on_event4 (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 71
  def test_on_event4
    book = @excel.workbooks.Add
    begin
      ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
      ev.on_event{ handler1 }
      ev.on_event{ handler2 }
      ev.on_event('SheetChange'){|arg1, arg2| handler3 }
      book.Worksheets(1).Range("A1").value = "OK"
    ensure
      book.saved = true
    end
    assert_equal("handler3", @event)
  end


teardown (TestWIN32OLE_EVENT)

# File ext/win32ole/tests/testOLEEVENT.rb, line 85
  def teardown
    @excel.quit
    @excel = nil
    GC.start
  end


setup (TestWIN32OLE_FOR_PROPERTYPUTREF)

# File ext/win32ole/tests/test_ole_methods.rb, line 13
    def setup
      @obj = WIN32OLE.new('Scripting.Dictionary')
    end


test_ole_methods (TestWIN32OLE_FOR_PROPERTYPUTREF)

# File ext/win32ole/tests/test_ole_methods.rb, line 17
    def test_ole_methods
      x = @obj.ole_methods.select {|m|
        m.invoke_kind == 'PROPERTYPUTREF'
      }
      assert(x.size > 0)
      assert_equal(1, x.size)
      assert_equal('Item', x[0].name)
    end


test_ole_put_methods (TestWIN32OLE_FOR_PROPERTYPUTREF)

# File ext/win32ole/tests/test_ole_methods.rb, line 26
    def test_ole_put_methods
      x = @obj.ole_put_methods.select {|m|
        m.invoke_kind == 'PROPERTYPUTREF'
      }
      assert(x.size > 0)
      assert_equal(1, x.size)
      assert_equal('Item', x[0].name)
    end


setup (TestWIN32OLE_PROPERTYPUTREF)

# File ext/win32ole/tests/test_propertyputref.rb, line 5
  def setup
    begin
      @sapi = WIN32OLE.new('SAPI.SpVoice')
    rescue WIN32OLERuntimeError
      @sapi = nil
    end
  end


test_sapi (TestWIN32OLE_PROPERTYPUTREF)

# File ext/win32ole/tests/test_propertyputref.rb, line 12
  def test_sapi
    if @sapi
      new_id = @sapi.getvoices.item(2).Id
      @sapi.voice = @sapi.getvoices.item(2)
      assert_equal(new_id, @sapi.voice.Id)
    end
  end


test_variant (TestWin32OLE_VARIANT)

# File ext/win32ole/tests/testVARIANT.rb, line 9
  def test_variant
    assert_equal(2, VT_I2)
    assert_equal(3, VT_I4)
    assert_equal(4, VT_R4)
    assert_equal(5, VT_R8)
    assert_equal(6, VT_CY)
    assert_equal(7, VT_DATE)
    assert_equal(8, VT_BSTR)
    assert_equal(9, VT_DISPATCH)
    assert_equal(10, VT_ERROR)
    assert_equal(11, VT_BOOL)
    assert_equal(12, VT_VARIANT)
    assert_equal(13, VT_UNKNOWN)
    assert_equal(16, VT_I1)
    assert_equal(17, VT_UI1)
    assert_equal(18, VT_UI2)
    assert_equal(19, VT_UI4)
    assert_equal(22, VT_INT)
    assert_equal(23, VT_UINT)
    assert_equal(0x2000, VT_ARRAY)
    assert_equal(0x4000, VT_BYREF)
  end


setup (TestWin32OLE_WITH_MSI)

# File ext/win32ole/tests/testWIN32OLE.rb, line 286
  def setup
    installer = WIN32OLE.new("WindowsInstaller.Installer")
    @record = installer.CreateRecord(2)
  end


test_setproperty (TestWin32OLE_WITH_MSI)

# File ext/win32ole/tests/testWIN32OLE.rb, line 299
  def test_setproperty
    @record.setproperty( "StringData", 1, 'dddd')
    assert_equal('dddd', @record.StringData(1))
  end


test_bracket_equal_with_arg (TestWin32OLE_WITH_MSI)

# File ext/win32ole/tests/testWIN32OLE.rb, line 303
  def test_bracket_equal_with_arg
    @record[ "StringData", 1 ] =  'ffff'
    assert_equal('ffff', @record.StringData(1))
  end


test__invoke (TestWin32OLE_WITH_MSI)

# File ext/win32ole/tests/testWIN32OLE.rb, line 308
  def test__invoke
    shell=WIN32OLE.new('Shell.Application')
    assert_equal(shell.NameSpace(0).title, shell._invoke(0x60020002, [0], [WIN32OLE::VARIANT::VT_VARIANT]).title)
  end


setup (TestWIN32OLE_WITH_WORD)

# File ext/win32ole/tests/test_word.rb, line 13
    def setup
      begin
        @obj = WIN32OLE.new('Word.Application')
      rescue WIN32OLERuntimeError
        @obj = nil
      end
    end


test_ole_methods (TestWIN32OLE_WITH_WORD)

# File ext/win32ole/tests/test_word.rb, line 21
    def test_ole_methods
      if @obj
        @obj.visible = true
        @obj.wordbasic.disableAutoMacros(true)
        assert(true)
      end
    end


teardown (TestWIN32OLE_WITH_WORD)

# File ext/win32ole/tests/test_word.rb, line 29
    def teardown
      if @obj
        @obj.quit
        @obj = nil
      end
    end


new (Thread)

/*
 *  call-seq:
 *     Thread.new([arg]*) {|args| block }   => thread
 *
 *  Creates and runs a new thread to execute the instructions given in
 *  <i>block</i>. Any arguments passed to <code>Thread::new</code> are passed
 *  into the block.
 *
 *     x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
 *     a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
 *     x.join # Let the threads finish before
 *     a.join # main thread exits...
 *
 *  <em>produces:</em>
 *
 *     abxyzc
 */

static VALUE
rb_thread_s_new(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    rb_thread_t th = rb_thread_alloc(klass);
    volatile VALUE *pos;

    pos = th->stk_pos;
    rb_obj_call_init(th->thread, argc, argv);
    if (th->stk_pos == 0) {
        rb_raise(rb_eThreadError, "uninitialized thread - check `%s#initialize'",
                 rb_class2name(klass));
    }

    return th->thread;
}


new (Thread)

/*
 *  call-seq:
 *     Thread.new([arg]*) {|args| block }   => thread
 *
 *  Creates and runs a new thread to execute the instructions given in
 *  <i>block</i>. Any arguments passed to <code>Thread::new</code> are passed
 *  into the block.
 *
 *     x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
 *     a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
 *     x.join # Let the threads finish before
 *     a.join # main thread exits...
 *
 *  <em>produces:</em>
 *
 *     abxyzc
 */

static VALUE
rb_thread_initialize(thread, args)
    VALUE thread, args;
{
    rb_thread_t th;

    if (!rb_block_given_p()) {
        rb_raise(rb_eThreadError, "must be called with a block");
    }
    th = rb_thread_check(thread);
    if (th->stk_max) {
        NODE *node = th->node;
        if (!node) {
            rb_raise(rb_eThreadError, "already initialized thread");
        }
        rb_raise(rb_eThreadError, "already initialized thread - %s:%d",
                 node->nd_file, nd_line(node));
    }
    return rb_thread_start_0(rb_thread_yield, args, th);
}


start (Thread)

/*
 *  call-seq:
 *     Thread.start([args]*) {|args| block }   => thread
 *     Thread.fork([args]*) {|args| block }    => thread
 *
 *  Basically the same as <code>Thread::new</code>. However, if class
 *  <code>Thread</code> is subclassed, then calling <code>start</code> in that
 *  subclass will not invoke the subclass's <code>initialize</code> method.
 */

static VALUE
rb_thread_start(klass, args)
    VALUE klass, args;
{
    if (!rb_block_given_p()) {
        rb_raise(rb_eThreadError, "must be called with a block");
    }
    return rb_thread_start_0(rb_thread_yield, args, rb_thread_alloc(klass));
}


fork (Thread)

/*
 *  call-seq:
 *     Thread.start([args]*) {|args| block }   => thread
 *     Thread.fork([args]*) {|args| block }    => thread
 *
 *  Basically the same as <code>Thread::new</code>. However, if class
 *  <code>Thread</code> is subclassed, then calling <code>start</code> in that
 *  subclass will not invoke the subclass's <code>initialize</code> method.
 */

static VALUE
rb_thread_start(klass, args)
    VALUE klass, args;
{
    if (!rb_block_given_p()) {
        rb_raise(rb_eThreadError, "must be called with a block");
    }
    return rb_thread_start_0(rb_thread_yield, args, rb_thread_alloc(klass));
}


stop (Thread)

/*
 *  call-seq:
 *     Thread.stop   => nil
 *
 *  Stops execution of the current thread, putting it into a ``sleep'' state,
 *  and schedules execution of another thread. Resets the ``critical'' condition
 *  to <code>false</code>.
 *
 *     a = Thread.new { print "a"; Thread.stop; print "c" }
 *     Thread.pass
 *     print "b"
 *     a.run
 *     a.join
 *
 *  <em>produces:</em>
 *
 *     abc
 */

VALUE
rb_thread_stop()
{
    enum rb_thread_status last_status = THREAD_RUNNABLE;

    rb_thread_critical = 0;
    if (curr_thread == curr_thread->next) {
        rb_raise(rb_eThreadError, "stopping only thread\n\tnote: use sleep to stop forever");
    }
    if (curr_thread->status == THREAD_TO_KILL)
        last_status = THREAD_TO_KILL;
    curr_thread->status = THREAD_STOPPED;
    rb_thread_schedule();
    curr_thread->status = last_status;

    return Qnil;
}


kill (Thread)

/*
 *  call-seq:
 *     Thread.kill(thread)   => thread
 *
 *  Causes the given <em>thread</em> to exit (see <code>Thread::exit</code>).
 *
 *     count = 0
 *     a = Thread.new { loop { count += 1 } }
 *     sleep(0.1)       #=> 0
 *     Thread.kill(a)   #=> #<Thread:0x401b3d30 dead>
 *     count            #=> 93947
 *     a.alive?         #=> false
 */

static VALUE
rb_thread_s_kill(obj, th)
    VALUE obj, th;
{
    return rb_thread_kill(th);
}


exit (Thread)

/*
 *  call-seq:
 *     Thread.exit   => thread
 *
 *  Terminates the currently running thread and schedules another thread to be
 *  run. If this thread is already marked to be killed, <code>exit</code>
 *  returns the <code>Thread</code>. If this is the main thread, or the last
 *  thread, exit the process.
 */

static VALUE
rb_thread_exit()
{
    return rb_thread_kill(curr_thread->thread);
}


pass (Thread)

/*
 *  call-seq:
 *     Thread.pass   => nil
 *
 *  Invokes the thread scheduler to pass execution to another thread.
 *
 *     a = Thread.new { print "a"; Thread.pass;
 *                      print "b"; Thread.pass;
 *                      print "c" }
 *     b = Thread.new { print "x"; Thread.pass;
 *                      print "y"; Thread.pass;
 *                      print "z" }
 *     a.join
 *     b.join
 *
 *  <em>produces:</em>
 *
 *     axbycz
 */

static VALUE
rb_thread_pass()
{
    rb_thread_schedule();
    return Qnil;
}


current (Thread)

/*
 *  call-seq:
 *     Thread.current   => thread
 *
 *  Returns the currently executing thread.
 *
 *     Thread.current   #=> #<Thread:0x401bdf4c run>
 */

VALUE
rb_thread_current()
{
    return curr_thread->thread;
}


main (Thread)

/*
 *  call-seq:
 *     Thread.main   => thread
 *
 *  Returns the main thread for the process.
 *
 *     Thread.main   #=> #<Thread:0x401bdf4c run>
 */

VALUE
rb_thread_main()
{
    return main_thread->thread;
}


list (Thread)

/*
 *  call-seq:
 *     Thread.list   => array
 *
 *  Returns an array of <code>Thread</code> objects for all threads that are
 *  either runnable or stopped.
 *
 *     Thread.new { sleep(200) }
 *     Thread.new { 1000000.times {|i| i*i } }
 *     Thread.new { Thread.stop }
 *     Thread.list.each {|t| p t}
 *
 *  <em>produces:</em>
 *
 *     #<Thread:0x401b3e84 sleep>
 *     #<Thread:0x401b3f38 run>
 *     #<Thread:0x401b3fb0 sleep>
 *     #<Thread:0x401bdf4c run>
 */

VALUE
rb_thread_list()
{
    rb_thread_t th;
    VALUE ary = rb_ary_new();

    FOREACH_THREAD(th) {
        switch (th->status) {
          case THREAD_RUNNABLE:
          case THREAD_STOPPED:
          case THREAD_TO_KILL:
            rb_ary_push(ary, th->thread);
          default:
            break;
        }
    }
    END_FOREACH(th);

    return ary;
}


critical (Thread)

/*
 *  call-seq:
 *     Thread.critical   => true or false
 *
 *  Returns the status of the global ``thread critical'' condition.
 */

static VALUE
rb_thread_critical_get()
{
    return rb_thread_critical?Qtrue:Qfalse;
}


critical= (Thread)

/*
 *  call-seq:
 *     Thread.critical= boolean   => true or false
 *
 *  Sets the status of the global ``thread critical'' condition and returns
 *  it. When set to <code>true</code>, prohibits scheduling of any existing
 *  thread. Does not block new threads from being created and run. Certain
 *  thread operations (such as stopping or killing a thread, sleeping in the
 *  current thread, and raising an exception) may cause a thread to be scheduled
 *  even when in a critical section.  <code>Thread::critical</code> is not
 *  intended for daily use: it is primarily there to support folks writing
 *  threading libraries.
 */

static VALUE
rb_thread_critical_set(obj, val)
    VALUE obj, val;
{
    rb_thread_critical = RTEST(val);
    return val;
}


abort_on_exception (Thread)

/*
 *  call-seq:
 *     Thread.abort_on_exception   => true or false
 *
 *  Returns the status of the global ``abort on exception'' condition.  The
 *  default is <code>false</code>. When set to <code>true</code>, or if the
 *  global <code>$DEBUG</code> flag is <code>true</code> (perhaps because the
 *  command line option <code>-d</code> was specified) all threads will abort
 *  (the process will <code>exit(0)</code>) if an exception is raised in any
 *  thread. See also <code>Thread::abort_on_exception=</code>.
 */

static VALUE
rb_thread_s_abort_exc()
{
    return ruby_thread_abort?Qtrue:Qfalse;
}


abort_on_exception= (Thread)

/*
 *  call-seq:
 *     Thread.abort_on_exception= boolean   => true or false
 *
 *  When set to <code>true</code>, all threads will abort if an exception is
 *  raised. Returns the new state.
 *
 *     Thread.abort_on_exception = true
 *     t1 = Thread.new do
 *       puts  "In new thread"
 *       raise "Exception from thread"
 *     end
 *     sleep(1)
 *     puts "not reached"
 *
 *  <em>produces:</em>
 *
 *     In new thread
 *     prog.rb:4: Exception from thread (RuntimeError)
 *      from prog.rb:2:in `initialize'
 *      from prog.rb:2:in `new'
 *      from prog.rb:2
 */

static VALUE
rb_thread_s_abort_exc_set(self, val)
    VALUE self, val;
{
    rb_secure(4);
    ruby_thread_abort = RTEST(val);
    return val;
}


run (Thread)

/*
 *  call-seq:
 *     thr.run   => thr
 *
 *  Wakes up <i>thr</i>, making it eligible for scheduling. If not in a critical
 *  section, then invokes the scheduler.
 *
 *     a = Thread.new { puts "a"; Thread.stop; puts "c" }
 *     Thread.pass
 *     puts "Got here"
 *     a.run
 *     a.join
 *
 *  <em>produces:</em>
 *
 *     a
 *     Got here
 *     c
 */

VALUE
rb_thread_run(thread)
    VALUE thread;
{
    rb_thread_wakeup(thread);
    if (!rb_thread_critical) rb_thread_schedule();

    return thread;
}


wakeup (Thread)

/*
 *  call-seq:
 *     thr.wakeup   => thr
 *
 *  Marks <i>thr</i> as eligible for scheduling (it may still remain blocked on
 *  I/O, however). Does not invoke the scheduler (see <code>Thread#run</code>).
 *
 *     c = Thread.new { Thread.stop; puts "hey!" }
 *     c.wakeup
 *
 *  <em>produces:</em>
 *
 *     hey!
 */

VALUE
rb_thread_wakeup(thread)
    VALUE thread;
{
    if (!RTEST(rb_thread_wakeup_alive(thread)))
        rb_raise(rb_eThreadError, "killed thread");
    return thread;
}


kill (Thread)

/*
 *  call-seq:
 *     thr.exit        => thr
 *     thr.kill        => thr
 *     thr.terminate   => thr
 *
 *  Terminates <i>thr</i> and schedules another thread to be run, returning
 *  the terminated <code>Thread</code>.  If this is the main thread, or the
 *  last thread, exits the process.
 */

VALUE
rb_thread_kill(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    rb_kill_thread(th, 0);
    return thread;
}


terminate (Thread)

/*
 *  call-seq:
 *     thr.exit        => thr
 *     thr.kill        => thr
 *     thr.terminate   => thr
 *
 *  Terminates <i>thr</i> and schedules another thread to be run, returning
 *  the terminated <code>Thread</code>.  If this is the main thread, or the
 *  last thread, exits the process.
 */

VALUE
rb_thread_kill(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    rb_kill_thread(th, 0);
    return thread;
}


exit (Thread)

/*
 *  call-seq:
 *     thr.exit        => thr
 *     thr.kill        => thr
 *     thr.terminate   => thr
 *
 *  Terminates <i>thr</i> and schedules another thread to be run, returning
 *  the terminated <code>Thread</code>.  If this is the main thread, or the
 *  last thread, exits the process.
 */

VALUE
rb_thread_kill(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    rb_kill_thread(th, 0);
    return thread;
}


kill! (Thread)

/*
 *  call-seq:
 *     thr.exit!        => thr
 *     thr.kill!        => thr
 *     thr.terminate!   => thr
 *
 *  Terminates <i>thr</i> without calling ensure clauses and schedules
 *  another thread to be run, returning the terminated <code>Thread</code>.
 *  If this is the main thread, or the last thread, exits the process.
 *
 *  See <code>Thread#exit</code> for the safer version.
 */

static VALUE
rb_thread_kill_bang(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    rb_kill_thread(th, THREAD_NO_ENSURE);
    return thread;
}


terminate! (Thread)

/*
 *  call-seq:
 *     thr.exit!        => thr
 *     thr.kill!        => thr
 *     thr.terminate!   => thr
 *
 *  Terminates <i>thr</i> without calling ensure clauses and schedules
 *  another thread to be run, returning the terminated <code>Thread</code>.
 *  If this is the main thread, or the last thread, exits the process.
 *
 *  See <code>Thread#exit</code> for the safer version.
 */

static VALUE
rb_thread_kill_bang(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    rb_kill_thread(th, THREAD_NO_ENSURE);
    return thread;
}


exit! (Thread)

/*
 *  call-seq:
 *     thr.exit!        => thr
 *     thr.kill!        => thr
 *     thr.terminate!   => thr
 *
 *  Terminates <i>thr</i> without calling ensure clauses and schedules
 *  another thread to be run, returning the terminated <code>Thread</code>.
 *  If this is the main thread, or the last thread, exits the process.
 *
 *  See <code>Thread#exit</code> for the safer version.
 */

static VALUE
rb_thread_kill_bang(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    rb_kill_thread(th, THREAD_NO_ENSURE);
    return thread;
}


value (Thread)

/*
 *  call-seq:
 *     thr.value   => obj
 *
 *  Waits for <i>thr</i> to complete (via <code>Thread#join</code>) and returns
 *  its value.
 *
 *     a = Thread.new { 2 + 2 }
 *     a.value   #=> 4
 */

static VALUE
rb_thread_value(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    while (!rb_thread_join(th, DELAY_INFTY));

    return th->result;
}


status (Thread)

/*
 *  call-seq:
 *     thr.status   => string, false or nil
 *
 *  Returns the status of <i>thr</i>: ``<code>sleep</code>'' if <i>thr</i> is
 *  sleeping or waiting on I/O, ``<code>run</code>'' if <i>thr</i> is executing,
 *  ``<code>aborting</code>'' if <i>thr</i> is aborting, <code>false</code> if
 *  <i>thr</i> terminated normally, and <code>nil</code> if <i>thr</i>
 *  terminated with an exception.
 *
 *     a = Thread.new { raise("die now") }
 *     b = Thread.new { Thread.stop }
 *     c = Thread.new { Thread.exit }
 *     d = Thread.new { sleep }
 *     Thread.critical = true
 *     d.kill                  #=> #<Thread:0x401b3678 aborting>
 *     a.status                #=> nil
 *     b.status                #=> "sleep"
 *     c.status                #=> false
 *     d.status                #=> "aborting"
 *     Thread.current.status   #=> "run"
 */

static VALUE
rb_thread_status_name(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (rb_thread_dead(th)) {
        if (!NIL_P(th->errinfo) && (th->flags & THREAD_RAISED))
            return Qnil;
        return Qfalse;
    }

    return rb_str_new2(thread_status_name(th->status));
}


join (Thread)

/*
 *  call-seq:
 *     thr.join          => thr
 *     thr.join(limit)   => thr
 *
 *  The calling thread will suspend execution and run <i>thr</i>. Does not
 *  return until <i>thr</i> exits or until <i>limit</i> seconds have passed. If
 *  the time limit expires, <code>nil</code> will be returned, otherwise
 *  <i>thr</i> is returned.
 *
 *  Any threads not joined will be killed when the main program exits.  If
 *  <i>thr</i> had previously raised an exception and the
 *  <code>abort_on_exception</code> and <code>$DEBUG</code> flags are not set
 *  (so the exception has not yet been processed) it will be processed at this
 *  time.
 *
 *     a = Thread.new { print "a"; sleep(10); print "b"; print "c" }
 *     x = Thread.new { print "x"; Thread.pass; print "y"; print "z" }
 *     x.join # Let x thread finish, a will be killed on exit.
 *
 *  <em>produces:</em>
 *
 *     axyz
 *
 *  The following example illustrates the <i>limit</i> parameter.
 *
 *     y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
 *     puts "Waiting" until y.join(0.15)
 *
 *  <em>produces:</em>
 *
 *     tick...
 *     Waiting
 *     tick...
 *     Waitingtick...
 *
 *
 *     tick...
 */

static VALUE
rb_thread_join_m(argc, argv, thread)
    int argc;
    VALUE *argv;
    VALUE thread;
{
    VALUE limit;
    double delay = DELAY_INFTY;
    rb_thread_t th = rb_thread_check(thread);

    rb_scan_args(argc, argv, "01", &limit);
    if (!NIL_P(limit)) delay = rb_num2dbl(limit);
    if (!rb_thread_join(th, delay))
        return Qnil;
    return thread;
}


alive? (Thread)

/*
 *  call-seq:
 *     thr.alive?   => true or false
 *
 *  Returns <code>true</code> if <i>thr</i> is running or sleeping.
 *
 *     thr = Thread.new { }
 *     thr.join                #=> #<Thread:0x401b3fb0 dead>
 *     Thread.current.alive?   #=> true
 *     thr.alive?              #=> false
 */

VALUE
rb_thread_alive_p(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (rb_thread_dead(th)) return Qfalse;
    return Qtrue;
}


stop? (Thread)

/*
 *  call-seq:
 *     thr.stop?   => true or false
 *
 *  Returns <code>true</code> if <i>thr</i> is dead or sleeping.
 *
 *     a = Thread.new { Thread.stop }
 *     b = Thread.current
 *     a.stop?   #=> true
 *     b.stop?   #=> false
 */

static VALUE
rb_thread_stop_p(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (rb_thread_dead(th)) return Qtrue;
    if (th->status == THREAD_STOPPED) return Qtrue;
    return Qfalse;
}


raise (Thread)

/*
 *  call-seq:
 *     thr.raise(exception)
 *
 *  Raises an exception (see <code>Kernel::raise</code>) from <i>thr</i>. The
 *  caller does not have to be <i>thr</i>.
 *
 *     Thread.abort_on_exception = true
 *     a = Thread.new { sleep(200) }
 *     a.raise("Gotcha")
 *
 *  <em>produces:</em>
 *
 *     prog.rb:3: Gotcha (RuntimeError)
 *      from prog.rb:2:in `initialize'
 *      from prog.rb:2:in `new'
 *      from prog.rb:2
 */

static VALUE
rb_thread_raise_m(argc, argv, thread)
    int argc;
    VALUE *argv;
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (ruby_safe_level > th->safe) {
        rb_secure(4);
    }
    rb_thread_raise(argc, argv, th);
    return Qnil;                /* not reached */
}


abort_on_exception (Thread)

/*
 *  call-seq:
 *     thr.abort_on_exception   => true or false
 *
 *  Returns the status of the thread-local ``abort on exception'' condition for
 *  <i>thr</i>. The default is <code>false</code>. See also
 *  <code>Thread::abort_on_exception=</code>.
 */

static VALUE
rb_thread_abort_exc(thread)
    VALUE thread;
{
    return rb_thread_check(thread)->abort?Qtrue:Qfalse;
}


abort_on_exception= (Thread)

/*
 *  call-seq:
 *     thr.abort_on_exception= boolean   => true or false
 *
 *  When set to <code>true</code>, causes all threads (including the main
 *  program) to abort if an exception is raised in <i>thr</i>. The process will
 *  effectively <code>exit(0)</code>.
 */

static VALUE
rb_thread_abort_exc_set(thread, val)
    VALUE thread, val;
{
    rb_secure(4);
    rb_thread_check(thread)->abort = RTEST(val);
    return val;
}


priority (Thread)

/*
 *  call-seq:
 *     thr.priority   => integer
 *
 *  Returns the priority of <i>thr</i>. Default is inherited from the
 *  current thread which creating the new thread, or zero for the
 *  initial main thread; higher-priority threads will run before
 *  lower-priority threads.
 *
 *     Thread.current.priority   #=> 0
 */

static VALUE
rb_thread_priority(thread)
    VALUE thread;
{
    return INT2NUM(rb_thread_check(thread)->priority);
}


priority= (Thread)

/*
 *  call-seq:
 *     thr.priority= integer   => thr
 *
 *  Sets the priority of <i>thr</i> to <i>integer</i>. Higher-priority threads
 *  will run before lower-priority threads.
 *
 *     count1 = count2 = 0
 *     a = Thread.new do
 *           loop { count1 += 1 }
 *         end
 *     a.priority = -1
 *
 *     b = Thread.new do
 *           loop { count2 += 1 }
 *         end
 *     b.priority = -2
 *     sleep 1   #=> 1
 *     Thread.critical = 1
 *     count1    #=> 622504
 *     count2    #=> 5832
 */

static VALUE
rb_thread_priority_set(thread, prio)
    VALUE thread, prio;
{
    rb_thread_t th;

    rb_secure(4);
    th = rb_thread_check(thread);

    th->priority = NUM2INT(prio);
    rb_thread_schedule();
    return prio;
}


safe_level (Thread)

/*
 *  call-seq:
 *     thr.safe_level   => integer
 *
 *  Returns the safe level in effect for <i>thr</i>. Setting thread-local safe
 *  levels can help when implementing sandboxes which run insecure code.
 *
 *     thr = Thread.new { $SAFE = 3; sleep }
 *     Thread.current.safe_level   #=> 0
 *     thr.safe_level              #=> 3
 */

static VALUE
rb_thread_safe_level(thread)
    VALUE thread;
{
    rb_thread_t th;

    th = rb_thread_check(thread);
    if (th == curr_thread) {
        return INT2NUM(ruby_safe_level);
    }
    return INT2NUM(th->safe);
}


group (Thread)

/*
 *  call-seq:
 *     thr.group   => thgrp or nil
 *
 *  Returns the <code>ThreadGroup</code> which contains <i>thr</i>, or nil if
 *  the thread is not a member of any group.
 *
 *     Thread.main.group   #=> #<ThreadGroup:0x4029d914>
 */

VALUE
rb_thread_group(thread)
    VALUE thread;
{
    VALUE group = rb_thread_check(thread)->thgroup;
    if (!group) {
        group = Qnil;
    }
    return group;
}


[] (Thread)

/*
 *  call-seq:
 *      thr[sym]   => obj or nil
 *
 *  Attribute Reference---Returns the value of a thread-local variable, using
 *  either a symbol or a string name. If the specified variable does not exist,
 *  returns <code>nil</code>.
 *
 *     a = Thread.new { Thread.current["name"] = "A"; Thread.stop }
 *     b = Thread.new { Thread.current[:name]  = "B"; Thread.stop }
 *     c = Thread.new { Thread.current["name"] = "C"; Thread.stop }
 *     Thread.list.each {|x| puts "#{x.inspect}: #{x[:name]}" }
 *
 *  <em>produces:</em>
 *
 *     #<Thread:0x401b3b3c sleep>: C
 *     #<Thread:0x401b3bc8 sleep>: B
 *     #<Thread:0x401b3c68 sleep>: A
 *     #<Thread:0x401bdf4c run>:
 */

static VALUE
rb_thread_aref(thread, id)
    VALUE thread, id;
{
    return rb_thread_local_aref(thread, rb_to_id(id));
}


[]= (Thread)

/*
 *  call-seq:
 *      thr[sym] = obj   => obj
 *
 *  Attribute Assignment---Sets or creates the value of a thread-local variable,
 *  using either a symbol or a string. See also <code>Thread#[]</code>.
 */

static VALUE
rb_thread_aset(thread, id, val)
    VALUE thread, id, val;
{
    return rb_thread_local_aset(thread, rb_to_id(id), val);
}


key? (Thread)

/*
 *  call-seq:
 *     thr.key?(sym)   => true or false
 *
 *  Returns <code>true</code> if the given string (or symbol) exists as a
 *  thread-local variable.
 *
 *     me = Thread.current
 *     me[:oliver] = "a"
 *     me.key?(:oliver)    #=> true
 *     me.key?(:stanley)   #=> false
 */

static VALUE
rb_thread_key_p(thread, id)
    VALUE thread, id;
{
    rb_thread_t th = rb_thread_check(thread);

    if (!th->locals) return Qfalse;
    if (st_lookup(th->locals, rb_to_id(id), 0))
        return Qtrue;
    return Qfalse;
}


keys (Thread)

/*
 *  call-seq:
 *     thr.keys   => array
 *
 *  Returns an an array of the names of the thread-local variables (as Symbols).
 *
 *     thr = Thread.new do
 *       Thread.current[:cat] = 'meow'
 *       Thread.current["dog"] = 'woof'
 *     end
 *     thr.join   #=> #<Thread:0x401b3f10 dead>
 *     thr.keys   #=> [:dog, :cat]
 */

static VALUE
rb_thread_keys(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    VALUE ary = rb_ary_new();

    if (th->locals) {
        st_foreach(th->locals, thread_keys_i, ary);
    }
    return ary;
}


inspect (Thread)

/*
 * call-seq:
 *   thr.inspect   => string
 *
 * Dump the name, id, and status of _thr_ to a string.
 */

static VALUE
rb_thread_inspect(thread)
    VALUE thread;
{
    char *cname = rb_obj_classname(thread);
    rb_thread_t th = rb_thread_check(thread);
    const char *status = thread_status_name(th->status);
    VALUE str;
    size_t len = strlen(cname)+7+16+9+1;

    str = rb_str_new(0, len); /* 7:tags 16:addr 9:status 1:nul */
    snprintf(RSTRING(str)->ptr, len, "#<%s:0x%lx %s>", cname, thread, status);
    RSTRING(str)->len = strlen(RSTRING(str)->ptr);
    OBJ_INFECT(str, thread);

    return str;
}


exclusive (Thread)

# File lib/thread.rb, line 24
  def Thread.exclusive
    _old = Thread.critical
    begin
      Thread.critical = true
      return yield
    ensure
      Thread.critical = _old
    end
  end


list (ThreadGroup)

/*
 *  call-seq:
 *     thgrp.list   => array
 *
 *  Returns an array of all existing <code>Thread</code> objects that belong to
 *  this group.
 *
 *     ThreadGroup::Default.list   #=> [#<Thread:0x401bdf4c run>]
 */

static VALUE
thgroup_list(group)
    VALUE group;
{
    struct thgroup *data;
    rb_thread_t th;
    VALUE ary;

    Data_Get_Struct(group, struct thgroup, data);
    ary = rb_ary_new();

    FOREACH_THREAD(th) {
        if (th->thgroup == data->group) {
            rb_ary_push(ary, th->thread);
        }
    }
    END_FOREACH(th);

    return ary;
}


enclose (ThreadGroup)

/*
 *  call-seq:
 *     thgrp.enclose   => thgrp
 *
 *  Prevents threads from being added to or removed from the receiving
 *  <code>ThreadGroup</code>. New threads can still be started in an enclosed
 *  <code>ThreadGroup</code>.
 *
 *     ThreadGroup::Default.enclose        #=> #<ThreadGroup:0x4029d914>
 *     thr = Thread::new { Thread.stop }   #=> #<Thread:0x402a7210 sleep>
 *     tg = ThreadGroup::new               #=> #<ThreadGroup:0x402752d4>
 *     tg.add thr
 *
 *  <em>produces:</em>
 *
 *     ThreadError: can't move from the enclosed thread group
 */

static VALUE
thgroup_enclose(group)
    VALUE group;
{
    struct thgroup *data;

    Data_Get_Struct(group, struct thgroup, data);
    data->enclosed = 1;

    return group;
}


enclosed? (ThreadGroup)

/*
 *  call-seq:
 *     thgrp.enclosed?   => true or false
 *
 *  Returns <code>true</code> if <em>thgrp</em> is enclosed. See also
 *  ThreadGroup#enclose.
 */

static VALUE
thgroup_enclosed_p(group)
    VALUE group;
{
    struct thgroup *data;

    Data_Get_Struct(group, struct thgroup, data);
    if (data->enclosed) return Qtrue;
    return Qfalse;
}


add (ThreadGroup)

/*
 *  call-seq:
 *     thgrp.add(thread)   => thgrp
 *
 *  Adds the given <em>thread</em> to this group, removing it from any other
 *  group to which it may have previously belonged.
 *
 *     puts "Initial group is #{ThreadGroup::Default.list}"
 *     tg = ThreadGroup.new
 *     t1 = Thread.new { sleep }
 *     t2 = Thread.new { sleep }
 *     puts "t1 is #{t1}"
 *     puts "t2 is #{t2}"
 *     tg.add(t1)
 *     puts "Initial group now #{ThreadGroup::Default.list}"
 *     puts "tg group now #{tg.list}"
 *
 *  <em>produces:</em>
 *
 *     Initial group is #<Thread:0x401bdf4c>
 *     t1 is #<Thread:0x401b3c90>
 *     t2 is #<Thread:0x401b3c18>
 *     Initial group now #<Thread:0x401b3c18>#<Thread:0x401bdf4c>
 *     tg group now #<Thread:0x401b3c90>
 */

static VALUE
thgroup_add(group, thread)
    VALUE group, thread;
{
    rb_thread_t th;
    struct thgroup *data;

    rb_secure(4);
    th = rb_thread_check(thread);
    if (!th->next || !th->prev) {
        rb_raise(rb_eTypeError, "wrong argument type %s (expected Thread)",
                 rb_obj_classname(thread));
    }

    if (OBJ_FROZEN(group)) {
      rb_raise(rb_eThreadError, "can't move to the frozen thread group");
    }
    Data_Get_Struct(group, struct thgroup, data);
    if (data->enclosed) {
        rb_raise(rb_eThreadError, "can't move to the enclosed thread group");
    }

    if (!th->thgroup) {
        return Qnil;
    }
    if (OBJ_FROZEN(th->thgroup)) {
        rb_raise(rb_eThreadError, "can't move from the frozen thread group");
    }
    Data_Get_Struct(th->thgroup, struct thgroup, data);
    if (data->enclosed) {
        rb_raise(rb_eThreadError, "can't move from the enclosed thread group");
    }

    th->thgroup = group;
    return group;
}


all_waits (ThreadsWait)

# File lib/thwait.rb, line 65
  def ThreadsWait.all_waits(*threads) # :yield: thread
    tw = ThreadsWait.new(*threads)
    if block_given?
      tw.all_waits do |th|
        yield th
      end
    else
      tw.all_waits
    end
  end


new (ThreadsWait)

# File lib/thwait.rb, line 80
  def initialize(*threads)
    @threads = []
    @wait_queue = Queue.new
    join_nowait(*threads) unless threads.empty?
  end


empty? (ThreadsWait)

# File lib/thwait.rb, line 92
  def empty?
    @threads.empty?
  end


finished? (ThreadsWait)

# File lib/thwait.rb, line 99
  def finished?
    !@wait_queue.empty?
  end


join (ThreadsWait)

# File lib/thwait.rb, line 106
  def join(*threads)
    join_nowait(*threads)
    next_wait
  end


join_nowait (ThreadsWait)

# File lib/thwait.rb, line 115
  def join_nowait(*threads)
    threads.flatten!
    @threads.concat threads
    for th in threads
      Thread.start(th) do |t|
        begin
          t.join
        ensure
          @wait_queue.push t
        end
      end
    end
  end


next_wait (ThreadsWait)

# File lib/thwait.rb, line 136
  def next_wait(nonblock = nil)
    ThreadsWait.fail ErrNoWaitingThread if @threads.empty?
    begin
      @threads.delete(th = @wait_queue.pop(nonblock))
      th
    rescue ThreadError
      ThreadsWait.fail ErrNoFinishedThread
    end
  end


all_waits (ThreadsWait)

# File lib/thwait.rb, line 152
  def all_waits
    until @threads.empty?
      th = next_wait
      yield th if block_given?
    end
  end


at (Time)

/*
 *  call-seq:
 *     Time.at( aTime ) => time
 *     Time.at( seconds [, microseconds] ) => time
 *
 *  Creates a new time object with the value given by <i>aTime</i>, or
 *  the given number of <i>seconds</i> (and optional
 *  <i>microseconds</i>) from epoch. A non-portable feature allows the
 *  offset to be negative on some systems.
 *
 *     Time.at(0)            #=> Wed Dec 31 18:00:00 CST 1969
 *     Time.at(946702800)    #=> Fri Dec 31 23:00:00 CST 1999
 *     Time.at(-284061600)   #=> Sat Dec 31 00:00:00 CST 1960
 */

static VALUE
time_s_at(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    struct timeval tv;
    VALUE time, t;

    if (rb_scan_args(argc, argv, "11", &time, &t) == 2) {
        tv.tv_sec = NUM2LONG(time);
        tv.tv_usec = NUM2LONG(t);
    }
    else {
        tv = rb_time_timeval(time);
    }
    t = time_new_internal(klass, tv.tv_sec, tv.tv_usec);
    if (TYPE(time) == T_DATA && RDATA(time)->dfree == time_free) {
        struct time_object *tobj, *tobj2;

        GetTimeval(time, tobj);
        GetTimeval(t, tobj2);
        tobj2->gmt = tobj->gmt;
    }
    return t;
}


utc (Time)

/*
 *  call-seq:
 *     Time.utc( year [, month, day, hour, min, sec, usec] ) => time
 *     Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz
 *     ) => time
 *     Time.gm( year [, month, day, hour, min, sec, usec] ) => time
 *     Time.gm( sec, min, hour, day, month, year, wday, yday, isdst, tz
 *     ) => time
 *
 *  Creates a time based on given values, interpreted as UTC (GMT). The
 *  year must be specified. Other values default to the minimum value
 *  for that field (and may be <code>nil</code> or omitted). Months may
 *  be specified by numbers from 1 to 12, or by the three-letter English
 *  month names. Hours are specified on a 24-hour clock (0..23). Raises
 *  an <code>ArgumentError</code> if any values are out of range. Will
 *  also accept ten arguments in the order output by
 *  <code>Time#to_a</code>.
 *
 *     Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
 *     Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 */
static VALUE
time_s_mkutc(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return time_utc_or_local(argc, argv, Qtrue, klass);
}


gm (Time)

/*
 *  call-seq:
 *     Time.utc( year [, month, day, hour, min, sec, usec] ) => time
 *     Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz
 *     ) => time
 *     Time.gm( year [, month, day, hour, min, sec, usec] ) => time
 *     Time.gm( sec, min, hour, day, month, year, wday, yday, isdst, tz
 *     ) => time
 *
 *  Creates a time based on given values, interpreted as UTC (GMT). The
 *  year must be specified. Other values default to the minimum value
 *  for that field (and may be <code>nil</code> or omitted). Months may
 *  be specified by numbers from 1 to 12, or by the three-letter English
 *  month names. Hours are specified on a 24-hour clock (0..23). Raises
 *  an <code>ArgumentError</code> if any values are out of range. Will
 *  also accept ten arguments in the order output by
 *  <code>Time#to_a</code>.
 *
 *     Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
 *     Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 */
static VALUE
time_s_mkutc(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return time_utc_or_local(argc, argv, Qtrue, klass);
}


local (Time)

/*
 *  call-seq:
 *     Time.local( year [, month, day, hour, min, sec, usec] ) => time
 *     Time.local( sec, min, hour, day, month, year, wday, yday, isdst,
 *     tz ) => time
 *     Time.mktime( year, month, day, hour, min, sec, usec )   => time
 *
 *  Same as <code>Time::gm</code>, but interprets the values in the
 *  local time zone.
 *
 *     Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
 */

static VALUE
time_s_mktime(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return time_utc_or_local(argc, argv, Qfalse, klass);
}


mktime (Time)

/*
 *  call-seq:
 *     Time.local( year [, month, day, hour, min, sec, usec] ) => time
 *     Time.local( sec, min, hour, day, month, year, wday, yday, isdst,
 *     tz ) => time
 *     Time.mktime( year, month, day, hour, min, sec, usec )   => time
 *
 *  Same as <code>Time::gm</code>, but interprets the values in the
 *  local time zone.
 *
 *     Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
 */

static VALUE
time_s_mktime(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return time_utc_or_local(argc, argv, Qfalse, klass);
}


times (Time)

/*
 *  call-seq:
 *     Time.times => struct_tms
 *
 *  Deprecated in favor of <code>Process::times</code>
 */

static VALUE
time_s_times(obj)
    VALUE obj;
{
    rb_warn("obsolete method Time::times; use Process::times");
    return rb_proc_times(obj);
}


to_i (Time)

/*
 *  call-seq:
 *     time.to_i   => int
 *     time.tv_sec => int
 *
 *  Returns the value of <i>time</i> as an integer number of seconds
 *  since epoch.
 *
 *     t = Time.now
 *     "%10.5f" % t.to_f   #=> "1049896564.17839"
 *     t.to_i              #=> 1049896564
 */

static VALUE
time_to_i(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return LONG2NUM(tobj->tv.tv_sec);
}


to_f (Time)

/*
 *  call-seq:
 *     time.to_f => float
 *
 *  Returns the value of <i>time</i> as a floating point number of
 *  seconds since epoch.
 *
 *     t = Time.now
 *     "%10.5f" % t.to_f   #=> "1049896564.13654"
 *     t.to_i              #=> 1049896564
 */

static VALUE
time_to_f(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return rb_float_new((double)tobj->tv.tv_sec+(double)tobj->tv.tv_usec/1e6);
}


<=> (Time)

/*
 *  call-seq:
 *     time <=> other_time => -1, 0, +1
 *     time <=> numeric    => -1, 0, +1
 *
 *  Comparison---Compares <i>time</i> with <i>other_time</i> or with
 *  <i>numeric</i>, which is the number of seconds (possibly
 *  fractional) since epoch.
 *
 *     t = Time.now       #=> Wed Apr 09 08:56:03 CDT 2003
 *     t2 = t + 2592000   #=> Fri May 09 08:56:03 CDT 2003
 *     t <=> t2           #=> -1
 *     t2 <=> t           #=> 1
 *     t <=> t            #=> 0
 */

static VALUE
time_cmp(time1, time2)
    VALUE time1, time2;
{
    struct time_object *tobj1, *tobj2;

    GetTimeval(time1, tobj1);
    if (TYPE(time2) == T_DATA && RDATA(time2)->dfree == time_free) {
        GetTimeval(time2, tobj2);
        if (tobj1->tv.tv_sec == tobj2->tv.tv_sec) {
            if (tobj1->tv.tv_usec == tobj2->tv.tv_usec) return INT2FIX(0);
            if (tobj1->tv.tv_usec > tobj2->tv.tv_usec) return INT2FIX(1);
            return INT2FIX(-1);
        }
        if (tobj1->tv.tv_sec > tobj2->tv.tv_sec) return INT2FIX(1);
        return INT2FIX(-1);
    }

    return Qnil;
}


eql? (Time)

/*
 * call-seq:
 *  time.eql?(other_time)
 *
 * Return <code>true</code> if <i>time</i> and <i>other_time</i> are
 * both <code>Time</code> objects with the same seconds and fractional
 * seconds.
 */

static VALUE
time_eql(time1, time2)
    VALUE time1, time2;
{
    struct time_object *tobj1, *tobj2;

    GetTimeval(time1, tobj1);
    if (TYPE(time2) == T_DATA && RDATA(time2)->dfree == time_free) {
        GetTimeval(time2, tobj2);
        if (tobj1->tv.tv_sec == tobj2->tv.tv_sec) {
            if (tobj1->tv.tv_usec == tobj2->tv.tv_usec) return Qtrue;
        }
    }
    return Qfalse;
}


hash (Time)

/*
 * call-seq:
 *   time.hash   => fixnum
 *
 * Return a hash code for this time object.
 */

static VALUE
time_hash(time)
    VALUE time;
{
    struct time_object *tobj;
    long hash;

    GetTimeval(time, tobj);
    hash = tobj->tv.tv_sec ^ tobj->tv.tv_usec;
    return LONG2FIX(hash);
}


new (Time)

/*
 *  Document-method: now
 *
 *  Synonym for <code>Time.new</code>. Returns a +Time+ object
 *  initialized tot he current system time.
 *
 *  call-seq:
 *     Time.new -> time
 *
 *  Returns a <code>Time</code> object initialized to the current system
 *  time. <b>Note:</b> The object created will be created using the
 *  resolution available on your system clock, and so may include
 *  fractional seconds.
 *
 *     a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
 *     b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
 *     a == b            #=> false
 *     "%.6f" % a.to_f   #=> "1049896563.230740"
 *     "%.6f" % b.to_f   #=> "1049896563.231466"
 *
 */

static VALUE
time_init(time)
    VALUE time;
{
    struct time_object *tobj;

    time_modify(time);
    GetTimeval(time, tobj);
    tobj->tm_got=0;
    tobj->tv.tv_sec = 0;
    tobj->tv.tv_usec = 0;
    if (gettimeofday(&tobj->tv, 0) < 0) {
        rb_sys_fail("gettimeofday");
    }

    return time;
}


localtime (Time)

/*
 *  call-seq:
 *     time.localtime => time
 *
 *  Converts <i>time</i> to local time (using the local time zone in
 *  effect for this process) modifying the receiver.
 *
 *     t = Time.gm(2000, "jan", 1, 20, 15, 1)
 *     t.gmt?        #=> true
 *     t.localtime   #=> Sat Jan 01 14:15:01 CST 2000
 *     t.gmt?        #=> false
 */

static VALUE
time_localtime(time)
    VALUE time;
{
    struct time_object *tobj;
    struct tm *tm_tmp;
    time_t t;

    GetTimeval(time, tobj);
    if (!tobj->gmt) {
        if (tobj->tm_got)
            return time;
    }
    else {
        time_modify(time);
    }
    t = tobj->tv.tv_sec;
    tm_tmp = localtime(&t);
    if (!tm_tmp)
        rb_raise(rb_eArgError, "localtime error");
    tobj->tm = *tm_tmp;
    tobj->tm_got = 1;
    tobj->gmt = 0;
    return time;
}


gmtime (Time)

/*
 *  call-seq:
 *     time.gmtime    => time
 *     time.utc       => time
 *
 *  Converts <i>time</i> to UTC (GMT), modifying the receiver.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.gmt?         #=> false
 *     t.gmtime       #=> Wed Apr 09 13:56:03 UTC 2003
 *     t.gmt?         #=> true
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.utc?         #=> false
 *     t.utc          #=> Wed Apr 09 13:56:04 UTC 2003
 *     t.utc?         #=> true
 */

static VALUE
time_gmtime(time)
    VALUE time;
{
    struct time_object *tobj;
    struct tm *tm_tmp;
    time_t t;

    GetTimeval(time, tobj);
    if (tobj->gmt) {
        if (tobj->tm_got)
            return time;
    }
    else {
        time_modify(time);
    }
    t = tobj->tv.tv_sec;
    tm_tmp = gmtime(&t);
    if (!tm_tmp)
        rb_raise(rb_eArgError, "gmtime error");
    tobj->tm = *tm_tmp;
    tobj->tm_got = 1;
    tobj->gmt = 1;
    return time;
}


utc (Time)

/*
 *  call-seq:
 *     time.gmtime    => time
 *     time.utc       => time
 *
 *  Converts <i>time</i> to UTC (GMT), modifying the receiver.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.gmt?         #=> false
 *     t.gmtime       #=> Wed Apr 09 13:56:03 UTC 2003
 *     t.gmt?         #=> true
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.utc?         #=> false
 *     t.utc          #=> Wed Apr 09 13:56:04 UTC 2003
 *     t.utc?         #=> true
 */

static VALUE
time_gmtime(time)
    VALUE time;
{
    struct time_object *tobj;
    struct tm *tm_tmp;
    time_t t;

    GetTimeval(time, tobj);
    if (tobj->gmt) {
        if (tobj->tm_got)
            return time;
    }
    else {
        time_modify(time);
    }
    t = tobj->tv.tv_sec;
    tm_tmp = gmtime(&t);
    if (!tm_tmp)
        rb_raise(rb_eArgError, "gmtime error");
    tobj->tm = *tm_tmp;
    tobj->tm_got = 1;
    tobj->gmt = 1;
    return time;
}


getlocal (Time)

/*
 *  call-seq:
 *     time.getlocal => new_time
 *
 *  Returns a new <code>new_time</code> object representing <i>time</i> in
 *  local time (using the local time zone in effect for this process).
 *
 *     t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.gmt?                          #=> true
 *     l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
 *     l.gmt?                          #=> false
 *     t == l                          #=> true
 */

static VALUE
time_getlocaltime(time)
    VALUE time;
{
    return time_localtime(time_dup(time));
}


getgm (Time)

/*
 *  call-seq:
 *     time.getgm  => new_time
 *     time.getutc => new_time
 *
 *  Returns a new <code>new_time</code> object representing <i>time</i> in
 *  UTC.
 *
 *     t = Time.local(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
 *     t.gmt?                             #=> false
 *     y = t.getgm                        #=> Sun Jan 02 02:15:01 UTC 2000
 *     y.gmt?                             #=> true
 *     t == y                             #=> true
 */

static VALUE
time_getgmtime(time)
    VALUE time;
{
    return time_gmtime(time_dup(time));
}


getutc (Time)

/*
 *  call-seq:
 *     time.getgm  => new_time
 *     time.getutc => new_time
 *
 *  Returns a new <code>new_time</code> object representing <i>time</i> in
 *  UTC.
 *
 *     t = Time.local(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
 *     t.gmt?                             #=> false
 *     y = t.getgm                        #=> Sun Jan 02 02:15:01 UTC 2000
 *     y.gmt?                             #=> true
 *     t == y                             #=> true
 */

static VALUE
time_getgmtime(time)
    VALUE time;
{
    return time_gmtime(time_dup(time));
}


ctime (Time)

/*
 *  call-seq:
 *     time.asctime => string
 *     time.ctime   => string
 *
 *  Returns a canonical string representation of <i>time</i>.
 *
 *     Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"
 */

static VALUE
time_asctime(time)
    VALUE time;
{
    struct time_object *tobj;
    char *s;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    s = asctime(&tobj->tm);
    if (s[24] == '\n') s[24] = '\0';

    return rb_str_new2(s);
}


asctime (Time)

/*
 *  call-seq:
 *     time.asctime => string
 *     time.ctime   => string
 *
 *  Returns a canonical string representation of <i>time</i>.
 *
 *     Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"
 */

static VALUE
time_asctime(time)
    VALUE time;
{
    struct time_object *tobj;
    char *s;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    s = asctime(&tobj->tm);
    if (s[24] == '\n') s[24] = '\0';

    return rb_str_new2(s);
}


to_s (Time)

/*
 *  call-seq:
 *     time.inspect => string
 *     time.to_s    => string
 *
 *  Returns a string representing <i>time</i>. Equivalent to calling
 *  <code>Time#strftime</code> with a format string of ``<code>%a</code>
 *  <code>%b</code> <code>%d</code> <code>%H:%M:%S</code>
 *  <code>%Z</code> <code>%Y</code>''.
 *
 *     Time.now.to_s   #=> "Wed Apr 09 08:56:04 CDT 2003"
 */

static VALUE
time_to_s(time)
    VALUE time;
{
    struct time_object *tobj;
    char buf[128];
    int len;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    if (tobj->gmt == 1) {
        len = strftime(buf, 128, "%a %b %d %H:%M:%S UTC %Y", &tobj->tm);
    }
    else {
        time_t off;
        char buf2[32];
        char sign = '+';
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
        off = tobj->tm.tm_gmtoff;
#else
        VALUE tmp = time_utc_offset(time);
        off = NUM2INT(tmp);
#endif
        if (off < 0) {
            sign = '-';
            off = -off;
        }
        sprintf(buf2, "%%a %%b %%d %%H:%%M:%%S %c%02d%02d %%Y",
                sign, (int)(off/3600), (int)(off%3600/60));
        len = strftime(buf, 128, buf2, &tobj->tm);
    }
    return rb_str_new(buf, len);
}


inspect (Time)

/*
 *  call-seq:
 *     time.inspect => string
 *     time.to_s    => string
 *
 *  Returns a string representing <i>time</i>. Equivalent to calling
 *  <code>Time#strftime</code> with a format string of ``<code>%a</code>
 *  <code>%b</code> <code>%d</code> <code>%H:%M:%S</code>
 *  <code>%Z</code> <code>%Y</code>''.
 *
 *     Time.now.to_s   #=> "Wed Apr 09 08:56:04 CDT 2003"
 */

static VALUE
time_to_s(time)
    VALUE time;
{
    struct time_object *tobj;
    char buf[128];
    int len;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    if (tobj->gmt == 1) {
        len = strftime(buf, 128, "%a %b %d %H:%M:%S UTC %Y", &tobj->tm);
    }
    else {
        time_t off;
        char buf2[32];
        char sign = '+';
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
        off = tobj->tm.tm_gmtoff;
#else
        VALUE tmp = time_utc_offset(time);
        off = NUM2INT(tmp);
#endif
        if (off < 0) {
            sign = '-';
            off = -off;
        }
        sprintf(buf2, "%%a %%b %%d %%H:%%M:%%S %c%02d%02d %%Y",
                sign, (int)(off/3600), (int)(off%3600/60));
        len = strftime(buf, 128, buf2, &tobj->tm);
    }
    return rb_str_new(buf, len);
}


to_a (Time)

/*
 *  call-seq:
 *     time.to_a => array
 *
 *  Returns a ten-element <i>array</i> of values for <i>time</i>:
 *  {<code>[ sec, min, hour, day, month, year, wday, yday, isdst, zone
 *  ]</code>}. See the individual methods for an explanation of the
 *  valid ranges of each value. The ten elements can be passed directly
 *  to <code>Time::utc</code> or <code>Time::local</code> to create a
 *  new <code>Time</code>.
 *
 *     now = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t = now.to_a     #=> [4, 56, 8, 9, 4, 2003, 3, 99, true, "CDT"]
 */

static VALUE
time_to_a(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return rb_ary_new3(10,
                    INT2FIX(tobj->tm.tm_sec),
                    INT2FIX(tobj->tm.tm_min),
                    INT2FIX(tobj->tm.tm_hour),
                    INT2FIX(tobj->tm.tm_mday),
                    INT2FIX(tobj->tm.tm_mon+1),
                    LONG2NUM((long)tobj->tm.tm_year+1900),
                    INT2FIX(tobj->tm.tm_wday),
                    INT2FIX(tobj->tm.tm_yday+1),
                    tobj->tm.tm_isdst?Qtrue:Qfalse,
                    time_zone(time));
}


+ (Time)

/*
 *  call-seq:
 *     time + numeric => time
 *
 *  Addition---Adds some number of seconds (possibly fractional) to
 *  <i>time</i> and returns that value as a new time.
 *
 *     t = Time.now         #=> Wed Apr 09 08:56:03 CDT 2003
 *     t + (60 * 60 * 24)   #=> Thu Apr 10 08:56:03 CDT 2003
 */

static VALUE
time_plus(time1, time2)
    VALUE time1, time2;
{
    struct time_object *tobj;
    GetTimeval(time1, tobj);

    if (TYPE(time2) == T_DATA && RDATA(time2)->dfree == time_free) {
        rb_raise(rb_eTypeError, "time + time?");
    }
    return time_add(tobj, time2, 1);
}


- (Time)

/*
 *  call-seq:
 *     time - other_time => float
 *     time - numeric    => time
 *
 *  Difference---Returns a new time that represents the difference
 *  between two times, or subtracts the given number of seconds in
 *  <i>numeric</i> from <i>time</i>.
 *
 *     t = Time.now       #=> Wed Apr 09 08:56:03 CDT 2003
 *     t2 = t + 2592000   #=> Fri May 09 08:56:03 CDT 2003
 *     t2 - t             #=> 2592000.0
 *     t2 - 2592000       #=> Wed Apr 09 08:56:03 CDT 2003
 */

static VALUE
time_minus(time1, time2)
    VALUE time1, time2;
{
    struct time_object *tobj;

    GetTimeval(time1, tobj);
    if (TYPE(time2) == T_DATA && RDATA(time2)->dfree == time_free) {
        struct time_object *tobj2;
        double f;

        GetTimeval(time2, tobj2);
        f = (double)tobj->tv.tv_sec - (double)tobj2->tv.tv_sec;
        f += ((double)tobj->tv.tv_usec - (double)tobj2->tv.tv_usec)*1e-6;
        /* XXX: should check float overflow on 64bit time_t platforms */

        return rb_float_new(f);
    }
    return time_add(tobj, time2, -1);
}


succ (Time)

/*
 * call-seq:
 *   time.succ   => new_time
 *
 * Return a new time object, one second later than <code>time</code>.
 */

static VALUE
time_succ(time)
    VALUE time;
{
    struct time_object *tobj;
    int gmt;

    GetTimeval(time, tobj);
    gmt = tobj->gmt;
    time = rb_time_new(tobj->tv.tv_sec + 1, tobj->tv.tv_usec);
    GetTimeval(time, tobj);
    tobj->gmt = gmt;
    return time;
}


sec (Time)

/*
 *  call-seq:
 *     time.sec => fixnum
 *
 *  Returns the second of the minute (0..60)<em>[Yes, seconds really can
 *  range from zero to 60. This allows the system to inject leap seconds
 *  every now and then to correct for the fact that years are not really
 *  a convenient number of hours long.]</em> for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.sec          #=> 4
 */

static VALUE
time_sec(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_sec);
}


min (Time)

/*
 *  call-seq:
 *     time.min => fixnum
 *
 *  Returns the minute of the hour (0..59) for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.min          #=> 56
 */

static VALUE
time_min(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_min);
}


hour (Time)

/*
 *  call-seq:
 *     time.hour => fixnum
 *
 *  Returns the hour of the day (0..23) for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.hour         #=> 8
 */

static VALUE
time_hour(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_hour);
}


mday (Time)

/*
 *  call-seq:
 *     time.day  => fixnum
 *     time.mday => fixnum
 *
 *  Returns the day of the month (1..n) for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.day          #=> 9
 *     t.mday         #=> 9
 */

static VALUE
time_mday(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_mday);
}


day (Time)

/*
 *  call-seq:
 *     time.day  => fixnum
 *     time.mday => fixnum
 *
 *  Returns the day of the month (1..n) for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.day          #=> 9
 *     t.mday         #=> 9
 */

static VALUE
time_mday(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_mday);
}


mon (Time)

/*
 *  call-seq:
 *     time.mon   => fixnum
 *     time.month => fixnum
 *
 *  Returns the month of the year (1..12) for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.mon          #=> 4
 *     t.month        #=> 4
 */

static VALUE
time_mon(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_mon+1);
}


month (Time)

/*
 *  call-seq:
 *     time.mon   => fixnum
 *     time.month => fixnum
 *
 *  Returns the month of the year (1..12) for <i>time</i>.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.mon          #=> 4
 *     t.month        #=> 4
 */

static VALUE
time_mon(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_mon+1);
}


year (Time)

/*
 *  call-seq:
 *     time.year => fixnum
 *
 *  Returns the year for <i>time</i> (including the century).
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.year         #=> 2003
 */

static VALUE
time_year(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return LONG2NUM((long)tobj->tm.tm_year+1900);
}


wday (Time)

/*
 *  call-seq:
 *     time.wday => fixnum
 *
 *  Returns an integer representing the day of the week, 0..6, with
 *  Sunday == 0.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.wday         #=> 3
 */

static VALUE
time_wday(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_wday);
}


yday (Time)

/*
 *  call-seq:
 *     time.yday => fixnum
 *
 *  Returns an integer representing the day of the year, 1..366.
 *
 *     t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.yday         #=> 99
 */

static VALUE
time_yday(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return INT2FIX(tobj->tm.tm_yday+1);
}


isdst (Time)

/*
 *  call-seq:
 *     time.isdst => true or false
 *     time.dst?  => true or false
 *
 *  Returns <code>true</code> if <i>time</i> occurs during Daylight
 *  Saving Time in its time zone.
 *
 *     Time.local(2000, 7, 1).isdst   #=> true
 *     Time.local(2000, 1, 1).isdst   #=> false
 *     Time.local(2000, 7, 1).dst?    #=> true
 *     Time.local(2000, 1, 1).dst?    #=> false
 */

static VALUE
time_isdst(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return tobj->tm.tm_isdst?Qtrue:Qfalse;
}


dst? (Time)

/*
 *  call-seq:
 *     time.isdst => true or false
 *     time.dst?  => true or false
 *
 *  Returns <code>true</code> if <i>time</i> occurs during Daylight
 *  Saving Time in its time zone.
 *
 *     Time.local(2000, 7, 1).isdst   #=> true
 *     Time.local(2000, 1, 1).isdst   #=> false
 *     Time.local(2000, 7, 1).dst?    #=> true
 *     Time.local(2000, 1, 1).dst?    #=> false
 */

static VALUE
time_isdst(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    return tobj->tm.tm_isdst?Qtrue:Qfalse;
}


zone (Time)

/*
 *  call-seq:
 *     time.zone => string
 *
 *  Returns the name of the time zone used for <i>time</i>. As of Ruby
 *  1.8, returns ``UTC'' rather than ``GMT'' for UTC times.
 *
 *     t = Time.gm(2000, "jan", 1, 20, 15, 1)
 *     t.zone   #=> "UTC"
 *     t = Time.local(2000, "jan", 1, 20, 15, 1)
 *     t.zone   #=> "CST"
 */

static VALUE
time_zone(time)
    VALUE time;
{
    struct time_object *tobj;
#if !defined(HAVE_TM_ZONE) && (!defined(HAVE_TZNAME) || !defined(HAVE_DAYLIGHT))
    char buf[64];
    int len;
#endif

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }

    if (tobj->gmt == 1) {
        return rb_str_new2("UTC");
    }
#if defined(HAVE_TM_ZONE)
    return rb_str_new2(tobj->tm.tm_zone);
#elif defined(HAVE_TZNAME) && defined(HAVE_DAYLIGHT)
    return rb_str_new2(tzname[daylight && tobj->tm.tm_isdst]);
#else
    len = strftime(buf, 64, "%Z", &tobj->tm);
    return rb_str_new(buf, len);
#endif
}


gmtoff (Time)

/*
 *  call-seq:
 *     time.gmt_offset => fixnum
 *     time.gmtoff     => fixnum
 *     time.utc_offset => fixnum
 *
 *  Returns the offset in seconds between the timezone of <i>time</i>
 *  and UTC.
 *
 *     t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.gmt_offset                    #=> 0
 *     l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
 *     l.gmt_offset                    #=> -21600
 */

static VALUE
time_utc_offset(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }

    if (tobj->gmt == 1) {
        return INT2FIX(0);
    }
    else {
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
        return INT2NUM(tobj->tm.tm_gmtoff);
#else
        struct tm *u, *l;
        time_t t;
        long off;
        l = &tobj->tm;
        t = tobj->tv.tv_sec;
        u = gmtime(&t);
        if (!u)
            rb_raise(rb_eArgError, "gmtime error");
        if (l->tm_year != u->tm_year)
            off = l->tm_year < u->tm_year ? -1 : 1;
        else if (l->tm_mon != u->tm_mon)
            off = l->tm_mon < u->tm_mon ? -1 : 1;
        else if (l->tm_mday != u->tm_mday)
            off = l->tm_mday < u->tm_mday ? -1 : 1;
        else
            off = 0;
        off = off * 24 + l->tm_hour - u->tm_hour;
        off = off * 60 + l->tm_min - u->tm_min;
        off = off * 60 + l->tm_sec - u->tm_sec;
        return LONG2FIX(off);
#endif
    }
}


gmt_offset (Time)

/*
 *  call-seq:
 *     time.gmt_offset => fixnum
 *     time.gmtoff     => fixnum
 *     time.utc_offset => fixnum
 *
 *  Returns the offset in seconds between the timezone of <i>time</i>
 *  and UTC.
 *
 *     t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.gmt_offset                    #=> 0
 *     l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
 *     l.gmt_offset                    #=> -21600
 */

static VALUE
time_utc_offset(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }

    if (tobj->gmt == 1) {
        return INT2FIX(0);
    }
    else {
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
        return INT2NUM(tobj->tm.tm_gmtoff);
#else
        struct tm *u, *l;
        time_t t;
        long off;
        l = &tobj->tm;
        t = tobj->tv.tv_sec;
        u = gmtime(&t);
        if (!u)
            rb_raise(rb_eArgError, "gmtime error");
        if (l->tm_year != u->tm_year)
            off = l->tm_year < u->tm_year ? -1 : 1;
        else if (l->tm_mon != u->tm_mon)
            off = l->tm_mon < u->tm_mon ? -1 : 1;
        else if (l->tm_mday != u->tm_mday)
            off = l->tm_mday < u->tm_mday ? -1 : 1;
        else
            off = 0;
        off = off * 24 + l->tm_hour - u->tm_hour;
        off = off * 60 + l->tm_min - u->tm_min;
        off = off * 60 + l->tm_sec - u->tm_sec;
        return LONG2FIX(off);
#endif
    }
}


utc_offset (Time)

/*
 *  call-seq:
 *     time.gmt_offset => fixnum
 *     time.gmtoff     => fixnum
 *     time.utc_offset => fixnum
 *
 *  Returns the offset in seconds between the timezone of <i>time</i>
 *  and UTC.
 *
 *     t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.gmt_offset                    #=> 0
 *     l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
 *     l.gmt_offset                    #=> -21600
 */

static VALUE
time_utc_offset(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }

    if (tobj->gmt == 1) {
        return INT2FIX(0);
    }
    else {
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
        return INT2NUM(tobj->tm.tm_gmtoff);
#else
        struct tm *u, *l;
        time_t t;
        long off;
        l = &tobj->tm;
        t = tobj->tv.tv_sec;
        u = gmtime(&t);
        if (!u)
            rb_raise(rb_eArgError, "gmtime error");
        if (l->tm_year != u->tm_year)
            off = l->tm_year < u->tm_year ? -1 : 1;
        else if (l->tm_mon != u->tm_mon)
            off = l->tm_mon < u->tm_mon ? -1 : 1;
        else if (l->tm_mday != u->tm_mday)
            off = l->tm_mday < u->tm_mday ? -1 : 1;
        else
            off = 0;
        off = off * 24 + l->tm_hour - u->tm_hour;
        off = off * 60 + l->tm_min - u->tm_min;
        off = off * 60 + l->tm_sec - u->tm_sec;
        return LONG2FIX(off);
#endif
    }
}


utc? (Time)

/*
 *  call-seq:
 *     time.utc? => true or false
 *     time.gmt? => true or false
 *
 *  Returns <code>true</code> if <i>time</i> represents a time in UTC
 *  (GMT).
 *
 *     t = Time.now                        #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.utc?                              #=> false
 *     t = Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.utc?                              #=> true
 *
 *     t = Time.now                        #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.gmt?                              #=> false
 *     t = Time.gm(2000,1,1,20,15,1)       #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.gmt?                              #=> true
 */

static VALUE
time_utc_p(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->gmt) return Qtrue;
    return Qfalse;
}


gmt? (Time)

/*
 *  call-seq:
 *     time.utc? => true or false
 *     time.gmt? => true or false
 *
 *  Returns <code>true</code> if <i>time</i> represents a time in UTC
 *  (GMT).
 *
 *     t = Time.now                        #=> Wed Apr 09 08:56:04 CDT 2003
 *     t.utc?                              #=> false
 *     t = Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.utc?                              #=> true
 *
 *     t = Time.now                        #=> Wed Apr 09 08:56:03 CDT 2003
 *     t.gmt?                              #=> false
 *     t = Time.gm(2000,1,1,20,15,1)       #=> Sat Jan 01 20:15:01 UTC 2000
 *     t.gmt?                              #=> true
 */

static VALUE
time_utc_p(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (tobj->gmt) return Qtrue;
    return Qfalse;
}


tv_sec (Time)

/*
 *  call-seq:
 *     time.to_i   => int
 *     time.tv_sec => int
 *
 *  Returns the value of <i>time</i> as an integer number of seconds
 *  since epoch.
 *
 *     t = Time.now
 *     "%10.5f" % t.to_f   #=> "1049896564.17839"
 *     t.to_i              #=> 1049896564
 */

static VALUE
time_to_i(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return LONG2NUM(tobj->tv.tv_sec);
}


tv_usec (Time)

/*
 *  call-seq:
 *     time.usec    => int
 *     time.tv_usec => int
 *
 *  Returns just the number of microseconds for <i>time</i>.
 *
 *     t = Time.now        #=> Wed Apr 09 08:56:04 CDT 2003
 *     "%10.6f" % t.to_f   #=> "1049896564.259970"
 *     t.usec              #=> 259970
 */

static VALUE
time_usec(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return LONG2NUM(tobj->tv.tv_usec);
}


usec (Time)

/*
 *  call-seq:
 *     time.usec    => int
 *     time.tv_usec => int
 *
 *  Returns just the number of microseconds for <i>time</i>.
 *
 *     t = Time.now        #=> Wed Apr 09 08:56:04 CDT 2003
 *     "%10.6f" % t.to_f   #=> "1049896564.259970"
 *     t.usec              #=> 259970
 */

static VALUE
time_usec(time)
    VALUE time;
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return LONG2NUM(tobj->tv.tv_usec);
}


strftime (Time)

/*
 *  call-seq:
 *     time.strftime( string ) => string
 *
 *  Formats <i>time</i> according to the directives in the given format
 *  string. Any text not listed as a directive will be passed through
 *  to the output string.
 *
 *  Format meaning:
 *    %a - The abbreviated weekday name (``Sun'')
 *    %A - The  full  weekday  name (``Sunday'')
 *    %b - The abbreviated month name (``Jan'')
 *    %B - The  full  month  name (``January'')
 *    %c - The preferred local date and time representation
 *    %d - Day of the month (01..31)
 *    %H - Hour of the day, 24-hour clock (00..23)
 *    %I - Hour of the day, 12-hour clock (01..12)
 *    %j - Day of the year (001..366)
 *    %m - Month of the year (01..12)
 *    %M - Minute of the hour (00..59)
 *    %p - Meridian indicator (``AM''  or  ``PM'')
 *    %S - Second of the minute (00..60)
 *    %U - Week  number  of the current year,
 *            starting with the first Sunday as the first
 *            day of the first week (00..53)
 *    %W - Week  number  of the current year,
 *            starting with the first Monday as the first
 *            day of the first week (00..53)
 *    %w - Day of the week (Sunday is 0, 0..6)
 *    %x - Preferred representation for the date alone, no time
 *    %X - Preferred representation for the time alone, no date
 *    %y - Year without a century (00..99)
 *    %Y - Year with century
 *    %Z - Time zone name
 *    %% - Literal ``%'' character
 *
 *     t = Time.now
 *     t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
 *     t.strftime("at %I:%M%p")            #=> "at 08:56AM"
 */

static VALUE
time_strftime(time, format)
    VALUE time, format;
{
    struct time_object *tobj;
    char buffer[SMALLBUF], *buf = buffer;
    const char *fmt;
    long len;
    VALUE str;

    GetTimeval(time, tobj);
    if (tobj->tm_got == 0) {
        time_get_tm(time, tobj->gmt);
    }
    StringValue(format);
    format = rb_str_new4(format);
    fmt = RSTRING(format)->ptr;
    len = RSTRING(format)->len;
    if (len == 0) {
        rb_warning("strftime called with empty format string");
    }
    else if (strlen(fmt) < len) {
        /* Ruby string may contain \0's. */
        const char *p = fmt, *pe = fmt + len;

        str = rb_str_new(0, 0);
        while (p < pe) {
            len = rb_strftime(&buf, p, &tobj->tm);
            rb_str_cat(str, buf, len);
            p += strlen(p);
            if (buf != buffer) {
                free(buf);
                buf = buffer;
            }
            for (fmt = p; p < pe && !*p; ++p);
            if (p > fmt) rb_str_cat(str, fmt, p - fmt);
        }
        return str;
    }
    else {
        len = rb_strftime(&buf, RSTRING(format)->ptr, &tobj->tm);
    }
    str = rb_str_new(buf, len);
    if (buf != buffer) free(buf);
    return str;
}


_dump (Time)

/*
 * call-seq:
 *   time._dump   => string
 *
 * Dump _time_ for marshaling.
 */

static VALUE
time_dump(argc, argv, time)
    int argc;
    VALUE *argv;
    VALUE time;
{
    VALUE str;

    rb_scan_args(argc, argv, "01", 0);
    str = time_mdump(time);
    if (FL_TEST(time, FL_EXIVAR)) {
        rb_copy_generic_ivar(str, time);
        FL_SET(str, FL_EXIVAR);
    }

    return str;
}


_load (Time)

/*
 * call-seq:
 *   Time._load(string)   => time
 *
 * Unmarshal a dumped +Time+ object.
 */

static VALUE
time_load(klass, str)
    VALUE klass, str;
{
    VALUE time = time_s_alloc(klass);

    if (FL_TEST(str, FL_EXIVAR)) {
        rb_copy_generic_ivar(time, str);
        FL_SET(time, FL_EXIVAR);
    }
    time_mload(time, str);
    return time;
}


marshal_dump (Time)

/*
 * undocumented
 */

static VALUE
time_mdump(time)
    VALUE time;
{
    struct time_object *tobj;
    struct tm *tm;
    unsigned long p, s;
    char buf[8];
    time_t t;
    int i;

    GetTimeval(time, tobj);

    t = tobj->tv.tv_sec;
    tm = gmtime(&t);

    if ((tm->tm_year & 0xffff) != tm->tm_year)
        rb_raise(rb_eArgError, "year too big to marshal");

    p = 0x1UL        << 31 | /*  1 */
        tm->tm_year  << 14 | /* 16 */
        tm->tm_mon   << 10 | /*  4 */
        tm->tm_mday  <<  5 | /*  5 */
        tm->tm_hour;         /*  5 */
    s = tm->tm_min   << 26 | /*  6 */
        tm->tm_sec   << 20 | /*  6 */
        tobj->tv.tv_usec;    /* 20 */

    for (i=0; i<4; i++) {
        buf[i] = p & 0xff;
        p = RSHIFT(p, 8);
    }
    for (i=4; i<8; i++) {
        buf[i] = s & 0xff;
        s = RSHIFT(s, 8);
    }

    return rb_str_new(buf, 8);
}


marshal_load (Time)

/*
 * undocumented
 */

static VALUE
time_mload(time, str)
    VALUE time, str;
{
    struct time_object *tobj;
    unsigned long p, s;
    time_t sec, usec;
    unsigned char *buf;
    struct tm tm;
    int i;

    time_modify(time);
    StringValue(str);
    buf = (unsigned char *)RSTRING(str)->ptr;
    if (RSTRING(str)->len != 8) {
        rb_raise(rb_eTypeError, "marshaled time format differ");
    }

    p = s = 0;
    for (i=0; i<4; i++) {
        p |= buf[i]<<(8*i);
    }
    for (i=4; i<8; i++) {
        s |= buf[i]<<(8*(i-4));
    }

    if ((p & (1UL<<31)) == 0) {
        sec = p;
        usec = s;
    }
    else {
       p &= ~(1UL<<31);
        tm.tm_year = (p >> 14) & 0xffff;
        tm.tm_mon  = (p >> 10) & 0xf;
        tm.tm_mday = (p >>  5) & 0x1f;
        tm.tm_hour =  p        & 0x1f;
        tm.tm_min  = (s >> 26) & 0x3f;
        tm.tm_sec  = (s >> 20) & 0x3f;
        tm.tm_isdst = 0;

        sec = make_time_t(&tm, Qtrue);
        usec = (time_t)(s & 0xfffff);
    }
    time_overflow_p(&sec, &usec);

    GetTimeval(time, tobj);
    tobj->tm_got = 0;
    tobj->tv.tv_sec = sec;
    tobj->tv.tv_usec = usec;
    return time;
}


w3cdtf (Time)

# File lib/rss/rss.rb, line 6
      def w3cdtf(date)
        if /\A\s*
            (-?\d+)-(\d\d)-(\d\d)
            (?:T
            (\d\d):(\d\d)(?::(\d\d))?
            (\.\d+)?
            (Z|[+-]\d\d:\d\d)?)?
            \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8))
          datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
          datetime << $7.to_f * 1000000 if $7
          if $8
            Time.utc(*datetime) - zone_offset($8)
          else
            Time.local(*datetime)
          end
        else
          raise ArgumentError.new("invalid date: #{date.inspect}")
        end
      end


zone_offset (Time)

# File lib/time.rb, line 69
    def zone_offset(zone, year=Time.now.year)
      off = nil
      zone = zone.upcase
      if /\A([+-])(\d\d):?(\d\d)\z/ =~ zone
        off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60
      elsif /\A[+-]\d\d\z/ =~ zone
        off = zone.to_i * 3600
      elsif ZoneOffset.include?(zone)
        off = ZoneOffset[zone] * 3600
      elsif ((t = Time.local(year, 1, 1)).zone.upcase == zone rescue false)
        off = t.utc_offset
      elsif ((t = Time.local(year, 7, 1)).zone.upcase == zone rescue false)
        off = t.utc_offset
      end
      off
    end


parse (Time)

# File lib/time.rb, line 239
    def parse(date, now=Time.now)
      d = Date._parse(date, false)
      year = d[:year]
      year = yield(year) if year && block_given?
      make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
    end


rfc2822 (Time)

# File lib/time.rb, line 261
    def rfc2822(date)
      if /\A\s*
          (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
          (\d{1,2})\s+
          (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
          (\d{2,})\s+
          (\d{2})\s*
          :\s*(\d{2})\s*
          (?::\s*(\d{2}))?\s+
          ([+-]\d{4}|
           UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
        # Since RFC 2822 permit comments, the regexp has no right anchor.
        day = $1.to_i
        mon = MonthValue[$2.upcase]
        year = $3.to_i
        hour = $4.to_i
        min = $5.to_i
        sec = $6 ? $6.to_i : 0
        zone = $7

        # following year completion is compliant with RFC 2822.
        year = if year < 50
                 2000 + year
               elsif year < 1000
                 1900 + year
               else
                 year
               end

        year, mon, day, hour, min, sec =
          apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
        t = self.utc(year, mon, day, hour, min, sec)
        t.localtime if !zone_utc?(zone)
        t
      else
        raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
      end
    end


httpdate (Time)

# File lib/time.rb, line 310
    def httpdate(date)
      if /\A\s*
          (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
          (\d{2})\x20
          (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
          (\d{4})\x20
          (\d{2}):(\d{2}):(\d{2})\x20
          GMT
          \s*\z/ix =~ date
        self.rfc2822(date)
      elsif /\A\s*
             (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
             (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
             (\d\d):(\d\d):(\d\d)\x20
             GMT
             \s*\z/ix =~ date
        self.parse(date)
      elsif /\A\s*
             (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
             (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
             (\d\d|\x20\d)\x20
             (\d\d):(\d\d):(\d\d)\x20
             (\d{4})
             \s*\z/ix =~ date
        self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
                 $3.to_i, $4.to_i, $5.to_i)
      else
        raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
      end
    end


xmlschema (Time)

# File lib/time.rb, line 351
    def xmlschema(date)
      if /\A\s*
          (-?\d+)-(\d\d)-(\d\d)
          T
          (\d\d):(\d\d):(\d\d)
          (\.\d*)?
          (Z|[+-]\d\d:\d\d)?
          \s*\z/ix =~ date
        year = $1.to_i
        mon = $2.to_i
        day = $3.to_i
        hour = $4.to_i
        min = $5.to_i
        sec = $6.to_i
        usec = 0
        usec = $7.to_f * 1000000 if $7
        if $8
          zone = $8
          year, mon, day, hour, min, sec =
            apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
          Time.utc(year, mon, day, hour, min, sec, usec)
        else
          Time.local(year, mon, day, hour, min, sec, usec)
        end
      else
        raise ArgumentError.new("invalid date: #{date.inspect}")
      end
    end


rfc2822 (Time)

# File lib/time.rb, line 391
  def rfc2822
    sprintf('%s, %02d %s %d %02d:%02d:%02d ',
      RFC2822_DAY_NAME[wday],
      day, RFC2822_MONTH_NAME[mon-1], year,
      hour, min, sec) +
    if utc?
      '-0000'
    else
      off = utc_offset
      sign = off < 0 ? '-' : '+'
      sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
    end
  end


httpdate (Time)

# File lib/time.rb, line 422
  def httpdate
    t = dup.utc
    sprintf('%s, %02d %s %d %02d:%02d:%02d GMT',
      RFC2822_DAY_NAME[t.wday],
      t.day, RFC2822_MONTH_NAME[t.mon-1], t.year,
      t.hour, t.min, t.sec)
  end


xmlschema (Time)

# File lib/time.rb, line 444
  def xmlschema(fraction_digits=0)
    sprintf('%d-%02d-%02dT%02d:%02d:%02d',
      year, mon, day, hour, min, sec) +
    if fraction_digits == 0
      ''
    elsif fraction_digits <= 6
      '.' + sprintf('%06d', usec)[0, fraction_digits]
    else
      '.' + sprintf('%06d', usec) + '0' * (fraction_digits - 6)
    end +
    if utc?
      'Z'
    else
      off = utc_offset
      sign = off < 0 ? '-' : '+'
      sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60))
    end
  end


yaml_new (Time)

# File lib/yaml/rubytypes.rb, line 303
    def Time.yaml_new( klass, tag, val )
        if Hash === val
            t = val.delete( 'at' )
            val.each { |k,v| t.instance_variable_set( k, v ) }
            t
        else
            raise YAML::TypeError, "Invalid Time: " + val.inspect
        end
    end


to_yaml (Time)

# File lib/yaml/rubytypes.rb, line 312
        def to_yaml( opts = {} )
                YAML::quick_emit( object_id, opts ) do |out|
            tz = "Z"
            # from the tidy Tobias Peters <t-peters@gmx.de> Thanks!
            unless self.utc?
                utc_same_instant = self.dup.utc
                utc_same_writing = Time.utc(year,month,day,hour,min,sec,usec)
                difference_to_utc = utc_same_writing - utc_same_instant
                if (difference_to_utc < 0)
                    difference_sign = '-'
                    absolute_difference = -difference_to_utc
                else
                    difference_sign = '+'
                    absolute_difference = difference_to_utc
                end
                difference_minutes = (absolute_difference/60).round
                tz = "%s%02d:%02d" % [ difference_sign, difference_minutes / 60, difference_minutes % 60]
            end
            standard = self.strftime( "%Y-%m-%d %H:%M:%S" )
            standard += ".%06d" % [usec] if usec.nonzero?
            standard += " %s" % [tz]
            if to_yaml_properties.empty?
                out.scalar( taguri, standard, :plain )
            else
                out.map( taguri, to_yaml_style ) do |map|
                    map.add( 'at', standard )
                    to_yaml_properties.each do |m|
                        map.add( m, instance_variable_get( m ) )
                    end
                end
            end
        end
        end


timeout (Timeout)

# File lib/timeout.rb, line 47
  def timeout(sec, exception=Error)
    return yield if sec == nil or sec.zero?
    raise ThreadError, "timeout within critical session" if Thread.critical
    begin
      x = Thread.current
      y = Thread.start {
        sleep sec
        x.raise exception, "execution expired" if x.alive?
      }
      yield sec
      #    return true
    ensure
      y.kill if y and y.alive?
    end
  end


token_stream (TokenStream)

# File lib/rdoc/tokenstream.rb, line 9
  def token_stream
    @token_stream
  end


start_collecting_tokens (TokenStream)

# File lib/rdoc/tokenstream.rb, line 13
  def start_collecting_tokens
    @token_stream = []
  end


add_token (TokenStream)

# File lib/rdoc/tokenstream.rb, line 16
  def add_token(tk)
    @token_stream << tk
  end


add_tokens (TokenStream)

# File lib/rdoc/tokenstream.rb, line 19
  def add_tokens(tks)
    tks.each  {|tk| add_token(tk)}
  end


pop_token (TokenStream)

# File lib/rdoc/tokenstream.rb, line 22
  def pop_token
    @token_stream.pop
  end


trace_func (Tracer)

# File lib/debug.rb, line 14
  def Tracer.trace_func(*vars)
    Single.trace_func(*vars)
  end


new (Tracer)

# File lib/tracer.rb, line 37
  def initialize
    @threads = Hash.new
    if defined? Thread.main
      @threads[Thread.main.object_id] = 0
    else
      @threads[Thread.current.object_id] = 0
    end

    @get_line_procs = {}

    @filters = []
  end


stdout (Tracer)

# File lib/tracer.rb, line 50
  def stdout
    Tracer.stdout
  end


on (Tracer)

# File lib/tracer.rb, line 54
  def on
    if block_given?
      on
      begin
        yield
      ensure
        off
      end
    else
      set_trace_func method(:trace_func).to_proc
      stdout.print "Trace on\n" if Tracer.verbose?
    end
  end


off (Tracer)

# File lib/tracer.rb, line 68
  def off
    set_trace_func nil
    stdout.print "Trace off\n" if Tracer.verbose?
  end


add_filter (Tracer)

# File lib/tracer.rb, line 73
  def add_filter(p = proc)
    @filters.push p
  end


set_get_line_procs (Tracer)

# File lib/tracer.rb, line 77
  def set_get_line_procs(file, p = proc)
    @get_line_procs[file] = p
  end


get_line (Tracer)

# File lib/tracer.rb, line 81
  def get_line(file, line)
    if p = @get_line_procs[file]
      return p.call(line)
    end

    unless list = SCRIPT_LINES__[file]
      begin
        f = open(file)
        begin
          SCRIPT_LINES__[file] = list = f.readlines
        ensure
          f.close
        end
      rescue
        SCRIPT_LINES__[file] = list = []
      end
    end

    if l = list[line - 1]
      l
    else
      "-\n"
    end
  end


get_thread_no (Tracer)

# File lib/tracer.rb, line 106
  def get_thread_no
    if no = @threads[Thread.current.object_id]
      no
    else
      @threads[Thread.current.object_id] = @threads.size
    end
  end


trace_func (Tracer)

# File lib/tracer.rb, line 114
  def trace_func(event, file, line, id, binding, klass, *)
    return if file == __FILE__

    for p in @filters
      return unless p.call event, file, line, id, binding, klass
    end

    saved_crit = Thread.critical
    Thread.critical = true
    stdout.printf("#%d:%s:%d:%s:%s: %s",
      get_thread_no,
      file,
      line,
      klass || '',
      EVENT_SYMBOL[event],
      get_line(file, line))
    Thread.critical = saved_crit
  end


on (Tracer)

# File lib/tracer.rb, line 134
  def Tracer.on
    if block_given?
      Single.on{yield}
    else
      Single.on
    end
  end


off (Tracer)

# File lib/tracer.rb, line 142
  def Tracer.off
    Single.off
  end


set_get_line_procs (Tracer)

# File lib/tracer.rb, line 146
  def Tracer.set_get_line_procs(file_name, p = proc)
    Single.set_get_line_procs(file_name, p)
  end


add_filter (Tracer)

# File lib/tracer.rb, line 150
  def Tracer.add_filter(p = proc)
    Single.add_filter(p)
  end


to_s (TrueClass)

/*
 * call-seq:
 *   true.to_s   =>  "true"
 *
 * The string representation of <code>true</code> is "true".
 */

static VALUE
true_to_s(obj)
    VALUE obj;
{
    return rb_str_new2("true");
}


& (TrueClass)

/*
 *  call-seq:
 *     true & obj    => true or false
 *
 *  And---Returns <code>false</code> if <i>obj</i> is
 *  <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
 */

static VALUE
true_and(obj, obj2)
    VALUE obj, obj2;
{
    return RTEST(obj2)?Qtrue:Qfalse;
}


| (TrueClass)

/*
 *  call-seq:
 *     true | obj   => true
 *
 *  Or---Returns <code>true</code>. As <i>anObject</i> is an argument to
 *  a method call, it is always evaluated; there is no short-circuit
 *  evaluation in this case.
 *
 *     true |  puts("or")
 *     true || puts("logical or")
 *
 *  <em>produces:</em>
 *
 *     or
 */

static VALUE
true_or(obj, obj2)
    VALUE obj, obj2;
{
    return Qtrue;
}


^ (TrueClass)

/*
 *  call-seq:
 *     true ^ obj   => !obj
 *
 *  Exclusive Or---Returns <code>true</code> if <i>obj</i> is
 *  <code>nil</code> or <code>false</code>, <code>false</code>
 *  otherwise.
 */

static VALUE
true_xor(obj, obj2)
    VALUE obj, obj2;
{
    return RTEST(obj2)?Qfalse:Qtrue;
}


to_yaml (TrueClass)

# File lib/yaml/rubytypes.rb, line 384
        def to_yaml( opts = {} )
                YAML::quick_emit( nil, opts ) do |out|
            out.scalar( taguri, "true", :plain )
        end
        end


tsort (TSort)

# File lib/tsort.rb, line 134
  def tsort
    result = []
    tsort_each {|element| result << element}
    result
  end


tsort_each (TSort)

# File lib/tsort.rb, line 148
  def tsort_each # :yields: node
    each_strongly_connected_component {|component|
      if component.size == 1
        yield component.first
      else
        raise Cyclic.new("topological sort failed: #{component.inspect}")
      end
    }
  end


strongly_connected_components (TSort)

# File lib/tsort.rb, line 163
  def strongly_connected_components
    result = []
    each_strongly_connected_component {|component| result << component}
    result
  end


each_strongly_connected_component (TSort)

# File lib/tsort.rb, line 178
  def each_strongly_connected_component # :yields: nodes
    id_map = {}
    stack = []
    tsort_each_node {|node|
      unless id_map.include? node
        each_strongly_connected_component_from(node, id_map, stack) {|c|
          yield c
        }
      end
    }
    nil
  end


each_strongly_connected_component_from (TSort)

# File lib/tsort.rb, line 199
  def each_strongly_connected_component_from(node, id_map={}, stack=[]) # :yields: nodes
    minimum_id = node_id = id_map[node] = id_map.size
    stack_length = stack.length
    stack << node

    tsort_each_child(node) {|child|
      if id_map.include? child
        child_id = id_map[child]
        minimum_id = child_id if child_id && child_id < minimum_id
      else
        sub_minimum_id =
          each_strongly_connected_component_from(child, id_map, stack) {|c|
            yield c
          }
        minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
      end
    }

    if node_id == minimum_id
      component = stack.slice!(stack_length .. -1)
      component.each {|n| id_map[n] = nil}
      yield component
    end

    minimum_id
  end


tsort_each_node (TSort)

# File lib/tsort.rb, line 231
  def tsort_each_node # :yields: node
    raise NotImplementedError.new
  end


tsort_each_child (TSort)

# File lib/tsort.rb, line 240
  def tsort_each_child(node) # :yields: child
    raise NotImplementedError.new
  end


bind (UDPSocket)

# File lib/resolv-replace.rb, line 25
  def bind(host, port)
    original_resolv_bind(IPSocket.getaddress(host), port)
  end


connect (UDPSocket)

# File lib/resolv-replace.rb, line 30
  def connect(host, port)
    original_resolv_connect(IPSocket.getaddress(host), port)
  end


send (UDPSocket)

# File lib/resolv-replace.rb, line 35
  def send(mesg, flags, *rest)
    if rest.length == 2
      host, port = rest
      begin
        addrs = Resolv.getaddresses(host)
      rescue Resolv::ResolvError
        raise SocketError, "Hostname not known: #{host}"
      end
      err = nil
      addrs[0...-1].each {|addr|
        begin
          return original_resolv_send(mesg, flags, addr, port)
        rescue SystemCallError
        end
      }
      original_resolv_send(mesg, flags, addrs[-1], port)
    else
      original_resolv_send(mesg, flags, *rest)
    end
  end


recvfrom_nonblock (UDPSocket)

/*
 * call-seq:
 *      udpsocket.recvfrom_nonblock(maxlen) => [mesg, sender_inet_addr]
 *      udpsocket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_inet_addr]
 *
 * Receives up to _maxlen_ bytes from +udpsocket+ using recvfrom(2) after
 * O_NONBLOCK is set for the underlying file descriptor.
 * _flags_ is zero or more of the +MSG_+ options.
 * The first element of the results, _mesg_, is the data received.
 * The second element, _sender_inet_addr_, is an array to represent the sender address.
 *
 * When recvfrom(2) returns 0,
 * Socket#recvfrom_nonblock returns an empty string as data.
 * It means an empty packet.
 *
 * === Parameters
 * * +maxlen+ - the number of bytes to receive from the socket
 * * +flags+ - zero or more of the +MSG_+ options
 *
 * === Example
 *      require 'socket'
 *      s1 = UDPSocket.new
 *      s1.bind("127.0.0.1", 0)
 *      s2 = UDPSocket.new
 *      s2.bind("127.0.0.1", 0)
 *      s2.connect(*s1.addr.values_at(3,1))
 *      s1.connect(*s2.addr.values_at(3,1))
 *      s1.send "aaa", 0
 *      IO.select([s2])
 *      p s2.recvfrom_nonblock(10)  #=> ["aaa", ["AF_INET", 33302, "localhost.localdomain", "127.0.0.1"]]
 *
 * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
 * to _recvfrom_nonblock_ fails.
 *
 * UDPSocket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
 * including Errno::EAGAIN.
 *
 * === See
 * * Socket#recvfrom
 */
static VALUE
udp_recvfrom_nonblock(int argc, VALUE *argv, VALUE sock)
{
    return s_recvfrom_nonblock(sock, argc, argv, RECV_IP);
}


== (UnboundMethod)

/*
 * call-seq:
 *   meth == other_meth  => true or false
 *
 * Two method objects are equal if that are bound to the same
 * object and contain the same body.
 */

static VALUE
method_eq(method, other)
    VALUE method, other;
{
    struct METHOD *m1, *m2;

    if (TYPE(other) != T_DATA || RDATA(other)->dmark != (RUBY_DATA_FUNC)bm_mark)
        return Qfalse;
    if (CLASS_OF(method) != CLASS_OF(other))
        return Qfalse;

    Data_Get_Struct(method, struct METHOD, m1);
    Data_Get_Struct(other, struct METHOD, m2);

    if (m1->klass != m2->klass || m1->rklass != m2->rklass ||
        m1->recv != m2->recv || m1->body != m2->body)
        return Qfalse;

    return Qtrue;
}


clone (UnboundMethod)

/*
 * MISSING: documentation
 */

static VALUE
method_clone(self)
    VALUE self;
{
    VALUE clone;
    struct METHOD *orig, *data;

    Data_Get_Struct(self, struct METHOD, orig);
    clone = Data_Make_Struct(CLASS_OF(self),struct METHOD, bm_mark, free, data);
    CLONESETUP(clone, self);
    *data = *orig;

    return clone;
}


arity (UnboundMethod)

/*
 *  call-seq:
 *     meth.arity    => fixnum
 *
 *  Returns an indication of the number of arguments accepted by a
 *  method. Returns a nonnegative integer for methods that take a fixed
 *  number of arguments. For Ruby methods that take a variable number of
 *  arguments, returns -n-1, where n is the number of required
 *  arguments. For methods written in C, returns -1 if the call takes a
 *  variable number of arguments.
 *
 *     class C
 *       def one;    end
 *       def two(a); end
 *       def three(*a);  end
 *       def four(a, b); end
 *       def five(a, b, *c);    end
 *       def six(a, b, *c, &d); end
 *     end
 *     c = C.new
 *     c.method(:one).arity     #=> 0
 *     c.method(:two).arity     #=> 1
 *     c.method(:three).arity   #=> -1
 *     c.method(:four).arity    #=> 2
 *     c.method(:five).arity    #=> -3
 *     c.method(:six).arity     #=> -3
 *
 *     "cat".method(:size).arity      #=> 0
 *     "cat".method(:replace).arity   #=> 1
 *     "cat".method(:squeeze).arity   #=> -1
 *     "cat".method(:count).arity     #=> -1
 */

static VALUE
method_arity(method)
    VALUE method;
{
    struct METHOD *data;
    NODE *body;
    int n;

    Data_Get_Struct(method, struct METHOD, data);

    body = data->body;
    switch (nd_type(body)) {
      case NODE_CFUNC:
        if (body->nd_argc < 0) return INT2FIX(-1);
        return INT2FIX(body->nd_argc);
      case NODE_ZSUPER:
        return INT2FIX(-1);
      case NODE_ATTRSET:
        return INT2FIX(1);
      case NODE_IVAR:
        return INT2FIX(0);
      case NODE_BMETHOD:
        return proc_arity(body->nd_cval);
      case NODE_DMETHOD:
        return method_arity(body->nd_cval);
      case NODE_SCOPE:
        body = body->nd_next;  /* skip NODE_SCOPE */
        if (nd_type(body) == NODE_BLOCK)
            body = body->nd_head;
        if (!body) return INT2FIX(0);
        n = body->nd_cnt;
        if (body->nd_opt || body->nd_rest)
            n = -n-1;
        return INT2FIX(n);
      default:
        rb_raise(rb_eArgError, "invalid node 0x%x", nd_type(body));
   }
}


inspect (UnboundMethod)

/*
 *  call-seq:
 *   meth.to_s      =>  string
 *   meth.inspect   =>  string
 *
 *  Show the name of the underlying method.
 *
 *    "cat".method(:count).inspect   #=> "#<Method: String#count>"
 */

static VALUE
method_inspect(method)
    VALUE method;
{
    struct METHOD *data;
    VALUE str;
    const char *s;
    char *sharp = "#";

    Data_Get_Struct(method, struct METHOD, data);
    str = rb_str_buf_new2("#<");
    s = rb_obj_classname(method);
    rb_str_buf_cat2(str, s);
    rb_str_buf_cat2(str, ": ");

    if (FL_TEST(data->klass, FL_SINGLETON)) {
        VALUE v = rb_iv_get(data->klass, "__attached__");

        if (data->recv == Qundef) {
            rb_str_buf_append(str, rb_inspect(data->klass));
        }
        else if (data->recv == v) {
            rb_str_buf_append(str, rb_inspect(v));
            sharp = ".";
        }
        else {
            rb_str_buf_append(str, rb_inspect(data->recv));
            rb_str_buf_cat2(str, "(");
            rb_str_buf_append(str, rb_inspect(v));
            rb_str_buf_cat2(str, ")");
            sharp = ".";
        }
    }
    else {
        rb_str_buf_cat2(str, rb_class2name(data->rklass));
        if (data->rklass != data->klass) {
            VALUE klass = data -> klass;
            if (TYPE(klass) == T_ICLASS) {
                klass = RBASIC(klass)->klass;
            }
            rb_str_buf_cat2(str, "(");
            rb_str_buf_cat2(str, rb_class2name(klass));
            rb_str_buf_cat2(str, ")");
        }
    }
    rb_str_buf_cat2(str, sharp);
    rb_str_buf_cat2(str, rb_id2name(data->oid));
    rb_str_buf_cat2(str, ">");

    return str;
}


to_s (UnboundMethod)

/*
 *  call-seq:
 *   meth.to_s      =>  string
 *   meth.inspect   =>  string
 *
 *  Show the name of the underlying method.
 *
 *    "cat".method(:count).inspect   #=> "#<Method: String#count>"
 */

static VALUE
method_inspect(method)
    VALUE method;
{
    struct METHOD *data;
    VALUE str;
    const char *s;
    char *sharp = "#";

    Data_Get_Struct(method, struct METHOD, data);
    str = rb_str_buf_new2("#<");
    s = rb_obj_classname(method);
    rb_str_buf_cat2(str, s);
    rb_str_buf_cat2(str, ": ");

    if (FL_TEST(data->klass, FL_SINGLETON)) {
        VALUE v = rb_iv_get(data->klass, "__attached__");

        if (data->recv == Qundef) {
            rb_str_buf_append(str, rb_inspect(data->klass));
        }
        else if (data->recv == v) {
            rb_str_buf_append(str, rb_inspect(v));
            sharp = ".";
        }
        else {
            rb_str_buf_append(str, rb_inspect(data->recv));
            rb_str_buf_cat2(str, "(");
            rb_str_buf_append(str, rb_inspect(v));
            rb_str_buf_cat2(str, ")");
            sharp = ".";
        }
    }
    else {
        rb_str_buf_cat2(str, rb_class2name(data->rklass));
        if (data->rklass != data->klass) {
            VALUE klass = data -> klass;
            if (TYPE(klass) == T_ICLASS) {
                klass = RBASIC(klass)->klass;
            }
            rb_str_buf_cat2(str, "(");
            rb_str_buf_cat2(str, rb_class2name(klass));
            rb_str_buf_cat2(str, ")");
        }
    }
    rb_str_buf_cat2(str, sharp);
    rb_str_buf_cat2(str, rb_id2name(data->oid));
    rb_str_buf_cat2(str, ">");

    return str;
}


bind (UnboundMethod)

/*
 *  call-seq:
 *     umeth.bind(obj) -> method
 *
 *  Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class
 *  from which <i>umeth</i> was obtained,
 *  <code>obj.kind_of?(Klass)</code> must be true.
 *
 *     class A
 *       def test
 *         puts "In test, class = #{self.class}"
 *       end
 *     end
 *     class B < A
 *     end
 *     class C < B
 *     end
 *
 *
 *     um = B.instance_method(:test)
 *     bm = um.bind(C.new)
 *     bm.call
 *     bm = um.bind(B.new)
 *     bm.call
 *     bm = um.bind(A.new)
 *     bm.call
 *
 *  <em>produces:</em>
 *
 *     In test, class = C
 *     In test, class = B
 *     prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
 *      from prog.rb:16
 */

static VALUE
umethod_bind(method, recv)
    VALUE method, recv;
{
    struct METHOD *data, *bound;
    VALUE rklass = CLASS_OF(recv);

    Data_Get_Struct(method, struct METHOD, data);
    if (data->rklass != rklass) {
        if (FL_TEST(data->rklass, FL_SINGLETON)) {
            rb_raise(rb_eTypeError, "singleton method bound for a different object");
        }
        if (TYPE(data->rklass) == T_MODULE) {
            st_table *m_tbl = RCLASS(data->rklass)->m_tbl;
            while (RCLASS(rklass)->m_tbl != m_tbl) {
                rklass = RCLASS(rklass)->super;
                if (!rklass) goto not_instace;
            }
        }
        else if (!rb_obj_is_kind_of(recv, data->rklass)) {
          not_instace:
            rb_raise(rb_eTypeError, "bind argument must be an instance of %s",
                     rb_class2name(data->rklass));
        }
    }

    method = Data_Make_Struct(rb_cMethod,struct METHOD,bm_mark,free,bound);
    *bound = *data;
    bound->recv = recv;
    bound->rklass = rklass;

    return method;
}


accept_nonblock (UNIXServer)

/*
 * call-seq:
 *      unixserver.accept_nonblock => unixsocket
 *
 * Accepts an incoming connection using accept(2) after
 * O_NONBLOCK is set for the underlying file descriptor.
 * It returns an accepted UNIXSocket for the incoming connection.
 *
 * === Example
 *      require 'socket'
 *      serv = UNIXServer.new("/tmp/sock")
 *      begin
 *        sock = serv.accept_nonblock
 *      rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
 *        IO.select([serv])
 *        retry
 *      end
 *      # sock is an accepted socket.
 *
 * Refer to Socket#accept for the exceptions that may be thrown if the call
 * to UNIXServer#accept_nonblock fails.
 *
 * UNIXServer#accept_nonblock may raise any error corresponding to accept(2) failure,
 * including Errno::EAGAIN.
 *
 * === See
 * * UNIXServer#accept
 * * Socket#accept
 */
static VALUE
unix_accept_nonblock(sock)
    VALUE sock;
{
    OpenFile *fptr;
    struct sockaddr_un from;
    socklen_t fromlen;

    GetOpenFile(sock, fptr);
    fromlen = sizeof(from);
    return s_accept_nonblock(rb_cUNIXSocket, fptr,
                             (struct sockaddr *)&from, &fromlen);
}


listen (UNIXServer)

/*
 * call-seq:
 *      socket.listen( int ) => 0
 *
 * Listens for connections, using the specified +int+ as the backlog. A call
 * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
 * SOCK_SEQPACKET.
 *
 * === Parameter
 * * +backlog+ - the maximum length of the queue for pending connections.
 *
 * === Example 1
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
 *      socket.bind( sockaddr )
 *      socket.listen( 5 )
 *
 * === Example 2 (listening on an arbitary port, unix-based systems only):
 *      require 'socket'
 *      include Socket::Constants
 *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
 *      socket.listen( 1 )
 *
 * === Unix-based Exceptions
 * On unix based systems the above will work because a new +sockaddr+ struct
 * is created on the address ADDR_ANY, for an arbitrary port number as handed
 * off by the kernel. It will not work on Windows, because Windows requires that
 * the +socket+ is bound by calling _bind_ before it can _listen_.
 *
 * If the _backlog_ amount exceeds the implementation-dependent maximum
 * queue length, the implementation's maximum queue length will be used.
 *
 * On unix-based based systems the following system exceptions may be raised if the
 * call to _listen_ fails:
 * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
 * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
 *   the protocol does not support listening on an unbound socket
 * * Errno::EINVAL - the _socket_ is already connected
 * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
 * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
 * * Errno::EACCES - the calling process does not have approriate privileges
 * * Errno::EINVAL - the _socket_ has been shut down
 * * Errno::ENOBUFS - insufficient resources are available in the system to
 *   complete the call
 *
 * === Windows Exceptions
 * On Windows systems the following system exceptions may be raised if
 * the call to _listen_ fails:
 * * Errno::ENETDOWN - the network is down
 * * Errno::EADDRINUSE - the socket's local address is already in use. This
 *   usually occurs during the execution of _bind_ but could be delayed
 *   if the call to _bind_ was to a partially wildcard address (involving
 *   ADDR_ANY) and if a specific address needs to be commmitted at the
 *   time of the call to _listen_
 * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
 *   service provider is still processing a callback function
 * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
 * * Errno::EISCONN - the +socket+ is already connected
 * * Errno::EMFILE - no more socket descriptors are available
 * * Errno::ENOBUFS - no buffer space is available
 * * Errno::ENOTSOC - +socket+ is not a socket
 * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
 *   the _listen_ method
 *
 * === See
 * * listen manual pages on unix-based systems
 * * listen function in Microsoft's Winsock functions reference
 */
static VALUE
sock_listen(sock, log)
    VALUE sock, log;
{
    OpenFile *fptr;
    int backlog;

    rb_secure(4);
    backlog = NUM2INT(log);
    GetOpenFile(sock, fptr);
    if (listen(fileno(fptr->f), backlog) < 0)
        rb_sys_fail("listen(2)");

    return INT2FIX(0);
}


escape (URI::Escape)

# File lib/uri/common.rb, line 284
    def escape(str, unsafe = UNSAFE)
      unless unsafe.kind_of?(Regexp)
        # perhaps unsafe is String object
        unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false, 'N')
      end
      str.gsub(unsafe) do |us|
        tmp = ''
        us.each_byte do |uc|
          tmp << sprintf('%%%02X', uc)
        end
        tmp
      end
    end


unescape (URI::Escape)

# File lib/uri/common.rb, line 319
    def unescape(str)
      str.gsub(ESCAPED) do
        $&[1,2].hex.chr
      end
    end


new2 (URI::FTP)

# File lib/uri/ftp.rb, line 35
    def self.new2(user, password, host, port, path,
                  typecode = nil, arg_check = true)
      typecode = nil if typecode.size == 0
      if typecode && !TYPECODE.include?(typecode)
        raise ArgumentError,
          "bad typecode is specified: #{typecode}"
      end

      # do escape

      self.new('ftp',
               [user, password],
               host, port, nil,
               typecode ? path + TYPECODE_PREFIX + typecode : path,
               nil, nil, nil, arg_check)
    end


build (URI::FTP)

# File lib/uri/ftp.rb, line 59
    def self.build(args)
      tmp = Util::make_components_hash(self, args)

      if tmp[:typecode]
        if tmp[:typecode].size == 1
          tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode]
        end
        tmp[:path] << tmp[:typecode]
      end

      return super(tmp)
    end


new (URI::FTP)

# File lib/uri/ftp.rb, line 86
    def initialize(*arg)
      super(*arg)
      @typecode = nil
      tmp = @path.index(TYPECODE_PREFIX)
      if tmp
        typecode = @path[tmp + TYPECODE_PREFIX.size..-1]
        self.set_path(@path[0..tmp - 1])

        if arg[-1]
          self.typecode = typecode
        else
          self.set_typecode(typecode)
        end
      end
    end


set_typecode (URI::FTP)

# File lib/uri/ftp.rb, line 113
    def set_typecode(v)
      @typecode = v
    end


typecode= (URI::FTP)

# File lib/uri/ftp.rb, line 118
    def typecode=(typecode)
      check_typecode(typecode)
      set_typecode(typecode)
      typecode
    end


to_s (URI::FTP)

# File lib/uri/ftp.rb, line 133
    def to_s
      save_path = nil
      if @typecode
        save_path = @path
        @path = @path + TYPECODE_PREFIX + @typecode
      end
      str = super
      if @typecode
        @path = save_path
      end

      return str
    end


find_proxy (URI::Generic)

# File lib/open-uri.rb, line 551
    def find_proxy
      name = self.scheme.downcase + '_proxy'
      proxy_uri = nil
      if name == 'http_proxy' && ENV.include?('REQUEST_METHOD') # CGI?
        # HTTP_PROXY conflicts with *_proxy for proxy settings and
        # HTTP_* for header information in CGI.
        # So it should be careful to use it.
        pairs = ENV.reject {|k, v| /\Ahttp_proxy\z/i !~ k }
        case pairs.length
        when 0 # no proxy setting anyway.
          proxy_uri = nil
        when 1
          k, v = pairs.shift
          if k == 'http_proxy' && ENV[k.upcase] == nil
            # http_proxy is safe to use because ENV is case sensitive.
            proxy_uri = ENV[name]
          else
            proxy_uri = nil
          end
        else # http_proxy is safe to use because ENV is case sensitive.
          proxy_uri = ENV[name]
        end
        if !proxy_uri
          # Use CGI_HTTP_PROXY.  cf. libwww-perl.
          proxy_uri = ENV["CGI_#{name.upcase}"]
        end
      elsif name == 'http_proxy'
        unless proxy_uri = ENV[name]
          if proxy_uri = ENV[name.upcase]
            warn 'The environment variable HTTP_PROXY is discouraged.  Use http_proxy.'
          end
        end
      else
        proxy_uri = ENV[name] || ENV[name.upcase]
      end

      if proxy_uri && self.host
        require 'socket'
        begin
          addr = IPSocket.getaddress(self.host)
          proxy_uri = nil if /\A127\.|\A::1\z/ =~ addr
        rescue SocketError
        end
      end

      if proxy_uri
        proxy_uri = URI.parse(proxy_uri)
        name = 'no_proxy'
        if no_proxy = ENV[name] || ENV[name.upcase]
          no_proxy.scan(/([^:,]*)(?::(\d+))?/) {|host, port|
            if /(\A|\.)#{Regexp.quote host}\z/i =~ self.host &&
               (!port || self.port == port.to_i)
              proxy_uri = nil
              break
            end
          }
        end
        proxy_uri
      else
        nil
      end
    end


default_port (URI::Generic)

# File lib/uri/generic.rb, line 26
    def self.default_port
      self::DEFAULT_PORT
    end


default_port (URI::Generic)

# File lib/uri/generic.rb, line 30
    def default_port
      self.class.default_port
    end


component (URI::Generic)

# File lib/uri/generic.rb, line 45
    def self.component
      self::COMPONENT
    end


use_registry (URI::Generic)

# File lib/uri/generic.rb, line 54
    def self.use_registry
      self::USE_REGISTRY
    end


build2 (URI::Generic)

# File lib/uri/generic.rb, line 70
    def self.build2(args)
      begin
        return self.build(args)
      rescue InvalidComponentError
        if args.kind_of?(Array)
          return self.build(args.collect{|x|
            if x
              URI.escape(x)
            else
              x
            end
          })
        elsif args.kind_of?(Hash)
          tmp = {}
          args.each do |key, value|
            tmp[key] = if value
                URI.escape(value)
              else
                value
              end
          end
          return self.build(tmp)
        end
      end
    end


build (URI::Generic)

# File lib/uri/generic.rb, line 108
    def self.build(args)
      if args.kind_of?(Array) &&
          args.size == ::URI::Generic::COMPONENT.size
        tmp = args
      elsif args.kind_of?(Hash)
        tmp = ::URI::Generic::COMPONENT.collect do |c|
          if args.include?(c)
            args[c]
          else
            nil
          end
        end
      else
        raise ArgumentError,
        "expected Array of or Hash of components of #{self.class} (#{self.class.component.join(', ')})"
      end

      tmp << true
      return self.new(*tmp)
    end


new (URI::Generic)

# File lib/uri/generic.rb, line 156
    def initialize(scheme,
                   userinfo, host, port, registry,
                   path, opaque,
                   query,
                   fragment,
                   arg_check = false)
      @scheme = nil
      @user = nil
      @password = nil
      @host = nil
      @port = nil
      @path = nil
      @query = nil
      @opaque = nil
      @registry = nil
      @fragment = nil

      if arg_check
        self.scheme = scheme
        self.userinfo = userinfo
        self.host = host
        self.port = port
        self.path = path
        self.query = query
        self.opaque = opaque
        self.registry = registry
        self.fragment = fragment
      else
        self.set_scheme(scheme)
        self.set_userinfo(userinfo)
        self.set_host(host)
        self.set_port(port)
        self.set_path(path)
        self.set_query(query)
        self.set_opaque(opaque)
        self.set_registry(registry)
        self.set_fragment(fragment)
      end
      if @registry && !self.class.use_registry
        raise InvalidURIError,
          "the scheme #{@scheme} does not accept registry part: #{@registry} (or bad hostname?)"
      end

      @scheme.freeze if @scheme
      self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2)
      self.set_port(self.default_port) if self.default_port && !@port
    end


component (URI::Generic)

# File lib/uri/generic.rb, line 224
    def component
      self.class.component
    end


set_scheme (URI::Generic)

# File lib/uri/generic.rb, line 238
    def set_scheme(v)
      @scheme = v
    end


scheme= (URI::Generic)

# File lib/uri/generic.rb, line 243
    def scheme=(v)
      check_scheme(v)
      set_scheme(v)
      v
    end


userinfo= (URI::Generic)

# File lib/uri/generic.rb, line 301
    def userinfo=(userinfo)
      if userinfo.nil?
        return nil
      end
      check_userinfo(*userinfo)
      set_userinfo(*userinfo)
      # returns userinfo
    end


user= (URI::Generic)

# File lib/uri/generic.rb, line 310
    def user=(user)
      check_user(user)
      set_user(user)
      # returns user
    end


password= (URI::Generic)

# File lib/uri/generic.rb, line 316
    def password=(password)
      check_password(password)
      set_password(password)
      # returns password
    end


set_userinfo (URI::Generic)

# File lib/uri/generic.rb, line 322
    def set_userinfo(user, password = nil)
      unless password
        user, password = split_userinfo(user)
      end
      @user     = user
      @password = password if password

      [@user, @password]
    end


set_user (URI::Generic)

# File lib/uri/generic.rb, line 333
    def set_user(v)
      set_userinfo(v, @password)
      v
    end


set_password (URI::Generic)

# File lib/uri/generic.rb, line 339
    def set_password(v)
      @password = v
      # returns v
    end


userinfo (URI::Generic)

# File lib/uri/generic.rb, line 358
    def userinfo
      if @user.nil?
        nil
      elsif @password.nil?
        @user
      else
        @user + ':' + @password
      end
    end


user (URI::Generic)

# File lib/uri/generic.rb, line 368
    def user
      @user
    end


password (URI::Generic)

# File lib/uri/generic.rb, line 372
    def password
      @password
    end


set_host (URI::Generic)

# File lib/uri/generic.rb, line 391
    def set_host(v)
      @host = v
    end


host= (URI::Generic)

# File lib/uri/generic.rb, line 396
    def host=(v)
      check_host(v)
      set_host(v)
      v
    end


set_port (URI::Generic)

# File lib/uri/generic.rb, line 417
    def set_port(v)
      unless !v || v.kind_of?(Fixnum)
        if v.empty?
          v = nil
        else
          v = v.to_i
        end
      end
      @port = v
    end


port= (URI::Generic)

# File lib/uri/generic.rb, line 429
    def port=(v)
      check_port(v)
      set_port(v)
      port
    end


set_registry (URI::Generic)

# File lib/uri/generic.rb, line 453
    def set_registry(v)
      @registry = v
    end


registry= (URI::Generic)

# File lib/uri/generic.rb, line 458
    def registry=(v)
      check_registry(v)
      set_registry(v)
      v
    end


set_path (URI::Generic)

# File lib/uri/generic.rb, line 489
    def set_path(v)
      @path = v
    end


path= (URI::Generic)

# File lib/uri/generic.rb, line 494
    def path=(v)
      check_path(v)
      set_path(v)
      v
    end


set_query (URI::Generic)

# File lib/uri/generic.rb, line 520
    def set_query(v)
      @query = v
    end


query= (URI::Generic)

# File lib/uri/generic.rb, line 525
    def query=(v)
      check_query(v)
      set_query(v)
      v
    end


set_opaque (URI::Generic)

# File lib/uri/generic.rb, line 549
    def set_opaque(v)
      @opaque = v
    end


opaque= (URI::Generic)

# File lib/uri/generic.rb, line 554
    def opaque=(v)
      check_opaque(v)
      set_opaque(v)
      v
    end


set_fragment (URI::Generic)

# File lib/uri/generic.rb, line 572
    def set_fragment(v)
      @fragment = v
    end


fragment= (URI::Generic)

# File lib/uri/generic.rb, line 577
    def fragment=(v)
      check_fragment(v)
      set_fragment(v)
      v
    end


hierarchical? (URI::Generic)

# File lib/uri/generic.rb, line 586
    def hierarchical?
      if @path
        true
      else
        false
      end
    end


absolute? (URI::Generic)

# File lib/uri/generic.rb, line 597
    def absolute?
      if @scheme
        true
      else
        false
      end
    end


relative? (URI::Generic)

# File lib/uri/generic.rb, line 609
    def relative?
      !absolute?
    end


merge! (URI::Generic)

# File lib/uri/generic.rb, line 700
    def merge!(oth)
      t = merge(oth)
      if self == t
        nil
      else
        replace!(t)
        self
      end
    end


merge (URI::Generic)

# File lib/uri/generic.rb, line 728
    def merge(oth)
      begin
        base, rel = merge0(oth)
      rescue
        raise $!.class, $!.message
      end

      if base == rel
        return base
      end

      authority = rel.userinfo || rel.host || rel.port

      # RFC2396, Section 5.2, 2)
      if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query
        base.set_fragment(rel.fragment) if rel.fragment
        return base
      end

      base.set_query(nil)
      base.set_fragment(nil)

      # RFC2396, Section 5.2, 4)
      if !authority
        base.set_path(merge_path(base.path, rel.path)) if base.path && rel.path
      else
        # RFC2396, Section 5.2, 4)
        base.set_path(rel.path) if rel.path
      end

      # RFC2396, Section 5.2, 7)
      base.set_userinfo(rel.userinfo) if rel.userinfo
      base.set_host(rel.host)         if rel.host
      base.set_port(rel.port)         if rel.port
      base.set_query(rel.query)       if rel.query
      base.set_fragment(rel.fragment) if rel.fragment

      return base
    end


route_from (URI::Generic)

# File lib/uri/generic.rb, line 914
    def route_from(oth)
      # you can modify `rel', but can not `oth'.
      begin
        oth, rel = route_from0(oth)
      rescue
        raise $!.class, $!.message
      end
      if oth == rel
        return rel
      end

      rel.set_path(route_from_path(oth.path, self.path))
      if rel.path == './' && self.query
        # "./?foo" -> "?foo"
        rel.set_path('')
      end

      return rel
    end


route_to (URI::Generic)

# File lib/uri/generic.rb, line 954
    def route_to(oth)
      case oth
      when Generic
      when String
        oth = URI.parse(oth)
      else
        raise ArgumentError,
          "bad argument(expected URI object or URI string)"
      end

      oth.route_from(self)
    end


normalize (URI::Generic)

# File lib/uri/generic.rb, line 970
    def normalize
      uri = dup
      uri.normalize!
      uri
    end


normalize! (URI::Generic)

# File lib/uri/generic.rb, line 979
    def normalize!
      if path && path == ''
        set_path('/')
      end
      if host && host != host.downcase
        set_host(self.host.downcase)
      end
    end


to_s (URI::Generic)

# File lib/uri/generic.rb, line 1000
    def to_s
      str = ''
      if @scheme
        str << @scheme
        str << ':'
      end

      if @opaque
        str << @opaque

      else
        if @registry
          str << @registry
        else
          if @host
            str << '//'
          end
          if self.userinfo
            str << self.userinfo
            str << '@'
          end
          if @host
            str << @host
          end
          if @port && @port != self.default_port
            str << ':'
            str << @port.to_s
          end
        end

        str << path_query
      end

      if @fragment
        str << '#'
        str << @fragment
      end

      str
    end


== (URI::Generic)

# File lib/uri/generic.rb, line 1044
    def ==(oth)
      if self.class == oth.class
        self.normalize.component_ary == oth.normalize.component_ary
      else
        false
      end
    end


hash (URI::Generic)

# File lib/uri/generic.rb, line 1052
    def hash
      self.component_ary.hash
    end


eql? (URI::Generic)

# File lib/uri/generic.rb, line 1056
    def eql?(oth)
      self.component_ary.eql?(oth.component_ary)
    end


component_ary (URI::Generic)

# File lib/uri/generic.rb, line 1071
    def component_ary
      component.collect do |x|
        self.send(x)
      end
    end


select (URI::Generic)

# File lib/uri/generic.rb, line 1095
    def select(*components)
      components.collect do |c|
        if component.include?(c)
          self.send(c)
        else
          raise ArgumentError,
            "expected of components of #{self.class} (#{self.class.component.join(', ')})"
        end
      end
    end


inspect (URI::Generic)

# File lib/uri/generic.rb, line 1106
    def inspect
      sprintf("#<%s:%#0x URL:%s>", self.class.to_s, self.object_id, self.to_s)
    end


coerce (URI::Generic)

# File lib/uri/generic.rb, line 1110
    def coerce(oth)
      case oth
      when String
        oth = URI.parse(oth)
      else
        super
      end

      return oth, self
    end


build (URI::HTTP)

# File lib/uri/http.rb, line 57
    def self.build(args)
      tmp = Util::make_components_hash(self, args)
      return super(tmp)
    end


new (URI::HTTP)

# File lib/uri/http.rb, line 77
    def initialize(*arg)
      super(*arg)
    end


request_uri (URI::HTTP)

# File lib/uri/http.rb, line 89
    def request_uri
      r = path_query
      if r[0] != ?/
        r = '/' + r
      end

      r
    end


build (URI::LDAP)

# File lib/uri/ldap.rb, line 41
    def self.build(args)
      tmp = Util::make_components_hash(self, args)

      if tmp[:dn]
        tmp[:path] = tmp[:dn]
      end

      query = []
      [:extensions, :filter, :scope, :attributes].collect do |x|
        next if !tmp[x] && query.size == 0
        query.unshift(tmp[x])
      end

      tmp[:query] = query.join('?')

      return super(tmp)
    end


new (URI::LDAP)

# File lib/uri/ldap.rb, line 59
    def initialize(*arg)
      super(*arg)

      if @fragment
        raise InvalidURIError, 'bad LDAP URL'
      end

      parse_dn
      parse_query
    end


dn (URI::LDAP)

# File lib/uri/ldap.rb, line 104
    def dn
      @dn
    end


set_dn (URI::LDAP)

# File lib/uri/ldap.rb, line 108
    def set_dn(val)
      @dn = val
      build_path_query
      @dn
    end


dn= (URI::LDAP)

# File lib/uri/ldap.rb, line 115
    def dn=(val)
      set_dn(val)
      val
    end


attributes (URI::LDAP)

# File lib/uri/ldap.rb, line 120
    def attributes
      @attributes
    end


set_attributes (URI::LDAP)

# File lib/uri/ldap.rb, line 124
    def set_attributes(val)
      @attributes = val
      build_path_query
      @attributes
    end


attributes= (URI::LDAP)

# File lib/uri/ldap.rb, line 131
    def attributes=(val)
      set_attributes(val)
      val
    end


scope (URI::LDAP)

# File lib/uri/ldap.rb, line 136
    def scope
      @scope
    end


set_scope (URI::LDAP)

# File lib/uri/ldap.rb, line 140
    def set_scope(val)
      @scope = val
      build_path_query
      @scope
    end


scope= (URI::LDAP)

# File lib/uri/ldap.rb, line 147
    def scope=(val)
      set_scope(val)
      val
    end


filter (URI::LDAP)

# File lib/uri/ldap.rb, line 152
    def filter
      @filter
    end


set_filter (URI::LDAP)

# File lib/uri/ldap.rb, line 156
    def set_filter(val)
      @filter = val
      build_path_query
      @filter
    end


filter= (URI::LDAP)

# File lib/uri/ldap.rb, line 163
    def filter=(val)
      set_filter(val)
      val
    end


extensions (URI::LDAP)

# File lib/uri/ldap.rb, line 168
    def extensions
      @extensions
    end


set_extensions (URI::LDAP)

# File lib/uri/ldap.rb, line 172
    def set_extensions(val)
      @extensions = val
      build_path_query
      @extensions
    end


extensions= (URI::LDAP)

# File lib/uri/ldap.rb, line 179
    def extensions=(val)
      set_extensions(val)
      val
    end


hierarchical? (URI::LDAP)

# File lib/uri/ldap.rb, line 184
    def hierarchical?
      false
    end


build (URI::MailTo)

# File lib/uri/mailto.rb, line 88
    def self.build(args)
      tmp = Util::make_components_hash(self, args)

      if tmp[:to]
        tmp[:opaque] = tmp[:to]
      else
        tmp[:opaque] = ''
      end

      if tmp[:headers]
        tmp[:opaque] << '?'

        if tmp[:headers].kind_of?(Array)
          tmp[:opaque] << tmp[:headers].collect { |x|
            if x.kind_of?(Array)
              x[0] + '=' + x[1..-1].to_s
            else
              x.to_s
            end
          }.join('&')

        elsif tmp[:headers].kind_of?(Hash)
          tmp[:opaque] << tmp[:headers].collect { |h,v|
            h + '=' + v
          }.join('&')

        else
          tmp[:opaque] << tmp[:headers].to_s
        end
      end

      return super(tmp)
    end


new (URI::MailTo)

# File lib/uri/mailto.rb, line 131
    def initialize(*arg)
      super(*arg)

      @to = nil
      @headers = []

      if MAILTO_REGEXP =~ @opaque
         if arg[-1]
          self.to = $1
          self.headers = $2
        else
          set_to($1)
          set_headers($2)
        end

      else
        raise InvalidComponentError,
          "unrecognised opaque part for mailtoURL: #{@opaque}"
      end
    end


set_to (URI::MailTo)

# File lib/uri/mailto.rb, line 171
    def set_to(v)
      @to = v
    end


to= (URI::MailTo)

# File lib/uri/mailto.rb, line 176
    def to=(v)
      check_to(v)
      set_to(v)
      v
    end


set_headers (URI::MailTo)

# File lib/uri/mailto.rb, line 196
    def set_headers(v)
      @headers = []
      if v
        v.scan(HEADER_REGEXP) do |x|
          @headers << x.split(/=/o, 2)
        end
      end
    end


headers= (URI::MailTo)

# File lib/uri/mailto.rb, line 206
    def headers=(v)
      check_headers(v)
      set_headers(v)
      v
    end


to_s (URI::MailTo)

# File lib/uri/mailto.rb, line 212
    def to_s
      @scheme + ':' +
        if @to
          @to
        else
          ''
        end +
        if @headers.size > 0
          '?' + @headers.collect{|x| x.join('=')}.join('&')
        else
          ''
        end +
        if @fragment
          '#' + @fragment
        else
          ''
        end
    end


to_mailtext (URI::MailTo)

# File lib/uri/mailto.rb, line 241
    def to_mailtext
      to = URI::unescape(@to)
      head = ''
      body = ''
      @headers.each do |x|
        case x[0]
        when 'body'
          body = URI::unescape(x[1])
        when 'to'
          to << ', ' + URI::unescape(x[1])
        else
          head << URI::unescape(x[0]).capitalize + ': ' +
            URI::unescape(x[1])  + "\n"
        end
      end

      return "To: #{to}
#{head}
#{body}
"
    end


split (URI)

# File lib/uri/common.rb, line 380
  def self.split(uri)
    case uri
    when ''
      # null uri

    when ABS_URI
      scheme, opaque, userinfo, host, port,
        registry, path, query, fragment = $~[1..-1]

      # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      # opaque_part   = uric_no_slash *uric

      # abs_path      = "/"  path_segments
      # net_path      = "//" authority [ abs_path ]

      # authority     = server | reg_name
      # server        = [ [ userinfo "@" ] hostport ]

      if !scheme
        raise InvalidURIError,
          "bad URI(absolute but no scheme): #{uri}"
      end
      if !opaque && (!path && (!host && !registry))
        raise InvalidURIError,
          "bad URI(absolute but no path): #{uri}"
      end

    when REL_URI
      scheme = nil
      opaque = nil

      userinfo, host, port, registry,
        rel_segment, abs_path, query, fragment = $~[1..-1]
      if rel_segment && abs_path
        path = rel_segment + abs_path
      elsif rel_segment
        path = rel_segment
      elsif abs_path
        path = abs_path
      end

      # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

      # relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

      # net_path      = "//" authority [ abs_path ]
      # abs_path      = "/"  path_segments
      # rel_path      = rel_segment [ abs_path ]

      # authority     = server | reg_name
      # server        = [ [ userinfo "@" ] hostport ]

    else
      raise InvalidURIError, "bad URI(is not URI?): #{uri}"
    end

    path = '' if !path && !opaque # (see RFC2396 Section 5.2)
    ret = [
      scheme,
      userinfo, host, port,         # X
      registry,                        # X
      path,                         # Y
      opaque,                        # Y
      query,
      fragment
    ]
    return ret
  end


parse (URI)

# File lib/uri/common.rb, line 483
  def self.parse(uri)
    scheme, userinfo, host, port,
      registry, path, opaque, query, fragment = self.split(uri)

    if scheme && @@schemes.include?(scheme.upcase)
      @@schemes[scheme.upcase].new(scheme, userinfo, host, port,
                                   registry, path, opaque, query,
                                   fragment)
    else
      Generic.new(scheme, userinfo, host, port,
                  registry, path, opaque, query,
                  fragment)
    end
  end


join (URI)

# File lib/uri/common.rb, line 519
  def self.join(*str)
    u = self.parse(str[0])
    str[1 .. -1].each do |x|
      u = u.merge(x)
    end
    u
  end


extract (URI)

# File lib/uri/common.rb, line 551
  def self.extract(str, schemes = nil, &block)
    if block_given?
      str.scan(regexp(schemes)) { yield $& }
      nil
    else
      result = []
      str.scan(regexp(schemes)) { result.push $& }
      result
    end
  end


regexp (URI)

# File lib/uri/common.rb, line 593
  def self.regexp(schemes = nil)
    unless schemes
      ABS_URI_REF
    else
      /(?=#{Regexp.union(*schemes)}:)#{PATTERN::X_ABS_URI}/xn
    end
  end


[] (Vector)

# File lib/matrix.rb, line 999
  def Vector.[](*array)
    new(:init_elements, array, copy = false)
  end


elements (Vector)

# File lib/matrix.rb, line 1007
  def Vector.elements(array, copy = true)
    new(:init_elements, array, copy)
  end


new (Vector)

# File lib/matrix.rb, line 1014
  def initialize(method, array, copy)
    self.send(method, array, copy)
  end


init_elements (Vector)

# File lib/matrix.rb, line 1021
  def init_elements(array, copy)
    if copy
      @elements = array.dup
    else
      @elements = array
    end
  end


[] (Vector)

# File lib/matrix.rb, line 1034
  def [](i)
    @elements[i]
  end


size (Vector)

# File lib/matrix.rb, line 1041
  def size
    @elements.size
  end


each2 (Vector)

# File lib/matrix.rb, line 1052
  def each2(v) # :yield: e1, e2
    Vector.Raise ErrDimensionMismatch if size != v.size
    0.upto(size - 1) do
      |i|
      yield @elements[i], v[i]
    end
  end


collect2 (Vector)

# File lib/matrix.rb, line 1064
  def collect2(v) # :yield: e1, e2
    Vector.Raise ErrDimensionMismatch if size != v.size
    (0 .. size - 1).collect do
      |i|
      yield @elements[i], v[i]
    end
  end


== (Vector)

# File lib/matrix.rb, line 1079
  def ==(other)
    return false unless Vector === other

    other.compare_by(@elements)
  end


compare_by (Vector)

# File lib/matrix.rb, line 1089
  def compare_by(elements)
    @elements == elements
  end


clone (Vector)

# File lib/matrix.rb, line 1096
  def clone
    Vector.elements(@elements)
  end


hash (Vector)

# File lib/matrix.rb, line 1103
  def hash
    @elements.hash
  end


* (Vector)

# File lib/matrix.rb, line 1114
  def *(x)
    case x
    when Numeric
      els = @elements.collect{|e| e * x}
      Vector.elements(els, false)
    when Matrix
      Matrix.column_vector(self) * x
    else
      s, x = x.coerce(self)
      s * x
    end
  end


+ (Vector)

# File lib/matrix.rb, line 1130
  def +(v)
    case v
    when Vector
      Vector.Raise ErrDimensionMismatch if size != v.size
      els = collect2(v) {
        |v1, v2|
        v1 + v2
      }
      Vector.elements(els, false)
    when Matrix
      Matrix.column_vector(self) + v
    else
      s, x = v.coerce(self)
      s + x
    end
  end


- (Vector)

# File lib/matrix.rb, line 1150
  def -(v)
    case v
    when Vector
      Vector.Raise ErrDimensionMismatch if size != v.size
      els = collect2(v) {
        |v1, v2|
        v1 - v2
      }
      Vector.elements(els, false)
    when Matrix
      Matrix.column_vector(self) - v
    else
      s, x = v.coerce(self)
      s - x
    end
  end


inner_product (Vector)

# File lib/matrix.rb, line 1175
  def inner_product(v)
    Vector.Raise ErrDimensionMismatch if size != v.size

    p = 0
    each2(v) {
      |v1, v2|
      p += v1 * v2
    }
    p
  end


collect (Vector)

# File lib/matrix.rb, line 1189
  def collect # :yield: e
    els = @elements.collect {
      |v|
      yield v
    }
    Vector.elements(els, false)
  end


map2 (Vector)

# File lib/matrix.rb, line 1201
  def map2(v) # :yield: e1, e2
    els = collect2(v) {
      |v1, v2|
      yield v1, v2
    }
    Vector.elements(els, false)
  end


r (Vector)

# File lib/matrix.rb, line 1213
  def r
    v = 0
    for e in @elements
      v += e*e
    end
    return Math.sqrt(v)
  end


covector (Vector)

# File lib/matrix.rb, line 1228
  def covector
    Matrix.row_vector(self)
  end


to_a (Vector)

# File lib/matrix.rb, line 1235
  def to_a
    @elements.dup
  end


coerce (Vector)

# File lib/matrix.rb, line 1242
  def coerce(other)
    case other
    when Numeric
      return Scalar.new(other), self
    else
      raise TypeError, "#{self.class} can't be coerced into #{other.class}"
    end
  end


to_s (Vector)

# File lib/matrix.rb, line 1258
  def to_s
    "Vector[" + @elements.join(", ") + "]"
  end


inspect (Vector)

# File lib/matrix.rb, line 1265
  def inspect
    str = "Vector"+@elements.inspect
  end


new (WeakRef)

# File lib/weakref.rb, line 49
  def initialize(orig)
    super
    __setobj__(orig)
  end


__getobj__ (WeakRef)

# File lib/weakref.rb, line 57
  def __getobj__
    unless @@id_rev_map[self.__id__] == @__id
      raise RefError, "Illegal Reference - probably recycled", caller(2)
    end
    begin
      ObjectSpace._id2ref(@__id)
    rescue RangeError
      raise RefError, "Illegal Reference - probably recycled", caller(2)
    end
  end


__setobj__ (WeakRef)

# File lib/weakref.rb, line 68
  def __setobj__(obj)
    @__id = obj.__id__
    __old_status = Thread.critical
    begin
      Thread.critical = true
      unless @@id_rev_map.key?(self)
        ObjectSpace.define_finalizer obj, @@final
        ObjectSpace.define_finalizer self, @@final
      end
      @@id_map[@__id] = [] unless @@id_map[@__id]
    ensure
      Thread.critical = __old_status
    end
    @@id_map[@__id].push self.__id__
    @@id_rev_map[self.__id__] = @__id
  end


weakref_alive? (WeakRef)

# File lib/weakref.rb, line 87
  def weakref_alive?
    @@id_rev_map[self.__id__] == @__id
  end


setup_params (WEBrick::AccessLog)

# File lib/webrick/accesslog.rb, line 25
    def setup_params(config, req, res)
      params = Hash.new("")
      params["a"] = req.peeraddr[3]
      params["b"] = res.sent_size
      params["e"] = ENV
      params["f"] = res.filename || ""
      params["h"] = req.peeraddr[2]
      params["i"] = req
      params["l"] = "-"
      params["m"] = req.request_method
      params["n"] = req.attributes
      params["o"] = res
      params["p"] = req.port
      params["q"] = req.query_string
      params["r"] = req.request_line.sub(/\x0d?\x0a\z/o, '')
      params["s"] = res.status       # won't support "%>s"
      params["t"] = req.request_time
      params["T"] = Time.now - req.request_time
      params["u"] = req.user || "-"
      params["U"] = req.unparsed_uri
      params["v"] = config[:ServerName]
      params
    end


format (WEBrick::AccessLog)

# File lib/webrick/accesslog.rb, line 49
    def format(format_string, params)
      format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/){
         param, spec = $1, $2
         case spec[0]
         when ?e, ?i, ?n, ?o
           raise AccessLogError,
             "parameter is required for \"#{spec}\"" unless param
           params[spec][param] || "-"
         when ?t
           params[spec].strftime(param || CLF_TIME_FORMAT)
         when ?%
           "%"
         else
           params[spec]
         end
      }
    end


new (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 18
    def initialize(log_file=nil, level=nil)
      @level = level || INFO
      case log_file
      when String
        @log = open(log_file, "a+")
        @log.sync = true
        @opened = true
      when NilClass
        @log = $stderr
      else
        @log = log_file  # requires "<<". (see BasicLog#log)
      end
    end


close (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 32
    def close
      @log.close if @opened
      @log = nil
    end


log (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 37
    def log(level, data)
      if @log && level <= @level
        data += "\n" if /\n\Z/ !~ data
        @log << data
      end
    end


<< (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 44
    def <<(obj)
      log(INFO, obj.to_s)
    end


fatal (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 48
    def fatal(msg) log(FATAL, "FATAL " << format(msg)); end


error (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 49
    def error(msg) log(ERROR, "ERROR " << format(msg)); end


warn (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 50
    def warn(msg)  log(WARN,  "WARN  " << format(msg)); end


info (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 51
    def info(msg)  log(INFO,  "INFO  " << format(msg)); end


debug (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 52
    def debug(msg) log(DEBUG, "DEBUG " << format(msg)); end


fatal? (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 54
    def fatal?; @level >= FATAL; end


error? (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 55
    def error?; @level >= ERROR; end


warn? (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 56
    def warn?;  @level >= WARN; end


info? (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 57
    def info?;  @level >= INFO; end


debug? (WEBrick::BasicLog)

# File lib/webrick/log.rb, line 58
    def debug?; @level >= DEBUG; end


new (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 126
      def initialize(config, env, stdin, stdout)
        @config = config
        @env = env
        @header_part = StringIO.new
        @body_part = stdin
        @out_port = stdout
        @out_port.binmode

        @server_addr = @env["SERVER_ADDR"] || "0.0.0.0"
        @server_name = @env["SERVER_NAME"]
        @server_port = @env["SERVER_PORT"]
        @remote_addr = @env["REMOTE_ADDR"]
        @remote_host = @env["REMOTE_HOST"] || @remote_addr
        @remote_port = @env["REMOTE_PORT"] || 0

        begin
          @header_part << request_line << CRLF
          setup_header
          @header_part << CRLF
          @header_part.rewind
        rescue Exception => ex
          raise CGIError, "invalid CGI environment"
        end
      end


peeraddr (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 192
      def peeraddr
        [nil, @remote_port, @remote_host, @remote_addr]
      end


addr (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 196
      def addr
        [nil, @server_port, @server_name, @server_addr]
      end


gets (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 200
      def gets(eol=LF)
        input.gets(eol)
      end


read (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 204
      def read(size=nil)
        input.read(size)
      end


each (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 208
      def each
        input.each{|line| yield(line) }
      end


<< (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 212
      def <<(data)
        @out_port << data
      end


cert (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 216
      def cert
        return nil unless defined?(OpenSSL)
        if pem = @env["SSL_SERVER_CERT"]
          OpenSSL::X509::Certificate.new(pem) unless pem.empty?
        end
      end


peer_cert (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 223
      def peer_cert
        return nil unless defined?(OpenSSL)
        if pem = @env["SSL_CLIENT_CERT"]
          OpenSSL::X509::Certificate.new(pem) unless pem.empty?
        end
      end


peer_cert_chain (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 230
      def peer_cert_chain
        return nil unless defined?(OpenSSL)
        if @env["SSL_CLIENT_CERT_CHAIN_0"]
          keys = @env.keys
          certs = keys.sort.collect{|k|
            if /^SSL_CLIENT_CERT_CHAIN_\d+$/ =~ k
              if pem = @env[k]
                OpenSSL::X509::Certificate.new(pem) unless pem.empty?
              end
            end
          }
          certs.compact
        end
      end


cipher (WEBrick::CGI::Socket)

# File lib/webrick/cgi.rb, line 245
      def cipher
        return nil unless defined?(OpenSSL)
        if cipher = @env["SSL_CIPHER"]
          ret = [ cipher ]
          ret << @env["SSL_PROTOCOL"]
          ret << @env["SSL_CIPHER_USEKEYSIZE"]
          ret << @env["SSL_CIPHER_ALGKEYSIZE"]
          ret
        end
      end


new (WEBrick::CGI)

# File lib/webrick/cgi.rb, line 21
    def initialize(*args)
      if defined?(MOD_RUBY)
        unless ENV.has_key?("GATEWAY_INTERFACE")
          Apache.request.setup_cgi_env
        end
      end
      if %r{HTTP/(\d+\.\d+)} =~ ENV["SERVER_PROTOCOL"]
        httpv = $1
      end
      @config = WEBrick::Config::HTTP.dup.update(
        :ServerSoftware => ENV["SERVER_SOFTWARE"] || "null",
        :HTTPVersion    => HTTPVersion.new(httpv || "1.0"),
        :RunOnCGI       => true,   # to detect if it runs on CGI.
        :NPH            => false   # set true to run as NPH script.
      )
      if config = args.shift
        @config.update(config)
      end
      @config[:Logger] ||= WEBrick::BasicLog.new($stderr)
      @logger = @config[:Logger]
      @options = args
    end


[] (WEBrick::CGI)

# File lib/webrick/cgi.rb, line 44
    def [](key)
      @config[key]
    end


start (WEBrick::CGI)

# File lib/webrick/cgi.rb, line 48
    def start(env=ENV, stdin=$stdin, stdout=$stdout)
      sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout)
      req = HTTPRequest.new(@config)
      res = HTTPResponse.new(@config)
      unless @config[:NPH] or defined?(MOD_RUBY)
        def res.setup_header
          unless @header["status"]
            phrase = HTTPStatus::reason_phrase(@status)
            @header["status"] = "#{@status} #{phrase}"
          end
          super
        end
        def res.status_line
          ""
        end
      end

      begin
        req.parse(sock)
        req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup
        req.path_info = (env["PATH_INFO"] || "").dup
        req.query_string = env["QUERY_STRING"]
        req.user = env["REMOTE_USER"]
        res.request_method = req.request_method
        res.request_uri = req.request_uri
        res.request_http_version = req.http_version
        res.keep_alive = req.keep_alive?
        self.service(req, res)
      rescue HTTPStatus::Error => ex
        res.set_error(ex)
      rescue HTTPStatus::Status => ex
        res.status = ex.code
      rescue Exception => ex
        @logger.error(ex)
        res.set_error(ex, true)
      ensure
        req.fixup
        if defined?(MOD_RUBY)
          res.setup_header
          Apache.request.status_line = "#{res.status} #{res.reason_phrase}"
          Apache.request.status = res.status
          table = Apache.request.headers_out
          res.header.each{|key, val|
            case key
            when /^content-encoding$/i
              Apache::request.content_encoding = val
            when /^content-type$/i
              Apache::request.content_type = val
            else
              table[key] = val.to_s
            end
          }
          res.cookies.each{|cookie|
            table.add("Set-Cookie", cookie.to_s)
          }
          Apache.request.send_http_header
          res.send_body(sock)
        else
          res.send_response(sock)
        end
      end
    end


service (WEBrick::CGI)

# File lib/webrick/cgi.rb, line 111
    def   serviceserviceservice(req, res)
      method_name = "do_" + req.request_method.gsub(/-/, "_")
      if respond_to?(method_name)
        __send__(method_name, req, res)
      else
        raise HTTPStatus::MethodNotAllowed,
              "unsupported method `#{req.request_method}'."
      end
    end


new (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 23
    def initialize(name, value)
      @name = name
      @value = value
      @version = 0     # Netscape Cookie

      @domain = @path = @secure = @comment = @max_age =
      @expires = @comment_url = @discard = @port = nil
    end


expires= (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 32
    def expires=(t)
      @expires = t && (t.is_a?(Time) ? t.httpdate : t.to_s)
    end


expires (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 36
    def expires
      @expires && Time.parse(@expires)
    end


to_s (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 40
    def to_s
      ret = ""
      ret << @name << "=" << @value
      ret << "; " << "Version=" << @version.to_s if @version > 0
      ret << "; " << "Domain="  << @domain  if @domain
      ret << "; " << "Expires=" << @expires if @expires
      ret << "; " << "Max-Age=" << @max_age.to_s if @max_age
      ret << "; " << "Comment=" << @comment if @comment
      ret << "; " << "Path="    << @path if @path
      ret << "; " << "Secure"   if @secure
      ret
    end


parse (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 55
    def self.parse(str)
      if str
        ret = []
        cookie = nil
        ver = 0
        str.split(/[;,]\s+/).each{|x|
          key, val = x.split(/=/,2)
          val = val ? HTTPUtils::dequote(val) : ""
          case key
          when "$Version"; ver = val.to_i
          when "$Path";    cookie.path = val
          when "$Domain";  cookie.domain = val
          when "$Port";    cookie.port = val
          else
            ret << cookie if cookie
            cookie = self.new(key, val)
            cookie.version = ver
          end
        }
        ret << cookie if cookie
        ret
      end
    end


parse_set_cookie (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 79
    def self.parse_set_cookie(str)
      cookie_elem = str.split(/;/)
      first_elem = cookie_elem.shift
      first_elem.strip!
      key, value = first_elem.split(/=/, 2)
      cookie = new(key, HTTPUtils.dequote(value))
      cookie_elem.each{|pair|
        pair.strip!
        key, value = pair.split(/=/, 2)
        if value
          value = HTTPUtils.dequote(value.strip)
        end
        case key.downcase
        when "domain"  then cookie.domain  = value
        when "path"    then cookie.path    = value
        when "expires" then cookie.expires = value
        when "max-age" then cookie.max_age = Integer(value)
        when "comment" then cookie.comment = value
        when "version" then cookie.version = Integer(value)
        when "secure"  then cookie.secure = true
        end
      }
      return cookie
    end


parse_set_cookies (WEBrick::Cookie)

# File lib/webrick/cookie.rb, line 104
    def self.parse_set_cookies(str)
      return str.split(/,(?=[^;,]*=)|,$/).collect{|c|
        parse_set_cookie(c)
      }
    end


start (WEBrick::Daemon)

# File lib/webrick/server.rb, line 28
    def Daemon.start
      exit!(0) if fork
      Process::setsid
      exit!(0) if fork
      Dir::chdir("/")
      File::umask(0)
      STDIN.reopen("/dev/null")
      STDOUT.reopen("/dev/null", "w")
      STDERR.reopen("/dev/null", "w")
      yield if block_given?
    end


new (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 44
    def initialize(config={}, default=Config::General)
      @config = default.dup.update(config)
      @status = :Stop
      @config[:Logger] ||= Log::new
      @logger = @config[:Logger]

      @tokens = SizedQueue.new(@config[:MaxClients])
      @config[:MaxClients].times{ @tokens.push(nil) }

      webrickv = WEBrick::VERSION
      rubyv = "#{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
      @logger.info("WEBrick #{webrickv}")
      @logger.info("ruby #{rubyv}")

      @listeners = []
      unless @config[:DoNotListen]
        if @config[:Listen]
          warn(":Listen option is deprecated; use GenericServer#listen")
        end
        listen(@config[:BindAddress], @config[:Port])
        if @config[:Port] == 0
          @config[:Port] = @listeners[0].addr[1]
        end
      end
    end


[] (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 70
    def [](key)
      @config[key]
    end


listen (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 74
    def listen(address, port)
      @listeners += Utils::create_listeners(address, port, @logger)
    end


start (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 78
    def start(&block)
      raise ServerError, "already started." if @status != :Stop
      server_type = @config[:ServerType] || SimpleServer

      server_type.start{
        @logger.info \
          "#{self.class}#start: pid=#{$$} port=#{@config[:Port]}"
        call_callback(:StartCallback)

        thgroup = ThreadGroup.new
        @status = :Running
        while @status == :Running
          begin
            if svrs = IO.select(@listeners, nil, nil, 2.0)
              svrs[0].each{|svr|
                @tokens.pop          # blocks while no token is there.
                if sock = accept_client(svr)
                  th = start_thread(sock, &block)
                  th[:WEBrickThread] = true
                  thgroup.add(th)
                else
                  @tokens.push(nil)
                end
              }
            end
          rescue Errno::EBADF, IOError => ex
            # if the listening socket was closed in GenericServer#shutdown,
            # IO::select raise it.
          rescue Exception => ex
            msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
            @logger.error msg
          end
        end

        @logger.info "going to shutdown ..."
        thgroup.list.each{|th| th.join if th[:WEBrickThread] }
        call_callback(:StopCallback)
        @logger.info "#{self.class}#start done."
        @status = :Stop
      }
    end


stop (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 120
    def stop
      if @status == :Running
        @status = :Shutdown
      end
    end


shutdown (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 126
    def shutdown
      stop
      @listeners.each{|s|
        if @logger.debug?
          addr = s.addr
          @logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
        end
        s.close
      }
      @listeners.clear
    end


run (WEBrick::GenericServer)

# File lib/webrick/server.rb, line 138
    def run(sock)
      @logger.fatal "run() must be provided by user."
    end


ssl_context (WEBrick::GenericServer)

# File lib/webrick/ssl.rb, line 82
    def ssl_context
      @ssl_context ||= nil
    end


listen (WEBrick::GenericServer)

# File lib/webrick/ssl.rb, line 86
    def listen(address, port)
      listeners = Utils::create_listeners(address, port, @logger)
      if @config[:SSLEnable]
        unless ssl_context
          @ssl_context = setup_ssl_context(@config)
          @logger.info("\n" + @config[:SSLCertificate].to_text)
        end
        listeners.collect!{|svr|
          ssvr = ::OpenSSL::SSL::SSLServer.new(svr, ssl_context)
          ssvr.start_immediately = @config[:SSLStartImmediately]
          ssvr
        }
      end
      @listeners += listeners
    end


setup_ssl_context (WEBrick::GenericServer)

# File lib/webrick/ssl.rb, line 102
    def setup_ssl_context(config)
      unless config[:SSLCertificate]
        cn = config[:SSLCertName]
        comment = config[:SSLCertComment]
        cert, key = Utils::create_self_signed_cert(1024, cn, comment)
        config[:SSLCertificate] = cert
        config[:SSLPrivateKey] = key
      end
      ctx = OpenSSL::SSL::SSLContext.new
      ctx.key = config[:SSLPrivateKey]
      ctx.cert = config[:SSLCertificate]
      ctx.client_ca = config[:SSLClientCA]
      ctx.extra_chain_cert = config[:SSLExtraChainCert]
      ctx.ca_file = config[:SSLCACertificateFile]
      ctx.ca_path = config[:SSLCACertificatePath]
      ctx.cert_store = config[:SSLCertificateStore]
      ctx.verify_mode = config[:SSLVerifyClient]
      ctx.verify_depth = config[:SSLVerifyDepth]
      ctx.verify_callback = config[:SSLVerifyCallback]
      ctx.timeout = config[:SSLTimeout]
      ctx.options = config[:SSLOptions]
      ctx
    end


escape (WEBrick::HTMLUtils)

# File lib/webrick/htmlutils.rb, line 14
    def escape(string)
      str = string ? string.dup : ""
      str.gsub!(/&/n, '&amp;')
      str.gsub!(/\"/n, '&quot;')
      str.gsub!(/>/n, '&gt;')
      str.gsub!(/</n, '&lt;')
      str
    end


make_passwd (WEBrick::HTTPAuth::BasicAuth)

# File lib/webrick/httpauth/basicauth.rb, line 21
      def self.make_passwd(realm, user, pass)
        pass ||= ""
        pass.crypt(Utils::random_string(2))
      end


new (WEBrick::HTTPAuth::BasicAuth)

# File lib/webrick/httpauth/basicauth.rb, line 28
      def initialize(config, default=Config::BasicAuth)
        check_init(config)
        @config = default.dup.update(config)
      end


authenticate (WEBrick::HTTPAuth::BasicAuth)

# File lib/webrick/httpauth/basicauth.rb, line 33
      def authenticate(req, res)
        unless basic_credentials = check_scheme(req)
          challenge(req, res)
        end
        userid, password = basic_credentials.unpack("m*")[0].split(":", 2)
        password ||= ""
        if userid.empty?
          error("user id was not given.")
          challenge(req, res)
        end
        unless encpass = @userdb.get_passwd(@realm, userid, @reload_db)
          error("%s: the user is not allowed.", userid)
          challenge(req, res)
        end
        if password.crypt(encpass) != encpass
          error("%s: password unmatch.", userid)
          challenge(req, res)
        end
        info("%s: authentication succeeded.", userid)
        req.user = userid
      end


challenge (WEBrick::HTTPAuth::BasicAuth)

# File lib/webrick/httpauth/basicauth.rb, line 55
      def challenge(req, res)
        res[@response_field] = "#{@auth_scheme} realm=\"#{@realm}\""
        raise @auth_exception
      end


make_passwd (WEBrick::HTTPAuth::DigestAuth)

# File lib/webrick/httpauth/digestauth.rb, line 29
      def self.make_passwd(realm, user, pass)
        pass ||= ""
        Digest::MD5::hexdigest([user, realm, pass].join(":"))
      end


new (WEBrick::HTTPAuth::DigestAuth)

# File lib/webrick/httpauth/digestauth.rb, line 34
      def initialize(config, default=Config::DigestAuth)
        check_init(config)
        @config                 = default.dup.update(config)
        @algorithm              = @config[:Algorithm]
        @domain                 = @config[:Domain]
        @qop                    = @config[:Qop]
        @use_opaque             = @config[:UseOpaque]
        @use_next_nonce         = @config[:UseNextNonce]
        @check_nc               = @config[:CheckNc]
        @use_auth_info_header   = @config[:UseAuthenticationInfoHeader]
        @nonce_expire_period    = @config[:NonceExpirePeriod]
        @nonce_expire_delta     = @config[:NonceExpireDelta]
        @internet_explorer_hack = @config[:InternetExplorerHack]
        @opera_hack             = @config[:OperaHack]

        case @algorithm
        when 'MD5','MD5-sess'
          @h = Digest::MD5
        when 'SHA1','SHA1-sess'  # it is a bonus feature :-)
          @h = Digest::SHA1
        else
          msg = format('Alogrithm "%s" is not supported.', @algorithm)
          raise ArgumentError.new(msg)
        end

        @instance_key = hexdigest(self.__id__, Time.now.to_i, Process.pid)
        @opaques = {}
        @last_nonce_expire = Time.now
        @mutex = Mutex.new
      end


authenticate (WEBrick::HTTPAuth::DigestAuth)

# File lib/webrick/httpauth/digestauth.rb, line 65
      def authenticate(req, res)
        unless result = @mutex.synchronize{ _authenticate(req, res) }
          challenge(req, res)
        end
        if result == :nonce_is_stale
          challenge(req, res, true)
        end
        return true
      end


challenge (WEBrick::HTTPAuth::DigestAuth)

# File lib/webrick/httpauth/digestauth.rb, line 75
      def challenge(req, res, stale=false)
        nonce = generate_next_nonce(req)
        if @use_opaque
          opaque = generate_opaque(req)
          @opaques[opaque].nonce = nonce
        end

        param = Hash.new
        param["realm"]  = HTTPUtils::quote(@realm)
        param["domain"] = HTTPUtils::quote(@domain.to_a.join(" ")) if @domain
        param["nonce"]  = HTTPUtils::quote(nonce)
        param["opaque"] = HTTPUtils::quote(opaque) if opaque
        param["stale"]  = stale.to_s
        param["algorithm"] = @algorithm
        param["qop"]    = HTTPUtils::quote(@qop.to_a.join(",")) if @qop

        res[@response_field] =
          "#{@auth_scheme} " + param.map{|k,v| "#{k}=#{v}" }.join(", ")
        info("%s: %s", @response_field, res[@response_field]) if $DEBUG
        raise @auth_exception
      end


new (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 19
      def initialize(path)
        @path = path
        @mtime = Time.at(0)
        @digest = Hash.new
        @mutex = Mutex::new
        @auth_type = DigestAuth
        open(@path,"a").close unless File::exist?(@path)
        reload
      end


reload (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 29
      def reload
        mtime = File::mtime(@path)
        if mtime > @mtime
          @digest.clear
          open(@path){|io|
            while line = io.gets
              line.chomp!
              user, realm, pass = line.split(/:/, 3)
              unless @digest[realm]
                @digest[realm] = Hash.new
              end
              @digest[realm][user] = pass
            end
          }
          @mtime = mtime
        end
      end


flush (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 47
      def flush(output=nil)
        output ||= @path
        tmp = Tempfile.new("htpasswd", File::dirname(output))
        begin
          each{|item| tmp.puts(item.join(":")) }
          tmp.close
          File::rename(tmp.path, output)
        rescue
          tmp.close(true)
        end
      end


get_passwd (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 59
      def get_passwd(realm, user, reload_db)
        reload() if reload_db
        if hash = @digest[realm]
          hash[user]
        end
      end


set_passwd (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 66
      def set_passwd(realm, user, pass)
        @mutex.synchronize{
          unless @digest[realm]
            @digest[realm] = Hash.new
          end
          @digest[realm][user] = make_passwd(realm, user, pass)
        }
      end


delete_passwd (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 75
      def delete_passwd(realm, user)
        if hash = @digest[realm]
          hash.delete(user)
        end
      end


each (WEBrick::HTTPAuth::Htdigest)

# File lib/webrick/httpauth/htdigest.rb, line 81
      def each
        @digest.keys.sort.each{|realm|
          hash = @digest[realm]
          hash.keys.sort.each{|user|
            yield([user, realm, hash[user]])
          }
        }
      end


new (WEBrick::HTTPAuth::Htgroup)

# File lib/webrick/httpauth/htgroup.rb, line 15
      def initialize(path)
        @path = path
        @mtime = Time.at(0)
        @group = Hash.new
        open(@path,"a").close unless File::exist?(@path)
        reload
      end


reload (WEBrick::HTTPAuth::Htgroup)

# File lib/webrick/httpauth/htgroup.rb, line 23
      def reload
        if (mtime = File::mtime(@path)) > @mtime
          @group.clear
          open(@path){|io|
            while line = io.gets
              line.chomp!
              group, members = line.split(/:\s*/)
              @group[group] = members.split(/\s+/)
            end
          }
          @mtime = mtime
        end
      end


flush (WEBrick::HTTPAuth::Htgroup)

# File lib/webrick/httpauth/htgroup.rb, line 37
      def flush(output=nil)
        output ||= @path
        tmp = Tempfile.new("htgroup", File::dirname(output))
        begin
          @group.keys.sort.each{|group|
            tmp.puts(format("%s: %s", group, self.members(group).join(" ")))
          }
          tmp.close
          File::rename(tmp.path, output)
        rescue
          tmp.close(true)
        end
      end


members (WEBrick::HTTPAuth::Htgroup)

# File lib/webrick/httpauth/htgroup.rb, line 51
      def members(group)
        reload
        @group[group] || []
      end


add (WEBrick::HTTPAuth::Htgroup)

# File lib/webrick/httpauth/htgroup.rb, line 56
      def add(group, members)
        @group[group] = members(group) | members
      end


new (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 19
      def initialize(path)
        @path = path
        @mtime = Time.at(0)
        @passwd = Hash.new
        @auth_type = BasicAuth
        open(@path,"a").close unless File::exist?(@path)
        reload
      end


reload (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 28
      def reload
        mtime = File::mtime(@path)
        if mtime > @mtime
          @passwd.clear
          open(@path){|io|
            while line = io.gets
              line.chomp!
              case line
              when %r!\A[^:]+:[a-zA-Z0-9./]{13}\z!
                user, pass = line.split(":")
              when /:\$/, /:\{SHA\}/
                raise NotImplementedError,
                      'MD5, SHA1 .htpasswd file not supported'
              else
                raise StandardError, 'bad .htpasswd file'
              end
              @passwd[user] = pass
            end
          }
          @mtime = mtime
        end
      end


flush (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 51
      def flush(output=nil)
        output ||= @path
        tmp = Tempfile.new("htpasswd", File::dirname(output))
        begin
          each{|item| tmp.puts(item.join(":")) }
          tmp.close
          File::rename(tmp.path, output)
        rescue
          tmp.close(true)
        end
      end


get_passwd (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 63
      def get_passwd(realm, user, reload_db)
        reload() if reload_db
        @passwd[user]
      end


set_passwd (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 68
      def set_passwd(realm, user, pass)
        @passwd[user] = make_passwd(realm, user, pass)
      end


delete_passwd (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 72
      def delete_passwd(realm, user)
        @passwd.delete(user)
      end


each (WEBrick::HTTPAuth::Htpasswd)

# File lib/webrick/httpauth/htpasswd.rb, line 76
      def each
        @passwd.keys.sort.each{|user|
          yield([user, @passwd[user]])
        }
      end


check_uri (WEBrick::HTTPAuth::ProxyDigestAuth)

# File lib/webrick/httpauth/digestauth.rb, line 338
      def check_uri(req, auth_req)
        return true
      end


make_passwd (WEBrick::HTTPAuth::UserDB)

# File lib/webrick/httpauth/userdb.rb, line 15
      def make_passwd(realm, user, pass)
        @auth_type::make_passwd(realm, user, pass)
      end


set_passwd (WEBrick::HTTPAuth::UserDB)

# File lib/webrick/httpauth/userdb.rb, line 19
      def set_passwd(realm, user, pass)
        self[user] = pass
      end


get_passwd (WEBrick::HTTPAuth::UserDB)

# File lib/webrick/httpauth/userdb.rb, line 23
      def get_passwd(realm, user, reload_db=false)
        # reload_db is dummy
        make_passwd(realm, user, self[user])
      end


_basic_auth (WEBrick::HTTPAuth)

# File lib/webrick/httpauth.rb, line 21
    def _basic_auth(req, res, realm, req_field, res_field, err_type, block)
      user = pass = nil
      if /^Basic\s+(.*)/o =~ req[req_field]
        userpass = $1
        user, pass = userpass.unpack("m*")[0].split(":", 2)
      end
      if block.call(user, pass)
        req.user = user
        return
      end
      res[res_field] = "Basic realm=\"#{realm}\""
      raise err_type
    end


basic_auth (WEBrick::HTTPAuth)

# File lib/webrick/httpauth.rb, line 35
    def basic_auth(req, res, realm, &block)
      _basic_auth(req, res, realm, "Authorization", "WWW-Authenticate",
                  HTTPStatus::Unauthorized, block)
    end


proxy_basic_auth (WEBrick::HTTPAuth)

# File lib/webrick/httpauth.rb, line 40
    def proxy_basic_auth(req, res, realm, &block)
      _basic_auth(req, res, realm, "Proxy-Authorization", "Proxy-Authenticate",
                  HTTPStatus::ProxyAuthenticationRequired, block)
    end


new (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 27
    def initialize(config)
      super
      c = @config
      @via = "#{c[:HTTPVersion]} #{c[:ServerName]}:#{c[:Port]}"
    end


service (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 33
    def service(req, res)
      if req.request_method == "CONNECT"
        proxy_connect(req, res)
      elsif req.unparsed_uri =~ %r!^http://!
        proxy_service(req, res)
      else
        super(req, res)
      end
    end


proxy_auth (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 43
    def proxy_auth(req, res)
      if proc = @config[:ProxyAuthProc]
        proc.call(req, res)
      end
      req.header.delete("proxy-authorization")
    end


split_field (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 54
    def split_field(f) f ? f.split(/,\s+/).collect{|i| i.downcase } : [] end


choose_header (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 56
    def choose_header(src, dst)
      connections = split_field(src['connection'])
      src.each{|key, value|
        key = key.downcase
        if HopByHop.member?(key)          || # RFC2616: 13.5.1
           connections.member?(key)       || # RFC2616: 14.10
           ShouldNotTransfer.member?(key)    # pragmatics
          @logger.debug("choose_header: `#{key}: #{value}'")
          next
        end
        dst[key] = value
      }
    end


set_cookie (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 72
    def set_cookie(src, dst)
      if str = src['set-cookie']
        cookies = []
        str.split(/,\s*/).each{|token|
          if /^[^=]+;/o =~ token
            cookies[-1] << ", " << token
          elsif /=/o =~ token
            cookies << token
          else
            cookies[-1] << ", " << token
          end
        }
        dst.cookies.replace(cookies)
      end
    end


set_via (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 88
    def set_via(h)
      if @config[:ProxyVia]
        if  h['via']
          h['via'] << ", " << @via
        else
          h['via'] = @via
        end
      end
    end


proxy_uri (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 98
    def proxy_uri(req, res)
      @config[:ProxyURI]
    end


proxy_service (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 102
    def proxy_service(req, res)
      # Proxy Authentication
      proxy_auth(req, res)

      # Create Request-URI to send to the origin server
      uri  = req.request_uri
      path = uri.path.dup
      path << "?" << uri.query if uri.query

      # Choose header fields to transfer
      header = Hash.new
      choose_header(req, header)
      set_via(header)

      # select upstream proxy server
      if proxy = proxy_uri(req, res)
        proxy_host = proxy.host
        proxy_port = proxy.port
        if proxy.userinfo
          credentials = "Basic " + [proxy.userinfo].pack("m*")
          credentials.chomp!
          header['proxy-authorization'] = credentials
        end
      end

      response = nil
      begin
        http = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port)
        http.start{
          if @config[:ProxyTimeout]
            ##################################   these issues are
            http.open_timeout = 30   # secs  #   necessary (maybe bacause
            http.read_timeout = 60   # secs  #   Ruby's bug, but why?)
            ##################################
          end
          case req.request_method
          when "GET"  then response = http.get(path, header)
          when "POST" then response = http.post(path, req.body || "", header)
          when "HEAD" then response = http.head(path, header)
          else
            raise HTTPStatus::MethodNotAllowed,
              "unsupported method `#{req.request_method}'."
          end
        }
      rescue => err
        logger.debug("#{err.class}: #{err.message}")
        raise HTTPStatus::ServiceUnavailable, err.message
      end

      # Persistent connction requirements are mysterious for me.
      # So I will close the connection in every response.
      res['proxy-connection'] = "close"
      res['connection'] = "close"

      # Convert Net::HTTP::HTTPResponse to WEBrick::HTTPProxy
      res.status = response.code.to_i
      choose_header(response, res)
      set_cookie(response, res)
      set_via(res)
      res.body = response.body

      # Process contents
      if handler = @config[:ProxyContentHandler]
        handler.call(req, res)
      end
    end


proxy_connect (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 169
    def proxy_connect(req, res)
      # Proxy Authentication
      proxy_auth(req, res)

      ua = Thread.current[:WEBrickSocket]  # User-Agent
      raise HTTPStatus::InternalServerError,
        "[BUG] cannot get socket" unless ua

      host, port = req.unparsed_uri.split(":", 2)
      # Proxy authentication for upstream proxy server
      if proxy = proxy_uri(req, res)
        proxy_request_line = "CONNECT #{host}:#{port} HTTP/1.0"
        if proxy.userinfo
          credentials = "Basic " + [proxy.userinfo].pack("m*")
          credentials.chomp!
        end
        host, port = proxy.host, proxy.port
      end

      begin
        @logger.debug("CONNECT: upstream proxy is `#{host}:#{port}'.")
        os = TCPSocket.new(host, port)     # origin server

        if proxy
          @logger.debug("CONNECT: sending a Request-Line")
          os << proxy_request_line << CRLF
          @logger.debug("CONNECT: > #{proxy_request_line}")
          if credentials
            @logger.debug("CONNECT: sending a credentials")
            os << "Proxy-Authorization: " << credentials << CRLF
          end
          os << CRLF
          proxy_status_line = os.gets(LF)
          @logger.debug("CONNECT: read a Status-Line form the upstream server")
          @logger.debug("CONNECT: < #{proxy_status_line}")
          if %r{^HTTP/\d+\.\d+\s+200\s*} =~ proxy_status_line
            while line = os.gets(LF)
              break if /\A(#{CRLF}|#{LF})\z/om =~ line
            end
          else
            raise HTTPStatus::BadGateway
          end
        end
        @logger.debug("CONNECT #{host}:#{port}: succeeded")
        res.status = HTTPStatus::RC_OK
      rescue => ex
        @logger.debug("CONNECT #{host}:#{port}: failed `#{ex.message}'")
        res.set_error(ex)
        raise HTTPStatus::EOFError
      ensure
        if handler = @config[:ProxyContentHandler]
          handler.call(req, res)
        end
        res.send_response(ua)
        access_log(@config, req, res)

        # Should clear request-line not to send the sesponse twice.
        # see: HTTPServer#run
        req.parse(NullReader) rescue nil
      end

      begin
        while fds = IO::select([ua, os])
          if fds[0].member?(ua)
            buf = ua.sysread(1024);
            @logger.debug("CONNECT: #{buf.size} byte from User-Agent")
            os.syswrite(buf)
          elsif fds[0].member?(os)
            buf = os.sysread(1024);
            @logger.debug("CONNECT: #{buf.size} byte from #{host}:#{port}")
            ua.syswrite(buf)
          end
        end
      rescue => ex
        os.close
        @logger.debug("CONNECT #{host}:#{port}: closed")
      end

      raise HTTPStatus::EOFError
    end


do_OPTIONS (WEBrick::HTTPProxyServer)

# File lib/webrick/httpproxy.rb, line 250
    def do_OPTIONS(req, res)
      res['allow'] = "GET,HEAD,POST,OPTIONS,CONNECT"
    end


new (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 45
    def initialize(config)
      @config = config
      @logger = config[:Logger]

      @request_line = @request_method =
        @unparsed_uri = @http_version = nil

      @request_uri = @host = @port = @path = nil
      @script_name = @path_info = nil
      @query_string = nil
      @query = nil
      @form_data = nil

      @raw_header = Array.new
      @header = nil
      @cookies = []
      @accept = []
      @accept_charset = []
      @accept_encoding = []
      @accept_language = []
      @body = ""

      @addr = @peeraddr = nil
      @attributes = {}
      @user = nil
      @keep_alive = false
      @request_time = nil

      @remaining_size = nil
      @socket = nil
    end


parse (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 77
    def parse(socket=nil)
      @socket = socket
      begin
        @peeraddr = socket.respond_to?(:peeraddr) ? socket.peeraddr : []
        @addr = socket.respond_to?(:addr) ? socket.addr : []
      rescue Errno::ENOTCONN
        raise HTTPStatus::EOFError
      end

      read_request_line(socket)
      if @http_version.major > 0
        read_header(socket)
        @header['cookie'].each{|cookie|
          @cookies += Cookie::parse(cookie)
        }
        @accept = HTTPUtils.parse_qvalues(self['accept'])
        @accept_charset = HTTPUtils.parse_qvalues(self['accept-charset'])
        @accept_encoding = HTTPUtils.parse_qvalues(self['accept-encoding'])
        @accept_language = HTTPUtils.parse_qvalues(self['accept-language'])
      end
      return if @request_method == "CONNECT"
      return if @unparsed_uri == "*"

      begin
        @request_uri = parse_uri(@unparsed_uri)
        @path = HTTPUtils::unescape(@request_uri.path)
        @path = HTTPUtils::normalize_path(@path)
        @host = @request_uri.host
        @port = @request_uri.port
        @query_string = @request_uri.query
        @script_name = ""
        @path_info = @path.dup
      rescue
        raise HTTPStatus::BadRequest, "bad URI `#{@unparsed_uri}'."
      end

      if /close/io =~ self["connection"]
        @keep_alive = false
      elsif /keep-alive/io =~ self["connection"]
        @keep_alive = true
      elsif @http_version < "1.1"
        @keep_alive = false
      else
        @keep_alive = true
      end
    end


body (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 124
    def body(&block)
      block ||= Proc.new{|chunk| @body << chunk }
      read_body(@socket, block)
      @body.empty? ? nil : @body
    end


query (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 130
    def query
      unless @query
        parse_query()
      end
      @query
    end


content_length (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 137
    def content_length
      return Integer(self['content-length'])
    end


content_type (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 141
    def content_type
      return self['content-type']
    end


[] (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 145
    def [](header_name)
      if @header
        value = @header[header_name.downcase]
        value.empty? ? nil : value.join(", ")
      end
    end


each (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 152
    def each
      @header.each{|k, v|
        value = @header[k]
        yield(k, value.empty? ? nil : value.join(", "))
      }
    end


keep_alive? (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 159
    def keep_alive?
      @keep_alive
    end


to_s (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 163
    def to_s
      ret = @request_line.dup
      @raw_header.each{|line| ret << line }
      ret << CRLF
      ret << body if body
      ret
    end


fixup (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 171
    def fixup()
      begin
        body{|chunk| }   # read remaining body
      rescue HTTPStatus::Error => ex
        @logger.error("HTTPRequest#fixup: #{ex.class} occured.")
        @keep_alive = false
      rescue => ex
        @logger.error(ex)
        @keep_alive = false
      end
    end


meta_vars (WEBrick::HTTPRequest)

# File lib/webrick/httprequest.rb, line 183
    def meta_vars
      # This method provides the metavariables defined by the revision 3
      # of ``The WWW Common Gateway Interface Version 1.1''.
      # (http://Web.Golux.Com/coar/cgi/)

      meta = Hash.new

      cl = self["Content-Length"]
      ct = self["Content-Type"]
      meta["CONTENT_LENGTH"]    = cl if cl.to_i > 0
      meta["CONTENT_TYPE"]      = ct.dup if ct
      meta["GATEWAY_INTERFACE"] = "CGI/1.1"
      meta["PATH_INFO"]         = @path_info ? @path_info.dup : ""
     #meta["PATH_TRANSLATED"]   = nil      # no plan to be provided
      meta["QUERY_STRING"]      = @query_string ? @query_string.dup : ""
      meta["REMOTE_ADDR"]       = @peeraddr[3]
      meta["REMOTE_HOST"]       = @peeraddr[2]
     #meta["REMOTE_IDENT"]      = nil      # no plan to be provided
      meta["REMOTE_USER"]       = @user
      meta["REQUEST_METHOD"]    = @request_method.dup
      meta["REQUEST_URI"]       = @request_uri.to_s
      meta["SCRIPT_NAME"]       = @script_name.dup
      meta["SERVER_NAME"]       = @host
      meta["SERVER_PORT"]       = @port.to_s
      meta["SERVER_PROTOCOL"]   = "HTTP/" + @config[:HTTPVersion].to_s
      meta["SERVER_SOFTWARE"]   = @config[:ServerSoftware].dup

      self.each{|key, val|
        next if /^content-type$/i =~ key
        next if /^content-length$/i =~ key
        name = "HTTP_" + key
        name.gsub!(/-/o, "_")
        name.upcase!
        meta[name] = val
      }

      meta
    end


parse (WEBrick::HTTPRequest)

# File lib/webrick/https.rb, line 23
    def parse(socket=nil)
      if socket.respond_to?(:cert)
        @server_cert = socket.cert || @config[:SSLCertificate]
        @client_cert = socket.peer_cert
        @client_cert_chain = socket.peer_cert_chain
        @cipher      = socket.cipher
      end
      orig_parse(socket)
    end


parse_uri (WEBrick::HTTPRequest)

# File lib/webrick/https.rb, line 35
    def parse_uri(str, scheme="https")
      if @server_cert
        return orig_parse_uri(str, scheme)
      end
      return orig_parse_uri(str)
    end


meta_vars (WEBrick::HTTPRequest)

# File lib/webrick/https.rb, line 44
    def meta_vars
      meta = orig_meta_vars
      if @server_cert
        meta["HTTPS"] = "on"
        meta["SSL_SERVER_CERT"] = @server_cert.to_pem
        meta["SSL_CLIENT_CERT"] = @client_cert ? @client_cert.to_pem : ""
        if @client_cert_chain
          @client_cert_chain.each_with_index{|cert, i|
            meta["SSL_CLIENT_CERT_CHAIN_#{i}"] = cert.to_pem
          }
        end
        meta["SSL_CIPHER"] = @cipher[0]
        meta["SSL_PROTOCOL"] = @cipher[1]
        meta["SSL_CIPHER_USEKEYSIZE"] = @cipher[2].to_s
        meta["SSL_CIPHER_ALGKEYSIZE"] = @cipher[3].to_s
      end
      meta
    end


new (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 31
    def initialize(config)
      @config = config
      @logger = config[:Logger]
      @header = Hash.new
      @status = HTTPStatus::RC_OK
      @reason_phrase = nil
      @http_version = HTTPVersion::convert(@config[:HTTPVersion])
      @body = ''
      @keep_alive = true
      @cookies = []
      @request_method = nil
      @request_uri = nil
      @request_http_version = @http_version  # temporary
      @chunked = false
      @filename = nil
      @sent_size = 0
    end


status_line (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 49
    def status_line
      "HTTP/#@http_version #@status #@reason_phrase #{CRLF}"
    end


status= (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 53
    def status=(status)
      @status = status
      @reason_phrase = HTTPStatus::reason_phrase(status)
    end


[] (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 58
    def [](field)
      @header[field.downcase]
    end


[]= (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 62
    def []=(field, value)
      @header[field.downcase] = value.to_s
    end


content_length (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 66
    def content_length
      if len = self['content-length']
        return Integer(len)
      end
    end


content_length= (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 72
    def content_length=(len)
      self['content-length'] = len.to_s
    end


content_type (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 76
    def content_type
      self['content-type']
    end


content_type= (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 80
    def content_type=(type)
      self['content-type'] = type
    end


each (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 84
    def each
      @header.each{|k, v|  yield(k, v) }
    end


chunked? (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 88
    def chunked?
      @chunked
    end


chunked= (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 92
    def chunked=(val)
      @chunked = val ? true : false
    end


keep_alive? (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 96
    def keep_alive?
      @keep_alive
    end


send_response (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 100
    def send_response(socket)
      begin
        setup_header()
        send_header(socket)
        send_body(socket)
      rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ENOTCONN => ex
        @logger.debug(ex)
        @keep_alive = false
      rescue Exception => ex
        @logger.error(ex)
        @keep_alive = false
      end
    end


setup_header (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 114
    def setup_header()
      @reason_phrase    ||= HTTPStatus::reason_phrase(@status)
      @header['server'] ||= @config[:ServerSoftware]
      @header['date']   ||= Time.now.httpdate

      # HTTP/0.9 features
      if @request_http_version < "1.0"
        @http_version = HTTPVersion.new("0.9")
        @keep_alive = false
      end

      # HTTP/1.0 features
      if @request_http_version < "1.1"
        if chunked?
          @chunked = false
          ver = @request_http_version.to_s
          msg = "chunked is set for an HTTP/#{ver} request. (ignored)"
          @logger.warn(msg)
        end
      end

      # Determin the message length (RFC2616 -- 4.4 Message Length)
      if @status == 304 || @status == 204 || HTTPStatus::info?(@status)
        @header.delete('content-length')
        @body = ""
      elsif chunked?
        @header["transfer-encoding"] = "chunked"
        @header.delete('content-length')
      elsif %r{^multipart/byteranges} =~ @header['content-type']
        @header.delete('content-length')
      elsif @header['content-length'].nil?
        unless @body.is_a?(IO)
          @header['content-length'] = @body ? @body.size : 0
        end
      end

      # Keep-Alive connection.
      if @header['connection'] == "close"
         @keep_alive = false
      elsif keep_alive?
        if chunked? || @header['content-length']
          @header['connection'] = "Keep-Alive"
        end
      else
        @header['connection'] = "close"
      end

      # Location is a single absoluteURI.
      if location = @header['location']
        if @request_uri
          @header['location'] = @request_uri.merge(location)
        end
      end
    end


send_header (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 169
    def send_header(socket)
      if @http_version.major > 0
        data = status_line()
        @header.each{|key, value|
          tmp = key.gsub(/\bwww|^te$|\b\w/){|s| s.upcase }
          data << "#{tmp}: #{value}" << CRLF
        }
        @cookies.each{|cookie|
          data << "Set-Cookie: " << cookie.to_s << CRLF
        }
        data << CRLF
        _write_data(socket, data)
      end
    end


send_body (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 184
    def send_body(socket)
      case @body
      when IO then send_body_io(socket)
      else send_body_string(socket)
      end
    end


to_s (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 191
    def to_s
      ret = ""
      send_response(ret)
      ret
    end


set_redirect (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 197
    def set_redirect(status, url)
      @body = "<HTML><A HREF=\"#{url.to_s}\">#{url.to_s}</A>.</HTML>\n"
      @header['location'] = url.to_s
      raise status
    end


set_error (WEBrick::HTTPResponse)

# File lib/webrick/httpresponse.rb, line 203
    def set_error(ex, backtrace=false)
      case ex
      when HTTPStatus::Status
        @keep_alive = false if HTTPStatus::error?(ex.code)
        self.status = ex.code
      else
        @keep_alive = false
        self.status = HTTPStatus::RC_INTERNAL_SERVER_ERROR
      end
      @header['content-type'] = "text/html"

      if respond_to?(:create_error_page)
        create_error_page()
        return
      end

      if @request_uri
        host, port = @request_uri.host, @request_uri.port
      else
        host, port = @config[:ServerName], @config[:Port]
      end

      @body = ''
      @body << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\">\n<HTML>\n<HEAD><TITLE>\#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>\n<BODY>\n<H1>\#{HTMLUtils::escape(@reason_phrase)}</H1>\n\#{HTMLUtils::escape(ex.message)}\n<HR>\n"

      if backtrace && $DEBUG
        @body << "backtrace of `#{HTMLUtils::escape(ex.class.to_s)}' "
        @body << "#{HTMLUtils::escape(ex.message)}"
        @body << "<PRE>"
        ex.backtrace.each{|line| @body << "\t#{line}\n"}
        @body << "</PRE><HR>"
      end

      @body << "<ADDRESS>\n\#{HTMLUtils::escape(@config[:ServerSoftware])} at\n\#{host}:\#{port}\n</ADDRESS>\n</BODY>\n</HTML>\n"
    end


new (WEBrick::HTTPServer::MountTable)

# File lib/webrick/httpserver.rb, line 164
      def initialize
        @tab = Hash.new
        compile
      end


[] (WEBrick::HTTPServer::MountTable)

# File lib/webrick/httpserver.rb, line 169
      def [](dir)
        dir = normalize(dir)
        @tab[dir]
      end


[]= (WEBrick::HTTPServer::MountTable)

# File lib/webrick/httpserver.rb, line 174
      def []=(dir, val)
        dir = normalize(dir)
        @tab[dir] = val
        compile
        val
      end


delete (WEBrick::HTTPServer::MountTable)

# File lib/webrick/httpserver.rb, line 181
      def delete(dir)
        dir = normalize(dir)
        res = @tab.delete(dir)
        compile
        res
      end


scan (WEBrick::HTTPServer::MountTable)

# File lib/webrick/httpserver.rb, line 188
      def scan(path)
        @scanner =~ path
        [ $&, $' ]
      end


new (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 23
    def initialize(config={}, default=Config::HTTP)
      super
      @http_version = HTTPVersion::convert(@config[:HTTPVersion])

      @mount_tab = MountTable.new
      if @config[:DocumentRoot]
        mount("/", HTTPServlet::FileHandler, @config[:DocumentRoot],
              @config[:DocumentRootOptions])
      end

      unless @config[:AccessLog]
        @config[:AccessLog] = [
          [ $stderr, AccessLog::COMMON_LOG_FORMAT ],
          [ $stderr, AccessLog::REFERER_LOG_FORMAT ]
        ]
      end

      @virtual_hosts = Array.new
    end


run (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 43
    def run(sock)
      while true
        res = HTTPResponse.new(@config)
        req = HTTPRequest.new(@config)
        server = self
        begin
          timeout = @config[:RequestTimeout]
          while timeout > 0
            break if IO.select([sock], nil, nil, 0.5)
            timeout = 0 if @status != :Running
            timeout -= 0.5
          end
          raise HTTPStatus::EOFError if timeout <= 0 || sock.eof?
          req.parse(sock)
          res.request_method = req.request_method
          res.request_uri = req.request_uri
          res.request_http_version = req.http_version
          res.keep_alive = req.keep_alive?
          server = lookup_server(req) || self
          if callback = server[:RequestCallback] || server[:RequestHandler]
            callback.call(req, res)
          end
          server.service(req, res)
        rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout => ex
          res.set_error(ex)
        rescue HTTPStatus::Error => ex
          @logger.error(ex.message)
          res.set_error(ex)
        rescue HTTPStatus::Status => ex
          res.status = ex.code
        rescue StandardError => ex
          @logger.error(ex)
          res.set_error(ex, true)
        ensure
          if req.request_line
            req.fixup()
            res.send_response(sock)
            server.access_log(@config, req, res)
          end
        end
        break if @http_version < "1.1"
        break unless req.keep_alive?
        break unless res.keep_alive?
      end
    end


service (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 89
    def service(req, res)
      if req.unparsed_uri == "*"
        if req.request_method == "OPTIONS"
          do_OPTIONS(req, res)
          raise HTTPStatus::OK
        end
        raise HTTPStatus::NotFound, "`#{req.unparsed_uri}' not found."
      end

      servlet, options, script_name, path_info = search_servlet(req.path)
      raise HTTPStatus::NotFound, "`#{req.path}' not found." unless servlet
      req.script_name = script_name
      req.path_info = path_info
      si = servlet.get_instance(self, *options)
      @logger.debug(format("%s is invoked.", si.class.name))
      si.service(req, res)
    end


do_OPTIONS (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 107
    def do_OPTIONS(req, res)
      res["allow"] = "GET,HEAD,POST,OPTIONS"
    end


mount (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 111
    def mount(dir, servlet, *options)
      @logger.debug(sprintf("%s is mounted on %s.", servlet.inspect, dir))
      @mount_tab[dir] = [ servlet, options ]
    end


mount_proc (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 116
    def mount_proc(dir, proc=nil, &block)
      proc ||= block
      raise HTTPServerError, "must pass a proc or block" unless proc
      mount(dir, HTTPServlet::ProcHandler.new(proc))
    end


unmount (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 122
    def unmount(dir)
      @logger.debug(sprintf("unmount %s.", dir))
      @mount_tab.delete(dir)
    end


search_servlet (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 128
    def search_servlet(path)
      script_name, path_info = @mount_tab.scan(path)
      servlet, options = @mount_tab[script_name]
      if servlet
        [ servlet, options, script_name, path_info ]
      end
    end


virtual_host (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 136
    def virtual_host(server)
      @virtual_hosts << server
      @virtual_hosts = @virtual_hosts.sort_by{|s|
        num = 0
        num -= 4 if s[:BindAddress]
        num -= 2 if s[:Port]
        num -= 1 if s[:ServerName]
        num
      }
    end


lookup_server (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 147
    def lookup_server(req)
      @virtual_hosts.find{|s|
        (s[:BindAddress].nil? || req.addr[3] == s[:BindAddress]) &&
        (s[:Port].nil?        || req.port == s[:Port])           &&
        ((s[:ServerName].nil?  || req.host == s[:ServerName]) ||
         (!s[:ServerAlias].nil? && s[:ServerAlias].find{|h| h === req.host}))
      }
    end


access_log (WEBrick::HTTPServer)

# File lib/webrick/httpserver.rb, line 156
    def access_log(config, req, res)
      param = AccessLog::setup_params(config, req, res)
      @config[:AccessLog].each{|logger, fmt|
        logger << AccessLog::format(fmt+"\n", param)
      }
    end


get_instance (WEBrick::HTTPServlet::AbstractServlet)

# File lib/webrick/httpservlet/abstract.rb, line 22
      def self.get_instance(config, *options)
        self.new(config, *options)
      end


new (WEBrick::HTTPServlet::AbstractServlet)

# File lib/webrick/httpservlet/abstract.rb, line 26
      def initialize(server, *options)
        @server = @config = server
        @logger = @server[:Logger]
        @options = options
      end


service (WEBrick::HTTPServlet::AbstractServlet)

# File lib/webrick/httpservlet/abstract.rb, line 32
      def service(req, res)
        method_name = "do_" + req.request_method.gsub(/-/, "_")
        if respond_to?(method_name)
          __send__(method_name, req, res)
        else
          raise HTTPStatus::MethodNotAllowed,
                "unsupported method `#{req.request_method}'."
        end
      end


do_GET (WEBrick::HTTPServlet::AbstractServlet)

# File lib/webrick/httpservlet/abstract.rb, line 42
      def do_GET(req, res)
        raise HTTPStatus::NotFound, "not found."
      end


do_HEAD (WEBrick::HTTPServlet::AbstractServlet)

# File lib/webrick/httpservlet/abstract.rb, line 46
      def do_HEAD(req, res)
        do_GET(req, res)
      end


do_OPTIONS (WEBrick::HTTPServlet::AbstractServlet)

# File lib/webrick/httpservlet/abstract.rb, line 50
      def do_OPTIONS(req, res)
        m = self.methods.grep(/^do_[A-Z]+$/)
        m.collect!{|i| i.sub(/do_/, "") }
        m.sort!
        res["allow"] = m.join(",")
      end


new (WEBrick::HTTPServlet::CGIHandler)

# File lib/webrick/httpservlet/cgihandler.rb, line 25
      def initialize(server, name)
        super
        @script_filename = name
        @tempdir = server[:TempDir]
        @cgicmd = "#{CGIRunner} #{server[:CGIInterpreter]}"
      end


do_GET (WEBrick::HTTPServlet::CGIHandler)

# File lib/webrick/httpservlet/cgihandler.rb, line 32
      def do_GET(req, res)
        data = nil
        status = -1

        cgi_in = IO::popen(@cgicmd, "wb")
        cgi_out = Tempfile.new("webrick.cgiout.", @tempdir)
        cgi_err = Tempfile.new("webrick.cgierr.", @tempdir)
        begin
          cgi_in.sync = true
          meta = req.meta_vars
          meta["SCRIPT_FILENAME"] = @script_filename
          meta["PATH"] = @config[:CGIPathEnv]
          if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
            meta["SystemRoot"] = ENV["SystemRoot"]
          end
          dump = Marshal.dump(meta)

          cgi_in.write("%8d" % cgi_out.path.size)
          cgi_in.write(cgi_out.path)
          cgi_in.write("%8d" % cgi_err.path.size)
          cgi_in.write(cgi_err.path)
          cgi_in.write("%8d" % dump.size)
          cgi_in.write(dump)

          if req.body and req.body.size > 0
            cgi_in.write(req.body)
          end
        ensure
          cgi_in.close
          status = $?.exitstatus
          sleep 0.1 if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
          data = cgi_out.read
          cgi_out.close(true)
          if errmsg = cgi_err.read
            if errmsg.size > 0
              @logger.error("CGIHandler: #{@script_filename}:\n" + errmsg)
            end
          end
          cgi_err.close(true)
        end

        if status != 0
          @logger.error("CGIHandler: #{@script_filename} exit with #{status}")
        end

        data = "" unless data
        raw_header, body = data.split(/^[\xd\xa]+/on, 2)
        raise HTTPStatus::InternalServerError,
          "Premature end of script headers: #{@script_filename}" if body.nil?

        begin
          header = HTTPUtils::parse_header(raw_header)
          if /^(\d+)/ =~ header['status'][0]
            res.status = $1.to_i
            header.delete('status')
          end
          if header.has_key?('set-cookie')
            header['set-cookie'].each{|k|
              res.cookies << Cookie.parse_set_cookie(k)
            }
            header.delete('set-cookie')
          end
          header.each{|key, val| res[key] = val.join(", ") }
        rescue => ex
          raise HTTPStatus::InternalServerError, ex.message
        end
        res.body = body
      end


new (WEBrick::HTTPServlet::DefaultFileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 22
      def initialize(server, local_path)
        super
        @local_path = local_path
      end


do_GET (WEBrick::HTTPServlet::DefaultFileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 27
      def do_GET(req, res)
        st = File::stat(@local_path)
        mtime = st.mtime
        res['etag'] = sprintf("%x-%x-%x", st.ino, st.size, st.mtime.to_i)

        if not_modified?(req, res, mtime, res['etag'])
          res.body = ''
          raise HTTPStatus::NotModified
        elsif req['range']
          make_partial_content(req, res, @local_path, st.size)
          raise HTTPStatus::PartialContent
        else
          mtype = HTTPUtils::mime_type(@local_path, @config[:MimeTypes])
          res['content-type'] = mtype
          res['content-length'] = st.size
          res['last-modified'] = mtime.httpdate
          res.body = open(@local_path, "rb")
        end
      end


not_modified? (WEBrick::HTTPServlet::DefaultFileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 47
      def not_modified?(req, res, mtime, etag)
        if ir = req['if-range']
          begin
            if Time.httpdate(ir) >= mtime
              return true
            end
          rescue
            if HTTPUtils::split_header_value(ir).member?(res['etag'])
              return true
            end
          end
        end

        if (ims = req['if-modified-since']) && Time.parse(ims) >= mtime
          return true
        end

        if (inm = req['if-none-match']) &&
           HTTPUtils::split_header_value(inm).member?(res['etag'])
          return true
        end

        return false
      end


make_partial_content (WEBrick::HTTPServlet::DefaultFileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 72
      def make_partial_content(req, res, filename, filesize)
        mtype = HTTPUtils::mime_type(filename, @config[:MimeTypes])
        unless ranges = HTTPUtils::parse_range_header(req['range'])
          raise HTTPStatus::BadRequest,
            "Unrecognized range-spec: \"#{req['range']}\""
        end
        open(filename, "rb"){|io|
          if ranges.size > 1
            time = Time.now
            boundary = "#{time.sec}_#{time.usec}_#{Process::pid}"
            body = ''
            ranges.each{|range|
              first, last = prepare_range(range, filesize)
              next if first < 0
              io.pos = first
              content = io.read(last-first+1)
              body << "--" << boundary << CRLF
              body << "Content-Type: #{mtype}" << CRLF
              body << "Content-Range: #{first}-#{last}/#{filesize}" << CRLF
              body << CRLF
              body << content
              body << CRLF
            }
            raise HTTPStatus::RequestRangeNotSatisfiable if body.empty?
            body << "--" << boundary << "--" << CRLF
            res["content-type"] = "multipart/byteranges; boundary=#{boundary}"
            res.body = body
          elsif range = ranges[0]
            first, last = prepare_range(range, filesize)
            raise HTTPStatus::RequestRangeNotSatisfiable if first < 0
            if last == filesize - 1
              content = io.dup
              content.pos = first
            else
              io.pos = first
              content = io.read(last-first+1)
            end
            res['content-type'] = mtype
            res['content-range'] = "#{first}-#{last}/#{filesize}"
            res['content-length'] = last - first + 1
            res.body = content
          else
            raise HTTPStatus::BadRequest
          end
        }
      end


prepare_range (WEBrick::HTTPServlet::DefaultFileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 119
      def prepare_range(range, filesize)
        first = range.first < 0 ? filesize + range.first : range.first
        return -1, -1 if first < 0 || first >= filesize
        last = range.last < 0 ? filesize + range.last : range.last
        last = filesize - 1 if last >= filesize
        return first, last
      end


new (WEBrick::HTTPServlet::ERBHandler)

# File lib/webrick/httpservlet/erbhandler.rb, line 19
      def initialize(server, name)
        super
        @script_filename = name
      end


do_GET (WEBrick::HTTPServlet::ERBHandler)

# File lib/webrick/httpservlet/erbhandler.rb, line 24
      def do_GET(req, res)
        unless defined?(ERB)
          @logger.warn "#{self.class}: ERB not defined."
          raise HTTPStatus::Forbidden, "ERBHandler cannot work."
        end
        begin
          data = open(@script_filename){|io| io.read }
          res.body = evaluate(ERB.new(data), req, res)
          res['content-type'] =
            HTTPUtils::mime_type(@script_filename, @config[:MimeTypes])
        rescue StandardError => ex
          raise
        rescue Exception => ex
          @logger.error(ex)
          raise HTTPStatus::InternalServerError, ex.message
        end
      end


add_handler (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 131
      def self.add_handler(suffix, handler)
        HandlerTable[suffix] = handler
      end


remove_handler (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 135
      def self.remove_handler(suffix)
        HandlerTable.delete(suffix)
      end


new (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 139
      def initialize(server, root, options={}, default=Config::FileHandler)
        @config = server.config
        @logger = @config[:Logger]
        @root = File.expand_path(root)
        if options == true || options == false
          options = { :FancyIndexing => options }
        end
        @options = default.dup.update(options)
      end


service (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 149
      def service(req, res)
        # if this class is mounted on "/" and /~username is requested.
        # we're going to override path informations before invoking service.
        if defined?(Etc) && @options[:UserDir] && req.script_name.empty?
          if %r|^(/~([^/]+))| =~ req.path_info
            script_name, user = $1, $2
            path_info = $'
            begin
              passwd = Etc::getpwnam(user)
              @root = File::join(passwd.dir, @options[:UserDir])
              req.script_name = script_name
              req.path_info = path_info
            rescue
              @logger.debug "#{self.class}#do_GET: getpwnam(#{user}) failed"
            end
          end
        end
        super(req, res)
      end


do_GET (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 169
      def do_GET(req, res)
        unless exec_handler(req, res)
          set_dir_list(req, res)
        end
      end


do_POST (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 175
      def do_POST(req, res)
        unless exec_handler(req, res)
          raise HTTPStatus::NotFound, "`#{req.path}' not found."
        end
      end


do_OPTIONS (WEBrick::HTTPServlet::FileHandler)

# File lib/webrick/httpservlet/filehandler.rb, line 181
      def do_OPTIONS(req, res)
        unless exec_handler(req, res)
          super(req, res)
        end
      end


get_instance (WEBrick::HTTPServlet::ProcHandler)

# File lib/webrick/httpservlet/prochandler.rb, line 17
      def get_instance(server, *options)
        self
      end


new (WEBrick::HTTPServlet::ProcHandler)

# File lib/webrick/httpservlet/prochandler.rb, line 21
      def initialize(proc)
        @proc = proc
      end


do_GET (WEBrick::HTTPServlet::ProcHandler)

# File lib/webrick/httpservlet/prochandler.rb, line 25
      def do_GET(request, response)
        @proc.call(request, response)
      end


reason_phrase (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 96
    def reason_phrase(code)
      StatusMessage[code.to_i]
    end


info? (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 99
    def info?(code)
      code.to_i >= 100 and code.to_i < 200
    end


success? (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 102
    def success?(code)
      code.to_i >= 200 and code.to_i < 300
    end


redirect? (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 105
    def redirect?(code)
      code.to_i >= 300 and code.to_i < 400
    end


error? (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 108
    def error?(code)
      code.to_i >= 400 and code.to_i < 600
    end


client_error? (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 111
    def client_error?(code)
      code.to_i >= 400 and code.to_i < 500
    end


server_error? (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 114
    def server_error?(code)
      code.to_i >= 500 and code.to_i < 600
    end


[] (WEBrick::HTTPStatus)

# File lib/webrick/httpstatus.rb, line 118
    def self.[](code)
      CodeToError[code]
    end


new (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 218
      def initialize(*args)
        @name = @filename = @next_data = nil
        if args.empty?
          @raw_header = []
          @header = nil
          super("")
        else
          @raw_header = EmptyRawHeader
          @header = EmptyHeader
          super(args.shift)
          unless args.empty?
            @next_data = self.class.new(*args)
          end
        end
      end


[] (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 234
      def [](*key)
        begin
          @header[key[0].downcase].join(", ")
        rescue StandardError, NameError
          super
        end
      end


<< (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 242
      def <<(str)
        if @header
          super
        elsif str == CRLF
          @header = HTTPUtils::parse_header(@raw_header)
          if cd = self['content-disposition']
            if /\s+name="(.*?)"/ =~ cd then @name = $1 end
            if /\s+filename="(.*?)"/ =~ cd then @filename = $1 end
          end
        else
          @raw_header << str
        end
        self
      end


append_data (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 257
      def append_data(data)
        tmp = self
        while tmp
          unless tmp.next_data
            tmp.next_data = data
            break
          end
          tmp = tmp.next_data
        end
        self
      end


each_data (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 269
      def each_data
        tmp = self
        while tmp
          next_data = tmp.next_data
          yield(tmp)
          tmp = next_data
        end
      end


list (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 278
      def list
        ret = []
        each_data{|data|
          ret << data.to_s
        }
        ret
      end


to_s (WEBrick::HTTPUtils::FormData)

# File lib/webrick/httputils.rb, line 288
      def to_s
        String.new(self)
      end


normalize_path (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 21
    def normalize_path(path)
      raise "abnormal path `#{path}'" if path[0] != ?/
      ret = path.dup

      ret.gsub!(%r{/+}o, '/')                    # //      => /
      while ret.sub!(%r{/\.(/|\Z)}o, '/'); end   # /.      => /
      begin                                      # /foo/.. => /foo
        match = ret.sub!(%r{/([^/]+)/\.\.(/|\Z)}o){
          if $1 == ".."
            raise "abnormal path `#{path}'"
          else
            "/"
          end
        }
      end while match

      raise "abnormal path `#{path}'" if %r{/\.\.(/|\Z)} =~ ret
      ret
    end


load_mime_types (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 101
    def load_mime_types(file)
      open(file){ |io|
        hash = Hash.new
        io.each{ |line|
          next if /^#/ =~ line
          line.chomp!
          mimetype, ext0 = line.split(/\s+/, 2)
          next unless ext0
          next if ext0.empty?
          ext0.split(/\s+/).each{ |ext| hash[ext] = mimetype }
        }
        hash
      }
    end


mime_type (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 117
    def mime_type(filename, mime_tab)
      suffix1 = (/\.(\w+)$/ =~ filename && $1.downcase)
      suffix2 = (/\.(\w+)\.[\w\-]+$/ =~ filename && $1.downcase)
      mime_tab[suffix1] || mime_tab[suffix2] || "application/octet-stream"
    end


parse_header (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 126
    def parse_header(raw)
      header = Hash.new([].freeze)
      field = nil
      raw.each{|line|
        case line
        when /^([A-Za-z0-9!\#$%&'*+\-.^_`|~]+):\s*(.*?)\s*\z/om
          field, value = $1, $2
          field.downcase!
          header[field] = [] unless header.has_key?(field)
          header[field] << value
        when /^\s+(.*?)\s*\z/om
          value = $1
          unless field
            raise "bad header '#{line.inspect}'."
          end
          header[field][-1] << " " << value
        else
          raise "bad header '#{line.inspect}'."
        end
      }
      header.each{|key, values|
        values.each{|value|
          value.strip!
          value.gsub!(/\s+/, " ")
        }
      }
      header
    end


split_header_value (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 156
    def split_header_value(str)
      str.scan(/((?:"(?:\\.|[^"])+?"|[^",]+)+)
                (?:,\s*|\Z)/xn).collect{|v| v[0] }
    end


parse_range_header (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 162
    def parse_range_header(ranges_specifier)
      if /^bytes=(.*)/ =~ ranges_specifier
        byte_range_set = split_header_value($1)
        byte_range_set.collect{|range_spec|
          case range_spec
          when /^(\d+)-(\d+)/ then $1.to_i .. $2.to_i
          when /^(\d+)-/      then $1.to_i .. -1
          when /^-(\d+)/      then -($1.to_i) .. -1
          else return nil
          end
        }
      end
    end


parse_qvalues (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 177
    def parse_qvalues(value)
      tmp = []
      if value
        parts = value.split(/,\s*/)
        parts.each {|part|
          if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
            val = m[1]
            q = (m[2] or 1).to_f
            tmp.push([val, q])
          end
        }
        tmp = tmp.sort_by{|val, q| -q}
        tmp.collect!{|val, q| val}
      end
      return tmp
    end


dequote (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 197
    def dequote(str)
      ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
      ret.gsub!(/\\(.)/, "\\1")
      ret
    end


quote (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 204
    def quote(str)
      '"' << str.gsub(/[\\\"]/o, "\\\1") << '"'
    end


parse_query (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 293
    def parse_query(str)
      query = Hash.new
      if str
        str.split(/[&;]/).each{|x|
          next if x.empty?
          key, val = x.split(/=/,2)
          key = unescape_form(key)
          val = unescape_form(val.to_s)
          val = FormData.new(val)
          val.name = key
          if query.has_key?(key)
            query[key].append_data(val)
            next
          end
          query[key] = val
        }
      end
      query
    end


parse_form_data (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 314
    def parse_form_data(io, boundary)
      boundary_regexp = /\A--#{boundary}(--)?#{CRLF}\z/
      form_data = Hash.new
      return form_data unless io
      data = nil
      io.each{|line|
        if boundary_regexp =~ line
          if data
            data.chop!
            key = data.name
            if form_data.has_key?(key)
              form_data[key].append_data(data)
            else
              form_data[key] = data
            end
          end
          data = FormData.new
          next
        else
          if data
            data << line
          end
        end
      }
      return form_data
    end


_make_regex (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 358
    def _make_regex(str) /([#{Regexp.escape(str)}])/n end
    def _make_regex!(str) /([^#{Regexp.escape(str)}])/n end
    def _escape(str, regex) str.gsub(regex){ "%%%02X" % $1[0] } end
    def _unescape(str, regex) str.gsub(regex){ $1.hex.chr } end

    UNESCAPED = _make_regex(control+space+delims+unwise+nonascii)
    UNESCAPED_FORM = _make_regex(reserved+control+delims+unwise+nonascii)
    NONASCII  = _make_regex(nonascii)
    ESCAPED   = /%([0-9a-fA-F]{2})/
    UNESCAPED_PCHAR = _make_regex!(unreserved+":@&=+$,")

    def escape(str)
      _escape(str, UNESCAPED)
    end

    def unescape(str)
      _unescape(str, ESCAPED)
    end

    def escape_form(str)
      ret = _escape(str, UNESCAPED_FORM)
      ret.gsub!(/ /, "+")
      ret
    end

    def unescape_form(str)
      _unescape(str.gsub(/\+/, " "), ESCAPED)
    end

    def escape_path(str)
      result = ""
      str.scan(%r{/([^/]*)}).each{|i|
        result << "/" << _escape(i[0], UNESCAPED_PCHAR)
      }
      return result
    end

    def escape8bit(str)
      _escape(str, NONASCII)
    end
  end
end


_make_regex! (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 359
    def _make_regex!(str) /([^#{Regexp.escape(str)}])/n end
    def _escape(str, regex) str.gsub(regex){ "%%%02X" % $1[0] } end
    def _unescape(str, regex) str.gsub(regex){ $1.hex.chr } end

    UNESCAPED = _make_regex(control+space+delims+unwise+nonascii)
    UNESCAPED_FORM = _make_regex(reserved+control+delims+unwise+nonascii)
    NONASCII  = _make_regex(nonascii)
    ESCAPED   = /%([0-9a-fA-F]{2})/
    UNESCAPED_PCHAR = _make_regex!(unreserved+":@&=+$,")

    def escape(str)
      _escape(str, UNESCAPED)
    end

    def unescape(str)
      _unescape(str, ESCAPED)
    end

    def escape_form(str)
      ret = _escape(str, UNESCAPED_FORM)
      ret.gsub!(/ /, "+")
      ret
    end

    def unescape_form(str)
      _unescape(str.gsub(/\+/, " "), ESCAPED)
    end

    def escape_path(str)
      result = ""
      str.scan(%r{/([^/]*)}).each{|i|
        result << "/" << _escape(i[0], UNESCAPED_PCHAR)
      }
      return result
    end

    def escape8bit(str)
      _escape(str, NONASCII)
    end
  end


_escape (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 360
    def _escape(str, regex) str.gsub(regex){ "%%%02X" % $1[0] } end


_unescape (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 361
    def _unescape(str, regex) str.gsub(regex){ $1.hex.chr } end


escape (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 369
    def escape(str)
      _escape(str, UNESCAPED)
    end


unescape (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 373
    def unescape(str)
      _unescape(str, ESCAPED)
    end


escape_form (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 377
    def escape_form(str)
      ret = _escape(str, UNESCAPED_FORM)
      ret.gsub!(/ /, "+")
      ret
    end


unescape_form (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 383
    def unescape_form(str)
      _unescape(str.gsub(/\+/, " "), ESCAPED)
    end


escape_path (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 387
    def escape_path(str)
      result = ""
      str.scan(%r{/([^/]*)}).each{|i|
        result << "/" << _escape(i[0], UNESCAPED_PCHAR)
      }
      return result
    end


escape8bit (WEBrick::HTTPUtils)

# File lib/webrick/httputils.rb, line 395
    def escape8bit(str)
      _escape(str, NONASCII)
    end


convert (WEBrick::HTTPVersion)

# File lib/webrick/httpversion.rb, line 16
    def self.convert(version)
      version.is_a?(self) ? version : new(version)
    end


new (WEBrick::HTTPVersion)

# File lib/webrick/httpversion.rb, line 20
    def initialize(version)
      case version
      when HTTPVersion
        @major, @minor = version.major, version.minor
      when String
        if /^(\d+)\.(\d+)$/ =~ version
          @major, @minor = $1.to_i, $2.to_i
        end
      end
      if @major.nil? || @minor.nil?
        raise ArgumentError,
          format("cannot convert %s into %s", version.class, self.class)
      end
    end


<=> (WEBrick::HTTPVersion)

# File lib/webrick/httpversion.rb, line 35
    def <=>(other)
      unless other.is_a?(self.class)
        other = self.class.new(other)
      end
      if (ret = @major <=> other.major) == 0
        return @minor <=> other.minor
      end
      return ret
    end


to_s (WEBrick::HTTPVersion)

# File lib/webrick/httpversion.rb, line 45
    def to_s
      format("%d.%d", @major, @minor)
    end


debug (WEBrick::Log)

# File lib/soap/rpc/soaplet.rb, line 26
    def debug(msg = nil)
      if block_given? and msg.nil?
        __debug(yield)
      else
        __debug(msg)
      end
    end


new (WEBrick::Log)

# File lib/webrick/log.rb, line 77
    def initialize(log_file=nil, level=nil)
      super(log_file, level)
      @time_format = "[%Y-%m-%d %H:%M:%S]"
    end


log (WEBrick::Log)

# File lib/webrick/log.rb, line 82
    def log(level, data)
      tmp = Time.now.strftime(@time_format)
      tmp << " " << data
      super(level, tmp)
    end


start (WEBrick::SimpleServer)

# File lib/webrick/server.rb, line 22
    def SimpleServer.start
      yield
    end


set_non_blocking (WEBrick::Utils)

# File lib/webrick/utils.rb, line 21
    def set_non_blocking(io)
      flag = File::NONBLOCK
      if defined?(Fcntl::F_GETFL)
        flag |= io.fcntl(Fcntl::F_GETFL)
      end
      io.fcntl(Fcntl::F_SETFL, flag)
    end


set_close_on_exec (WEBrick::Utils)

# File lib/webrick/utils.rb, line 30
    def set_close_on_exec(io)
      if defined?(Fcntl::FD_CLOEXEC)
        io.fcntl(Fcntl::FD_CLOEXEC, 1)
      end
    end


su (WEBrick::Utils)

# File lib/webrick/utils.rb, line 37
    def su(user)
      if defined?(Etc)
        pw = Etc.getpwnam(user)
        Process::initgroups(user, pw.gid)
        Process::Sys::setgid(pw.gid)
        Process::Sys::setuid(pw.uid)
      else
        warn("WEBrick::Utils::su doesn't work on this platform")
      end
    end


getservername (WEBrick::Utils)

# File lib/webrick/utils.rb, line 49
    def getservername
      host = Socket::gethostname
      begin
        Socket::gethostbyname(host)[0]
      rescue
        host
      end
    end


create_listeners (WEBrick::Utils)

# File lib/webrick/utils.rb, line 59
    def create_listeners(address, port, logger=nil)
      unless port
        raise ArgumentError, "must specify port"
      end
      res = Socket::getaddrinfo(address, port,
                                Socket::AF_UNSPEC,   # address family
                                Socket::SOCK_STREAM, # socket type
                                0,                   # protocol
                                Socket::AI_PASSIVE)  # flag
      last_error = nil
      sockets = []
      res.each{|ai|
        begin
          logger.debug("TCPServer.new(#{ai[3]}, #{port})") if logger
          sock = TCPServer.new(ai[3], port)
          port = sock.addr[1] if port == 0
          Utils::set_close_on_exec(sock)
          sockets << sock
        rescue => ex
          logger.warn("TCPServer Error: #{ex}") if logger
          last_error  = ex
        end
      }
      raise last_error if sockets.empty?
      return sockets
    end


random_string (WEBrick::Utils)

# File lib/webrick/utils.rb, line 91
    def random_string(len)
      rand_max = RAND_CHARS.size
      ret = ""
      len.times{ ret << RAND_CHARS[rand(rand_max)] }
      ret
    end


create_self_signed_cert (WEBrick::Utils)

# File lib/webrick/ssl.rb, line 39
    def create_self_signed_cert(bits, cn, comment)
      rsa = OpenSSL::PKey::RSA.new(bits){|p, n|
        case p
        when 0; $stderr.putc "."  # BN_generate_prime
        when 1; $stderr.putc "+"  # BN_generate_prime
        when 2; $stderr.putc "*"  # searching good prime,
                                  # n = #of try,
                                  # but also data from BN_generate_prime
        when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
                                  # but also data from BN_generate_prime
        else;   $stderr.putc "*"  # BN_generate_prime
        end
      }
      cert = OpenSSL::X509::Certificate.new
      cert.version = 3
      cert.serial = 0
      name = OpenSSL::X509::Name.new(cn)
      cert.subject = name
      cert.issuer = name
      cert.not_before = Time.now
      cert.not_after = Time.now + (365*24*60*60)
      cert.public_key = rsa.public_key

      ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
      ef.issuer_certificate = cert
      cert.extensions = [
        ef.create_extension("basicConstraints","CA:FALSE"),
        ef.create_extension("keyUsage", "keyEncipherment"),
        ef.create_extension("subjectKeyIdentifier", "hash"),
        ef.create_extension("extendedKeyUsage", "serverAuth"),
        ef.create_extension("nsComment", comment),
      ]
      aki = ef.create_extension("authorityKeyIdentifier",
                                "keyid:always,issuer:always")
      cert.add_extension(aki)
      cert.sign(rsa, OpenSSL::Digest::SHA1.new)

      return [ cert, rsa ]
    end


new (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 10
  def initialize(typelib)
    @typelib = typelib
    @reciever = ""
  end


ole_classes (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 16
  def ole_classes(typelib)
    begin
      @ole = WIN32OLE.new(typelib)
      [@ole.ole_obj_help]
    rescue
      WIN32OLE_TYPE.ole_classes(typelib)
    end
  end


generate_args (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 25
  def generate_args(method)
    args = []
    if method.size_opt_params >= 0
      size_required_params = method.size_params - method.size_opt_params
    else
      size_required_params = method.size_params - 1
    end
    size_required_params.times do |i|
      if method.params[i] && method.params[i].optional?
        args.push "arg#{i}=nil"
      else
        args.push "arg#{i}"
      end
    end
    if method.size_opt_params >= 0
      method.size_opt_params.times do |i|
        args.push "arg#{i + size_required_params}=nil"
      end
    else
      args.push "*arg"
    end
    args.join(", ")
  end


generate_argtype (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 49
  def generate_argtype(typedetails)
    ts = ''
    typedetails.each do |t|
      case t
      when 'CARRAY', 'VOID', 'UINT', 'RESULT', 'DECIMAL', 'I8', 'UI8'
#         raise "Sorry type\"" + t + "\" not supported"
      ts << "\"??? NOT SUPPORTED TYPE:`#{t}'\""
      when 'USERDEFINED', 'Unknown Type 9'
        ts << 'VT_DISPATCH'
        break;
      when 'SAFEARRAY'
        ts << 'VT_ARRAY|'
      when 'PTR'
        ts << 'VT_BYREF|'
      when 'INT'
        ts << 'VT_I4'
      else
        if String === t
          ts << 'VT_' + t
        end
      end
    end
    if ts.empty?
      ts = 'VT_VARIANT'
    elsif ts[-1] == ?|
        ts += 'VT_VARIANT'
    end
    ts
  end


generate_argtypes (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 79
  def generate_argtypes(method, proptypes)
    types = method.params.collect{|param|
      generate_argtype(param.ole_type_detail)
    }.join(", ")
    if proptypes
      types += ", " if types.size > 0
      types += generate_argtype(proptypes)
    end
    types
  end


generate_method_body (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 90
  def generate_method_body(method, disptype, types=nil)
    "    ret = #{@reciever}#{disptype}(#{method.dispid}, [" +
    generate_args(method).gsub("=nil", "") +
    "], [" +
    generate_argtypes(method, types) +
    "])\n" +
    "    @lastargs = WIN32OLE::ARGV\n" +
    "    ret"
  end


generate_method_help (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 100
  def generate_method_help(method, type = nil)
    str = "  # "
    if type
      str += type
    else
      str += method.return_type
    end
    str += " #{method.name}"
    if method.event?
      str += " EVENT"
      str += " in #{method.event_interface}"
    end
    if method.helpstring && method.helpstring != ""
      str += "\n  # "
      str += method.helpstring
    end
    args_help = generate_method_args_help(method)
    if args_help
      str += "\n"
      str += args_help
    end
    str
  end


generate_method_args_help (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 124
  def generate_method_args_help(method)
    args = []
    method.params.each_with_index {|param, i|
      h = "  #   #{param.ole_type} arg#{i} --- #{param.name}"
      inout = []
      inout.push "IN" if param.input?
      inout.push "OUT" if param.output?
      h += " [#{inout.join('/')}]"
      h += " ( = #{param.default})" if param.default
      args.push h
    }
    if args.size > 0
      args.join("\n")
    else
      nil
    end
  end


generate_method (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 142
  def generate_method(method, disptype, io = STDOUT, types = nil)
    io.puts "\n"
    io.puts  generate_method_help(method)
    if method.invoke_kind == 'PROPERTYPUT'
      io.print "  def #{method.name}=("
    else
      io.print "  def #{method.name}("
    end
    io.print generate_args(method)
    io.puts ")"
    io.puts generate_method_body(method, disptype, types)
    io.puts "  end"
  end


generate_propputref_methods (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 156
  def generate_propputref_methods(klass, io = STDOUT)
    klass.ole_methods.select {|method|
      method.invoke_kind == 'PROPERTYPUTREF' && method.visible?
    }.each do |method|
      generate_method(method, io)
    end
  end


generate_properties_with_args (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 164
  def generate_properties_with_args(klass, io = STDOUT)
    klass.ole_methods.select {|method|
      method.invoke_kind == 'PROPERTYGET' &&
      method.visible? &&
      method.size_params > 0
    }.each do |method|
      types = method.return_type_detail
      io.puts "\n"
      io.puts  generate_method_help(method, types[0])
      io.puts  "  def #{method.name}"
      if klass.ole_type == "Class"
        io.print "    OLEProperty.new(@dispatch, #{method.dispid}, ["
      else
        io.print "    OLEProperty.new(self, #{method.dispid}, ["
      end
      io.print generate_argtypes(method, nil)
      io.print "], ["
      io.print generate_argtypes(method, types)
      io.puts "])"
      io.puts  "  end"
    end
  end


generate_propput_methods (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 187
  def generate_propput_methods(klass, io = STDOUT)
    klass.ole_methods.select {|method|
      method.invoke_kind == 'PROPERTYPUT' && method.visible? &&
      method.size_params == 1
    }.each do |method|
      ms = klass.ole_methods.select {|m|
        m.invoke_kind == 'PROPERTYGET' &&
        m.dispid == method.dispid
      }
      types = []
      if ms.size == 1
        types = ms[0].return_type_detail
      end
      generate_method(method, '_setproperty', io, types)
    end
  end


generate_propget_methods (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 204
  def generate_propget_methods(klass, io = STDOUT)
    klass.ole_methods.select {|method|
      method.invoke_kind == 'PROPERTYGET' && method.visible? &&
      method.size_params == 0
    }.each do |method|
      generate_method(method, '_getproperty', io)
    end
  end


generate_func_methods (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 213
  def generate_func_methods(klass, io = STDOUT)
    klass.ole_methods.select {|method|
      method.invoke_kind == "FUNC" && method.visible?
    }.each do |method|
      generate_method(method, '_invoke', io)
    end
  end


generate_methods (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 221
  def generate_methods(klass, io = STDOUT)
    generate_propget_methods(klass, io)
    generate_propput_methods(klass, io)
    generate_properties_with_args(klass, io)
    generate_func_methods(klass, io)
#   generate_propputref_methods(klass, io)
  end


generate_constants (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 229
  def generate_constants(klass, io = STDOUT)
    klass.variables.select {|v|
      v.visible? && v.variable_kind == 'CONSTANT'
    }.each do |v|
      io.print "  "
      io.print v.name.sub(/^./){|c| c.upcase}
      io.print " = "
      io.puts  v.value
    end
  end


class_name (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 240
  def class_name(klass)
    klass_name = klass.name
    if klass.ole_type == "Class" &&
       klass.guid &&
       klass.progid
       klass_name = klass.progid.gsub(/\./, '_')
    end
    if /^[A-Z]/ !~ klass_name || Module.constants.include?(klass_name)
      klass_name = 'OLE' + klass_name
    end
    klass_name
  end


define_initialize (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 253
  def define_initialize(klass)
    "\n  def initialize(obj = nil)\n    @clsid = \"\#{klass.guid}\"\n    @progid = \"\#{klass.progid}\"\n    if obj.nil?\n      @dispatch = WIN32OLE.new @progid\n    else\n      @dispatch = obj\n    end\n  end\n"
  end


define_include (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 269
  def define_include
    "  include WIN32OLE::VARIANT"
  end


define_instance_variables (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 273
  def define_instance_variables
    "  attr_reader :lastargs"
  end


define_method_missing (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 277
  def define_method_missing
    "\n  def method_missing(cmd, *arg)\n    @dispatch.method_missing(cmd, *arg)\n  end\n"
  end


define_class (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 287
  def define_class(klass, io = STDOUT)
    io.puts "class #{class_name(klass)} # #{klass.name}"
    io.puts define_include
    io.puts define_instance_variables
    io.puts "  attr_reader :dispatch"
    io.puts "  attr_reader :clsid"
    io.puts "  attr_reader :progid"
    io.puts define_initialize(klass)
    io.puts define_method_missing
  end


define_module (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 298
  def define_module(klass, io = STDOUT)
    io.puts "module #{class_name(klass)}"
    io.puts define_include
    io.puts define_instance_variables
  end


generate_class (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 304
  def generate_class(klass, io = STDOUT)
    io.puts "\n# #{klass.helpstring}"
    if klass.ole_type == "Class" &&
       klass.guid &&
       klass.progid
      @reciever = "@dispatch."
      define_class(klass, io)
    else
      @reciever = ""
      define_module(klass, io)
    end
    generate_constants(klass, io)
    generate_methods(klass, io)
    io.puts "end"
  end


generate (WIN32COMGen)

# File ext/win32ole/sample/olegen.rb, line 320
  def generate(io = STDOUT)
    io.puts "require 'win32ole'"
    io.puts "require 'win32ole/property'"

    ole_classes(typelib).select{|klass|
      klass.visible? &&
      (klass.ole_type == "Class" ||
       klass.ole_type == "Interface" ||
       klass.ole_type == "Dispatch" ||
       klass.ole_type == "Enum")
    }.each do |klass|
      generate_class(klass, io)
    end
    begin
      @ole.quit if @ole
    rescue
    end
  end


new (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.new(server, [host]) -> WIN32OLE object
 *
 *  Returns a new WIN32OLE object(OLE Automation object).
 *  The first argument server specifies OLE Automation server.
 *  The first argument should be CLSID or PROGID.
 *  If second argument host specified, then returns OLE Automation
 *  object on host.
 *
 *      WIN32OLE.new('Excel.Application') # => Excel OLE Automation WIN32OLE object.
 *      WIN32OLE.new('{00024500-0000-0000-C000-000000000046}') # => Excel OLE Automation WIN32OLE object.
 */
static VALUE
fole_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE svr_name;
    VALUE host;
    VALUE others;
    HRESULT hr;
    CLSID   clsid;
    OLECHAR *pBuf;
    IDispatch *pDispatch;

    rb_secure(4);
    rb_call_super(0, 0);
    rb_scan_args(argc, argv, "11*", &svr_name, &host, &others);

    if (ruby_safe_level > 0 && OBJ_TAINTED(svr_name)) {
        rb_raise(rb_eSecurityError, "Insecure Object Creation - %s",
                 StringValuePtr(svr_name));
    }
    if (!NIL_P(host)) {
        if (ruby_safe_level > 0 && OBJ_TAINTED(host)) {
            rb_raise(rb_eSecurityError, "Insecure Object Creation - %s",
                     StringValuePtr(svr_name));
        }
        return ole_create_dcom(argc, argv, self);
    }

    /* get CLSID from OLE server name */
    pBuf  = ole_mb2wc(StringValuePtr(svr_name), -1);
    hr = CLSIDFromProgID(pBuf, &clsid);
    if(FAILED(hr)) {
        hr = CLSIDFromString(pBuf, &clsid);
    }
    SysFreeString(pBuf);
    if(FAILED(hr)) {
        ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
                  "unknown OLE server: `%s'",
                  StringValuePtr(svr_name));
    }

    /* get IDispatch interface */
    hr = CoCreateInstance(&clsid, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
                          &IID_IDispatch, (void**)&pDispatch);
    if(FAILED(hr)) {
        ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
                  "failed to create WIN32OLE object from `%s'",
                  StringValuePtr(svr_name));
    }

    ole_set_member(self, pDispatch);
    return self;
}


connect (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.connect( ole ) --> aWIN32OLE
 *
 *  Returns running OLE Automation object or WIN32OLE object from moniker.
 *  1st argument should be OLE program id or class id or moniker.
 *
 *     WIN32OLE.connect('Excel.Application') # => WIN32OLE object which represents running Excel.
 */
static VALUE
fole_s_connect(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE svr_name;
    VALUE others;
    HRESULT hr;
    CLSID   clsid;
    OLECHAR *pBuf;
    IDispatch *pDispatch;
    IUnknown *pUnknown;

    rb_secure(4);
    /* initialize to use OLE */
    ole_initialize();

    rb_scan_args(argc, argv, "1*", &svr_name, &others);
    if (ruby_safe_level > 0 && OBJ_TAINTED(svr_name)) {
        rb_raise(rb_eSecurityError, "Insecure Object Connection - %s",
                 StringValuePtr(svr_name));
    }

    /* get CLSID from OLE server name */
    pBuf  = ole_mb2wc(StringValuePtr(svr_name), -1);
    hr = CLSIDFromProgID(pBuf, &clsid);
    if(FAILED(hr)) {
        hr = CLSIDFromString(pBuf, &clsid);
    }
    SysFreeString(pBuf);
    if(FAILED(hr)) {
        return ole_bind_obj(svr_name, argc, argv, self);
    }

    hr = GetActiveObject(&clsid, 0, &pUnknown);
    if (FAILED(hr)) {
        ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
                  "OLE server `%s' not running", StringValuePtr(svr_name));
    }
    hr = pUnknown->lpVtbl->QueryInterface(pUnknown, &IID_IDispatch,
                                             (void **)&pDispatch);
    if(FAILED(hr)) {
        OLE_RELEASE(pUnknown);
        ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
                  "failed to create WIN32OLE server `%s'",
                  StringValuePtr(svr_name));
    }

    OLE_RELEASE(pUnknown);

    return create_win32ole_object(self, pDispatch, argc, argv);
}


const_load (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.const_load( ole, mod = WIN32OLE)
 *
 *  Defines the constants of OLE Automation server as mod's constants.
 *  The first argument is WIN32OLE object or type library name.
 *  If 2nd argument is omitted, the default is WIN32OLE.
 *  The first letter of Ruby's constant variable name is upper case,
 *  so constant variable name of WIN32OLE object is capitalized.
 *  For example, the 'xlTop' constant of Excel is changed to 'XlTop'
 *  in WIN32OLE.
 *  If the first letter of constant variabl is not [A-Z], then
 *  the constant is defined as CONSTANTS hash element.
 *
 *     module EXCEL_CONST
 *     end
 *     excel = WIN32OLE.new('Excel.Application')
 *     WIN32OLE.const_load(excel, EXCEL_CONST)
 *     puts EXCEL_CONST::XlTop # => -4160
 *     puts EXCEL_CONST::CONSTANTS['_xlDialogChartSourceData'] # => 541
 *
 *     WIN32OLE.const_load(excel)
 *     puts WIN32OLE::XlTop # => -4160
 *
 *     module MSO
 *     end
 *     WIN32OLE.const_load('Microsoft Office 9.0 Object Library', MSO)
 *     puts MSO::MsoLineSingle # => 1
 */
static VALUE
fole_s_const_load(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE ole;
    VALUE klass;
    struct oledata *pole;
    ITypeInfo *pTypeInfo;
    ITypeLib *pTypeLib;
    unsigned int index;
    HRESULT hr;
    OLECHAR *pBuf;
    VALUE file;
    LCID    lcid = LOCALE_SYSTEM_DEFAULT;

    rb_secure(4);
    rb_scan_args(argc, argv, "11", &ole, &klass);
    if (TYPE(klass) != T_CLASS &&
        TYPE(klass) != T_MODULE &&
        TYPE(klass) != T_NIL) {
        rb_raise(rb_eTypeError, "2nd parameter must be Class or Module");
    }
    if (rb_obj_is_kind_of(ole, cWIN32OLE)) {
        OLEData_Get_Struct(ole, pole);
        hr = pole->pDispatch->lpVtbl->GetTypeInfo(pole->pDispatch,
                                                  0, lcid, &pTypeInfo);
        if(FAILED(hr)) {
            ole_raise(hr, rb_eRuntimeError, "failed to GetTypeInfo");
        }
        hr = pTypeInfo->lpVtbl->GetContainingTypeLib(pTypeInfo, &pTypeLib, &index);
        if(FAILED(hr)) {
            OLE_RELEASE(pTypeInfo);
            ole_raise(hr, rb_eRuntimeError, "failed to GetContainingTypeLib");
        }
        OLE_RELEASE(pTypeInfo);
        if(TYPE(klass) != T_NIL) {
            ole_const_load(pTypeLib, klass, self);
        }
        else {
            ole_const_load(pTypeLib, cWIN32OLE, self);
        }
        OLE_RELEASE(pTypeLib);
    }
    else if(TYPE(ole) == T_STRING) {
        file = typelib_file(ole);
        if (file == Qnil) {
            file = ole;
        }
        pBuf = ole_mb2wc(StringValuePtr(file), -1);
        hr = LoadTypeLibEx(pBuf, REGKIND_NONE, &pTypeLib);
        SysFreeString(pBuf);
        if (FAILED(hr))
            ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to LoadTypeLibEx");
        if(TYPE(klass) != T_NIL) {
            ole_const_load(pTypeLib, klass, self);
        }
        else {
            ole_const_load(pTypeLib, cWIN32OLE, self);
        }
        OLE_RELEASE(pTypeLib);
    }
    else {
        rb_raise(rb_eTypeError, "1st parameter must be WIN32OLE instance");
    }
    return Qnil;
}


ole_free (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.ole_free(aWIN32OLE) --> number
 *
 *  Invokes Release method of Dispatch interface of WIN32OLE object.
 *  You should not use this method because this method
 *  exists only for debugging WIN32OLE.
 *  The return value is reference counter of OLE object.
 */
static VALUE
fole_s_free(self, obj)
    VALUE self;
    VALUE obj;
{
    ULONG n = 0;
    struct oledata * pole;
    OLEData_Get_Struct(obj, pole);
    if(pole->pDispatch) {
        if (reference_count(pole) > 0) {
            n = OLE_RELEASE(pole->pDispatch);
        }
    }
    return INT2NUM(n);
}


ole_reference_count (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.ole_reference_count(aWIN32OLE) --> number
 *
 *  Returns reference counter of Dispatch interface of WIN32OLE object.
 *  You should not use this method because this method
 *  exists only for debugging WIN32OLE.
 */
static VALUE
fole_s_reference_count(self, obj)
    VALUE self;
    VALUE obj;
{
    struct oledata * pole;
    OLEData_Get_Struct(obj, pole);
    return INT2NUM(reference_count(pole));
}


ole_show_help (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.ole_show_help(obj [,helpcontext])
 *
 *  Displays helpfile. The 1st argument specifies WIN32OLE_TYPE
 *  object or WIN32OLE_METHOD object or helpfile.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     typeobj = excel.ole_type
 *     WIN32OLE.ole_show_help(typeobj)
 */
static VALUE
fole_s_show_help(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE target;
    VALUE helpcontext;
    VALUE helpfile;
    VALUE name;
    HWND  hwnd;
    rb_scan_args(argc, argv, "11", &target, &helpcontext);
    if (rb_obj_is_kind_of(target, cWIN32OLE_TYPE) ||
        rb_obj_is_kind_of(target, cWIN32OLE_METHOD)) {
        helpfile = rb_funcall(target, rb_intern("helpfile"), 0);
        if(strlen(StringValuePtr(helpfile)) == 0) {
            name = rb_ivar_get(target, rb_intern("name"));
            rb_raise(rb_eRuntimeError, "no helpfile of `%s'",
                     StringValuePtr(name));
        }
        helpcontext = rb_funcall(target, rb_intern("helpcontext"), 0);
    } else {
        helpfile = target;
    }
    if (TYPE(helpfile) != T_STRING) {
        rb_raise(rb_eTypeError, "1st parameter must be (String|WIN32OLE_TYPE|WIN32OLE_METHOD)");
    }
    hwnd = ole_show_help(helpfile, helpcontext);
    if(hwnd == 0) {
        rb_raise(rb_eRuntimeError, "failed to open help file `%s'",
                 StringValuePtr(helpfile));
    }
    return Qnil;
}


codepage (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.codepage
 *
 *  Returns current codepage.
 *     WIN32OLE.codepage # => WIN32OLE::CP_ACP
 */
static VALUE
fole_s_get_code_page(self)
    VALUE self;
{
    return INT2FIX(cWIN32OLE_cp);
}


codepage= (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE.codepage = CP
 *
 *  Sets current codepage.
 *     WIN32OLE.codepage = WIN32OLE::CP_UTF8
 */
static VALUE
fole_s_set_code_page(self, vcp)
    VALUE self;
    VALUE vcp;
{
    UINT cp = FIX2INT(vcp);

    switch(cp) {
    case CP_ACP:
    case CP_OEMCP:
    case CP_MACCP:
    case CP_THREAD_ACP:
    case CP_SYMBOL:
    case CP_UTF7:
    case CP_UTF8:
        cWIN32OLE_cp = cp;
        break;
    default:
        rb_raise(eWIN32OLE_RUNTIME_ERROR, "codepage should be WIN32OLE::CP_ACP, WIN32OLE::CP_OEMCP, WIN32OLE::CP_MACCP, WIN32OLE::CP_THREAD_ACP, WIN32OLE::CP_SYMBOL, WIN32OLE::CP_UTF7, WIN32OLE::CP_UTF8");
        break;
    }

    /*
     * Should this method return old codepage?
     */
    return Qnil;
}


invoke (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#invoke(method, [arg1,...])  => return value of method.
 *
 *  Runs OLE method.
 *  The first argument specifies the method name of OLE Automation object.
 *  The others specify argument of the <i>method</i>.
 *  If you can not execute <i>method</i> directly, then use this method instead.
 *
 *    excel = WIN32OLE.new('Excel.Application')
 *    excel.invoke('Quit')  # => same as excel.Quit
 *
 */
static VALUE
fole_invoke(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    return ole_invoke(argc, argv, self, DISPATCH_METHOD|DISPATCH_PROPERTYGET);
}


[] (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE['property']
 *
 *  Returns property of OLE object.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     puts excel['Visible'] # => false
 */
static VALUE
fole_getproperty(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    return ole_invoke(argc, argv, self, DISPATCH_PROPERTYGET);
}


_invoke (WIN32OLE)

/*
 *   call-seq:
 *      WIN32OLE#_invoke(dispid, args, types)
 *
 *   Runs the early binding method.
 *   The 1st argument specifies dispatch ID,
 *   the 2nd argument specifies the array of arguments,
 *   the 3rd argument specifies the array of the type of arguments.
 *
 *      excel = WIN32OLE.new('Excel.Application')
 *      excel._invoke(302, [], []) #  same effect as excel.Quit
 */
static VALUE
fole_invoke2(self, dispid, args, types)
    VALUE self;
    VALUE dispid;
    VALUE args;
    VALUE types;
{
    return ole_invoke2(self, dispid, args, types, DISPATCH_METHOD);
}


_getproperty (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#_getproperty(dispid, args, types)
 *
 *  Runs the early binding method to get property.
 *  The 1st argument specifies dispatch ID,
 *  the 2nd argument specifies the array of arguments,
 *  the 3rd argument specifies the array of the type of arguments.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     puts excel._getproperty(558, [], []) # same effect as puts excel.visible
 */
static VALUE
fole_getproperty2(self, dispid, args, types)
    VALUE self;
    VALUE dispid;
    VALUE args;
    VALUE types;
{
    return ole_invoke2(self, dispid, args, types, DISPATCH_PROPERTYGET);
}


_setproperty (WIN32OLE)

/*
 *   call-seq:
 *      WIN32OLE#_setproperty(dispid, args, types)
 *
 *   Runs the early binding method to set property.
 *   The 1st argument specifies dispatch ID,
 *   the 2nd argument specifies the array of arguments,
 *   the 3rd argument specifies the array of the type of arguments.
 *
 *      excel = WIN32OLE.new('Excel.Application')
 *      excel._setproperty(558, [true], [WIN32OLE::VARIANT::VT_BOOL]) # same effect as excel.visible = true
 */
static VALUE
fole_setproperty2(self, dispid, args, types)
    VALUE self;
    VALUE dispid;
    VALUE args;
    VALUE types;
{
    return ole_invoke2(self, dispid, args, types, DISPATCH_PROPERTYPUT);
}


[]= (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE['property']=val
 *     WIN32OLE.setproperty('property', [arg1, arg2,...] val)
 *
 *  Sets property of OLE object.
 *  When you want to set property with argument, you can use this method.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     excel['Visible'] = true
 *     book = excel.workbooks.add
 *     sheet = book.worksheets(1)
 *     sheet.setproperty('Cells', 1, 2, 10) # => The B1 cell value is 10.
 */
static VALUE
fole_setproperty(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    return ole_invoke(argc, argv, self, DISPATCH_PROPERTYPUT);
}


ole_free (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#ole_free
 *
 *  invokes Release method of Dispatch interface of WIN32OLE object.
 *  Usually, you do not need to call this method because Release method
 *  called automatically when WIN32OLE object garbaged.
 *
 */
static VALUE
fole_free(self)
    VALUE self;
{
    struct oledata *pole;
    rb_secure(4);
    OLEData_Get_Struct(self, pole);
    OLE_FREE(pole->pDispatch);
    pole->pDispatch = NULL;
    return Qnil;
}


each (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#each {|i|...}
 *
 *  Iterates over each item of OLE collection which has IEnumVARIANT interface.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     book = excel.workbooks.add
 *     sheets = book.worksheets(1)
 *     cells = sheets.cells("A1:A5")
 *     cells.each do |cell|
 *       cell.value = 10
 *     end
 */
static VALUE
fole_each(self)
    VALUE self;
{
    LCID    lcid = LOCALE_SYSTEM_DEFAULT;

    struct oledata *pole;

    unsigned int argErr;
    EXCEPINFO excepinfo;
    DISPPARAMS dispParams;
    VARIANT result;
    HRESULT hr;
    IEnumVARIANT *pEnum = NULL;

    VariantInit(&result);
    dispParams.rgvarg = NULL;
    dispParams.rgdispidNamedArgs = NULL;
    dispParams.cNamedArgs = 0;
    dispParams.cArgs = 0;
    memset(&excepinfo, 0, sizeof(excepinfo));

    OLEData_Get_Struct(self, pole);
    hr = pole->pDispatch->lpVtbl->Invoke(pole->pDispatch, DISPID_NEWENUM,
                                         &IID_NULL, lcid,
                                         DISPATCH_METHOD | DISPATCH_PROPERTYGET,
                                         &dispParams, &result,
                                         &excepinfo, &argErr);

    if (FAILED(hr)) {
        VariantClear(&result);
        ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to get IEnum Interface");
    }

    if (V_VT(&result) == VT_UNKNOWN)
        hr = V_UNKNOWN(&result)->lpVtbl->QueryInterface(V_UNKNOWN(&result),
                                                        &IID_IEnumVARIANT,
                                                        (void**)&pEnum);
    else if (V_VT(&result) == VT_DISPATCH)
        hr = V_DISPATCH(&result)->lpVtbl->QueryInterface(V_DISPATCH(&result),
                                                         &IID_IEnumVARIANT,
                                                         (void**)&pEnum);
    if (FAILED(hr) || !pEnum) {
        VariantClear(&result);
        ole_raise(hr, rb_eRuntimeError, "failed to get IEnum Interface");
    }

    VariantClear(&result);
    rb_ensure(ole_each_sub, (VALUE)pEnum, ole_ienum_free, (VALUE)pEnum);
    return Qnil;
}


method_missing (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#method_missing(id [,arg1, arg2, ...])
 *
 *  Calls WIN32OLE#invoke method.
 */
static VALUE
fole_missing(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    ID id;
    char* mname;
    int n;
    id = rb_to_id(argv[0]);
    mname = rb_id2name(id);
    if(!mname) {
        rb_raise(rb_eRuntimeError, "fail: unknown method or property");
    }
    n = strlen(mname);
    if(mname[n-1] == '=') {
        argv[0] = rb_str_new(mname, n-1);

        return ole_propertyput(self, argv[0], argv[1]);
    }
    else {
        argv[0] = rb_str_new2(mname);
        return ole_invoke(argc, argv, self, DISPATCH_METHOD|DISPATCH_PROPERTYGET);
    }
}


setproperty (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE['property']=val
 *     WIN32OLE.setproperty('property', [arg1, arg2,...] val)
 *
 *  Sets property of OLE object.
 *  When you want to set property with argument, you can use this method.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     excel['Visible'] = true
 *     book = excel.workbooks.add
 *     sheet = book.worksheets(1)
 *     sheet.setproperty('Cells', 1, 2, 10) # => The B1 cell value is 10.
 */
static VALUE
fole_setproperty(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    return ole_invoke(argc, argv, self, DISPATCH_PROPERTYPUT);
}


ole_methods (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#ole_methods
 *
 *  Returns the array of WIN32OLE_METHOD object.
 *  The element is OLE method of WIN32OLE object.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     methods = excel.ole_methods
 *
 */
static VALUE
fole_methods( self )
    VALUE self;
{
    return ole_methods( self, INVOKE_FUNC | INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT | INVOKE_PROPERTYPUTREF);
}


ole_get_methods (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#ole_get_methods
 *
 *  Returns the array of WIN32OLE_METHOD object .
 *  The element of the array is property (gettable) of WIN32OLE object.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     properties = excel.ole_get_methods
 */
static VALUE
fole_get_methods( self )
    VALUE self;
{
    return ole_methods( self, INVOKE_PROPERTYGET);
}


ole_put_methods (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#ole_put_methods
 *
 *  Returns the array of WIN32OLE_METHOD object .
 *  The element of the array is property (settable) of WIN32OLE object.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     properties = excel.ole_put_methods
 */
static VALUE
fole_put_methods( self )
    VALUE self;
{
    return ole_methods( self, INVOKE_PROPERTYPUT | INVOKE_PROPERTYPUTREF);
}


ole_func_methods (WIN32OLE)

/*
 *  call-seq:
 *     WIN32OLE#ole_func_methods
 *
 *  Returns the array of WIN32OLE_METHOD object .
 *  The element of the array is functional method of WIN32OLE object.
 *
 *     excel = WIN32OLE.new('Excel.Application')
 *     properties = excel.ole_func_methods
 *
 */
static VALUE
fole_func_methods( self )
    VALUE self;
{
    return ole_methods( self, INVOKE_FUNC);
}


ole_method (WIN32OLE)

/*
 *   call-seq:
 *      WIN32OLE#ole_method_help(method)
 *
 *   Returns WIN32OLE_METHOD object corresponding with method
 *   specified by 1st argument.
 *
 *      excel = WIN32OLE.new('Excel.Application')
 *      method = excel.ole_method_help('Quit')
 *
 */
static VALUE
fole_method_help( self, cmdname )
    VALUE self;
    VALUE cmdname;
{
    ITypeInfo *pTypeInfo;
    HRESULT hr;
    struct oledata *pole;
    VALUE method, obj;
    LCID    lcid = LOCALE_SYSTEM_DEFAULT;

    Check_SafeStr(cmdname);
    OLEData_Get_Struct(self, pole);
    hr = typeinfo_from_ole(pole, &pTypeInfo);
    if(FAILED(hr))
        ole_raise(hr, rb_eRuntimeError, "failed to get ITypeInfo");
    method = folemethod_s_allocate(cWIN32OLE_METHOD);
    obj = olemethod_from_typeinfo(method, pTypeInfo, cmdname);
    OLE_RELEASE(pTypeInfo);
    if (obj == Qnil)
        rb_raise(eWIN32OLE_RUNTIME_ERROR, "not found %s",
                 StringValuePtr(cmdname));
    return obj;
}


ole_obj_help (WIN32OLE)

/*
 *   call-seq:
 *      WIN32OLE#ole_obj_help
 *
 *   Returns WIN32OLE_TYPE object.
 *
 *      excel = WIN32OLE.new('Excel.Application')
 *      tobj = excel.ole_obj_help
 */
static VALUE
fole_obj_help( self )
    VALUE self;
{
    unsigned int index;
    ITypeInfo *pTypeInfo;
    ITypeLib *pTypeLib;
    HRESULT hr;
    struct oledata *pole;
    BSTR bstr;
    LCID  lcid = LOCALE_SYSTEM_DEFAULT;
    VALUE type = Qnil;

    OLEData_Get_Struct(self, pole);

    hr = pole->pDispatch->lpVtbl->GetTypeInfo( pole->pDispatch, 0, lcid, &pTypeInfo );
    if(FAILED(hr)) {
        ole_raise(hr, rb_eRuntimeError, "failed to GetTypeInfo");
    }
    hr = pTypeInfo->lpVtbl->GetContainingTypeLib( pTypeInfo, &pTypeLib, &index );
    if(FAILED(hr)) {
        OLE_RELEASE(pTypeInfo);
        ole_raise(hr, rb_eRuntimeError, "failed to GetContainingTypeLib");
    }
    hr = pTypeLib->lpVtbl->GetDocumentation( pTypeLib, index,
                                             &bstr, NULL, NULL, NULL);
    if (SUCCEEDED(hr)) {
        type = foletype_s_allocate(cWIN32OLE_TYPE);
        oletype_set_member(type, pTypeInfo, WC2VSTR(bstr));
    }
    OLE_RELEASE(pTypeLib);
    OLE_RELEASE(pTypeInfo);

    return type;
}


new (WIN32OLE_EVENT)

/*
 *  call-seq:
 *     WIN32OLE_EVENT.new(ole, event) #=> WIN32OLE_EVENT object.
 *
 *  Returns OLE event object.
 *  The first argument specifies WIN32OLE object.
 *  The second argument specifies OLE event name.
 *     ie = WIN32OLE.new('InternetExplorer.Application')
 *     ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
 */
static VALUE
fev_initialize(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE ole, itf;
    struct oledata *pole;
    char *pitf;
    HRESULT hr;
    IID iid;
    ITypeInfo *pTypeInfo;
    IDispatch *pDispatch;
    IConnectionPointContainer *pContainer;
    IConnectionPoint *pConnectionPoint;
    IEVENTSINKOBJ *pIEV;
    DWORD dwCookie = 0;
    struct oleeventdata *poleev;

    rb_secure(4);
    rb_scan_args(argc, argv, "11", &ole, &itf);

    if (!rb_obj_is_kind_of(ole, cWIN32OLE)) {
        rb_raise(rb_eTypeError, "1st parameter must be WIN32OLE object");
    }

    if(TYPE(itf) != T_NIL) {
        if (ruby_safe_level > 0 && OBJ_TAINTED(itf)) {
            rb_raise(rb_eSecurityError, "Insecure Event Creation - %s",
                     StringValuePtr(itf));
        }
        Check_SafeStr(itf);
        pitf = StringValuePtr(itf);
        hr = find_iid(ole, pitf, &iid, &pTypeInfo);
    }
    else {
        hr = find_default_source(ole, &iid, &pTypeInfo);
    }
    if (FAILED(hr)) {
        ole_raise(hr, rb_eRuntimeError, "interface not found");
    }

    OLEData_Get_Struct(ole, pole);
    pDispatch = pole->pDispatch;
    hr = pDispatch->lpVtbl->QueryInterface(pDispatch,
                                           &IID_IConnectionPointContainer,
                                           (void**)&pContainer);
    if (FAILED(hr)) {
        OLE_RELEASE(pTypeInfo);
        ole_raise(hr, rb_eRuntimeError,
                  "failed to query IConnectionPointContainer");
    }

    hr = pContainer->lpVtbl->FindConnectionPoint(pContainer,
                                                 &iid,
                                                 &pConnectionPoint);
    OLE_RELEASE(pContainer);
    if (FAILED(hr)) {
        OLE_RELEASE(pTypeInfo);
        ole_raise(hr, rb_eRuntimeError, "failed to query IConnectionPoint");
    }
    pIEV = EVENTSINK_Constructor();
    pIEV->m_iid = iid;
    hr = pConnectionPoint->lpVtbl->Advise(pConnectionPoint,
                                          (IUnknown*)pIEV,
                                          &dwCookie);
    if (FAILED(hr)) {
        ole_raise(hr, rb_eRuntimeError, "Advise Error");
    }

    Data_Get_Struct(self, struct oleeventdata, poleev);
    poleev->pEvent = pIEV;
    poleev->pEvent->m_event_id
        = NUM2INT(rb_funcall(ary_ole_event, rb_intern("length"), 0));
    poleev->pEvent->pConnectionPoint = pConnectionPoint;
    poleev->pEvent->pTypeInfo = pTypeInfo;
    poleev->pEvent->m_dwCookie = dwCookie;
    poleev->freed = 0;
    poleev->pEvent->ptr_freed = &(poleev->freed);
    rb_ary_push(ary_ole_event, self);
    return self;
}


message_loop (WIN32OLE_EVENT)

/*
 *  call-seq:
 *     WIN32OLE_EVENT.message_loop
 *
 *  Translates and dispatches Windows message.
 */
static VALUE
fev_s_msg_loop(klass)
    VALUE klass;
{
    ole_msg_loop();
    return Qnil;
}


on_event (WIN32OLE_EVENT)

/*
 *  call-seq:
 *     WIN32OLE_EVENT#on_event([event]){...}
 *
 *  Defines the callback event.
 *  If argument is omitted, this method defines the callback of all events.
 *    ie = WIN32OLE.new('InternetExplorer.Application')
 *    ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
 *    ev.on_event("NavigateComplete") {|url| puts url}
 */
static VALUE
fev_on_event(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    return ev_on_event(argc, argv, self, Qfalse);
}


on_event_with_outargs (WIN32OLE_EVENT)

/*
 *  call-seq:
 *     WIN32OLE_EVENT#on_event_with_outargs([event]){...}
 *
 *  Defines the callback of event.
 *  If you want modify argument in callback,
 *  you should use this method instead of WIN32OLE_EVENT#on_event.
 */
static VALUE
fev_on_event_with_outargs(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    return ev_on_event(argc, argv, self, Qtrue);
}


new (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD.new(ole_type,  method) -> WIN32OLE_METHOD object
 *
 *  Returns a new WIN32OLE_METHOD object which represents the information
 *  about OLE method.
 *  The first argument <i>ole_type</i> specifies WIN32OLE_TYPE object.
 *  The second argument <i>method</i> specifies OLE method name defined OLE class
 *  which represents WIN32OLE_TYPE object.
 *
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 */
static VALUE
folemethod_initialize(self, oletype, method)
    VALUE self;
    VALUE oletype;
    VALUE method;
{
    struct oletypedata *ptype;
    VALUE obj = Qnil;
    if (rb_obj_is_kind_of(oletype, cWIN32OLE_TYPE)) {
        Check_SafeStr(method);
        Data_Get_Struct(oletype, struct oletypedata, ptype);
        obj = olemethod_from_typeinfo(self, ptype->pTypeInfo, method);
        if (obj == Qnil) {
            rb_raise(eWIN32OLE_RUNTIME_ERROR, "not found %s",
                     StringValuePtr(method));
        }
    }
    else {
        rb_raise(rb_eTypeError, "1st argument should be WIN32OLE_TYPE object");
    }
    return obj;
}


name (WIN32OLE_METHOD)

/*
 *  call-seq
 *     WIN32OLE_METHOD#name
 *
 *  Returns the name of the method.
 *
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     puts method.name # => SaveAs
 *
 */
static VALUE
folemethod_name(self)
    VALUE self;
{
    return rb_ivar_get(self, rb_intern("name"));
}


return_type (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#return_type
 *
 *  Returns string of return value type of method.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.return_type # => Workbook
 *
 */
static VALUE
folemethod_return_type(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_return_type(pmethod->pTypeInfo, pmethod->index);
}


return_vtype (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#return_vtype
 *
 *  Returns number of return value type of method.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.return_vtype # => 26
 *
 */
static VALUE
folemethod_return_vtype(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_return_vtype(pmethod->pTypeInfo, pmethod->index);
}


return_type_detail (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#return_type_detail
 *
 *  Returns detail information of return value type of method.
 *  The information is array.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     p method.return_type_detail # => ["PTR", "USERDEFINED", "Workbook"]
 */
static VALUE
folemethod_return_type_detail(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_return_type_detail(pmethod->pTypeInfo, pmethod->index);
}


invoke_kind (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#invoke_kind
 *
 *  Returns the method kind string. The string is "UNKNOWN" or "PROPERTY"
 *  or "PROPERTY" or "PROPERTYGET" or "PROPERTYPUT" or "PROPERTYPPUTREF"
 *  or "FUNC".
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.invoke_kind # => "FUNC"
 */
static VALUE
folemethod_invoke_kind(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_invoke_kind(pmethod->pTypeInfo, pmethod->index);
}


invkind (WIN32OLE_METHOD)

/*
 *   call-seq:
 *      WIN32OLE_MTHOD#invkind
 *
 *   Returns the method invoke kind.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.invkind # => 1
 *
 */
static VALUE
folemethod_invkind(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_invkind(pmethod->pTypeInfo, pmethod->index);
}


visible? (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#visible?
 *
 *  Returns true if the method is public.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.visible? # => true
 */
static VALUE
folemethod_visible(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_visible(pmethod->pTypeInfo, pmethod->index);
}


event? (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#event?
 *
 *  Returns true if the method is event.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SheetActivate')
 *     puts method.event? # => true
 *
 */
static VALUE
folemethod_event(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    if (!pmethod->pOwnerTypeInfo)
        return Qfalse;
    return ole_method_event(pmethod->pOwnerTypeInfo,
                            pmethod->index,
                            rb_ivar_get(self, rb_intern("name")));
}


event_interface (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#event_interface
 *
 *  Returns event interface name if the method is event.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *    method = WIN32OLE_METHOD.new(tobj, 'SheetActivate')
 *    puts method.event_interface # =>  WorkbookEvents
 */
static VALUE
folemethod_event_interface(self)
    VALUE self;
{
    BSTR name;
    struct olemethoddata *pmethod;
    HRESULT hr;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    if(folemethod_event(self) == Qtrue) {
        hr = ole_docinfo_from_type(pmethod->pTypeInfo, &name, NULL, NULL, NULL);
        if(SUCCEEDED(hr))
            return WC2VSTR(name);
    }
    return Qnil;
}


helpstring (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#helpstring
 *
 *  Returns help string of OLE method. If the help string is not found,
 *  then the method returns nil.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
 *     method = WIN32OLE_METHOD.new(tobj, 'Navigate')
 *     puts method.helpstring # => Navigates to a URL or file.
 *
 */
static VALUE
folemethod_helpstring(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_helpstring(pmethod->pTypeInfo, pmethod->index);
}


helpfile (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#helpfile
 *
 *  Returns help file. If help file is not found, then
 *  the method returns nil.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.helpfile # => C:\...\VBAXL9.CHM
 */
static VALUE
folemethod_helpfile(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);

    return ole_method_helpfile(pmethod->pTypeInfo, pmethod->index);
}


helpcontext (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#helpcontext
 *
 *  Returns help context.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.helpcontext # => 65717
 */
static VALUE
folemethod_helpcontext(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_helpcontext(pmethod->pTypeInfo, pmethod->index);
}


dispid (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#dispid
 *
 *  Returns dispatch ID.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.dispid # => 181
 */
static VALUE
folemethod_dispid(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_dispid(pmethod->pTypeInfo, pmethod->index);
}


offset_vtbl (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#offset_vtbl
 *
 *  Returns the offset ov VTBL.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
 *     method = WIN32OLE_METHOD.new(tobj, 'Add')
 *     puts method.offset_vtbl # => 40
 */
static VALUE
folemethod_offset_vtbl(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_offset_vtbl(pmethod->pTypeInfo, pmethod->index);
}


size_params (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#size_params
 *
 *  Returns the size of arguments of the method.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     puts method.size_params # => 11
 *
 */
static VALUE
folemethod_size_params(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_size_params(pmethod->pTypeInfo, pmethod->index);
}


size_opt_params (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#size_opt_params
 *
 *  Returns the size of optional parameters.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     puts method.size_opt_params # => 4
 */
static VALUE
folemethod_size_opt_params(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_size_opt_params(pmethod->pTypeInfo, pmethod->index);
}


params (WIN32OLE_METHOD)

/*
 *  call-seq:
 *     WIN32OLE_METHOD#params
 *
 *  returns array of WIN32OLE_PARAM object corresponding with method parameters.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     p method.params # => [Filename, FileFormat, Password, WriteResPassword,
 *                           ReadOnlyRecommended, CreateBackup, AccessMode,
 *                           ConflictResolution, AddToMru, TextCodepage,
 *                           TextVisualLayout]
 */
static VALUE
folemethod_params(self)
    VALUE self;
{
    struct olemethoddata *pmethod;
    Data_Get_Struct(self, struct olemethoddata, pmethod);
    return ole_method_params(pmethod->pTypeInfo, pmethod->index);
}


name (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#name
 *
 *  Returns name.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     param1 = method.params[0]
 *     puts param1.name # => Filename
 */
static VALUE
foleparam_name(self)
    VALUE self;
{
    return rb_ivar_get(self, rb_intern("name"));
}


ole_type (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#ole_type
 *
 *  Returns OLE type of WIN32OLE_PARAM object(parameter of OLE method).
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     param1 = method.params[0]
 *     puts param1.ole_type # => VARIANT
 */
static VALUE
foleparam_ole_type(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_ole_type(pparam->pTypeInfo, pparam->method_index,
                              pparam->index);
}


ole_type_detail (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#ole_type_detail
 *
 *  Returns detail information of type of argument.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'IWorksheetFunction')
 *     method = WIN32OLE_METHOD.new(tobj, 'SumIf')
 *     param1 = method.params[0]
 *     p param1.ole_type_detail # => ["PTR", "USERDEFINED", "Range"]
 */
static VALUE
foleparam_ole_type_detail(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_ole_type_detail(pparam->pTypeInfo, pparam->method_index,
                                     pparam->index);
}


input? (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#input?
 *
 *  Returns true if the parameter is input.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     param1 = method.params[0]
 *     puts param1.input? # => true
 */
static VALUE foleparam_input(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_flag_mask(pparam->pTypeInfo, pparam->method_index,
                               pparam->index, PARAMFLAG_FIN);
}


output? (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE#output?
 *
 *  Returns true if argument is output.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'DWebBrowserEvents')
 *     method = WIN32OLE_METHOD.new(tobj, 'NewWindow')
 *     method.params.each do |param|
 *       puts "#{param.name} #{param.output?}"
 *     end
 *
 *     The result of above script is following:
 *       URL false
 *       Flags false
 *       TargetFrameName false
 *       PostData false
 *       Headers false
 *       Processed true
 */
static VALUE foleparam_output(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_flag_mask(pparam->pTypeInfo, pparam->method_index,
                               pparam->index, PARAMFLAG_FOUT);
}


optional? (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#optional?
 *
 *  Returns true if argument is optional.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     param1 = method.params[0]
 *     puts "#{param1.name} #{param1.optional?}" # => Filename true
 */
static VALUE foleparam_optional(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_flag_mask(pparam->pTypeInfo, pparam->method_index,
                               pparam->index, PARAMFLAG_FOPT);
}


retval? (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#retval?
 *
 *  Returns true if argument is return value.
 *     tobj = WIN32OLE_TYPE.new('DirectX 7 for Visual Basic Type Library',
 *                              'DirectPlayLobbyConnection')
 *     method = WIN32OLE_METHOD.new(tobj, 'GetPlayerShortName')
 *     param = method.params[0]
 *     puts "#{param.name} #{param.retval?}"  # => name true
 */
static VALUE foleparam_retval(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_flag_mask(pparam->pTypeInfo, pparam->method_index,
                               pparam->index, PARAMFLAG_FRETVAL);
}


default (WIN32OLE_PARAM)

/*
 *  call-seq:
 *     WIN32OLE_PARAM#default
 *
 *  Returns default value. If the default value does not exist,
 *  this method returns nil.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
 *     method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
 *     method.params.each do |param|
 *       if param.default
 *         puts "#{param.name} (= #{param.default})"
 *       else
 *         puts "#{param}"
 *       end
 *     end
 *
 *     The above script result is following:
 *         Filename
 *         FileFormat
 *         Password
 *         WriteResPassword
 *         ReadOnlyRecommended
 *         CreateBackup
 *         AccessMode (= 1)
 *         ConflictResolution
 *         AddToMru
 *         TextCodepage
 *         TextVisualLayout
 */
static VALUE foleparam_default(self)
    VALUE self;
{
    struct oleparamdata *pparam;
    Data_Get_Struct(self, struct oleparamdata, pparam);
    return ole_param_default(pparam->pTypeInfo, pparam->method_index,
                             pparam->index);
}


ole_classes (WIN32OLE_TYPE)

/*
 *   call-seq:
 *      WIN32OLE_TYPE.ole_classes(typelib)
 *
 *   Returns array of WIN32OLE_TYPE objects defined by the <i>typelib</i> type library.
 */
static VALUE
foletype_s_ole_classes(self, typelib)
    VALUE self;
    VALUE typelib;
{
    VALUE file, classes;
    OLECHAR * pbuf;
    ITypeLib *pTypeLib;
    HRESULT hr;

    rb_secure(4);
    classes = rb_ary_new();
    if(TYPE(typelib) == T_STRING) {
        file = typelib_file(typelib);
        if (file == Qnil) {
            file = typelib;
        }
        pbuf = ole_mb2wc(StringValuePtr(file), -1);
        hr = LoadTypeLibEx(pbuf, REGKIND_NONE, &pTypeLib);
        if (FAILED(hr))
          ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to LoadTypeLibEx");
        SysFreeString(pbuf);
        ole_classes_from_typelib(pTypeLib, classes);
        OLE_RELEASE(pTypeLib);
    } else {
        rb_raise(rb_eTypeError, "1st argument should be TypeLib string");
    }
    return classes;
}


typelibs (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE.typelibs
 *
 *  Returns array of type libraries.
 *
 */
static VALUE
foletype_s_typelibs(self)
    VALUE self;
{
    HKEY htypelib, hclsid;
    double fversion;
    DWORD i, j;
    LONG err;
    VALUE clsid;
    VALUE ver;
    VALUE v = Qnil;
    VALUE typelibs = rb_ary_new();

    err = reg_open_key(HKEY_CLASSES_ROOT, "TypeLib", &htypelib);
    if(err != ERROR_SUCCESS) {
        return typelibs;
    }
    for(i = 0; ; i++) {
        clsid = reg_enum_key(htypelib, i);
        if (clsid == Qnil)
            break;
        err = reg_open_vkey(htypelib, clsid, &hclsid);
        if (err != ERROR_SUCCESS)
            continue;
        fversion = 0;
        for(j = 0; ; j++) {
            ver = reg_enum_key(hclsid, j);
            if (ver == Qnil)
                break;
            if (fversion > atof(StringValuePtr(ver)))
                continue;
            fversion = atof(StringValuePtr(ver));
            if ( (v = reg_get_val(hclsid, StringValuePtr(ver))) != Qnil ) {
                rb_ary_push(typelibs, v);
            }
        }
        RegCloseKey(hclsid);
    }
    RegCloseKey(htypelib);
    return typelibs;
}


progids (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE.progids
 *
 *  Returns array of ProgID.
 */
static VALUE
foletype_s_progids(self)
    VALUE self;
{
    HKEY hclsids, hclsid;
    DWORD i;
    LONG err;
    VALUE clsid;
    VALUE v = rb_str_new2("");
    VALUE progids = rb_ary_new();

    err = reg_open_key(HKEY_CLASSES_ROOT, "CLSID", &hclsids);
    if(err != ERROR_SUCCESS) {
        return progids;
    }
    for(i = 0; ; i++) {
        clsid = reg_enum_key(hclsids, i);
        if (clsid == Qnil)
            break;
        err = reg_open_vkey(hclsids, clsid, &hclsid);
        if (err != ERROR_SUCCESS)
            continue;
        if ((v = reg_get_val(hclsid, "ProgID")) != Qnil)
            rb_ary_push(progids, v);
        if ((v = reg_get_val(hclsid, "VersionIndependentProgID")) != Qnil)
            rb_ary_push(progids, v);
        RegCloseKey(hclsid);
    }
    RegCloseKey(hclsids);
    return progids;
}


new (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE.new(typelib, ole_class) -> WIN32OLE_TYPE object
 *
 *  Returns a new WIN32OLE_TYPE object.
 *  The first argument <i>typelib</i> specifies OLE type library name.
 *  The second argument specifies OLE class name.
 *
 *      WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
 *          # => WIN32OLE_TYPE object of Application class of Excel.
 */
static VALUE
foletype_initialize(self, typelib, oleclass)
    VALUE self;
    VALUE typelib;
    VALUE oleclass;
{
    VALUE file;
    OLECHAR * pbuf;
    ITypeLib *pTypeLib;
    HRESULT hr;

    Check_SafeStr(oleclass);
    Check_SafeStr(typelib);
    file = typelib_file(typelib);
    if (file == Qnil) {
        file = typelib;
    }
    pbuf = ole_mb2wc(StringValuePtr(file), -1);
    hr = LoadTypeLibEx(pbuf, REGKIND_NONE, &pTypeLib);
    if (FAILED(hr))
        ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to LoadTypeLibEx");
    SysFreeString(pbuf);
    if (oleclass_from_typelib(self, pTypeLib, oleclass) == Qfalse) {
        OLE_RELEASE(pTypeLib);
        rb_raise(eWIN32OLE_RUNTIME_ERROR, "not found `%s` in `%s`",
                 StringValuePtr(oleclass), StringValuePtr(typelib));
    }
    OLE_RELEASE(pTypeLib);
    return self;
}


name (WIN32OLE_TYPE)

/*
 * call-seq:
 *    WIN32OLE_TYPE#name #=> OLE type name
 *
 * Returns OLE type name.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
 *    puts tobj.name  # => Application
 */
static VALUE
foletype_name(self)
    VALUE self;
{
    return rb_ivar_get(self, rb_intern("name"));
}


ole_type (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#ole_type #=> OLE type string.
 *
 *  returns type of OLE class.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
 *    puts tobj.ole_type  # => Class
 */
static VALUE
foletype_ole_type(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_ole_type(ptype->pTypeInfo);
}


guid (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#guid  #=> GUID
 *
 *  Returns GUID.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
 *    puts tobj.guid  # => {00024500-0000-0000-C000-000000000046}
 */
static VALUE
foletype_guid(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_guid(ptype->pTypeInfo);
}


progid (WIN32OLE_TYPE)

/*
 * call-seq:
 *    WIN32OLE_TYPE#progid  #=> ProgID
 *
 * Returns ProgID if it exists. If not found, then returns nil.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
 *    puts tobj.progid  # =>   Excel.Application.9
 */
static VALUE
foletype_progid(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_progid(ptype->pTypeInfo);
}


visible? (WIN32OLE_TYPE)

/*
 *  call-seq:
 *    WIN32OLE_TYPE#visible  #=> true or false
 *
 *  Returns true if the OLE class is public.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
 *    puts tobj.visible  # => true
 */
static VALUE
foletype_visible(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_visible(ptype->pTypeInfo);
}


major_version (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#major_version
 *
 *  Returns major version.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
 *     puts tobj.major_version # => 8
 */
static VALUE
foletype_major_version(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_major_version(ptype->pTypeInfo);
}


minor_version (WIN32OLE_TYPE)

/*
 *  call-seq:
 *    WIN32OLE_TYPE#minor_version #=> OLE minor version
 *
 *  Returns minor version.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
 *     puts tobj.minor_version # => 2
 */
static VALUE
foletype_minor_version(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_minor_version(ptype->pTypeInfo);
}


typekind (WIN32OLE_TYPE)

/*
 *  call-seq:
 *    WIN32OLE_TYPE#typekind #=> number of type.
 *
 *  Returns number which represents type.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
 *    puts tobj.typekind # => 4
 *
 */
static VALUE
foletype_typekind(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_typekind(ptype->pTypeInfo);
}


helpstring (WIN32OLE_TYPE)

/*
 *  call-seq:
 *    WIN32OLE_TYPE#helpstring #=> help string.
 *
 *  Returns help string.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
 *    puts tobj.helpstring # => Web Browser interface
 */
static VALUE
foletype_helpstring(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_helpstring(ptype->pTypeInfo);
}


src_type (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#src_type #=> OLE source class
 *
 *  Returns source class when the OLE class is 'Alias'.
 *     tobj =  WIN32OLE_TYPE.new('Microsoft Office 9.0 Object Library', 'MsoRGBType')
 *     puts tobj.src_type # => I4
 *
 */
static VALUE
foletype_src_type(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_src_type(ptype->pTypeInfo);
}


helpfile (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#helpfile
 *
 *  Returns helpfile path. If helpfile is not found, then returns nil.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
 *     puts tobj.helpfile # => C:\...\VBAXL9.CHM
 *
 */
static VALUE
foletype_helpfile(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_helpfile(ptype->pTypeInfo);
}


helpcontext (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#helpcontext
 *
 *  Returns helpcontext. If helpcontext is not found, then returns nil.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
 *     puts tobj.helpfile # => 131185
 */
static VALUE
foletype_helpcontext(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_type_helpcontext(ptype->pTypeInfo);
}


variables (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#variables
 *
 *  Returns array of WIN32OLE_VARIABLE objects which represent variables
 *  defined in OLE class.
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *     vars = tobj.variables
 *     vars.each do |v|
 *       puts "#{v.name} = #{v.value}"
 *     end
 *
 *     The result of above sample script is follows:
 *       xlChart = -4109
 *       xlDialogSheet = -4116
 *       xlExcel4IntlMacroSheet = 4
 *       xlExcel4MacroSheet = 3
 *       xlWorksheet = -4167
 *
 */
static VALUE
foletype_variables(self)
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_variables(ptype->pTypeInfo);
}


ole_methods (WIN32OLE_TYPE)

/*
 *  call-seq:
 *     WIN32OLE_TYPE#ole_methods # the array of WIN32OLE_METHOD objects.
 *
 *  Returns array of WIN32OLE_METHOD objects which represent OLE method defined in
 *  OLE type library.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
 *    methods = tobj.ole_methods.collect{|m|
 *      m.name
 *    }
 *    # => ['Activate', 'Copy', 'Delete',....]
 */
static VALUE
foletype_methods(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    struct oletypedata *ptype;
    Data_Get_Struct(self, struct oletypedata, ptype);
    return ole_methods_from_typeinfo(ptype->pTypeInfo, INVOKE_FUNC | INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT | INVOKE_PROPERTYPUTREF);
}


name (WIN32OLE_VARIABLE)

/*
 *  call-seq:
 *     WIN32OLE_VARIABLE#name
 *
 *  Returns the name of variable.
 *
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *     variables = tobj.variables
 *     variables.each do |variable|
 *       puts "#{variable.name}"
 *     end
 *
 *     The result of above script is following:
 *       xlChart
 *       xlDialogSheet
 *       xlExcel4IntlMacroSheet
 *       xlExcel4MacroSheet
 *       xlWorksheet
 *
 */
static VALUE
folevariable_name(self)
    VALUE self;
{
    return rb_ivar_get(self, rb_intern("name"));
}


ole_type (WIN32OLE_VARIABLE)

/*
 *   call-seq:
 *      WIN32OLE_VARIABLE#ole_type
 *
 *   Returns OLE type string.
 *
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *     variables = tobj.variables
 *     variables.each do |variable|
 *       puts "#{variable.ole_type} #{variable.name}"
 *     end
 *
 *     The result of above script is following:
 *       INT xlChart
 *       INT xlDialogSheet
 *       INT xlExcel4IntlMacroSheet
 *       INT xlExcel4MacroSheet
 *       INT xlWorksheet
 *
 */
static VALUE
folevariable_ole_type(self)
    VALUE self;
{
    struct olevariabledata *pvar;
    Data_Get_Struct(self, struct olevariabledata, pvar);
    return ole_variable_ole_type(pvar->pTypeInfo, pvar->index);
}


ole_type_detail (WIN32OLE_VARIABLE)

/*
 *  call-seq:
 *     WIN32OLE_VARIABLE#ole_type_detail
 *
 *  Returns detail information of type. The information is array of type.
 *
 *     tobj = WIN32OLE_TYPE.new('DirectX 7 for Visual Basic Type Library', 'D3DCLIPSTATUS')
 *     variable = tobj.variables.find {|variable| variable.name == 'lFlags'}
 *     tdetail  = variable.ole_type_detail
 *     p tdetail # => ["USERDEFINED", "CONST_D3DCLIPSTATUSFLAGS"]
 *
 */
static VALUE
folevariable_ole_type_detail(self)
    VALUE self;
{
    struct olevariabledata *pvar;
    Data_Get_Struct(self, struct olevariabledata, pvar);
    return ole_variable_ole_type_detail(pvar->pTypeInfo, pvar->index);
}


value (WIN32OLE_VARIABLE)

/*
 *  call-seq:
 *     WIN32OLE_VARIABLE#value
 *
 *  Returns value if value is exists. If the value does not exist,
 *  this method returns nil.
 *
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *     variables = tobj.variables
 *     variables.each do |variable|
 *       puts "#{variable.name} = #{variable.value}"
 *     end
 *
 *     The result of above script is following:
 *       xlChart = -4109
 *       xlDialogSheet = -4116
 *       xlExcel4IntlMacroSheet = 4
 *       xlExcel4MacroSheet = 3
 *       xlWorksheet = -4167
 *
 */
static VALUE
folevariable_value(self)
    VALUE self;
{
    struct olevariabledata *pvar;
    Data_Get_Struct(self, struct olevariabledata, pvar);
    return ole_variable_value(pvar->pTypeInfo, pvar->index);
}


visible? (WIN32OLE_VARIABLE)

/*
 *  call-seq:
 *     WIN32OLE_VARIABLE#visible?
 *
 *  Returns true if the variable is public.
 *
 *     tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *     variables = tobj.variables
 *     variables.each do |variable|
 *       puts "#{variable.name} #{variable.visible?}"
 *     end
 *
 *     The result of above script is following:
 *       xlChart true
 *       xlDialogSheet true
 *       xlExcel4IntlMacroSheet true
 *       xlExcel4MacroSheet true
 *       xlWorksheet true
 *
 */
static VALUE
folevariable_visible(self)
    VALUE self;
{
    struct olevariabledata *pvar;
    Data_Get_Struct(self, struct olevariabledata, pvar);
    return ole_variable_visible(pvar->pTypeInfo, pvar->index);
}


variable_kind (WIN32OLE_VARIABLE)

/*
 * call-seq:
 *   WIN32OLE_VARIABLE#variable_kind
 *
 * Returns variable kind string.
 *
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *    variables = tobj.variables
 *    variables.each do |variable|
 *      puts "#{variable.name} #{variable.variable_kind}"
 *    end
 *
 *    The result of above script is following:
 *      xlChart CONSTANT
 *      xlDialogSheet CONSTANT
 *      xlExcel4IntlMacroSheet CONSTANT
 *      xlExcel4MacroSheet CONSTANT
 *      xlWorksheet CONSTANT
 */
static VALUE
folevariable_variable_kind(self)
    VALUE self;
{
    struct olevariabledata *pvar;
    Data_Get_Struct(self, struct olevariabledata, pvar);
    return ole_variable_kind(pvar->pTypeInfo, pvar->index);
}


varkind (WIN32OLE_VARIABLE)

/*
 *  call-seq:
 *     WIN32OLE_VARIABLE#varkind
 *
 *  Returns the number which represents variable kind.
 *    tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
 *    variables = tobj.variables
 *    variables.each do |variable|
 *      puts "#{variable.name} #{variable.varkind}"
 *    end
 *
 *    The result of above script is following:
 *       xlChart 2
 *       xlDialogSheet 2
 *       xlExcel4IntlMacroSheet 2
 *       xlExcel4MacroSheet 2
 *       xlWorksheet 2
 */
static VALUE
folevariable_varkind(self)
    VALUE self;
{
    struct olevariabledata *pvar;
    Data_Get_Struct(self, struct olevariabledata, pvar);
    return ole_variable_varkind(pvar->pTypeInfo, pvar->index);
}


new (WSDL::Binding)

# File lib/wsdl/binding.rb, line 22
  def initialize
    super
    @name = nil
    @type = nil
    @operations = XSD::NamedElements.new
    @soapbinding = nil
  end


targetnamespace (WSDL::Binding)

# File lib/wsdl/binding.rb, line 30
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::Binding)

# File lib/wsdl/binding.rb, line 34
  def parse_element(element)
    case element
    when OperationName
      o = OperationBinding.new
      @operations << o
      o
    when SOAPBindingName
      o = WSDL::SOAP::Binding.new
      @soapbinding = o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Binding)

# File lib/wsdl/binding.rb, line 52
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    when TypeAttrName
      @type = value
    else
      nil
    end
  end


new (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 24
  def initialize
    super
    @name = nil
    @targetnamespace = nil
    @location = nil
    @importedschema = {}

    @types = nil
    @imports = []
    @messages = XSD::NamedElements.new
    @porttypes = XSD::NamedElements.new
    @bindings = XSD::NamedElements.new
    @services = XSD::NamedElements.new

    @anontypes = XSD::NamedElements.new
    @root = self
  end


inspect (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 42
  def inspect
    sprintf("#<%s:0x%x %s>", self.class.name, __id__, @name || '(unnamed)')
  end


targetnamespace= (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 46
  def targetnamespace=(targetnamespace)
    @targetnamespace = targetnamespace
    if @name
      @name = XSD::QName.new(@targetnamespace, @name.name)
    end
  end


collect_attributes (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 53
  def collect_attributes
    result = XSD::NamedElements.new
    if @types
      @types.schemas.each do |schema|
        result.concat(schema.collect_attributes)
      end
    end
    @imports.each do |import|
      result.concat(import.content.collect_attributes)
    end
    result
  end


collect_elements (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 66
  def collect_elements
    result = XSD::NamedElements.new
    if @types
      @types.schemas.each do |schema|
        result.concat(schema.collect_elements)
      end
    end
    @imports.each do |import|
      result.concat(import.content.collect_elements)
    end
    result
  end


collect_complextypes (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 79
  def collect_complextypes
    result = @anontypes.dup
    if @types
      @types.schemas.each do |schema|
        result.concat(schema.collect_complextypes)
      end
    end
    @imports.each do |import|
      result.concat(import.content.collect_complextypes)
    end
    result
  end


collect_simpletypes (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 92
  def collect_simpletypes
    result = XSD::NamedElements.new
    if @types
      @types.schemas.each do |schema|
        result.concat(schema.collect_simpletypes)
      end
    end
    @imports.each do |import|
      result.concat(import.content.collect_simpletypes)
    end
    result
  end


add_type (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 106
  def add_type(complextype)
    @anontypes << complextype
  end


messages (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 110
  def messages
    result = @messages.dup
    @imports.each do |import|
      result.concat(import.content.messages) if self.class === import.content
    end
    result
  end


porttypes (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 118
  def porttypes
    result = @porttypes.dup
    @imports.each do |import|
      result.concat(import.content.porttypes) if self.class === import.content
    end
    result
  end


bindings (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 126
  def bindings
    result = @bindings.dup
    @imports.each do |import|
      result.concat(import.content.bindings) if self.class === import.content
    end
    result
  end


services (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 134
  def services
    result = @services.dup
    @imports.each do |import|
      result.concat(import.content.services) if self.class === import.content
    end
    result
  end


message (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 142
  def message(name)
    message = @messages[name]
    return message if message
    @imports.each do |import|
      message = import.content.message(name) if self.class === import.content
      return message if message
    end
    nil
  end


porttype (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 152
  def porttype(name)
    porttype = @porttypes[name]
    return porttype if porttype
    @imports.each do |import|
      porttype = import.content.porttype(name) if self.class === import.content
      return porttype if porttype
    end
    nil
  end


binding (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 162
  def binding(name)
    binding = @bindings[name]
    return binding if binding
    @imports.each do |import|
      binding = import.content.binding(name) if self.class === import.content
      return binding if binding
    end
    nil
  end


service (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 172
  def service(name)
    service = @services[name]
    return service if service
    @imports.each do |import|
      service = import.content.service(name) if self.class === import.content
      return service if service
    end
    nil
  end


porttype_binding (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 182
  def porttype_binding(name)
    binding = @bindings.find { |item| item.type == name }
    return binding if binding
    @imports.each do |import|
      binding = import.content.porttype_binding(name) if self.class === import.content
      return binding if binding
    end
    nil
  end


parse_element (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 192
  def parse_element(element)
    case element
    when ImportName
      o = Import.new
      @imports << o
      o
    when TypesName
      o = Types.new
      @types = o
      o
    when MessageName
      o = Message.new
      @messages << o
      o
    when PortTypeName
      o = PortType.new
      @porttypes << o
      o
    when BindingName
      o = Binding.new
      @bindings << o
      o
    when ServiceName
      o = Service.new
      @services << o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 226
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    when TargetNamespaceAttrName
      self.targetnamespace = value.source
    else
      nil
    end
  end


parse_element (WSDL::Definitions)

# File lib/wsdl/definitions.rb, line 237
  def self.parse_element(element)
    if element == DefinitionsName
      Definitions.new
    else
      nil
    end
  end


soap_rpc_complextypes (WSDL::Definitions)

# File lib/wsdl/soap/definitions.rb, line 18
  def self.soap_rpc_complextypes
    types = XSD::NamedElements.new
    types << array_complextype
    types << fault_complextype
    types << exception_complextype
    types
  end


array_complextype (WSDL::Definitions)

# File lib/wsdl/soap/definitions.rb, line 26
  def self.array_complextype
    type = XMLSchema::ComplexType.new(::SOAP::ValueArrayName)
    type.complexcontent = XMLSchema::ComplexContent.new
    type.complexcontent.base = ::SOAP::ValueArrayName
    attr = XMLSchema::Attribute.new
    attr.ref = ::SOAP::AttrArrayTypeName
    anytype = XSD::AnyTypeName.dup
    anytype.name += '[]'
    attr.arytype = anytype
    type.complexcontent.attributes << attr
    type
  end


fault_complextype (WSDL::Definitions)

# File lib/wsdl/soap/definitions.rb, line 49
  def self.fault_complextype
    type = XMLSchema::ComplexType.new(::SOAP::EleFaultName)
    faultcode = XMLSchema::Element.new(::SOAP::EleFaultCodeName, XSD::XSDQName::Type)
    faultstring = XMLSchema::Element.new(::SOAP::EleFaultStringName, XSD::XSDString::Type)
    faultactor = XMLSchema::Element.new(::SOAP::EleFaultActorName, XSD::XSDAnyURI::Type)
    faultactor.minoccurs = 0
    detail = XMLSchema::Element.new(::SOAP::EleFaultDetailName, XSD::AnyTypeName)
    detail.minoccurs = 0
    type.all_elements = [faultcode, faultstring, faultactor, detail]
    type.final = 'extension'
    type
  end


exception_complextype (WSDL::Definitions)

# File lib/wsdl/soap/definitions.rb, line 62
  def self.exception_complextype
    type = XMLSchema::ComplexType.new(XSD::QName.new(
        ::SOAP::Mapping::RubyCustomTypeNamespace, 'SOAPException'))
    excn_name = XMLSchema::Element.new(XSD::QName.new(nil, 'excn_type_name'), XSD::XSDString::Type)
    cause = XMLSchema::Element.new(XSD::QName.new(nil, 'cause'), XSD::AnyTypeName)
    backtrace = XMLSchema::Element.new(XSD::QName.new(nil, 'backtrace'), ::SOAP::ValueArrayName)
    message = XMLSchema::Element.new(XSD::QName.new(nil, 'message'), XSD::XSDString::Type)
    type.all_elements = [excn_name, cause, backtrace, message]
    type
  end


soap_rpc_complextypes (WSDL::Definitions)

# File lib/wsdl/soap/definitions.rb, line 73
  def soap_rpc_complextypes(binding)
    types = rpc_operation_complextypes(binding)
    types + self.class.soap_rpc_complextypes
  end


collect_faulttypes (WSDL::Definitions)

# File lib/wsdl/soap/definitions.rb, line 78
  def collect_faulttypes
    result = []
    collect_fault_messages.each do |name|
      faultparts = message(name).parts
      if faultparts.size != 1
        raise RuntimeError.new("expecting fault message to have only 1 part")
      end
      if result.index(faultparts[0].type).nil?
        result << faultparts[0].type
      end
    end
    result
  end


new (WSDL::Documentation)

# File lib/wsdl/documentation.rb, line 16
  def initialize
    super
  end


parse_element (WSDL::Documentation)

# File lib/wsdl/documentation.rb, line 20
  def parse_element(element)
    # Accepts any element.
    self
  end


parse_attr (WSDL::Documentation)

# File lib/wsdl/documentation.rb, line 25
  def parse_attr(attr, value)
    # Accepts any attribute.
    true
  end


new (WSDL::Import)

# File lib/wsdl/import.rb, line 21
  def initialize
    super
    @namespace = nil
    @location = nil
    @content = nil
    @web_client = nil
  end


parse_element (WSDL::Import)

# File lib/wsdl/import.rb, line 29
  def parse_element(element)
    case element
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Import)

# File lib/wsdl/import.rb, line 39
  def parse_attr(attr, value)
    case attr
    when NamespaceAttrName
      @namespace = value.source
      if @content
        @content.targetnamespace = @namespace
      end
      @namespace
    when LocationAttrName
      @location = URI.parse(value.source)
      if @location.relative? and !parent.location.nil? and
          !parent.location.relative?
        @location = parent.location + @location
      end
      if root.importedschema.key?(@location)
        @content = root.importedschema[@location]
      else
        root.importedschema[@location] = nil      # placeholder
        @content = import(@location)
        if @content.is_a?(Definitions)
          @content.root = root
          if @namespace
            @content.targetnamespace = @namespace
          end
        end
        root.importedschema[@location] = @content
      end
      @location
    else
      nil
    end
  end


import (WSDL::Importer)

# File lib/wsdl/importer.rb, line 17
  def self.import(location, originalroot = nil)
    new.import(location, originalroot)
  end


new (WSDL::Info)

# File lib/wsdl/info.rb, line 17
  def initialize
    @root = nil
    @parent = nil
    @id = nil
  end


inspect (WSDL::Info)

# File lib/wsdl/info.rb, line 23
  def inspect
    if self.respond_to?(:name)
      sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.name)
    else
      sprintf("#<%s:0x%x>", self.class.name, __id__)
    end
  end


parse_element (WSDL::Info)

# File lib/wsdl/info.rb, line 31
  def parse_element(element); end


parse_attr (WSDL::Info)

# File lib/wsdl/info.rb, line 33
  def parse_attr(attr, value); end


parse_epilogue (WSDL::Info)

# File lib/wsdl/info.rb, line 35
  def parse_epilogue; end


new (WSDL::Message)

# File lib/wsdl/message.rb, line 19
  def initialize
    super
    @name = nil
    @parts = []
  end


targetnamespace (WSDL::Message)

# File lib/wsdl/message.rb, line 25
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::Message)

# File lib/wsdl/message.rb, line 29
  def parse_element(element)
    case element
    when PartName
      o = Part.new
      @parts << o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Message)

# File lib/wsdl/message.rb, line 43
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(parent.targetnamespace, value.source)
    else
      nil
    end
  end


new (WSDL::Operation::NameInfo)

# File lib/wsdl/operation.rb, line 20
    def initialize(op_name, optype_name, parts)
      @op_name = op_name
      @optype_name = optype_name
      @parts = parts
    end


new (WSDL::Operation)

# File lib/wsdl/operation.rb, line 34
  def initialize
    super
    @name = nil
    @type = nil
    @parameter_order = nil
    @input = nil
    @output = nil
    @fault = []
  end


targetnamespace (WSDL::Operation)

# File lib/wsdl/operation.rb, line 44
  def targetnamespace
    parent.targetnamespace
  end


input_info (WSDL::Operation)

# File lib/wsdl/operation.rb, line 48
  def input_info
    typename = input.find_message.name
    NameInfo.new(@name, typename, inputparts)
  end


output_info (WSDL::Operation)

# File lib/wsdl/operation.rb, line 53
  def output_info
    typename = output.find_message.name
    NameInfo.new(@name, typename, outputparts)
  end


inputparts (WSDL::Operation)

# File lib/wsdl/operation.rb, line 58
  def inputparts
    sort_parts(input.find_message.parts)
  end


inputname (WSDL::Operation)

# File lib/wsdl/operation.rb, line 62
  def inputname
    XSD::QName.new(targetnamespace, input.name ? input.name.name : @name.name)
  end


outputparts (WSDL::Operation)

# File lib/wsdl/operation.rb, line 66
  def outputparts
    sort_parts(output.find_message.parts)
  end


outputname (WSDL::Operation)

# File lib/wsdl/operation.rb, line 70
  def outputname
    XSD::QName.new(targetnamespace,
      output.name ? output.name.name : @name.name + 'Response')
  end


parse_element (WSDL::Operation)

# File lib/wsdl/operation.rb, line 75
  def parse_element(element)
    case element
    when InputName
      o = Param.new
      @input = o
      o
    when OutputName
      o = Param.new
      @output = o
      o
    when FaultName
      o = Param.new
      @fault << o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Operation)

# File lib/wsdl/operation.rb, line 97
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    when TypeAttrName
      @type = value
    when ParameterOrderAttrName
      @parameter_order = value.source.split(/\s+/)
    else
      nil
    end
  end


new (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 22
  def initialize
    super
    @name = nil
    @input = nil
    @output = nil
    @fault = []
    @soapoperation = nil
  end


targetnamespace (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 31
  def targetnamespace
    parent.targetnamespace
  end


porttype (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 35
  def porttype
    root.porttype(parent.type)
  end


find_operation (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 39
  def find_operation
    porttype.operations[@name] or raise RuntimeError.new("#{@name} not found")
  end


soapoperation_name (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 43
  def soapoperation_name
    if @soapoperation
      @soapoperation.input_info.op_name
    else
      find_operation.name
    end
  end


soapoperation_style (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 51
  def soapoperation_style
    style = nil
    if @soapoperation
      style = @soapoperation.operation_style
    elsif parent.soapbinding
      style = parent.soapbinding.style
    else
      raise TypeError.new("operation style definition not found")
    end
    style || :document
  end


soapaction (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 63
  def soapaction
    if @soapoperation
      @soapoperation.soapaction
    else
      nil
    end
  end


parse_element (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 71
  def parse_element(element)
    case element
    when InputName
      o = Param.new
      @input = o
      o
    when OutputName
      o = Param.new
      @output = o
      o
    when FaultName
      o = Param.new
      @fault << o
      o
    when SOAPOperationName
      o = WSDL::SOAP::Operation.new
      @soapoperation = o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::OperationBinding)

# File lib/wsdl/operationBinding.rb, line 97
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    else
      nil
    end
  end


new (WSDL::Param)

# File lib/wsdl/param.rb, line 22
  def initialize
    super
    @message = nil
    @name = nil
    @soapbody = nil
    @soapheader = []
    @soapfault = nil
  end


targetnamespace (WSDL::Param)

# File lib/wsdl/param.rb, line 31
  def targetnamespace
    parent.targetnamespace
  end


find_message (WSDL::Param)

# File lib/wsdl/param.rb, line 35
  def find_message
    root.message(@message) or raise RuntimeError.new("#{@message} not found")
  end


soapbody_use (WSDL::Param)

# File lib/wsdl/param.rb, line 39
  def soapbody_use
    if @soapbody
      @soapbody.use || :literal
    else
      raise RuntimeError.new("soap:body not found")
    end
  end


parse_element (WSDL::Param)

# File lib/wsdl/param.rb, line 47
  def parse_element(element)
    case element
    when SOAPBodyName
      o = WSDL::SOAP::Body.new
      @soapbody = o
      o
    when SOAPHeaderName
      o = WSDL::SOAP::Header.new
      @soapheader << o
      o
    when SOAPFaultName
      o = WSDL::SOAP::Fault.new
      @soap_fault = o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Param)

# File lib/wsdl/param.rb, line 69
  def parse_attr(attr, value)
    case attr
    when MessageAttrName
      if value.namespace.nil?
        value = XSD::QName.new(targetnamespace, value.source)
      end
      @message = value
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    else
      nil
    end
  end


new (WSDL::Parser::ParseFrame)

# File lib/wsdl/parser.rb, line 43
    def initialize(ns, name, node)
      @ns = ns
      @name = name
      @node = node
    end


new (WSDL::Parser)

# File lib/wsdl/parser.rb, line 52
  def initialize(opt = {})
    @parser = XSD::XMLParser.create_parser(self, opt)
    @parsestack = nil
    @lastnode = nil
    @ignored = {}
    @location = opt[:location]
    @originalroot = opt[:originalroot]
  end


parse (WSDL::Parser)

# File lib/wsdl/parser.rb, line 61
  def parse(string_or_readable)
    @parsestack = []
    @lastnode = nil
    @textbuf = ''
    @parser.do_parse(string_or_readable)
    @lastnode
  end


charset (WSDL::Parser)

# File lib/wsdl/parser.rb, line 69
  def charset
    @parser.charset
  end


start_element (WSDL::Parser)

# File lib/wsdl/parser.rb, line 73
  def start_element(name, attrs)
    lastframe = @parsestack.last
    ns = parent = nil
    if lastframe
      ns = lastframe.ns.clone_ns
      parent = lastframe.node
    else
      ns = XSD::NS.new
      parent = nil
    end
    attrs = XSD::XMLParser.filter_ns(ns, attrs)
    node = decode_tag(ns, name, attrs, parent)
    @parsestack << ParseFrame.new(ns, name, node)
  end


characters (WSDL::Parser)

# File lib/wsdl/parser.rb, line 88
  def characters(text)
    lastframe = @parsestack.last
    if lastframe
      # Need not to be cloned because character does not have attr.
      ns = lastframe.ns
      decode_text(ns, text)
    else
      p text if $DEBUG
    end
  end


end_element (WSDL::Parser)

# File lib/wsdl/parser.rb, line 99
  def end_element(name)
    lastframe = @parsestack.pop
    unless name == lastframe.name
      raise UnexpectedElementError.new("closing element name '#{name}' does not match with opening element '#{lastframe.name}'")
    end
    decode_tag_end(lastframe.ns, lastframe.node)
    @lastnode = lastframe.node
  end


new (WSDL::Part)

# File lib/wsdl/part.rb, line 20
  def initialize
    super
    @name = nil
    @element = nil
    @type = nil
  end


parse_element (WSDL::Part)

# File lib/wsdl/part.rb, line 27
  def parse_element(element)
    case element
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Part)

# File lib/wsdl/part.rb, line 37
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = value.source
    when ElementAttrName
      @element = value
    when TypeAttrName
      @type = value
    else
      nil
    end
  end


new (WSDL::Port)

# File lib/wsdl/port.rb, line 20
  def initialize
    super
    @name = nil
    @binding = nil
    @soap_address = nil
  end


targetnamespace (WSDL::Port)

# File lib/wsdl/port.rb, line 27
  def targetnamespace
    parent.targetnamespace
  end


porttype (WSDL::Port)

# File lib/wsdl/port.rb, line 31
  def porttype
    root.porttype(find_binding.type)
  end


find_binding (WSDL::Port)

# File lib/wsdl/port.rb, line 35
  def find_binding
    root.binding(@binding) or raise RuntimeError.new("#{@binding} not found")
  end


inputoperation_map (WSDL::Port)

# File lib/wsdl/port.rb, line 39
  def inputoperation_map
    result = {}
    find_binding.operations.each do |op_bind|
      op_info = op_bind.soapoperation.input_info
      result[op_info.op_name] = op_info
    end
    result
  end


outputoperation_map (WSDL::Port)

# File lib/wsdl/port.rb, line 48
  def outputoperation_map
    result = {}
    find_binding.operations.each do |op_bind|
      op_info = op_bind.soapoperation.output_info
      result[op_info.op_name] = op_info
    end
    result
  end


parse_element (WSDL::Port)

# File lib/wsdl/port.rb, line 57
  def parse_element(element)
    case element
    when SOAPAddressName
      o = WSDL::SOAP::Address.new
      @soap_address = o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Port)

# File lib/wsdl/port.rb, line 71
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    when BindingAttrName
      @binding = value
    else
      nil
    end
  end


targetnamespace (WSDL::PortType)

# File lib/wsdl/portType.rb, line 20
  def targetnamespace
    parent.targetnamespace
  end


new (WSDL::PortType)

# File lib/wsdl/portType.rb, line 24
  def initialize
    super
    @name = nil
    @operations = XSD::NamedElements.new
  end


find_binding (WSDL::PortType)

# File lib/wsdl/portType.rb, line 30
  def find_binding
    root.bindings.find { |item| item.type == @name } or
      raise RuntimeError.new("#{@name} not found")
  end


locations (WSDL::PortType)

# File lib/wsdl/portType.rb, line 35
  def locations
    bind_name = find_binding.name
    result = []
    root.services.each do |service|
      service.ports.each do |port|
        if port.binding == bind_name
          result << port.soap_address.location if port.soap_address
        end
      end
    end
    result
  end


parse_element (WSDL::PortType)

# File lib/wsdl/portType.rb, line 48
  def parse_element(element)
    case element
    when OperationName
      o = Operation.new
      @operations << o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::PortType)

# File lib/wsdl/portType.rb, line 62
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    else
      nil
    end
  end


new (WSDL::Service)

# File lib/wsdl/service.rb, line 21
  def initialize
    super
    @name = nil
    @ports = XSD::NamedElements.new
    @soap_address = nil
  end


targetnamespace (WSDL::Service)

# File lib/wsdl/service.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::Service)

# File lib/wsdl/service.rb, line 32
  def parse_element(element)
    case element
    when PortName
      o = Port.new
      @ports << o
      o
    when SOAPAddressName
      o = WSDL::SOAP::Address.new
      @soap_address = o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Service)

# File lib/wsdl/service.rb, line 50
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    else
      nil
    end
  end


new (WSDL::SOAP::Address)

# File lib/wsdl/soap/address.rb, line 19
  def initialize
    super
    @location = nil
  end


parse_element (WSDL::SOAP::Address)

# File lib/wsdl/soap/address.rb, line 24
  def parse_element(element)
    nil
  end


parse_attr (WSDL::SOAP::Address)

# File lib/wsdl/soap/address.rb, line 28
  def parse_attr(attr, value)
    case attr
    when LocationAttrName
      @location = value.source
    else
      nil
    end
  end


new (WSDL::SOAP::Binding)

# File lib/wsdl/soap/binding.rb, line 20
  def initialize
    super
    @style = nil
    @transport = nil
  end


parse_element (WSDL::SOAP::Binding)

# File lib/wsdl/soap/binding.rb, line 26
  def parse_element(element)
    nil
  end


parse_attr (WSDL::SOAP::Binding)

# File lib/wsdl/soap/binding.rb, line 30
  def parse_attr(attr, value)
    case attr
    when StyleAttrName
      if ["document", "rpc"].include?(value.source)
        @style = value.source.intern
      else
        raise Parser::AttributeConstraintError.new(
          "Unexpected value #{ value }.")
      end
    when TransportAttrName
      @transport = value.source
    else
      nil
    end
  end


new (WSDL::SOAP::Body)

# File lib/wsdl/soap/body.rb, line 22
  def initialize
    super
    @parts = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
  end


parse_element (WSDL::SOAP::Body)

# File lib/wsdl/soap/body.rb, line 30
  def parse_element(element)
    nil
  end


parse_attr (WSDL::SOAP::Body)

# File lib/wsdl/soap/body.rb, line 34
  def parse_attr(attr, value)
    case attr
    when PartsAttrName
      @parts = value.source
    when UseAttrName
      if ['literal', 'encoded'].include?(value.source)
        @use = value.source.intern
      else
        raise RuntimeError.new("unknown use of soap:body: #{value.source}")
      end
    when EncodingStyleAttrName
      @encodingstyle = value.source
    when NamespaceAttrName
      @namespace = value.source
    else
      nil
    end
  end


new (WSDL::SOAP::CGIStubCreator)

# File lib/wsdl/soap/cgiStubCreator.rb, line 24
  def initialize(definitions)
    @definitions = definitions
  end


dump (WSDL::SOAP::CGIStubCreator)

# File lib/wsdl/soap/cgiStubCreator.rb, line 28
  def dump(service_name)
    warn("CGI stub can have only 1 port.  Creating stub for the first port...  Rests are ignored.")
    port = @definitions.service(service_name).ports[0]
    dump_porttype(port.porttype.name)
  end


new (WSDL::SOAP::ClassDefCreator)

# File lib/wsdl/soap/classDefCreator.rb, line 21
  def initialize(definitions)
    @elements = definitions.collect_elements
    @simpletypes = definitions.collect_simpletypes
    @complextypes = definitions.collect_complextypes
    @faulttypes = nil
    if definitions.respond_to?(:collect_faulttypes)
      @faulttypes = definitions.collect_faulttypes
    end
  end


dump (WSDL::SOAP::ClassDefCreator)

# File lib/wsdl/soap/classDefCreator.rb, line 31
  def dump(type = nil)
    result = "require 'xsd/qname'\n"
    if type
      result = dump_classdef(type.name, type)
    else
      str = dump_element
      unless str.empty?
        result << "\n" unless result.empty?
        result << str
      end
      str = dump_complextype
      unless str.empty?
        result << "\n" unless result.empty?
        result << str
      end
      str = dump_simpletype
      unless str.empty?
        result << "\n" unless result.empty?
        result << str
      end
    end
    result
  end


create_class_name (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 22
  def create_class_name(qname)
    if klass = basetype_mapped_class(qname)
      ::SOAP::Mapping::DefaultRegistry.find_mapped_obj_class(klass).name
    else
      safeconstname(qname.name)
    end
  end


basetype_mapped_class (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 30
  def basetype_mapped_class(name)
    ::SOAP::TypeMap[name]
  end


dump_method_signature (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 34
  def dump_method_signature(operation)
    name = operation.name.name
    input = operation.input
    output = operation.output
    fault = operation.fault
    signature = "#{ name }#{ dump_inputparam(input) }"
    str = "# SYNOPSIS\n#   \#{name}\#{dump_inputparam(input)}\n#\n# ARGS\n\#{dump_inout_type(input).chomp}\n#\n# RETURNS\n\#{dump_inout_type(output).chomp}\n#\n"
    unless fault.empty?
      faultstr = (fault.collect { |f| dump_inout_type(f).chomp }).join(', ')
      str <<"# RAISES\n#   \#{faultstr}\n#\n"
    end
    str
  end


dq (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 64
  def dq(ele)
    ele.dump
  end


ndq (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 68
  def ndq(ele)
    ele.nil? ? 'nil' : dq(ele)
  end


sym (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 72
  def sym(ele)
    ':' + ele
  end


dqname (WSDL::SOAP::ClassDefCreatorSupport)

# File lib/wsdl/soap/classDefCreatorSupport.rb, line 76
  def dqname(qname)
    qname.dump
  end


new (WSDL::SOAP::ClientSkeltonCreator)

# File lib/wsdl/soap/clientSkeltonCreator.rb, line 22
  def initialize(definitions)
    @definitions = definitions
  end


dump (WSDL::SOAP::ClientSkeltonCreator)

# File lib/wsdl/soap/clientSkeltonCreator.rb, line 26
  def dump(service_name)
    result = ""
    @definitions.service(service_name).ports.each do |port|
      result << dump_porttype(port.porttype.name)
      result << "\n"
    end
    result
  end


new (WSDL::SOAP::DriverCreator)

# File lib/wsdl/soap/driverCreator.rb, line 25
  def initialize(definitions)
    @definitions = definitions
  end


dump (WSDL::SOAP::DriverCreator)

# File lib/wsdl/soap/driverCreator.rb, line 29
  def dump(porttype = nil)
    if porttype.nil?
      result = ""
      @definitions.porttypes.each do |type|
        result << dump_porttype(type.name)
        result << "\n"
      end
    else
      result = dump_porttype(porttype)
    end
    result
  end


new (WSDL::SOAP::Fault)

# File lib/wsdl/soap/fault.rb, line 22
  def initialize
    super
    @name = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
  end


targetnamespace (WSDL::SOAP::Fault)

# File lib/wsdl/soap/fault.rb, line 30
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::SOAP::Fault)

# File lib/wsdl/soap/fault.rb, line 34
  def parse_element(element)
    nil
  end


parse_attr (WSDL::SOAP::Fault)

# File lib/wsdl/soap/fault.rb, line 38
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    when UseAttrName
      @use = value.source
    when EncodingStyleAttrName
      @encodingstyle = value.source
    when NamespaceAttrName
      @namespace = value.source
    else
      nil
    end
  end


new (WSDL::SOAP::Header)

# File lib/wsdl/soap/header.rb, line 25
  def initialize
    super
    @message = nil
    @part = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
    @headerfault = nil
  end


targetnamespace (WSDL::SOAP::Header)

# File lib/wsdl/soap/header.rb, line 35
  def targetnamespace
    parent.targetnamespace
  end


find_message (WSDL::SOAP::Header)

# File lib/wsdl/soap/header.rb, line 39
  def find_message
    root.message(@message) or raise RuntimeError.new("#{@message} not found")
  end


find_part (WSDL::SOAP::Header)

# File lib/wsdl/soap/header.rb, line 43
  def find_part
    find_message.parts.each do |part|
      if part.name == @part
        return part
      end
    end
    raise RuntimeError.new("#{@part} not found")
  end


parse_element (WSDL::SOAP::Header)

# File lib/wsdl/soap/header.rb, line 52
  def parse_element(element)
    case element
    when HeaderFaultName
      o = WSDL::SOAP::HeaderFault.new
      @headerfault = o
      o
    else
      nil
    end
  end


parse_attr (WSDL::SOAP::Header)

# File lib/wsdl/soap/header.rb, line 63
  def parse_attr(attr, value)
    case attr
    when MessageAttrName
      if value.namespace.nil?
        value = XSD::QName.new(targetnamespace, value.source)
      end
      @message = value
    when PartAttrName
      @part = value.source
    when UseAttrName
      @use = value.source
    when EncodingStyleAttrName
      @encodingstyle = value.source
    when NamespaceAttrName
      @namespace = value.source
    else
      nil
    end
  end


new (WSDL::SOAP::HeaderFault)

# File lib/wsdl/soap/headerfault.rb, line 23
  def initialize
    super
    @message = nil
    @part = nil
    @use = nil
    @encodingstyle = nil
    @namespace = nil
  end


parse_element (WSDL::SOAP::HeaderFault)

# File lib/wsdl/soap/headerfault.rb, line 32
  def parse_element(element)
    nil
  end


parse_attr (WSDL::SOAP::HeaderFault)

# File lib/wsdl/soap/headerfault.rb, line 36
  def parse_attr(attr, value)
    case attr
    when MessageAttrName
      @message = value
    when PartAttrName
      @part = value.source
    when UseAttrName
      @use = value.source
    when EncodingStyleAttrName
      @encodingstyle = value.source
    when NamespaceAttrName
      @namespace = value.source
    else
      nil
    end
  end


new (WSDL::SOAP::MappingRegistryCreator)

# File lib/wsdl/soap/mappingRegistryCreator.rb, line 22
  def initialize(definitions)
    @definitions = definitions
    @complextypes = @definitions.collect_complextypes
    @types = nil
  end


dump (WSDL::SOAP::MappingRegistryCreator)

# File lib/wsdl/soap/mappingRegistryCreator.rb, line 28
  def dump(types)
    @types = types
    map_cache = []
    map = ""
    @types.each do |type|
      if map_cache.index(type).nil?
        map_cache << type
        if type.namespace != XSD::Namespace
          if typemap = dump_typemap(type)
            map << typemap
          end
        end
      end
   end
    return map
  end


new (WSDL::SOAP::MethodDefCreator)

# File lib/wsdl/soap/methodDefCreator.rb, line 23
  def initialize(definitions)
    @definitions = definitions
    @simpletypes = @definitions.collect_simpletypes
    @complextypes = @definitions.collect_complextypes
    @elements = @definitions.collect_elements
    @types = []
  end


dump (WSDL::SOAP::MethodDefCreator)

# File lib/wsdl/soap/methodDefCreator.rb, line 31
  def dump(porttype)
    @types.clear
    result = ""
    operations = @definitions.porttype(porttype).operations
    binding = @definitions.porttype_binding(porttype)
    operations.each do |operation|
      op_bind = binding.operations[operation.name]
      next unless op_bind # no binding is defined
      next unless op_bind.soapoperation # not a SOAP operation binding
      result << ",\n" unless result.empty?
      result << dump_method(operation, op_bind).chomp
    end
    return result, @types
  end


collect_rpcparameter (WSDL::SOAP::MethodDefCreator)

# File lib/wsdl/soap/methodDefCreator.rb, line 46
  def collect_rpcparameter(operation)
    result = operation.inputparts.collect { |part|
      collect_type(part.type)
      param_set(::SOAP::RPC::SOAPMethod::IN, part.name, rpcdefinedtype(part))
    }
    outparts = operation.outputparts
    if outparts.size > 0
      retval = outparts[0]
      collect_type(retval.type)
      result << param_set(::SOAP::RPC::SOAPMethod::RETVAL, retval.name,
        rpcdefinedtype(retval))
      cdr(outparts).each { |part|
        collect_type(part.type)
        result << param_set(::SOAP::RPC::SOAPMethod::OUT, part.name,
          rpcdefinedtype(part))
      }
    end
    result
  end


collect_documentparameter (WSDL::SOAP::MethodDefCreator)

# File lib/wsdl/soap/methodDefCreator.rb, line 66
  def collect_documentparameter(operation)
    param = []
    operation.inputparts.each do |input|
      param << param_set(::SOAP::RPC::SOAPMethod::IN, input.name,
        documentdefinedtype(input), elementqualified(input))
    end
    operation.outputparts.each do |output|
      param << param_set(::SOAP::RPC::SOAPMethod::OUT, output.name,
        documentdefinedtype(output), elementqualified(output))
    end
    param
  end


new (WSDL::SOAP::Operation::OperationInfo)

# File lib/wsdl/soap/operation.rb, line 26
    def initialize(style, op_name, optype_name, headerparts, bodyparts, faultpart, soapaction)
      @style = style
      @op_name = op_name
      @optype_name = optype_name
      @headerparts = headerparts
      @bodyparts = bodyparts
      @faultpart = faultpart
      @soapaction = soapaction
    end


new (WSDL::SOAP::Operation)

# File lib/wsdl/soap/operation.rb, line 40
  def initialize
    super
    @soapaction = nil
    @style = nil
  end


parse_element (WSDL::SOAP::Operation)

# File lib/wsdl/soap/operation.rb, line 46
  def parse_element(element)
    nil
  end


parse_attr (WSDL::SOAP::Operation)

# File lib/wsdl/soap/operation.rb, line 50
  def parse_attr(attr, value)
    case attr
    when StyleAttrName
      if ["document", "rpc"].include?(value.source)
        @style = value.source.intern
      else
        raise Parser::AttributeConstraintError.new(
          "Unexpected value #{ value }.")
      end
    when SOAPActionAttrName
      @soapaction = value.source
    else
      nil
    end
  end


input_info (WSDL::SOAP::Operation)

# File lib/wsdl/soap/operation.rb, line 66
  def input_info
    name_info = parent.find_operation.input_info
    param_info(name_info, parent.input)
  end


output_info (WSDL::SOAP::Operation)

# File lib/wsdl/soap/operation.rb, line 71
  def output_info
    name_info = parent.find_operation.output_info
    param_info(name_info, parent.output)
  end


operation_style (WSDL::SOAP::Operation)

# File lib/wsdl/soap/operation.rb, line 76
  def operation_style
    return @style if @style
    if parent_binding.soapbinding
      return parent_binding.soapbinding.style
    end
    nil
  end


new (WSDL::SOAP::ServantSkeltonCreator)

# File lib/wsdl/soap/servantSkeltonCreator.rb, line 24
  def initialize(definitions)
    @definitions = definitions
  end


dump (WSDL::SOAP::ServantSkeltonCreator)

# File lib/wsdl/soap/servantSkeltonCreator.rb, line 28
  def dump(porttype = nil)
    if porttype.nil?
      result = ""
      @definitions.porttypes.each do |type|
        result << dump_porttype(type.name)
        result << "\n"
      end
    else
      result = dump_porttype(porttype)
    end
    result
  end


new (WSDL::SOAP::StandaloneServerStubCreator)

# File lib/wsdl/soap/standaloneServerStubCreator.rb, line 24
  def initialize(definitions)
    @definitions = definitions
  end


dump (WSDL::SOAP::StandaloneServerStubCreator)

# File lib/wsdl/soap/standaloneServerStubCreator.rb, line 28
  def dump(service_name)
    warn("- Standalone stub can have only 1 port for now.  So creating stub for the first port and rests are ignored.")
    warn("- Standalone server stub ignores port location defined in WSDL.  Location is http://localhost:10080/ by default.  Generated client from WSDL must be configured to point this endpoint manually.")
    port = @definitions.service(service_name).ports[0]
    dump_porttype(port.porttype.name)
  end


run (WSDL::SOAP::WSDL2Ruby)

# File lib/wsdl/soap/wsdl2ruby.rb, line 30
  def run
    unless @location
      raise RuntimeError, "WSDL location not given"
    end
    @wsdl = import(@location)
    @name = @wsdl.name ? @wsdl.name.name : 'default'
    create_file
  end


new (WSDL::SOAP::WSDL2Ruby)

# File lib/wsdl/soap/wsdl2ruby.rb, line 41
  def initialize
    @location = nil
    @opt = {}
    @logger = Logger.new(STDERR)
    @basedir = nil
    @wsdl = nil
    @name = nil
  end


new (WSDL::Types)

# File lib/wsdl/types.rb, line 18
  def initialize
    super
    @schemas = []
  end


parse_element (WSDL::Types)

# File lib/wsdl/types.rb, line 23
  def parse_element(element)
    case element
    when SchemaName
      o = XMLSchema::Schema.new
      @schemas << o
      o
    when DocumentationName
      o = Documentation.new
      o
    else
      nil
    end
  end


parse_attr (WSDL::Types)

# File lib/wsdl/types.rb, line 37
  def parse_attr(attr, value)
    nil
  end


new (WSDL::XMLSchema::All)

# File lib/wsdl/xmlSchema/all.rb, line 21
  def initialize
    super()
    @minoccurs = '1'
    @maxoccurs = '1'
    @elements = []
  end


targetnamespace (WSDL::XMLSchema::All)

# File lib/wsdl/xmlSchema/all.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


elementformdefault (WSDL::XMLSchema::All)

# File lib/wsdl/xmlSchema/all.rb, line 32
  def elementformdefault
    parent.elementformdefault
  end


<< (WSDL::XMLSchema::All)

# File lib/wsdl/xmlSchema/all.rb, line 36
  def <<(element)
    @elements << element
  end


parse_element (WSDL::XMLSchema::All)

# File lib/wsdl/xmlSchema/all.rb, line 40
  def parse_element(element)
    case element
    when AnyName
      o = Any.new
      @elements << o
      o
    when ElementName
      o = Element.new
      @elements << o
      o
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::All)

# File lib/wsdl/xmlSchema/all.rb, line 55
  def parse_attr(attr, value)
    case attr
    when MaxOccursAttrName
      @maxoccurs = value.source
    when MinOccursAttrName
      @minoccurs = value.source
    else
      nil
    end
  end


new (WSDL::XMLSchema::Annotation)

# File lib/wsdl/xmlSchema/annotation.rb, line 17
  def initialize
    super
  end


parse_element (WSDL::XMLSchema::Annotation)

# File lib/wsdl/xmlSchema/annotation.rb, line 21
  def parse_element(element)
    # Accepts any element.
    self
  end


parse_attr (WSDL::XMLSchema::Annotation)

# File lib/wsdl/xmlSchema/annotation.rb, line 26
  def parse_attr(attr, value)
    # Accepts any attribute.
    true
  end


new (WSDL::XMLSchema::Any)

# File lib/wsdl/xmlSchema/any.rb, line 22
  def initialize
    super()
    @maxoccurs = '1'
    @minoccurs = '1'
    @namespace = '##any'
    @process_contents = 'strict'
  end


targetnamespace (WSDL::XMLSchema::Any)

# File lib/wsdl/xmlSchema/any.rb, line 30
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::XMLSchema::Any)

# File lib/wsdl/xmlSchema/any.rb, line 34
  def parse_element(element)
    nil
  end


parse_attr (WSDL::XMLSchema::Any)

# File lib/wsdl/xmlSchema/any.rb, line 38
  def parse_attr(attr, value)
    case attr
    when MaxOccursAttrName
      @maxoccurs = value.source
    when MinOccursAttrName
      @minoccurs = value.source
    when NamespaceAttrName
      @namespace = value.source
    when ProcessContentsAttrName
      @process_contents = value.source
    else
      nil
    end
  end


attr_reader_ref (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 19
      def attr_reader_ref(symbol)
        name = symbol.to_s
        define_method(name) {
          instance_variable_get("@#{name}") ||
            (refelement ? refelement.__send__(name) : nil)
        }
      end


attr_reader_ref (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 27
      def attr_reader_ref(symbol)
        name = symbol.to_s
        module_eval "def \#{name}\n@\#{name} || (refelement ? refelement.\#{name} : nil)\nend\n"
      end


new (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 58
  def initialize
    super
    @use = nil
    @form = nil
    @name = nil
    @type = nil
    @local_simpletype = nil
    @default = nil
    @fixed = nil
    @ref = nil
    @refelement = nil
    @arytype = nil
  end


refelement (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 72
  def refelement
    @refelement ||= root.collect_attributes[@ref]
  end


targetnamespace (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 76
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 80
  def parse_element(element)
    case element
    when SimpleTypeName
      @local_simpletype = SimpleType.new
      @local_simpletype
    end
  end


parse_attr (WSDL::XMLSchema::Attribute)

# File lib/wsdl/xmlSchema/attribute.rb, line 88
  def parse_attr(attr, value)
    case attr
    when RefAttrName
      @ref = value
    when UseAttrName
      @use = value.source
    when FormAttrName
      @form = value.source
    when NameAttrName
      if directelement?
        @name = XSD::QName.new(targetnamespace, value.source)
      else
        @name = XSD::QName.new(nil, value.source)
      end
    when TypeAttrName
      @type = value
    when DefaultAttrName
      @default = value.source
    when FixedAttrName
      @fixed = value.source
    when ArrayTypeAttrName
      @arytype = if value.namespace.nil?
          XSD::QName.new(XSD::Namespace, value.source)
        else
          value
        end
    else
      nil
    end
  end


new (WSDL::XMLSchema::Choice)

# File lib/wsdl/xmlSchema/choice.rb, line 21
  def initialize
    super()
    @minoccurs = '1'
    @maxoccurs = '1'
    @elements = []
  end


targetnamespace (WSDL::XMLSchema::Choice)

# File lib/wsdl/xmlSchema/choice.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


elementformdefault (WSDL::XMLSchema::Choice)

# File lib/wsdl/xmlSchema/choice.rb, line 32
  def elementformdefault
    parent.elementformdefault
  end


<< (WSDL::XMLSchema::Choice)

# File lib/wsdl/xmlSchema/choice.rb, line 36
  def <<(element)
    @elements << element
  end


parse_element (WSDL::XMLSchema::Choice)

# File lib/wsdl/xmlSchema/choice.rb, line 40
  def parse_element(element)
    case element
    when AnyName
      o = Any.new
      @elements << o
      o
    when ElementName
      o = Element.new
      @elements << o
      o
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::Choice)

# File lib/wsdl/xmlSchema/choice.rb, line 55
  def parse_attr(attr, value)
    case attr
    when MaxOccursAttrName
      @maxoccurs = value.source
    when MinOccursAttrName
      @minoccurs = value.source
    else
      nil
    end
  end


new (WSDL::XMLSchema::ComplexContent)

# File lib/wsdl/xmlSchema/complexContent.rb, line 23
  def initialize
    super
    @base = nil
    @derivetype = nil
    @content = nil
    @attributes = XSD::NamedElements.new
    @basetype = nil
  end


targetnamespace (WSDL::XMLSchema::ComplexContent)

# File lib/wsdl/xmlSchema/complexContent.rb, line 32
  def targetnamespace
    parent.targetnamespace
  end


elementformdefault (WSDL::XMLSchema::ComplexContent)

# File lib/wsdl/xmlSchema/complexContent.rb, line 36
  def elementformdefault
    parent.elementformdefault
  end


basetype (WSDL::XMLSchema::ComplexContent)

# File lib/wsdl/xmlSchema/complexContent.rb, line 40
  def basetype
    @basetype ||= root.collect_complextypes[@base]
  end


parse_element (WSDL::XMLSchema::ComplexContent)

# File lib/wsdl/xmlSchema/complexContent.rb, line 44
  def parse_element(element)
    case element
    when RestrictionName, ExtensionName
      @derivetype = element.name
      self
    when AllName
      if @derivetype.nil?
        raise Parser::ElementConstraintError.new("base attr not found.")
      end
      @content = All.new
      @content
    when SequenceName
      if @derivetype.nil?
        raise Parser::ElementConstraintError.new("base attr not found.")
      end
      @content = Sequence.new
      @content
    when ChoiceName
      if @derivetype.nil?
        raise Parser::ElementConstraintError.new("base attr not found.")
      end
      @content = Choice.new
      @content
    when AttributeName
      if @derivetype.nil?
        raise Parser::ElementConstraintError.new("base attr not found.")
      end
      o = Attribute.new
      @attributes << o
      o
    end
  end


parse_attr (WSDL::XMLSchema::ComplexContent)

# File lib/wsdl/xmlSchema/complexContent.rb, line 77
  def parse_attr(attr, value)
    if @derivetype.nil?
      return nil
    end
    case attr
    when BaseAttrName
      @base = value
    else
      nil
    end
  end


new (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 28
  def initialize(name = nil)
    super()
    @name = name
    @complexcontent = nil
    @simplecontent = nil
    @content = nil
    @final = nil
    @mixed = false
    @attributes = XSD::NamedElements.new
  end


targetnamespace (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 39
  def targetnamespace
    # inner elements can be qualified
    # parent.is_a?(WSDL::XMLSchema::Element) ? nil : parent.targetnamespace
    parent.targetnamespace
  end


elementformdefault (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 45
  def elementformdefault
    parent.elementformdefault
  end


each_element (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 50
  def each_element
    if content
      content.elements.each do |element|
        if element.is_a?(Any)
          yield(AnyAsElement)
        else
          yield(element)
        end
      end
    end
  end


find_element (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 62
  def find_element(name)
    if content
      content.elements.each do |element|
        if element.is_a?(Any)
          return AnyAsElement if name == AnyAsElement.name
        else
          return element if name == element.name
        end
      end
    end
    nil
  end


find_element_by_name (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 75
  def find_element_by_name(name)
    if content
      content.elements.each do |element|
        if element.is_a?(Any)
          return AnyAsElement if name == AnyAsElement.name.name
        else
          return element if name == element.name.name
        end
      end
    end
    nil
  end


sequence_elements= (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 88
  def sequence_elements=(elements)
    @content = Sequence.new
    elements.each do |element|
      @content << element
    end
  end


all_elements= (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 95
  def all_elements=(elements)
    @content = All.new
    elements.each do |element|
      @content << element
    end
  end


parse_element (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 102
  def parse_element(element)
    case element
    when AllName
      @content = All.new
    when SequenceName
      @content = Sequence.new
    when ChoiceName
      @content = Choice.new
    when ComplexContentName
      @complexcontent = ComplexContent.new
    when SimpleContentName
      @simplecontent = SimpleContent.new
    when AttributeName
      o = Attribute.new
      @attributes << o
      o
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/xmlSchema/complexType.rb, line 123
  def parse_attr(attr, value)
    case attr
    when FinalAttrName
      @final = value.source
    when MixedAttrName
      @mixed = (value.source == 'true')
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    else
      nil
    end
  end


compoundtype (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/soap/complexType.rb, line 18
  def compoundtype
    @compoundtype ||= check_type
  end


check_type (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/soap/complexType.rb, line 22
  def check_type
    if content
      if attributes.empty? and
          content.elements.size == 1 and content.elements[0].maxoccurs != '1'
        if name == ::SOAP::Mapping::MapQName
          :TYPE_MAP
        else
          :TYPE_ARRAY
        end
      else
        :TYPE_STRUCT
      end
    elsif complexcontent
      if complexcontent.base == ::SOAP::ValueArrayName
        :TYPE_ARRAY
      else
        complexcontent.basetype.check_type
      end
    elsif simplecontent
      :TYPE_SIMPLE
    elsif !attributes.empty?
      :TYPE_STRUCT
    else # empty complexType definition (seen in partner.wsdl of salesforce)
      :TYPE_EMPTY
    end
  end


child_type (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/soap/complexType.rb, line 49
  def child_type(name = nil)
    case compoundtype
    when :TYPE_STRUCT
      if ele = find_element(name)
        ele.type
      elsif ele = find_element_by_name(name.name)
        ele.type
      end
    when :TYPE_ARRAY
      @contenttype ||= content_arytype
    when :TYPE_MAP
      item_ele = find_element_by_name("item") or
        raise RuntimeError.new("'item' element not found in Map definition.")
      content = item_ele.local_complextype or
        raise RuntimeError.new("No complexType definition for 'item'.")
      if ele = content.find_element(name)
        ele.type
      elsif ele = content.find_element_by_name(name.name)
        ele.type
      end
    else
      raise NotImplementedError.new("Unknown kind of complexType.")
    end
  end


child_defined_complextype (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/soap/complexType.rb, line 74
  def child_defined_complextype(name)
    ele = nil
    case compoundtype
    when :TYPE_STRUCT, :TYPE_MAP
      unless ele = find_element(name)
        if name.namespace.nil?
          ele = find_element_by_name(name.name)
        end
      end
    when :TYPE_ARRAY
      if content.elements.size == 1
        ele = content.elements[0]
      else
        raise RuntimeError.new("Assert: must not reach.")
      end
    else
      raise RuntimeError.new("Assert: Not implemented.")
    end
    unless ele
      raise RuntimeError.new("Cannot find #{name} as a children of #{@name}.")
    end
    ele.local_complextype
  end


find_arytype (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/soap/complexType.rb, line 98
  def find_arytype
    unless compoundtype == :TYPE_ARRAY
      raise RuntimeError.new("Assert: not for array")
    end
    if complexcontent
      complexcontent.attributes.each do |attribute|
        if attribute.ref == ::SOAP::AttrArrayTypeName
          return attribute.arytype
        end
      end
      if check_array_content(complexcontent.content)
        return element_simpletype(complexcontent.content.elements[0])
      end
    elsif check_array_content(content)
      return element_simpletype(content.elements[0])
    end
    raise RuntimeError.new("Assert: Unknown array definition.")
  end


find_aryelement (WSDL::XMLSchema::ComplexType)

# File lib/wsdl/soap/complexType.rb, line 117
  def find_aryelement
    unless compoundtype == :TYPE_ARRAY
      raise RuntimeError.new("Assert: not for array")
    end
    if complexcontent
      if check_array_content(complexcontent.content)
        return complexcontent.content.elements[0]
      end
    elsif check_array_content(content)
      return content.elements[0]
    end
    nil # use default item name
  end


new (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 23
  def initialize
    super()
    @final = nil
    @mixed = false
    @type = nil
    @contents = []
    @elements = []
  end


targetnamespace (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 32
  def targetnamespace
    parent.targetnamespace
  end


<< (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 36
  def <<(content)
    @contents << content
    update_elements
  end


each (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 41
  def each
    @contents.each do |content|
      yield content
    end
  end


parse_element (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 47
  def parse_element(element)
    case element
    when AllName, SequenceName, ChoiceName
      o = Content.new
      o.type = element.name
      @contents << o
      o
    when AnyName
      o = Any.new
      @contents << o
      o
    when ElementName
      o = Element.new
      @contents << o
      o
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 67
  def parse_attr(attr, value)
    case attr
    when FinalAttrName
      @final = value.source
    when MixedAttrName
      @mixed = (value.source == 'true')
    else
      nil
    end
  end


parse_epilogue (WSDL::XMLSchema::Content)

# File lib/wsdl/xmlSchema/content.rb, line 78
  def parse_epilogue
    update_elements
  end


attr_reader_ref (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 19
      def attr_reader_ref(symbol)
        name = symbol.to_s
        define_method(name) {
          instance_variable_get("@#{name}") ||
            (refelement ? refelement.__send__(name) : nil)
        }
      end


attr_reader_ref (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 27
      def attr_reader_ref(symbol)
        name = symbol.to_s
        module_eval "def \#{name}\n@\#{name} || (refelement ? refelement.\#{name} : nil)\nend\n"
      end


new (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 61
  def initialize(name = nil, type = nil)
    super()
    @name = name
    @form = nil
    @type = type
    @local_simpletype = @local_complextype = nil
    @constraint = nil
    @maxoccurs = '1'
    @minoccurs = '1'
    @nillable = nil
    @ref = nil
    @refelement = nil
  end


refelement (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 75
  def refelement
    @refelement ||= (@ref ? root.collect_elements[@ref] : nil)
  end


targetnamespace (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 79
  def targetnamespace
    parent.targetnamespace
  end


elementformdefault (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 83
  def elementformdefault
    parent.elementformdefault
  end


elementform (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 87
  def elementform
    self.form.nil? ? parent.elementformdefault : self.form
  end


parse_element (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 91
  def parse_element(element)
    case element
    when SimpleTypeName
      @local_simpletype = SimpleType.new
      @local_simpletype
    when ComplexTypeName
      @type = nil
      @local_complextype = ComplexType.new
      @local_complextype
    when UniqueName
      @constraint = Unique.new
      @constraint
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::Element)

# File lib/wsdl/xmlSchema/element.rb, line 108
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      # namespace may be nil
      if directelement? or elementform == 'qualified'
        @name = XSD::QName.new(targetnamespace, value.source)
      else
        @name = XSD::QName.new(nil, value.source)
      end
    when FormAttrName
      @form = value.source
    when TypeAttrName
      @type = value
    when RefAttrName
      @ref = value
    when MaxOccursAttrName
      if parent.is_a?(All)
        if value.source != '1'
          raise Parser::AttrConstraintError.new(
            "cannot parse #{value} for #{attr}")
        end
      end
      @maxoccurs = value.source
    when MinOccursAttrName
      if parent.is_a?(All)
        unless ['0', '1'].include?(value.source)
          raise Parser::AttrConstraintError.new(
            "cannot parse #{value} for #{attr}")
        end
      end
      @minoccurs = value.source
    when NillableAttrName
      @nillable = (value.source == 'true')
    else
      nil
    end
  end


map_as_array? (WSDL::XMLSchema::Element)

# File lib/wsdl/soap/element.rb, line 17
  def map_as_array?
    maxoccurs != '1'
  end


attributes (WSDL::XMLSchema::Element)

# File lib/wsdl/soap/element.rb, line 21
  def attributes
    @local_complextype.attributes
  end


new (WSDL::XMLSchema::Enumeration)

# File lib/wsdl/xmlSchema/enumeration.rb, line 17
  def initialize
    super
  end


parse_element (WSDL::XMLSchema::Enumeration)

# File lib/wsdl/xmlSchema/enumeration.rb, line 21
  def parse_element(element)
    nil
  end


parse_attr (WSDL::XMLSchema::Enumeration)

# File lib/wsdl/xmlSchema/enumeration.rb, line 25
  def parse_attr(attr, value)
    case attr
    when ValueAttrName
      parent.enumeration << value.source
      value.source
    end
  end


new (WSDL::XMLSchema::Import)

# File lib/wsdl/xmlSchema/import.rb, line 22
  def initialize
    super
    @namespace = nil
    @schemalocation = nil
    @content = nil
  end


parse_element (WSDL::XMLSchema::Import)

# File lib/wsdl/xmlSchema/import.rb, line 29
  def parse_element(element)
    nil
  end


parse_attr (WSDL::XMLSchema::Import)

# File lib/wsdl/xmlSchema/import.rb, line 33
  def parse_attr(attr, value)
    case attr
    when NamespaceAttrName
      @namespace = value.source
    when SchemaLocationAttrName
      @schemalocation = URI.parse(value.source)
      if @schemalocation.relative? and !parent.location.nil? and
          !parent.location.relative?
        @schemalocation = parent.location + @schemalocation
      end
      if root.importedschema.key?(@schemalocation)
        @content = root.importedschema[@schemalocation]
      else
        root.importedschema[@schemalocation] = nil      # placeholder
        @content = import(@schemalocation)
        root.importedschema[@schemalocation] = @content
      end
      @schemalocation
    else
      nil
    end
  end


import (WSDL::XMLSchema::Importer)

# File lib/wsdl/xmlSchema/importer.rb, line 18
  def self.import(location, originalroot = nil)
    new.import(location, originalroot)
  end


new (WSDL::XMLSchema::Importer)

# File lib/wsdl/xmlSchema/importer.rb, line 22
  def initialize
    @web_client = nil
  end


import (WSDL::XMLSchema::Importer)

# File lib/wsdl/xmlSchema/importer.rb, line 26
  def import(location, originalroot = nil)
    unless location.is_a?(URI)
      location = URI.parse(location)
    end
    content = parse(fetch(location), location, originalroot)
    content.location = location
    content
  end


new (WSDL::XMLSchema::Include)

# File lib/wsdl/xmlSchema/include.rb, line 21
  def initialize
    super
    @schemalocation = nil
    @content = nil
  end


parse_element (WSDL::XMLSchema::Include)

# File lib/wsdl/xmlSchema/include.rb, line 27
  def parse_element(element)
    nil
  end


parse_attr (WSDL::XMLSchema::Include)

# File lib/wsdl/xmlSchema/include.rb, line 31
  def parse_attr(attr, value)
    case attr
    when SchemaLocationAttrName
      @schemalocation = URI.parse(value.source)
      if @schemalocation.relative?
        @schemalocation = parent.location + @schemalocation
      end
      @content = import(@schemalocation)
      @schemalocation
    else
      nil
    end
  end


new (WSDL::XMLSchema::Length)

# File lib/wsdl/xmlSchema/length.rb, line 17
  def initialize
    super
  end


parse_element (WSDL::XMLSchema::Length)

# File lib/wsdl/xmlSchema/length.rb, line 21
  def parse_element(element)
    nil
  end


parse_attr (WSDL::XMLSchema::Length)

# File lib/wsdl/xmlSchema/length.rb, line 25
  def parse_attr(attr, value)
    case attr
    when ValueAttrName
      value.source
    end
  end


new (WSDL::XMLSchema::Parser::ParseFrame)

# File lib/wsdl/xmlSchema/parser.rb, line 41
    def initialize(ns, name, node)
      @ns = ns
      @name = name
      @node = node
    end


new (WSDL::XMLSchema::Parser)

# File lib/wsdl/xmlSchema/parser.rb, line 50
  def initialize(opt = {})
    @parser = XSD::XMLParser.create_parser(self, opt)
    @parsestack = nil
    @lastnode = nil
    @ignored = {}
    @location = opt[:location]
    @originalroot = opt[:originalroot]
  end


parse (WSDL::XMLSchema::Parser)

# File lib/wsdl/xmlSchema/parser.rb, line 59
  def parse(string_or_readable)
    @parsestack = []
    @lastnode = nil
    @textbuf = ''
    @parser.do_parse(string_or_readable)
    @lastnode
  end


charset (WSDL::XMLSchema::Parser)

# File lib/wsdl/xmlSchema/parser.rb, line 67
  def charset
    @parser.charset
  end


start_element (WSDL::XMLSchema::Parser)

# File lib/wsdl/xmlSchema/parser.rb, line 71
  def start_element(name, attrs)
    lastframe = @parsestack.last
    ns = parent = nil
    if lastframe
      ns = lastframe.ns.clone_ns
      parent = lastframe.node
    else
      ns = XSD::NS.new
      parent = nil
    end
    attrs = XSD::XMLParser.filter_ns(ns, attrs)
    node = decode_tag(ns, name, attrs, parent)
    @parsestack << ParseFrame.new(ns, name, node)
  end


characters (WSDL::XMLSchema::Parser)

# File lib/wsdl/xmlSchema/parser.rb, line 86
  def characters(text)
    lastframe = @parsestack.last
    if lastframe
      # Need not to be cloned because character does not have attr.
      ns = lastframe.ns
      decode_text(ns, text)
    else
      p text if $DEBUG
    end
  end


end_element (WSDL::XMLSchema::Parser)

# File lib/wsdl/xmlSchema/parser.rb, line 97
  def end_element(name)
    lastframe = @parsestack.pop
    unless name == lastframe.name
      raise UnexpectedElementError.new("closing element name '#{name}' does not match with opening element '#{lastframe.name}'")
    end
    decode_tag_end(lastframe.ns, lastframe.node)
    @lastnode = lastframe.node
  end


new (WSDL::XMLSchema::Pattern)

# File lib/wsdl/xmlSchema/pattern.rb, line 17
  def initialize
    super
  end


parse_element (WSDL::XMLSchema::Pattern)

# File lib/wsdl/xmlSchema/pattern.rb, line 21
  def parse_element(element)
    nil
  end


parse_attr (WSDL::XMLSchema::Pattern)

# File lib/wsdl/xmlSchema/pattern.rb, line 25
  def parse_attr(attr, value)
    case attr
    when ValueAttrName
      parent.pattern = /\A#{value.source}\z/n
      value.source
    end
  end


new (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 29
  def initialize
    super
    @targetnamespace = nil
    @complextypes = XSD::NamedElements.new
    @simpletypes = XSD::NamedElements.new
    @elements = XSD::NamedElements.new
    @attributes = XSD::NamedElements.new
    @imports = []
    @attributeformdefault = "unqualified"
    @elementformdefault = "unqualified"
    @importedschema = {}
    @location = nil
    @root = self
  end


location (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 44
  def location
    @location || (root.nil? ? nil : root.location)
  end


location= (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 48
  def location=(location)
    @location = location
  end


parse_element (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 52
  def parse_element(element)
    case element
    when ImportName
      o = Import.new
      @imports << o
      o
    when IncludeName
      o = Include.new
      @imports << o
      o
    when ComplexTypeName
      o = ComplexType.new
      @complextypes << o
      o
    when SimpleTypeName
      o = SimpleType.new
      @simpletypes << o
      o
    when ElementName
      o = Element.new
      @elements << o
      o
    when AttributeName
      o = Attribute.new
      @attributes << o
      o
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 83
  def parse_attr(attr, value)
    case attr
    when TargetNamespaceAttrName
      @targetnamespace = value.source
    when AttributeFormDefaultAttrName
      @attributeformdefault = value.source
    when ElementFormDefaultAttrName
      @elementformdefault = value.source
    else
      nil
    end
  end


collect_attributes (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 96
  def collect_attributes
    result = XSD::NamedElements.new
    result.concat(@attributes)
    @imports.each do |import|
      result.concat(import.content.collect_attributes) if import.content
    end
    result
  end


collect_elements (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 105
  def collect_elements
    result = XSD::NamedElements.new
    result.concat(@elements)
    @imports.each do |import|
      result.concat(import.content.collect_elements) if import.content
    end
    result
  end


collect_complextypes (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 114
  def collect_complextypes
    result = XSD::NamedElements.new
    result.concat(@complextypes)
    @imports.each do |import|
      result.concat(import.content.collect_complextypes) if import.content
    end
    result
  end


collect_simpletypes (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 123
  def collect_simpletypes
    result = XSD::NamedElements.new
    result.concat(@simpletypes)
    @imports.each do |import|
      result.concat(import.content.collect_simpletypes) if import.content
    end
    result
  end


parse_element (WSDL::XMLSchema::Schema)

# File lib/wsdl/xmlSchema/schema.rb, line 132
  def self.parse_element(element)
    if element == SchemaName
      Schema.new
    else
      nil
    end
  end


new (WSDL::XMLSchema::Sequence)

# File lib/wsdl/xmlSchema/sequence.rb, line 21
  def initialize
    super()
    @minoccurs = '1'
    @maxoccurs = '1'
    @elements = []
  end


targetnamespace (WSDL::XMLSchema::Sequence)

# File lib/wsdl/xmlSchema/sequence.rb, line 28
  def targetnamespace
    parent.targetnamespace
  end


elementformdefault (WSDL::XMLSchema::Sequence)

# File lib/wsdl/xmlSchema/sequence.rb, line 32
  def elementformdefault
    parent.elementformdefault
  end


<< (WSDL::XMLSchema::Sequence)

# File lib/wsdl/xmlSchema/sequence.rb, line 36
  def <<(element)
    @elements << element
  end


parse_element (WSDL::XMLSchema::Sequence)

# File lib/wsdl/xmlSchema/sequence.rb, line 40
  def parse_element(element)
    case element
    when AnyName
      o = Any.new
      @elements << o
      o
    when ElementName
      o = Element.new
      @elements << o
      o
    else
      nil
    end
  end


parse_attr (WSDL::XMLSchema::Sequence)

# File lib/wsdl/xmlSchema/sequence.rb, line 55
  def parse_attr(attr, value)
    case attr
    when MaxOccursAttrName
      @maxoccurs = value.source
    when MinOccursAttrName
      @minoccurs = value.source
    else
      nil
    end
  end


check_lexical_format (WSDL::XMLSchema::SimpleContent)

# File lib/wsdl/xmlSchema/simpleContent.rb, line 21
  def check_lexical_format(value)
    check(value)
  end


new (WSDL::XMLSchema::SimpleContent)

# File lib/wsdl/xmlSchema/simpleContent.rb, line 25
  def initialize
    super
    @restriction = nil
    @extension = nil
  end


base (WSDL::XMLSchema::SimpleContent)

# File lib/wsdl/xmlSchema/simpleContent.rb, line 31
  def base
    content.base
  end


targetnamespace (WSDL::XMLSchema::SimpleContent)

# File lib/wsdl/xmlSchema/simpleContent.rb, line 35
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::XMLSchema::SimpleContent)

# File lib/wsdl/xmlSchema/simpleContent.rb, line 39
  def parse_element(element)
    case element
    when RestrictionName
      @restriction = SimpleRestriction.new
      @restriction
    when ExtensionName
      @extension = SimpleExtension.new
      @extension
    end
  end


new (WSDL::XMLSchema::SimpleExtension)

# File lib/wsdl/xmlSchema/simpleExtension.rb, line 21
  def initialize
    super
    @base = nil
    @attributes = XSD::NamedElements.new
  end


targetnamespace (WSDL::XMLSchema::SimpleExtension)

# File lib/wsdl/xmlSchema/simpleExtension.rb, line 27
  def targetnamespace
    parent.targetnamespace
  end


valid? (WSDL::XMLSchema::SimpleExtension)

# File lib/wsdl/xmlSchema/simpleExtension.rb, line 31
  def valid?(value)
    true
  end


parse_element (WSDL::XMLSchema::SimpleExtension)

# File lib/wsdl/xmlSchema/simpleExtension.rb, line 35
  def parse_element(element)
    case element
    when AttributeName
      o = Attribute.new
      @attributes << o
      o
    end
  end


parse_attr (WSDL::XMLSchema::SimpleExtension)

# File lib/wsdl/xmlSchema/simpleExtension.rb, line 44
  def parse_attr(attr, value)
    case attr
    when BaseAttrName
      @base = value
    end
  end


new (WSDL::XMLSchema::SimpleRestriction)

# File lib/wsdl/xmlSchema/simpleRestriction.rb, line 23
  def initialize
    super
    @base = nil
    @enumeration = []   # NamedElements?
    @length = nil
    @pattern = nil
  end


valid? (WSDL::XMLSchema::SimpleRestriction)

# File lib/wsdl/xmlSchema/simpleRestriction.rb, line 31
  def valid?(value)
    return false unless check_restriction(value)
    return false unless check_length(value)
    return false unless check_pattern(value)
    true
  end


parse_element (WSDL::XMLSchema::SimpleRestriction)

# File lib/wsdl/xmlSchema/simpleRestriction.rb, line 38
  def parse_element(element)
    case element
    when EnumerationName
      Enumeration.new   # just a parsing handler
    when LengthName
      Length.new   # just a parsing handler
    when PatternName
      Pattern.new   # just a parsing handler
    end
  end


parse_attr (WSDL::XMLSchema::SimpleRestriction)

# File lib/wsdl/xmlSchema/simpleRestriction.rb, line 49
  def parse_attr(attr, value)
    case attr
    when BaseAttrName
      @base = value
    end
  end


check_lexical_format (WSDL::XMLSchema::SimpleType)

# File lib/wsdl/xmlSchema/simpleType.rb, line 21
  def check_lexical_format(value)
    if @restriction
      check_restriction(value)
    else
      raise ArgumentError.new("incomplete simpleType")
    end
  end


base (WSDL::XMLSchema::SimpleType)

# File lib/wsdl/xmlSchema/simpleType.rb, line 29
  def base
    if @restriction
      @restriction.base
    else
      raise ArgumentError.new("incomplete simpleType")
    end
  end


new (WSDL::XMLSchema::SimpleType)

# File lib/wsdl/xmlSchema/simpleType.rb, line 37
  def initialize(name = nil)
    super()
    @name = name
    @restriction = nil
  end


targetnamespace (WSDL::XMLSchema::SimpleType)

# File lib/wsdl/xmlSchema/simpleType.rb, line 43
  def targetnamespace
    parent.targetnamespace
  end


parse_element (WSDL::XMLSchema::SimpleType)

# File lib/wsdl/xmlSchema/simpleType.rb, line 47
  def parse_element(element)
    case element
    when RestrictionName
      @restriction = SimpleRestriction.new
      @restriction
    end
  end


parse_attr (WSDL::XMLSchema::SimpleType)

# File lib/wsdl/xmlSchema/simpleType.rb, line 55
  def parse_attr(attr, value)
    case attr
    when NameAttrName
      @name = XSD::QName.new(targetnamespace, value.source)
    end
  end


new (WSDL::XMLSchema::Unique)

# File lib/wsdl/xmlSchema/unique.rb, line 17
  def initialize
    super
  end


parse_element (WSDL::XMLSchema::Unique)

# File lib/wsdl/xmlSchema/unique.rb, line 21
  def parse_element(element)
    # Accepts any element.
    self
  end


parse_attr (WSDL::XMLSchema::Unique)

# File lib/wsdl/xmlSchema/unique.rb, line 26
  def parse_attr(attr, value)
    # Accepts any attribute.
    true
  end


run (WSDL::XMLSchema::XSD2Ruby)

# File lib/wsdl/xmlSchema/xsd2ruby.rb, line 24
  def run
    unless @location
      raise RuntimeError, "XML Schema location not given"
    end
    @xsd = import(@location)
    @name = create_classname(@xsd)
    create_file
  end


new (WSDL::XMLSchema::XSD2Ruby)

# File lib/wsdl/xmlSchema/xsd2ruby.rb, line 35
  def initialize
    @location = nil
    @opt = {}
    @logger = Logger.new(STDERR)
    @basedir = nil
    @xsd = nil
    @name = nil
  end


new (XMP::StringInputMethod)

# File lib/irb/xmp.rb, line 56
    def initialize
      super
      @exps = []
    end


eof? (XMP::StringInputMethod)

# File lib/irb/xmp.rb, line 61
    def eof?
      @exps.empty?
    end


gets (XMP::StringInputMethod)

# File lib/irb/xmp.rb, line 65
    def gets
      while l = @exps.shift
        next if /^\s+$/ =~ l
        l.concat "\n"
        print @prompt, l
        break
      end
      l
    end


puts (XMP::StringInputMethod)

# File lib/irb/xmp.rb, line 75
    def puts(exps)
      @exps.concat exps.split(/\n/)
    end


new (XMP)

# File lib/irb/xmp.rb, line 19
  def initialize(bind = nil)
    IRB.init_config(nil)
    #IRB.parse_opts
    #IRB.load_modules

    IRB.conf[:PROMPT_MODE] = :XMP

    bind = IRB::Frame.top(1) unless bind
    ws = IRB::WorkSpace.new(bind)
    @io = StringInputMethod.new
    @irb = IRB::Irb.new(ws, @io)
    @irb.context.ignore_sigint = false

#    IRB.conf[:IRB_RC].call(@irb.context) if IRB.conf[:IRB_RC]
    IRB.conf[:MAIN_CONTEXT] = @irb.context
  end


puts (XMP)

# File lib/irb/xmp.rb, line 36
  def puts(exps)
    @io.puts exps

    if @irb.context.ignore_sigint
      begin
        trap_proc_b = trap("SIGINT"){@irb.signal_handle}
        catch(:IRB_EXIT) do
          @irb.eval_input
        end
      ensure
        trap("SIGINT", trap_proc_b)
      end
    else
      catch(:IRB_EXIT) do
        @irb.eval_input
      end
    end
  end


init (XSD::Charset)

# File lib/xsd/charset.rb, line 26
  def Charset.init
    EncodingConvertMap[['UTF8', 'X_ISO8859_1']] =
      Proc.new { |str| str.unpack('U*').pack('C*') }
    EncodingConvertMap[['X_ISO8859_1', 'UTF8']] =
      Proc.new { |str| str.unpack('C*').pack('U*') }
    begin
      require 'xsd/iconvcharset'
      @internal_encoding = 'UTF8'
      sjtag = (/(mswin|bccwin|mingw|cygwin|emx)/ =~ RUBY_PLATFORM) ? 'cp932' :
        'shift_jis'
      EncodingConvertMap[['UTF8', 'EUC' ]] =
        Proc.new { |str| IconvCharset.safe_iconv("euc-jp", "utf-8", str) }
      EncodingConvertMap[['EUC' , 'UTF8']] =
        Proc.new { |str| IconvCharset.safe_iconv("utf-8", "euc-jp", str) }
      EncodingConvertMap[['EUC' , 'SJIS']] =
        Proc.new { |str| IconvCharset.safe_iconv(sjtag, "euc-jp", str) }
      EncodingConvertMap[['UTF8', 'SJIS']] =
        Proc.new { |str| IconvCharset.safe_iconv(sjtag, "utf-8", str) }
      EncodingConvertMap[['SJIS', 'UTF8']] =
        Proc.new { |str| IconvCharset.safe_iconv("utf-8", sjtag, str) }
      EncodingConvertMap[['SJIS', 'EUC' ]] =
        Proc.new { |str| IconvCharset.safe_iconv("euc-jp", sjtag, str) }
    rescue LoadError
      begin
        require 'nkf'
        EncodingConvertMap[['EUC' , 'SJIS']] =
          Proc.new { |str| NKF.nkf('-sXm0', str) }
        EncodingConvertMap[['SJIS', 'EUC' ]] =
          Proc.new { |str| NKF.nkf('-eXm0', str) }
      rescue LoadError
      end

      begin
        require 'uconv'
        @internal_encoding = 'UTF8'
        EncodingConvertMap[['UTF8', 'EUC' ]] = Uconv.method(:u8toeuc)
        EncodingConvertMap[['UTF8', 'SJIS']] = Uconv.method(:u8tosjis)
        EncodingConvertMap[['EUC' , 'UTF8']] = Uconv.method(:euctou8)
        EncodingConvertMap[['SJIS', 'UTF8']] = Uconv.method(:sjistou8)
      rescue LoadError
      end
    end
  end


encoding (XSD::Charset)

# File lib/xsd/charset.rb, line 84
  def Charset.encoding
    @internal_encoding
  end


encoding= (XSD::Charset)

# File lib/xsd/charset.rb, line 88
  def Charset.encoding=(encoding)
    warn("xsd charset is set to #{encoding}") if $DEBUG
    @internal_encoding = encoding
  end


xml_encoding_label (XSD::Charset)

# File lib/xsd/charset.rb, line 93
  def Charset.xml_encoding_label
    charset_label(@internal_encoding)
  end


encoding_to_xml (XSD::Charset)

# File lib/xsd/charset.rb, line 97
  def Charset.encoding_to_xml(str, charset)
    encoding_conv(str, @internal_encoding, charset_str(charset))
  end


encoding_from_xml (XSD::Charset)

# File lib/xsd/charset.rb, line 101
  def Charset.encoding_from_xml(str, charset)
    encoding_conv(str, charset_str(charset), @internal_encoding)
  end


encoding_conv (XSD::Charset)

# File lib/xsd/charset.rb, line 105
  def Charset.encoding_conv(str, enc_from, enc_to)
    if enc_from == enc_to or enc_from == 'NONE' or enc_to == 'NONE'
      str
    elsif converter = EncodingConvertMap[[enc_from, enc_to]]
      converter.call(str)
    else
      raise CharsetConversionError.new(
        "Converter not found: #{enc_from} -> #{enc_to}")
    end
  end


charset_label (XSD::Charset)

# File lib/xsd/charset.rb, line 116
  def Charset.charset_label(encoding)
    CharsetMap[encoding.upcase]
  end


charset_str (XSD::Charset)

# File lib/xsd/charset.rb, line 120
  def Charset.charset_str(label)
    if CharsetMap.respond_to?(:key)
      CharsetMap.key(label.downcase) || 'X_UNKNOWN'
    else
      CharsetMap.index(label.downcase) || 'X_UNKNOWN'
    end
  end


is_us_ascii (XSD::Charset)

# File lib/xsd/charset.rb, line 154
  def Charset.is_us_ascii(str)
    USASCIIRegexp =~ str
  end


is_utf8 (XSD::Charset)

# File lib/xsd/charset.rb, line 158
  def Charset.is_utf8(str)
    UTF8Regexp =~ str
  end


is_euc (XSD::Charset)

# File lib/xsd/charset.rb, line 162
  def Charset.is_euc(str)
    EUCRegexp =~ str
  end


is_sjis (XSD::Charset)

# File lib/xsd/charset.rb, line 166
  def Charset.is_sjis(str)
    SJISRegexp =~ str
  end


is_ces (XSD::Charset)

# File lib/xsd/charset.rb, line 170
  def Charset.is_ces(str, code = $KCODE)
    case code
    when 'NONE'
      is_us_ascii(str)
    when 'UTF8'
      is_utf8(str)
    when 'EUC'
      is_euc(str)
    when 'SJIS'
      is_sjis(str)
    else
      raise UnknownCharsetError.new("Unknown charset: #{code}")
    end
  end


new (XSD::CodeGen::ClassDef)

# File lib/xsd/codegen/classdef.rb, line 21
  def initialize(name, baseclass = nil)
    super(name)
    @baseclass = baseclass
    @classvar = []
    @attrdef = []
  end


def_classvar (XSD::CodeGen::ClassDef)

# File lib/xsd/codegen/classdef.rb, line 28
  def def_classvar(var, value)
    var = var.sub(/\A@@/, "")
    unless safevarname?(var)
      raise ArgumentError.new("#{var} seems to be unsafe")
    end
    @classvar << [var, value]
  end


def_attr (XSD::CodeGen::ClassDef)

# File lib/xsd/codegen/classdef.rb, line 36
  def def_attr(attrname, writable = true, varname = nil)
    unless safevarname?(varname || attrname)
      raise ArgumentError.new("#{varname || attrname} seems to be unsafe")
    end
    @attrdef << [attrname, writable, varname]
  end


dump (XSD::CodeGen::ClassDef)

# File lib/xsd/codegen/classdef.rb, line 43
  def dump
    buf = ""
    unless @requirepath.empty?
      buf << dump_requirepath
    end
    buf << dump_emptyline unless buf.empty?
    package = @name.split(/::/)[0..-2]
    buf << dump_package_def(package) unless package.empty?
    buf << dump_comment if @comment
    buf << dump_class_def
    spacer = false
    unless @classvar.empty?
      spacer = true
      buf << dump_classvar
    end
    unless @const.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_const
    end
    unless @code.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_code
    end
    unless @attrdef.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_attributes
    end
    unless @methoddef.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_methods
    end
    buf << dump_class_def_end
    buf << dump_package_def_end(package) unless package.empty?
    buf.gsub(/^\s+$/, '')
  end


capitalize (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 58
  def capitalize(target)
    target.sub(/^([a-z])/) { $1.tr!('[a-z]', '[A-Z]') }
  end


uncapitalize (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 63
  def uncapitalize(target)
    target.sub(/^([A-Z])/) { $1.tr!('[A-Z]', '[a-z]') }
  end


safeconstname (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 68
  def safeconstname(name)
    safename = name.scan(/[a-zA-Z0-9_]+/).collect { |ele|
      GenSupport.capitalize(ele)
    }.join
    if /^[A-Z]/ !~ safename or keyword?(safename)
      safename = "C_#{safename}"
    end
    safename
  end


safeconstname? (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 79
  def safeconstname?(name)
    /\A[A-Z][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name)
  end


safemethodname (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 84
  def safemethodname(name)
    safename = name.scan(/[a-zA-Z0-9_]+/).join('_')
    safename = uncapitalize(safename)
    if /^[a-z]/ !~ safename
      safename = "m_#{safename}"
    end
    safename
  end


safemethodname? (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 94
  def safemethodname?(name)
    /\A[a-zA-Z_][a-zA-Z0-9_]*[=!?]?\z/ =~ name
  end


safevarname (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 99
  def safevarname(name)
    safename = uncapitalize(name.scan(/[a-zA-Z0-9_]+/).join('_'))
    if /^[a-z]/ !~ safename or keyword?(safename)
      "v_#{safename}"
    else
      safename
    end
  end


safevarname? (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 109
  def safevarname?(name)
    /\A[a-z_][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name)
  end


keyword? (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 114
  def keyword?(word)
    KEYWORD.key?(word)
  end


format (XSD::CodeGen::GenSupport)

# File lib/xsd/codegen/gensupport.rb, line 119
  def format(str, indent = nil)
    str = trim_eol(str)
    str = trim_indent(str)
    if indent
      str.gsub(/^/, " " * indent)
    else
      str
    end
  end


new (XSD::CodeGen::MethodDef)

# File lib/xsd/codegen/methoddef.rb, line 23
  def initialize(name, *params)
    unless safemethodname?(name)
      raise ArgumentError.new("name '#{name}' seems to be unsafe")
    end
    @name = name
    @params = params
    @comment = nil
    @definition = yield if block_given?
  end


dump (XSD::CodeGen::MethodDef)

# File lib/xsd/codegen/methoddef.rb, line 33
  def dump
    buf = ""
    buf << dump_comment if @comment
    buf << dump_method_def
    buf << dump_definition if @definition and !@definition.empty?
    buf << dump_method_def_end
    buf
  end


new (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 22
  def initialize(name)
    @name = name
    @comment = nil
    @const = []
    @code = []
    @requirepath = []
    @methoddef = []
  end


def_require (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 31
  def def_require(path)
    @requirepath << path
  end


def_const (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 35
  def def_const(const, value)
    unless safeconstname?(const)
      raise ArgumentError.new("#{const} seems to be unsafe")
    end
    @const << [const, value]
  end


def_code (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 42
  def def_code(code)
    @code << code
  end


def_method (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 46
  def def_method(name, *params)
    add_method(MethodDef.new(name, *params) { yield if block_given? }, :public)
  end


def_protectedmethod (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 51
  def def_protectedmethod(name, *params)
    add_method(MethodDef.new(name, *params) { yield if block_given? },
      :protected)
  end


def_privatemethod (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 56
  def def_privatemethod(name, *params)
    add_method(MethodDef.new(name, *params) { yield if block_given? }, :private)
  end


add_method (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 60
  def add_method(m, visibility = :public)
    @methoddef << [visibility, m]
  end


dump (XSD::CodeGen::ModuleDef)

# File lib/xsd/codegen/moduledef.rb, line 64
  def dump
    buf = ""
    unless @requirepath.empty?
      buf << dump_requirepath
    end
    buf << dump_emptyline unless buf.empty?
    package = @name.split(/::/)[0..-2]
    buf << dump_package_def(package) unless package.empty?
    buf << dump_comment if @comment
    buf << dump_module_def
    spacer = false
    unless @const.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_const
    end
    unless @code.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_code
    end
    unless @methoddef.empty?
      buf << dump_emptyline if spacer
      spacer = true
      buf << dump_methods
    end
    buf << dump_module_def_end
    buf << dump_package_def_end(package) unless package.empty?
    buf.gsub(/^\s+$/, '')
  end


safe_iconv (XSD::IconvCharset)

# File lib/xsd/iconvcharset.rb, line 16
  def self.safe_iconv(to, from, str)
    iconv = Iconv.new(to, from)
    out = ""
    begin
      out << iconv.iconv(str)
    rescue Iconv::IllegalSequence => e
      out << e.success
      ch, str = e.failed.split(//, 2)
      out << '?'
      warn("Failed to convert #{ch}")
      retry
    end
    return out
  end


obj2xml (XSD::Mapping)

# File lib/xsd/mapping.rb, line 23
  def self.obj2xml(obj, elename = nil, io = nil)
    if !elename.nil? and !elename.is_a?(XSD::QName)
      elename = XSD::QName.new(nil, elename)
    end
    elename ||= XSD::QName.new(nil, SOAP::Mapping.name2elename(obj.class.to_s))
    soap = SOAP::Mapping.obj2soap(obj, MappingRegistry)
    soap.elename = elename
    generator = SOAP::SOAPGenerator.new(MappingOpt)
    generator.generate(soap, io)
  end


xml2obj (XSD::Mapping)

# File lib/xsd/mapping.rb, line 34
  def self.xml2obj(stream)
    parser = SOAP::Parser.new(MappingOpt)
    soap = parser.parse(stream)
    SOAP::Mapping.soap2obj(soap, MappingRegistry)
  end


new (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 15
  def initialize
    @elements = []
    @cache = {}
  end


dup (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 20
  def dup
    o = NamedElements.new
    o.elements = @elements.dup
    o
  end


freeze (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 26
  def freeze
    super
    @elements.freeze
    self
  end


empty? (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 32
  def empty?
    size == 0
  end


size (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 36
  def size
    @elements.size
  end


[] (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 40
  def [](idx)
    if idx.is_a?(Numeric)
      @elements[idx]
    else
      @cache[idx] ||= @elements.find { |item| item.name == idx }
    end
  end


find_name (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 48
  def find_name(name)
    @elements.find { |item| item.name.name == name }
  end


keys (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 52
  def keys
    collect { |element| element.name }
  end


each (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 56
  def each
    @elements.each do |element|
      yield(element)
    end
  end


<< (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 62
  def <<(rhs)
    @elements << rhs
    self
  end


delete (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 67
  def delete(rhs)
    @elements.delete(rhs)
  end


+ (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 71
  def +(rhs)
    o = NamedElements.new
    o.elements = @elements + rhs.elements
    o
  end


concat (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 77
  def concat(rhs)
    @elements.concat(rhs.elements)
    self
  end


elements= (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 86
  def elements=(rhs)
    @elements = rhs
  end


elements (XSD::NamedElements)

# File lib/xsd/namedelements.rb, line 90
  def elements
    @elements
  end


new (XSD::NS::Assigner)

# File lib/xsd/ns.rb, line 17
    def initialize
      @count = 0
    end


assign (XSD::NS::Assigner)

# File lib/xsd/ns.rb, line 21
    def assign(ns)
      @count += 1
      "n#{@count}"
    end


new (XSD::NS)

# File lib/xsd/ns.rb, line 33
  def initialize(tag2ns = {})
    @tag2ns = tag2ns
    @assigner = nil
    @ns2tag = {}
    @tag2ns.each do |tag, ns|
      @ns2tag[ns] = tag
    end
    @default_namespace = nil
  end


assign (XSD::NS)

# File lib/xsd/ns.rb, line 43
  def assign(ns, tag = nil)
    if (tag == '')
      @default_namespace = ns
      tag
    else
      @assigner ||= Assigner.new
      tag ||= @assigner.assign(ns)
      @ns2tag[ns] = tag
      @tag2ns[tag] = ns
      tag
    end
  end


assigned? (XSD::NS)

# File lib/xsd/ns.rb, line 56
  def assigned?(ns)
    @default_namespace == ns or @ns2tag.key?(ns)
  end


assigned_tag? (XSD::NS)

# File lib/xsd/ns.rb, line 60
  def assigned_tag?(tag)
    @tag2ns.key?(tag)
  end


clone_ns (XSD::NS)

# File lib/xsd/ns.rb, line 64
  def clone_ns
    cloned = NS.new(@tag2ns.dup)
    cloned.assigner = @assigner
    cloned.assign(@default_namespace, '') if @default_namespace
    cloned
  end


name (XSD::NS)

# File lib/xsd/ns.rb, line 71
  def name(name)
    if (name.namespace == @default_namespace)
      name.name
    elsif @ns2tag.key?(name.namespace)
      "#{@ns2tag[name.namespace]}:#{name.name}"
    else
      raise FormatError.new("namespace: #{name.namespace} not defined yet")
    end
  end


compare (XSD::NS)

# File lib/xsd/ns.rb, line 81
  def compare(ns, name, rhs)
    if (ns == @default_namespace)
      return true if (name == rhs)
    end
    @tag2ns.each do |assigned_tag, assigned_ns|
      if assigned_ns == ns && "#{assigned_tag}:#{name}" == rhs
        return true
      end
    end
    false
  end


parse (XSD::NS)

# File lib/xsd/ns.rb, line 96
  def parse(str, local = false)
    if ParseRegexp =~ str
      if (name = $2) and (ns = @tag2ns[$1])
        return XSD::QName.new(ns, name)
      end
    end
    XSD::QName.new(local ? nil : @default_namespace, str)
  end


parse_local (XSD::NS)

# File lib/xsd/ns.rb, line 109
  def parse_local(elem)
    ParseRegexp =~ elem
    if $2
      ns = @tag2ns[$1]
      name = $2
      if !ns
        raise FormatError.new("unknown namespace qualifier: #{$1}")
      end
    elsif $1
      ns = nil
      name = $1
    else
      raise FormatError.new("illegal element format: #{elem}")
    end
    XSD::QName.new(ns, name)
  end


each_ns (XSD::NS)

# File lib/xsd/ns.rb, line 126
  def each_ns
    @ns2tag.each do |ns, tag|
      yield(ns, tag)
    end
  end


assigner= (XSD::NS)

# File lib/xsd/ns.rb, line 134
  def assigner=(assigner)
    @assigner = assigner
  end


inherited (XSD::NSDBase)

# File lib/xsd/datatypes.rb, line 92
  def self.inherited(klass)
    @@types << klass
  end


types (XSD::NSDBase)

# File lib/xsd/datatypes.rb, line 96
  def self.types
    @@types
  end


new (XSD::NSDBase)

# File lib/xsd/datatypes.rb, line 100
  def initialize
  end


init (XSD::NSDBase)

# File lib/xsd/datatypes.rb, line 103
  def init(type)
    @type = type
  end


new (XSD::QName)

# File lib/xsd/qname.rb, line 17
  def initialize(namespace = nil, name = nil)
    @namespace = namespace
    @name = name
    @source = nil
  end


dup_name (XSD::QName)

# File lib/xsd/qname.rb, line 23
  def dup_name(name)
    XSD::QName.new(@namespace, name)
  end


dump (XSD::QName)

# File lib/xsd/qname.rb, line 27
  def dump
    ns = @namespace.nil? ? 'nil' : @namespace.dump
    name = @name.nil? ? 'nil' : @name.dump
    "XSD::QName.new(#{ns}, #{name})"
  end


match (XSD::QName)

# File lib/xsd/qname.rb, line 33
  def match(rhs)
    if rhs.namespace and (rhs.namespace != @namespace)
      return false
    end
    if rhs.name and (rhs.name != @name)
      return false
    end
    true
  end


== (XSD::QName)

# File lib/xsd/qname.rb, line 43
  def ==(rhs)
    !rhs.nil? and @namespace == rhs.namespace and @name == rhs.name
  end


=== (XSD::QName)

# File lib/xsd/qname.rb, line 47
  def ===(rhs)
    (self == rhs)
  end


eql? (XSD::QName)

# File lib/xsd/qname.rb, line 51
  def eql?(rhs)
    (self == rhs)
  end


hash (XSD::QName)

# File lib/xsd/qname.rb, line 55
  def hash
    @namespace.hash ^ @name.hash
  end


to_s (XSD::QName)

# File lib/xsd/qname.rb, line 59
  def to_s
    "{#{ namespace }}#{ name }"
  end


inspect (XSD::QName)

# File lib/xsd/qname.rb, line 63
  def inspect
    sprintf("#<%s:0x%x %s>", self.class.name, __id__,
      "{#{ namespace }}#{ name }")
  end


parse (XSD::QName)

# File lib/xsd/qname.rb, line 69
  def parse(str)
    NormalizedNameRegexp =~ str
    self.new($1, $2)
  end


factory (XSD::XMLParser::Parser)

# File lib/xsd/xmlparser/parser.rb, line 28
  def self.factory
    @@parser_factory
  end


create_parser (XSD::XMLParser::Parser)

# File lib/xsd/xmlparser/parser.rb, line 32
  def self.create_parser(host, opt = {})
    @@parser_factory.new(host, opt)
  end


add_factory (XSD::XMLParser::Parser)

# File lib/xsd/xmlparser/parser.rb, line 36
  def self.add_factory(factory)
    if $DEBUG
      puts "Set #{ factory } as XML processor."
    end
    @@parser_factory = factory
  end


new (XSD::XMLParser::Parser)

# File lib/xsd/xmlparser/parser.rb, line 47
  def initialize(host, opt = {})
    @host = host
    @charset = opt[:charset] || nil
  end


parse (XSD::XMLParser::Parser)

# File lib/xsd/xmlparser/parser.rb, line 52
  def parse(string_or_readable)
    @textbuf = ''
    prologue
    do_parse(string_or_readable)
    epilogue
  end


do_parse (XSD::XMLParser::REXMLParser)

# File lib/xsd/xmlparser/rexmlparser.rb, line 21
  def do_parse(string_or_readable)
    source = nil
    source = REXML::SourceFactory.create_from(string_or_readable)
    source.encoding = charset if charset
    # Listener passes a String in utf-8.
    @charset = 'utf-8'
    REXML::Document.parse_stream(source, self)
  end


epilogue (XSD::XMLParser::REXMLParser)

# File lib/xsd/xmlparser/rexmlparser.rb, line 30
  def epilogue
  end


tag_start (XSD::XMLParser::REXMLParser)

# File lib/xsd/xmlparser/rexmlparser.rb, line 33
  def tag_start(name, attrs)
    start_element(name, attrs)
  end


tag_end (XSD::XMLParser::REXMLParser)

# File lib/xsd/xmlparser/rexmlparser.rb, line 37
  def tag_end(name)
    end_element(name)
  end


text (XSD::XMLParser::REXMLParser)

# File lib/xsd/xmlparser/rexmlparser.rb, line 41
  def text(text)
    characters(text)
  end


xmldecl (XSD::XMLParser::REXMLParser)

# File lib/xsd/xmlparser/rexmlparser.rb, line 45
  def xmldecl(version, encoding, standalone)
    # Version should be checked.
  end


do_parse (XSD::XMLParser::XMLParser)

# File lib/xsd/xmlparser/xmlparser.rb, line 27
  def do_parse(string_or_readable)
    # XMLParser passes a String in utf-8.
    @charset = 'utf-8'
    @parser = Listener.new
    @parser.parse(string_or_readable) do |type, name, data|
      case type
      when XML::Parser::START_ELEM
        start_element(name, data)
      when XML::Parser::END_ELEM
        end_element(name)
      when XML::Parser::CDATA
        characters(data)
      else
        raise FormatDecodeError.new("Unexpected XML: #{ type }/#{ name }/#{ data }.")
      end
    end
  end


do_parse (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 20
  def do_parse(string_or_readable)
    @attrs = {}
    @curattr = nil
    @scanner = XMLScan::XMLScanner.new(self)
    @scanner.kcode = XSD::Charset.charset_str(charset) if charset
    @scanner.parse(string_or_readable)
  end


scanner_kcode= (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 28
  def scanner_kcode=(charset)
    @scanner.kcode = XSD::Charset.charset_str(charset) if charset
    self.xmldecl_encoding = charset
  end


parse_error (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 41
  def parse_error(msg)
    raise ParseError.new(msg)
  end


wellformed_error (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 45
  def wellformed_error(msg)
    raise NotWellFormedError.new(msg)
  end


valid_error (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 49
  def valid_error(msg)
    raise NotValidError.new(msg)
  end


warning (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 53
  def warning(msg)
    p msg if $DEBUG
  end


on_xmldecl_version (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 59
  def on_xmldecl_version(str)
    # 1.0 expected.
  end


on_xmldecl_encoding (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 63
  def on_xmldecl_encoding(str)
    self.scanner_kcode = str
  end


on_chardata (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 81
  def on_chardata(str)
    characters(str)
  end


on_etag (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 87
  def on_etag(name)
    end_element(name)
  end


on_entityref (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 91
  def on_entityref(ref)
    characters(ENTITY_REF_MAP[ref])
  end


on_charref (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 95
  def on_charref(code)
    characters([code].pack('U'))
  end


on_charref_hex (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 99
  def on_charref_hex(code)
    on_charref(code)
  end


on_stag (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 107
  def on_stag(name)
    @attrs = {}
  end


on_attribute (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 111
  def on_attribute(name)
    @attrs[name] = @curattr = ''
  end


on_attr_value (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 115
  def on_attr_value(str)
    @curattr << str
  end


on_attr_entityref (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 119
  def on_attr_entityref(ref)
    @curattr << ENTITY_REF_MAP[ref]
  end


on_attr_charref (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 123
  def on_attr_charref(code)
    @curattr << [code].pack('U')
  end


on_attr_charref_hex (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 127
  def on_attr_charref_hex(code)
    on_attr_charref(code)
  end


on_stag_end_empty (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 133
  def on_stag_end_empty(name)
    on_stag_end(name)
    on_etag(name)
  end


on_stag_end (XSD::XMLParser::XMLScanner)

# File lib/xsd/xmlparser/xmlscanner.rb, line 138
  def on_stag_end(name)
    start_element(name, @attrs)
  end


create_parser (XSD::XMLParser)

# File lib/xsd/xmlparser.rb, line 16
  def create_parser(host, opt)
    XSD::XMLParser::Parser.create_parser(host, opt)
  end


filter_ns (XSD::XMLParser)

# File lib/xsd/xmlparser.rb, line 24
  def filter_ns(ns, attrs)
    return attrs if attrs.nil? or attrs.empty?
    newattrs = {}
    attrs.each do |key, value|
      if (NSParseRegexp =~ key)
        # '' means 'default namespace'.
        tag = $1 || ''
        ns.assign(value, tag)
      else
        newattrs[key] = value
      end
    end
    newattrs
  end


new (XSD::XSDAnySimpleType)

# File lib/xsd/datatypes.rb, line 121
  def initialize(value = nil)
    init(Type, value)
  end


check_lexical_format (XSD::XSDAnySimpleType)

# File lib/xsd/datatypes.rb, line 126
  def check_lexical_format(value)
    screen_data(value)
    true
  end


set (XSD::XSDAnySimpleType)

# File lib/xsd/datatypes.rb, line 133
  def set(value)
    if value.nil?
      @is_nil = true
      @data = nil
      _set(nil)
    else
      @is_nil = false
      _set(screen_data(value))
    end
  end


to_s (XSD::XSDAnySimpleType)

# File lib/xsd/datatypes.rb, line 145
  def to_s()
    if @is_nil
      ""
    else
      _to_s
    end
  end


new (XSD::XSDAnyURI)

# File lib/xsd/datatypes.rb, line 929
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDBase64Binary)

# File lib/xsd/datatypes.rb, line 903
  def initialize(value = nil)
    init(Type, value)
  end


set_encoded (XSD::XSDBase64Binary)

# File lib/xsd/datatypes.rb, line 907
  def set_encoded(value)
    if /^[A-Za-z0-9+\/=]*$/ !~ value
      raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.")
    end
    @data = String.new(value).strip
    @is_nil = false
  end


string (XSD::XSDBase64Binary)

# File lib/xsd/datatypes.rb, line 915
  def string
    @data.unpack("m")[0]
  end


new (XSD::XSDBoolean)

# File lib/xsd/datatypes.rb, line 207
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDByte)

# File lib/xsd/datatypes.rb, line 1145
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDDate)

# File lib/xsd/datatypes.rb, line 704
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDDateTime)

# File lib/xsd/datatypes.rb, line 591
  def initialize(value = nil)
    init(Type, value)
  end


to_obj (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 498
  def to_obj(klass)
    if klass == Time
      to_time
    elsif klass == Date
      to_date
    elsif klass == DateTime
      to_datetime
    else
      nil
    end
  end


to_time (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 510
  def to_time
    begin
      if @data.offset * SecInDay == Time.now.utc_offset
        d = @data
        usec = (d.sec_fraction * SecInDay * 1000000).round
        Time.local(d.year, d.month, d.mday, d.hour, d.min, d.sec, usec)
      else
        d = @data.newof
        usec = (d.sec_fraction * SecInDay * 1000000).round
        Time.gm(d.year, d.month, d.mday, d.hour, d.min, d.sec, usec)
      end
    rescue ArgumentError
      nil
    end
  end


to_date (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 526
  def to_date
    Date.new0(@data.class.jd_to_ajd(@data.jd, 0, 0), 0, @data.start)
  end


to_datetime (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 530
  def to_datetime
    data
  end


tz2of (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 534
  def tz2of(str)
    /^(?:Z|(?:([+\-])(\d\d):(\d\d))?)$/ =~ str
    sign = $1
    hour = $2.to_i
    min = $3.to_i

    of = case sign
      when '+'
        of = +(hour.to_r * 60 + min) / 1440    # 24 * 60
      when '-'
        of = -(hour.to_r * 60 + min) / 1440    # 24 * 60
      else
        0
      end
    of
  end


of2tz (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 551
  def of2tz(offset)
    diffmin = offset * 24 * 60
    if diffmin.zero?
      'Z'
    else
      ((diffmin < 0) ? '-' : '+') << format('%02d:%02d',
        (diffmin.abs / 60.0).to_i, (diffmin.abs % 60.0).to_i)
    end
  end


screen_data (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 561
  def screen_data(t)
    # convert t to a DateTime as an internal representation.
    if t.respond_to?(:to_datetime)      # 1.9 or later
      t.to_datetime
    elsif t.is_a?(DateTime)
      t
    elsif t.is_a?(Date)
      t = screen_data_str(t)
      t <<= 12 if t.year < 0
      t
    elsif t.is_a?(Time)
      jd = DateTime.civil_to_jd(t.year, t.mon, t.mday, DateTime::ITALY)
      fr = DateTime.time_to_day_fraction(t.hour, t.min, [t.sec, 59].min) +
        t.usec.to_r / 1000000 / SecInDay
      of = t.utc_offset.to_r / SecInDay
      DateTime.new0(DateTime.jd_to_ajd(jd, fr, of), of, DateTime::ITALY)
    else
      screen_data_str(t)
    end
  end


add_tz (XSD::XSDDateTimeImpl)

# File lib/xsd/datatypes.rb, line 582
  def add_tz(s)
    s + of2tz(@data.offset)
  end


new (XSD::XSDDecimal)

# File lib/xsd/datatypes.rb, line 232
  def initialize(value = nil)
    init(Type, value)
  end


nonzero? (XSD::XSDDecimal)

# File lib/xsd/datatypes.rb, line 236
  def nonzero?
    (@number != '0')
  end


new (XSD::XSDDouble)

# File lib/xsd/datatypes.rb, line 372
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDDuration)

# File lib/xsd/datatypes.rb, line 433
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDFloat)

# File lib/xsd/datatypes.rb, line 306
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDGDay)

# File lib/xsd/datatypes.rb, line 824
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDGMonth)

# File lib/xsd/datatypes.rb, line 850
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDGMonthDay)

# File lib/xsd/datatypes.rb, line 797
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDGYear)

# File lib/xsd/datatypes.rb, line 767
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDGYearMonth)

# File lib/xsd/datatypes.rb, line 736
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDHexBinary)

# File lib/xsd/datatypes.rb, line 876
  def initialize(value = nil)
    init(Type, value)
  end


set_encoded (XSD::XSDHexBinary)

# File lib/xsd/datatypes.rb, line 880
  def set_encoded(value)
    if /^[0-9a-fA-F]*$/ !~ value
      raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.")
    end
    @data = String.new(value).strip
    @is_nil = false
  end


string (XSD::XSDHexBinary)

# File lib/xsd/datatypes.rb, line 888
  def string
    [@data].pack("H*")
  end


new (XSD::XSDInt)

# File lib/xsd/datatypes.rb, line 1109
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDInteger)

# File lib/xsd/datatypes.rb, line 1006
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDLong)

# File lib/xsd/datatypes.rb, line 1091
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDNegativeInteger)

# File lib/xsd/datatypes.rb, line 1073
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDNil)

# File lib/xsd/datatypes.rb, line 178
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDNonNegativeInteger)

# File lib/xsd/datatypes.rb, line 1163
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDNonPositiveInteger)

# File lib/xsd/datatypes.rb, line 1055
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDNormalizedString)

# File lib/xsd/datatypes.rb, line 989
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDPositiveInteger)

# File lib/xsd/datatypes.rb, line 1253
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDQName)

# File lib/xsd/datatypes.rb, line 947
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDShort)

# File lib/xsd/datatypes.rb, line 1127
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDString)

# File lib/xsd/datatypes.rb, line 190
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDTime)

# File lib/xsd/datatypes.rb, line 654
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDUnsignedByte)

# File lib/xsd/datatypes.rb, line 1235
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDUnsignedInt)

# File lib/xsd/datatypes.rb, line 1199
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDUnsignedLong)

# File lib/xsd/datatypes.rb, line 1181
  def initialize(value = nil)
    init(Type, value)
  end


new (XSD::XSDUnsignedShort)

# File lib/xsd/datatypes.rb, line 1217
  def initialize(value = nil)
    init(Type, value)
  end


options (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 13
        def options( opt = nil )
            if opt
                @options[opt] || YAML::DEFAULTS[opt]
            else
                @options
            end
        end


options= (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 21
        def options=( opt )
            @options = opt
        end


binary_base64 (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 28
        def binary_base64( value )
            self << "!binary "
            self.node_text( [value].pack("m"), '|' )
        end


node_text (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 36
                def node_text( value, block = nil )
            @seq_map = false
                        valx = value.dup
            unless block
            block =
                if options(:UseBlock)
                    '|'
                elsif not options(:UseFold) and valx =~ /\n[ \t]/ and not valx =~ /#{YAML::ESCAPE_CHAR}/
                    '|'
                else
                    '>'
                end

                indt = $&.to_i if block =~ /\d+/
                if valx =~ /(\A\n*[ \t#]|^---\s+)/
                    indt = options(:Indent) unless indt.to_i > 0
                    block += indt.to_s
                end

            block +=
                if valx =~ /\n\Z\n/
                    "+"
                elsif valx =~ /\Z\n/
                    ""
                else
                    "-"
                end
            end
            block += "\n"
            if block[0] == ?"
                esc_skip = ( "\t\n" unless valx =~ /^[ \t]/ ) || ""
                valx = fold( YAML::escape( valx, esc_skip ) + "\"" ).chomp
                self << '"' + indent_text( valx, indt, false )
            else
                if block[0] == ?>
                    valx = fold( valx )
                end
                #p [block, indt]
                self << block + indent_text( valx, indt )
            end
                end


simple (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 81
                def simple( value )
            @seq_map = false
            self << value.to_s
                end


double (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 89
                def double( value )
                        "\"#{YAML.escape( value )}\""
                end


single (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 96
                def single( value )
                        "'#{value}'"
                end


indent_text (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 103
                def indent_text( text, mod, first_line = true )
                        return "" if text.to_s.empty?
            spacing = indent( mod )
            text = text.gsub( /\A([^\n])/, "#{ spacing }\\1" ) if first_line
                        return text.gsub( /\n^([^\n])/, "\n#{spacing}\\1" )
                end


indent (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 113
        def indent( mod = nil )
            #p [ self.id, level, mod, :INDENT ]
            if level <= 0
                mod ||= 0
            else
                mod ||= options(:Indent)
                mod += ( level - 1 ) * options(:Indent)
            end
            return " " * mod
                end


indent! (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 127
                def indent!
                        self << indent
                end


fold (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 134
                def fold( value )
            value.gsub( /(^[ \t]+.*$)|(\S.{0,#{options(:BestWidth) - 1}})(?:[ \t]+|(\n+(?=[ \t]|\Z))|$)/ ) do |s|
                $1 || $2 + ( $3 || "\n" )
            end
                end


map (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 143
        def map( type, &e )
            val = Mapping.new
            e.call( val )
                        self << "#{type} " if type.length.nonzero?

                        #
                        # Empty hashes
                        #
                        if val.length.zero?
                                self << "{}"
                @seq_map = false
                        else
                # FIXME
                # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero?
                            #     @headless = 1
                # end

                defkey = @options.delete( :DefaultKey )
                if defkey
                    seq_map_shortcut
                    self << "= : "
                    defkey.to_yaml( :Emitter => self )
                end

                                #
                                # Emit the key and value
                                #
                val.each { |v|
                    seq_map_shortcut
                    if v[0].is_complex_yaml?
                        self << "? "
                    end
                    v[0].to_yaml( :Emitter => self )
                    if v[0].is_complex_yaml?
                        self << "\n"
                        indent!
                    end
                    self << ": "
                    v[1].to_yaml( :Emitter => self )
                }
                        end
        end


seq_map_shortcut (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 186
        def seq_map_shortcut
            # FIXME: seq_map needs to work with the new anchoring system
            # if @seq_map
            #     @anchor_extras[@buffer.length - 1] = "\n" + indent
            #     @seq_map = false
            # else
                self << "\n"
                indent!
            # end
        end


seq (YAML::BaseEmitter)

# File lib/yaml/baseemitter.rb, line 200
        def seq( type, &e )
            @seq_map = false
            val = Sequence.new
            e.call( val )
                        self << "#{type} " if type.length.nonzero?

                        #
                        # Empty arrays
                        #
                        if val.length.zero?
                                self << "[]"
                        else
                # FIXME
                # if @buffer.length == 1 and options(:UseHeader) == false and type.length.zero?
                            #     @headless = 1
                # end

                                #
                                # Emit the key and value
                                #
                val.each { |v|
                    self << "\n"
                    indent!
                    self << "- "
                    @seq_map = true if v.class == Hash
                    v.to_yaml( :Emitter => self )
                }
                        end
        end


select (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 17
        def select( ypath_str )
            matches = match_path( ypath_str )

            #
            # Create a new generic view of the elements selected
            #
            if matches
                result = []
                matches.each { |m|
                    result.push m.last
                }
                YAML.transfer( 'seq', result )
            end
        end


select! (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 36
        def select!( ypath_str )
            matches = match_path( ypath_str )

            #
            # Create a new generic view of the elements selected
            #
            if matches
                result = []
                matches.each { |m|
                    result.push m.last.transform
                }
                result
            end
        end


search (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 55
        def search( ypath_str )
            matches = match_path( ypath_str )

            if matches
                matches.collect { |m|
                    path = []
                    m.each_index { |i|
                        path.push m[i] if ( i % 2 ).zero?
                    }
                    "/" + path.compact.join( "/" )
                }
            end
        end


at (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 69
        def at( seg )
            if Hash === @value
                self[seg]
            elsif Array === @value and seg =~ /\A\d+\Z/ and @value[seg.to_i]
                @value[seg.to_i]
            end
        end


match_path (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 80
        def match_path( ypath_str )
            depth = 0
            matches = []
            YPath.each_path( ypath_str ) do |ypath|
                seg = match_segment( ypath, 0 )
                matches += seg if seg
            end
            matches.uniq
        end


match_segment (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 93
        def match_segment( ypath, depth )
            deep_nodes = []
            seg = ypath.segments[ depth ]
            if seg == "/"
                unless String === @value
                    idx = -1
                    @value.collect { |v|
                        idx += 1
                        if Hash === @value
                            match_init = [v[0].transform, v[1]]
                            match_deep = v[1].match_segment( ypath, depth )
                        else
                            match_init = [idx, v]
                            match_deep = v.match_segment( ypath, depth )
                        end
                        if match_deep
                            match_deep.each { |m|
                                deep_nodes.push( match_init + m )
                            }
                        end
                    }
                end
                depth += 1
                seg = ypath.segments[ depth ]
            end
            match_nodes =
                case seg
                when "."
                    [[nil, self]]
                when ".."
                    [["..", nil]]
                when "*"
                    if @value.is_a? Enumerable
                        idx = -1
                        @value.collect { |h|
                            idx += 1
                            if Hash === @value
                                [h[0].transform, h[1]]
                            else
                                [idx, h]
                            end
                        }
                    end
                else
                    if seg =~ /^"(.*)"$/
                        seg = $1
                    elsif seg =~ /^'(.*)'$/
                        seg = $1
                    end
                    if ( v = at( seg ) )
                        [[ seg, v ]]
                    end
                end
            return deep_nodes unless match_nodes
            pred = ypath.predicates[ depth ]
            if pred
                case pred
                when /^\.=/
                    pred = $'   # '
                    match_nodes.reject! { |n|
                        n.last.value != pred
                    }
                else
                    match_nodes.reject! { |n|
                        n.last.at( pred ).nil?
                    }
                end
            end
            return match_nodes + deep_nodes unless ypath.segments.length > depth + 1

            #puts "DEPTH: #{depth + 1}"
            deep_nodes = []
            match_nodes.each { |n|
                if n[1].is_a? BaseNode
                    match_deep = n[1].match_segment( ypath, depth + 1 )
                    if match_deep
                        match_deep.each { |m|
                            deep_nodes.push( n + m )
                        }
                    end
                else
                    deep_nodes = []
                end
            }
            deep_nodes = nil if deep_nodes.length == 0
            deep_nodes
        end


[] (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 185
        def []( *key )
            if Hash === @value
                v = @value.detect { |k,v| k.transform == key.first }
                v[1] if v
            elsif Array === @value
                @value.[]( *key )
            end
        end


children (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 194
        def children
            if Hash === @value
                @value.values.collect { |c| c[1] }
            elsif Array === @value
                @value
            end
        end


children_with_index (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 202
        def children_with_index
            if Hash === @value
                @value.keys.collect { |i| [self[i], i] }
            elsif Array === @value
                i = -1; @value.collect { |v| i += 1; [v, i] }
            end
        end


emit (YAML::BaseNode)

# File lib/yaml/basenode.rb, line 210
        def emit
            transform.to_yaml
        end


[] (YAML::DBM)

# File lib/yaml/dbm.rb, line 11
    def []( key )
        fetch( key )
    end


[]= (YAML::DBM)

# File lib/yaml/dbm.rb, line 14
    def []=( key, val )
        store( key, val )
    end


fetch (YAML::DBM)

# File lib/yaml/dbm.rb, line 17
    def fetch( keystr, ifnone = nil )
        begin
            val = super( keystr )
            return YAML::load( val ) if String === val
        rescue IndexError
        end
        if block_given?
            yield keystr
        else
            ifnone
        end
    end


index (YAML::DBM)

# File lib/yaml/dbm.rb, line 29
    def index( keystr )
        super( keystr.to_yaml )
    end


values_at (YAML::DBM)

# File lib/yaml/dbm.rb, line 32
    def values_at( *keys )
        keys.collect { |k| fetch( k ) }
    end


delete (YAML::DBM)

# File lib/yaml/dbm.rb, line 35
    def delete( key )
        v = super( key )
        if String === v
            v = YAML::load( v )
        end
        v
    end


delete_if (YAML::DBM)

# File lib/yaml/dbm.rb, line 42
    def delete_if
        del_keys = keys.dup
        del_keys.delete_if { |k| yield( k, fetch( k ) ) == false }
        del_keys.each { |k| delete( k ) }
        self
    end


reject (YAML::DBM)

# File lib/yaml/dbm.rb, line 48
    def reject
        hsh = self.to_hash
        hsh.reject { |k,v| yield k, v }
    end


each_pair (YAML::DBM)

# File lib/yaml/dbm.rb, line 52
    def each_pair
        keys.each { |k| yield k, fetch( k ) }
        self
    end


each_value (YAML::DBM)

# File lib/yaml/dbm.rb, line 56
    def each_value
        super { |v| yield YAML::load( v ) }
        self
    end


values (YAML::DBM)

# File lib/yaml/dbm.rb, line 60
    def values
        super.collect { |v| YAML::load( v ) }
    end


has_value? (YAML::DBM)

# File lib/yaml/dbm.rb, line 63
    def has_value?( val )
        each_value { |v| return true if v == val }
        return false
    end


invert (YAML::DBM)

# File lib/yaml/dbm.rb, line 67
    def invert
        h = {}
        keys.each { |k| h[ self.fetch( k ) ] = k }
        h
    end


replace (YAML::DBM)

# File lib/yaml/dbm.rb, line 72
    def replace( hsh )
        clear
        update( hsh )
    end


shift (YAML::DBM)

# File lib/yaml/dbm.rb, line 76
    def shift
        a = super
        a[1] = YAML::load( a[1] ) if a
        a
    end


select (YAML::DBM)

# File lib/yaml/dbm.rb, line 81
    def select( *keys )
        if block_given?
            self.keys.collect { |k| v = self[k]; [k, v] if yield k, v }.compact
        else
            values_at( *keys )
        end
    end


store (YAML::DBM)

# File lib/yaml/dbm.rb, line 88
    def store( key, val )
        super( key, val.to_yaml )
        val
    end


update (YAML::DBM)

# File lib/yaml/dbm.rb, line 92
    def update( hsh )
        hsh.keys.each do |k|
            self.store( k, hsh.fetch( k ) )
        end
        self
    end


to_a (YAML::DBM)

# File lib/yaml/dbm.rb, line 98
    def to_a
        a = []
        keys.each { |k| a.push [ k, self.fetch( k ) ] }
        a
    end


to_hash (YAML::DBM)

# File lib/yaml/dbm.rb, line 103
    def to_hash
        h = {}
        keys.each { |k| h[ k ] = self.fetch( k ) }
        h
    end


tag_subclasses? (YAML::DomainType)

# File lib/yaml/types.rb, line 30
        def self.tag_subclasses?; false; end


new (YAML::DomainType)

# File lib/yaml/types.rb, line 33
        def initialize( domain, type, val )
            @domain = domain; @type_id = type; @value = val
            @value.taguri = "tag:#{ @domain }:#{ @type_id }"
        end


to_yaml (YAML::DomainType)

# File lib/yaml/types.rb, line 37
        def to_yaml( opts = {} )
            @value.to_yaml( opts )
        end


add (YAML::Mapping)

# File lib/yaml/baseemitter.rb, line 236
        def add( k, v )
            push [k, v]
        end


tag_subclasses? (YAML::Object)

# File lib/yaml/types.rb, line 48
        def self.tag_subclasses?; false; end


to_yaml (YAML::Object)

# File lib/yaml/types.rb, line 49
        def to_yaml( opts = {} )
            YAML::quick_emit( object_id, opts ) do |out|
                out.map( "tag:ruby.yaml.org,2002:object:#{ @class }", to_yaml_style ) do |map|
                    @ivars.each do |k,v|
                        map.add( k, v )
                    end
                end
            end
        end


yaml_initialize (YAML::Omap)

# File lib/yaml/types.rb, line 88
        def yaml_initialize( tag, val )
            if Array === val
                val.each do |v|
                    if Hash === v
                        concat( v.to_a )                # Convert the map to a sequence
                    else
                        raise YAML::Error, "Invalid !omap entry: " + val.inspect
                    end
                end
            else
                raise YAML::Error, "Invalid !omap: " + val.inspect
            end
            self
        end


[] (YAML::Omap)

# File lib/yaml/types.rb, line 102
        def self.[]( *vals )
            o = Omap.new
            0.step( vals.length - 1, 2 ) do |i|
                o[vals[i]] = vals[i+1]
            end
            o
        end


[] (YAML::Omap)

# File lib/yaml/types.rb, line 109
        def []( k )
            self.assoc( k ).to_a[1]
        end


[]= (YAML::Omap)

# File lib/yaml/types.rb, line 112
        def []=( k, *rest )
            val, set = rest.reverse
            if ( tmp = self.assoc( k ) ) and not set
                tmp[1] = val
            else
                self << [ k, val ]
            end
            val
        end


has_key? (YAML::Omap)

# File lib/yaml/types.rb, line 121
        def has_key?( k )
            self.assoc( k ) ? true : false
        end


is_complex_yaml? (YAML::Omap)

# File lib/yaml/types.rb, line 124
        def is_complex_yaml?
            true
        end


to_yaml (YAML::Omap)

# File lib/yaml/types.rb, line 127
        def to_yaml( opts = {} )
            YAML::quick_emit( self.object_id, opts ) do |out|
                out.seq( taguri, to_yaml_style ) do |seq|
                    self.each do |v|
                        seq.add( Hash[ *v ] )
                    end
                end
            end
        end


yaml_initialize (YAML::Pairs)

# File lib/yaml/types.rb, line 143
        def yaml_initialize( tag, val )
            if Array === val
                val.each do |v|
                    if Hash === v
                        concat( v.to_a )                # Convert the map to a sequence
                    else
                        raise YAML::Error, "Invalid !pairs entry: " + val.inspect
                    end
                end
            else
                raise YAML::Error, "Invalid !pairs: " + val.inspect
            end
            self
        end


[] (YAML::Pairs)

# File lib/yaml/types.rb, line 157
        def self.[]( *vals )
            p = Pairs.new
            0.step( vals.length - 1, 2 ) { |i|
                p[vals[i]] = vals[i+1]
            }
            p
        end


[] (YAML::Pairs)

# File lib/yaml/types.rb, line 164
        def []( k )
            self.assoc( k ).to_a
        end


[]= (YAML::Pairs)

# File lib/yaml/types.rb, line 167
        def []=( k, val )
            self << [ k, val ]
            val
        end


has_key? (YAML::Pairs)

# File lib/yaml/types.rb, line 171
        def has_key?( k )
            self.assoc( k ) ? true : false
        end


is_complex_yaml? (YAML::Pairs)

# File lib/yaml/types.rb, line 174
        def is_complex_yaml?
            true
        end


to_yaml (YAML::Pairs)

# File lib/yaml/types.rb, line 177
        def to_yaml( opts = {} )
            YAML::quick_emit( self.object_id, opts ) do |out|
                out.seq( taguri, to_yaml_style ) do |seq|
                    self.each do |v|
                        seq.add( Hash[ *v ] )
                    end
                end
            end
        end


tag_subclasses? (YAML::PrivateType)

# File lib/yaml/types.rb, line 12
        def self.tag_subclasses?; false; end


new (YAML::PrivateType)

# File lib/yaml/types.rb, line 15
        def initialize( type, val )
            @type_id = type; @value = val
            @value.taguri = "x-private:#{ @type_id }"
        end


to_yaml (YAML::PrivateType)

# File lib/yaml/types.rb, line 19
        def to_yaml( opts = {} )
            @value.to_yaml( opts )
        end


add (YAML::Sequence)

# File lib/yaml/baseemitter.rb, line 242
        def add( v )
            push v
        end


inspect (YAML::SpecialHash)

# File lib/yaml/types.rb, line 65
        def inspect
            self.default.to_s
        end


to_s (YAML::SpecialHash)

# File lib/yaml/types.rb, line 68
        def to_s
            self.default.to_s
        end


update (YAML::SpecialHash)

# File lib/yaml/types.rb, line 71
        def update( h )
            if YAML::SpecialHash === h
                @default = h.default if h.default
            end
            super( h )
        end


to_yaml (YAML::SpecialHash)

# File lib/yaml/types.rb, line 77
        def to_yaml( opts = {} )
            opts[:DefaultKey] = self.default
            super( opts )
        end


new (YAML::Store)

# File lib/yaml/store.rb, line 8
  def initialize( *o )
    @opt = YAML::DEFAULTS.dup
    if String === o.first
      super(o.shift)
    end
    if o.last.is_a? Hash
      @opt.update(o.pop)
    end
  end


dump (YAML::Store)

# File lib/yaml/store.rb, line 18
  def dump(table)
    @table.to_yaml(@opt)
  end


load (YAML::Store)

# File lib/yaml/store.rb, line 22
  def load(content)
    YAML::load(content)
  end


load_file (YAML::Store)

# File lib/yaml/store.rb, line 26
  def load_file(file)
    YAML::load(file)
  end


new (YAML::Stream)

# File lib/yaml/stream.rb, line 10
                def initialize( opts = {} )
                        @options = opts
                        @documents = []
                end


[] (YAML::Stream)

# File lib/yaml/stream.rb, line 15
        def []( i )
            @documents[ i ]
        end


add (YAML::Stream)

# File lib/yaml/stream.rb, line 19
                def add( doc )
                        @documents << doc
                end


edit (YAML::Stream)

# File lib/yaml/stream.rb, line 23
                def edit( doc_num, doc )
                        @documents[ doc_num ] = doc
                end


emit (YAML::Stream)

# File lib/yaml/stream.rb, line 27
                def emit( io = nil )
            # opts = @options.dup
                        # opts[:UseHeader] = true if @documents.length > 1
            out = YAML.emitter
            out.reset( io || io2 = StringIO.new )
            @documents.each { |v|
                v.to_yaml( out )
            }
            io || ( io2.rewind; io2.read )
                end


new (YAML::YamlNode)

# File lib/yaml/yamlnode.rb, line 14
        def initialize( t, v )
            @type_id = t
            if Hash === v
                @kind = 'map'
                @value = {}
                v.each { |k,v|
                    @value[ k.transform ] = [ k, v ]
                }
            elsif Array === v
                @kind = 'seq'
                @value = v
            elsif String === v
                @kind = 'scalar'
                @value = v
            end
        end


transform (YAML::YamlNode)

# File lib/yaml/yamlnode.rb, line 34
        def transform
            t = nil
            if @value.is_a? Hash
                t = {}
                @value.each { |k,v|
                    t[ k ] = v[1].transform
                }
            elsif @value.is_a? Array
                t = []
                @value.each { |v|
                    t.push v.transform
                }
            else
                t = @value
            end
            YAML.transfer_method( @type_id, t )
        end


new (YAML::YPath)

# File lib/yaml/ypath.rb, line 9
        def initialize( str )
            @segments = []
            @predicates = []
            @flags = nil
            while str =~ /^\/?(\/|[^\/\[]+)(?:\[([^\]]+)\])?/
                @segments.push $1
                @predicates.push $2
                str = $'
            end
            unless str.to_s.empty?
                @segments += str.split( "/" )
            end
            if @segments.length == 0
                @segments.push "."
            end
        end


each_path (YAML::YPath)

# File lib/yaml/ypath.rb, line 25
        def YPath.each_path( str )
            #
            # Find choices
            #
            paths = []
            str = "(#{ str })"
            while str.sub!( /\(([^()]+)\)/, "\n#{ paths.length }\n" )
                paths.push $1.split( '|' )
            end

            #
            # Construct all possible paths
            #
            all = [ str ]
            ( paths.length - 1 ).downto( 0 ) do |i|
                all = all.collect do |a|
                    paths[i].collect do |p|
                        a.gsub( /\n#{ i }\n/, p )
                    end
                end.flatten.uniq
            end
            all.collect do |path|
                yield YPath.new( path )
            end
        end


make_stream (YAML)

# File lib/yaml/stringio.rb, line 55
        def YAML.make_stream( io )
        if String === io
            io = StringIO.new( io )
        elsif not IO === io
            raise YAML::Error, "YAML stream must be an IO or String object."
        end
        if YAML::unicode
            def io.readline
                YAML.utf_to_internal( readline( @ln_sep ), @utf_encoding )
            end
            def io.check_unicode
                @utf_encoding = YAML.sniff_encoding( read( 4 ) )
                @ln_sep = YAML.enc_separator( @utf_encoding )
                seek( -4, IO::SEEK_CUR )
            end
                    def io.utf_encoding
                      @utf_encoding
                    end
            io.check_unicode
        else
            def io.utf_encoding
                :None
            end
        end
        io
        end


escape (YAML)

# File lib/yaml/encoding.rb, line 10
        def YAML.escape( value, skip = "" )
                value.gsub( /\\/, "\\\\\\" ).
              gsub( /"/, "\\\"" ).
              gsub( /([\x00-\x1f])/ ) do |x|
                 skip[x] || ESCAPES[ x.unpack("C")[0] ]
             end
        end


unescape (YAML)

# File lib/yaml/encoding.rb, line 21
        def YAML.unescape( value )
                value.gsub( /\\(?:([nevfbart\\])|0?x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/ ) { |x|
                        if $3
                                ["#$3".hex ].pack('U*')
                        elsif $2
                                [$2].pack( "H2" )
                        else
                                UNESCAPES[$1]
                        end
                }
        end


tag_class (YAML)

# File lib/yaml/tag.rb, line 35
    def YAML.tag_class( tag, cls )
        if @@tagged_classes.has_key? tag
            warn "class #{ @@tagged_classes[tag] } held ownership of the #{ tag } tag"
        end
        @@tagged_classes[tag] = cls
    end


tagged_classes (YAML)

# File lib/yaml/tag.rb, line 48
    def YAML.tagged_classes
        @@tagged_classes
    end


parser (YAML)

# File lib/yaml.rb, line 95
    def YAML.parser; Parser.new.set_resolver( YAML.resolver ); end


generic_parser (YAML)

# File lib/yaml.rb, line 97
    def YAML.generic_parser; Parser.new.set_resolver( GenericResolver ); end


resolver (YAML)

# File lib/yaml.rb, line 99
    def YAML.resolver; DefaultResolver; end


emitter (YAML)

# File lib/yaml.rb, line 101
    def YAML.emitter; Emitter.new.set_resolver( YAML.resolver ); end


dump (YAML)

# File lib/yaml.rb, line 116
        def YAML.dump( obj, io = nil )
        obj.to_yaml( io || io2 = StringIO.new )
        io || ( io2.rewind; io2.read )
        end


load (YAML)

# File lib/yaml.rb, line 132
        def YAML.load( io )
                yp = parser.load( io )
        end


load_file (YAML)

# File lib/yaml.rb, line 142
    def YAML.load_file( filepath )
        File.open( filepath ) do |f|
            load( f )
        end
    end


parse (YAML)

# File lib/yaml.rb, line 175
        def YAML.parse( io )
                yp = generic_parser.load( io )
        end


parse_file (YAML)

# File lib/yaml.rb, line 199
    def YAML.parse_file( filepath )
        File.open( filepath ) do |f|
            parse( f )
        end
    end


each_document (YAML)

# File lib/yaml.rb, line 216
        def YAML.each_document( io, &block )
                yp = parser.load_documents( io, &block )
    end


load_documents (YAML)

# File lib/yaml.rb, line 231
        def YAML.load_documents( io, &doc_proc )
                YAML.each_document( io, &doc_proc )
    end


each_node (YAML)

# File lib/yaml.rb, line 246
        def YAML.each_node( io, &doc_proc )
                yp = generic_parser.load_documents( io, &doc_proc )
    end


parse_documents (YAML)

# File lib/yaml.rb, line 261
        def YAML.parse_documents( io, &doc_proc )
                YAML.each_node( io, &doc_proc )
    end


load_stream (YAML)

# File lib/yaml.rb, line 270
        def YAML.load_stream( io )
                d = nil
                parser.load_documents( io ) do |doc|
                        d = YAML::Stream.new if not d
                        d.add( doc )
        end
                return d
        end


dump_stream (YAML)

# File lib/yaml.rb, line 288
        def YAML.dump_stream( *objs )
                d = YAML::Stream.new
        objs.each do |doc|
                        d.add( doc )
        end
        d.emit
        end


add_domain_type (YAML)

# File lib/yaml.rb, line 299
        def YAML.add_domain_type( domain, type_tag, &transfer_proc )
        resolver.add_type( "tag:#{ domain }:#{ type_tag }", transfer_proc )
        end


add_builtin_type (YAML)

# File lib/yaml.rb, line 306
        def YAML.add_builtin_type( type_tag, &transfer_proc )
            resolver.add_type( "tag:yaml.org,2002:#{ type_tag }", transfer_proc )
        end


add_ruby_type (YAML)

# File lib/yaml.rb, line 313
        def YAML.add_ruby_type( type_tag, &transfer_proc )
            resolver.add_type( "tag:ruby.yaml.org,2002:#{ type_tag }", transfer_proc )
        end


add_private_type (YAML)

# File lib/yaml.rb, line 320
        def YAML.add_private_type( type_re, &transfer_proc )
            resolver.add_type( "x-private:" + type_re, transfer_proc )
        end


detect_implicit (YAML)

# File lib/yaml.rb, line 327
    def YAML.detect_implicit( val )
        resolver.detect_implicit( val )
    end


tagurize (YAML)

# File lib/yaml.rb, line 334
    def YAML.tagurize( val )
        resolver.tagurize( val )
    end


transfer (YAML)

# File lib/yaml.rb, line 341
    def YAML.transfer( type_id, obj )
        resolver.transfer( YAML.tagurize( type_id ), obj )
    end


try_implicit (YAML)

# File lib/yaml.rb, line 348
        def YAML.try_implicit( obj )
                YAML.transfer( YAML.detect_implicit( obj ), obj )
        end


read_type_class (YAML)

# File lib/yaml.rb, line 356
    def YAML.read_type_class( type, obj_class )
        scheme, domain, type, tclass = type.split( ':', 4 )
        tclass.split( "::" ).each { |c| obj_class = obj_class.const_get( c ) } if tclass
        return [ type, obj_class ]
    end


object_maker (YAML)

# File lib/yaml.rb, line 365
    def YAML.object_maker( obj_class, val )
        if Hash === val
            o = obj_class.allocate
            val.each_pair { |k,v|
                o.instance_variable_set("@#{k}", v)
            }
            o
        else
            raise YAML::Error, "Invalid object explicitly tagged !ruby/Object: " + val.inspect
        end
    end


quick_emit (YAML)

# File lib/yaml.rb, line 380
        def YAML.quick_emit( oid, opts = {}, &e )
        out =
            if opts.is_a? YAML::Emitter
                opts
            else
                emitter.reset( opts )
            end
        out.emit( oid, &e )
        end


deflate (Zlib::Deflate)

/*
 * call-seq: Zlib::Deflate.deflate(string[, level])
 *
 * Compresses the given +string+. Valid values of level are
 * <tt>Zlib::NO_COMPRESSION</tt>, <tt>Zlib::BEST_SPEED</tt>,
 * <tt>Zlib::BEST_COMPRESSION</tt>, <tt>Zlib::DEFAULT_COMPRESSION</tt>, and an
 * integer from 0 to 9.
 *
 * This method is almost equivalent to the following code:
 *
 *   def deflate(string, level)
 *     z = Zlib::Deflate.new(level)
 *     dst = z.deflate(string, Zlib::FINISH)
 *     z.close
 *     dst
 *   end
 *
 * TODO: what's default value of +level+?
 *
 */
static VALUE
rb_deflate_s_deflate(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    struct zstream z;
    VALUE src, level, dst, args[2];
    int err, lev;

    rb_scan_args(argc, argv, "11", &src, &level);

    lev = ARG_LEVEL(level);
    StringValue(src);
    zstream_init_deflate(&z);
    err = deflateInit(&z.stream, lev);
    if (err != Z_OK) {
        raise_zlib_error(err, z.stream.msg);
    }
    ZSTREAM_READY(&z);

    args[0] = (VALUE)&z;
    args[1] = src;
    dst = rb_ensure(deflate_run, (VALUE)args, zstream_end, (VALUE)&z);

    OBJ_INFECT(dst, src);
    return dst;
}


new (Zlib::Deflate)

/*
 * call-seq: Zlib::Deflate.new(level=nil, windowBits=nil, memlevel=nil, strategy=nil)
 *
 * Creates a new deflate stream for compression. See zlib.h for details of
 * each argument. If an argument is nil, the default value of that argument is
 * used.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_initialize(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct zstream *z;
    VALUE level, wbits, memlevel, strategy;
    int err;

    rb_scan_args(argc, argv, "04", &level, &wbits, &memlevel, &strategy);
    Data_Get_Struct(obj, struct zstream, z);

    err = deflateInit2(&z->stream, ARG_LEVEL(level), Z_DEFLATED,
                       ARG_WBITS(wbits), ARG_MEMLEVEL(memlevel),
                       ARG_STRATEGY(strategy));
    if (err != Z_OK) {
        raise_zlib_error(err, z->stream.msg);
    }
    ZSTREAM_READY(z);

    return obj;
}


initialize_copy (Zlib::Deflate)

/*
 * Duplicates the deflate stream.
 */
static VALUE
rb_deflate_init_copy(self, orig)
    VALUE self, orig;
{
    struct zstream *z1 = get_zstream(self);
    struct zstream *z2 = get_zstream(orig);
    int err;

    err = deflateCopy(&z1->stream, &z2->stream);
    if (err != Z_OK) {
        raise_zlib_error(err, 0);
    }
    z1->flags = z2->flags;

    return self;
}


deflate (Zlib::Deflate)

/*
 * call-seq: deflate(string[, flush])
 *
 * Inputs +string+ into the deflate stream and returns the output from the
 * stream.  On calling this method, both the input and the output buffers of
 * the stream are flushed. If +string+ is nil, this method finishes the
 * stream, just like Zlib::ZStream#finish.
 *
 * The value of +flush+ should be either <tt>Zlib::NO_FLUSH</tt>,
 * <tt>Zlib::SYNC_FLUSH</tt>, <tt>Zlib::FULL_FLUSH</tt>, or
 * <tt>Zlib::FINISH</tt>. See zlib.h for details.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_deflate(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct zstream *z = get_zstream(obj);
    VALUE src, flush, dst;

    rb_scan_args(argc, argv, "11", &src, &flush);
    OBJ_INFECT(obj, src);
    do_deflate(z, src, ARG_FLUSH(flush));
    dst = zstream_detach_buffer(z);

    OBJ_INFECT(dst, obj);
    return dst;
}


<< (Zlib::Deflate)

/*
 * call-seq: << string
 *
 * Inputs +string+ into the deflate stream just like Zlib::Deflate#deflate, but
 * returns the Zlib::Deflate object itself.  The output from the stream is
 * preserved in output buffer.
 */
static VALUE
rb_deflate_addstr(obj, src)
    VALUE obj, src;
{
    OBJ_INFECT(obj, src);
    do_deflate(get_zstream(obj), src, Z_NO_FLUSH);
    return obj;
}


flush (Zlib::Deflate)

/*
 * call-seq: flush(flush)
 *
 * This method is equivalent to <tt>deflate('', flush)</tt>.  If flush is omitted,
 * <tt>Zlib::SYNC_FLUSH</tt> is used as flush.  This method is just provided
 * to improve the readability of your Ruby program.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_flush(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct zstream *z = get_zstream(obj);
    VALUE v_flush, dst;
    int flush;

    rb_scan_args(argc, argv, "01", &v_flush);
    flush = FIXNUMARG(v_flush, Z_SYNC_FLUSH);
    if (flush != Z_NO_FLUSH) {  /* prevent Z_BUF_ERROR */
        zstream_run(z, "", 0, flush);
    }
    dst = zstream_detach_buffer(z);

    OBJ_INFECT(dst, obj);
    return dst;
}


params (Zlib::Deflate)

/*
 * call-seq: params(level, strategy)
 *
 * Changes the parameters of the deflate stream. See zlib.h for details. The
 * output from the stream by changing the params is preserved in output
 * buffer.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_params(obj, v_level, v_strategy)
    VALUE obj, v_level, v_strategy;
{
    struct zstream *z = get_zstream(obj);
    int level, strategy;
    int err;

    level = ARG_LEVEL(v_level);
    strategy = ARG_STRATEGY(v_strategy);

    err = deflateParams(&z->stream, level, strategy);
    while (err == Z_BUF_ERROR) {
        rb_warning("deflateParams() returned Z_BUF_ERROR");
        zstream_expand_buffer(z);
        err = deflateParams(&z->stream, level, strategy);
    }
    if (err != Z_OK) {
        raise_zlib_error(err, z->stream.msg);
    }

    return Qnil;
}


set_dictionary (Zlib::Deflate)

/*
 * call-seq: set_dictionary(string)
 *
 * Sets the preset dictionary and returns +string+. This method is available
 * just only after Zlib::Deflate.new or Zlib::ZStream#reset method was called.
 * See zlib.h for details.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_set_dictionary(obj, dic)
    VALUE obj, dic;
{
    struct zstream *z = get_zstream(obj);
    VALUE src = dic;
    int err;

    OBJ_INFECT(obj, dic);
    StringValue(src);
    err = deflateSetDictionary(&z->stream,
                               RSTRING(src)->ptr, RSTRING(src)->len);
    if (err != Z_OK) {
        raise_zlib_error(err, z->stream.msg);
    }

    return dic;
}


wrap (Zlib::GzipFile)

/*
 * See Zlib::GzipReader#wrap and Zlib::GzipWriter#wrap.
 */
static VALUE
rb_gzfile_s_wrap(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    VALUE obj = rb_class_new_instance(argc, argv, klass);

    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, obj, gzfile_ensure_close, obj);
    }
    else {
        return obj;
    }
}


to_io (Zlib::GzipFile)

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_to_io(obj)
    VALUE obj;
{
    return get_gzfile(obj)->io;
}


crc (Zlib::GzipFile)

/*
 * Returns CRC value of the uncompressed data.
 */
static VALUE
rb_gzfile_crc(obj)
    VALUE obj;
{
    return rb_uint2inum(get_gzfile(obj)->crc);
}


mtime (Zlib::GzipFile)

/*
 * Returns last modification time recorded in the gzip file header.
 */
static VALUE
rb_gzfile_mtime(obj)
    VALUE obj;
{
    return rb_time_new(get_gzfile(obj)->mtime, (time_t)0);
}


level (Zlib::GzipFile)

/*
 * Returns compression level.
 */
static VALUE
rb_gzfile_level(obj)
    VALUE obj;
{
    return INT2FIX(get_gzfile(obj)->level);
}


os_code (Zlib::GzipFile)

/*
 * Returns OS code number recorded in the gzip file header.
 */
static VALUE
rb_gzfile_os_code(obj)
    VALUE obj;
{
    return INT2FIX(get_gzfile(obj)->os_code);
}


orig_name (Zlib::GzipFile)

/*
 * Returns original filename recorded in the gzip file header, or +nil+ if
 * original filename is not present.
 */
static VALUE
rb_gzfile_orig_name(obj)
    VALUE obj;
{
    VALUE str = get_gzfile(obj)->orig_name;
    if (!NIL_P(str)) {
        str = rb_str_dup(str);
    }
    OBJ_TAINT(str);  /* for safe */
    return str;
}


comment (Zlib::GzipFile)

/*
 * Returns comments recorded in the gzip file header, or nil if the comments
 * is not present.
 */
static VALUE
rb_gzfile_comment(obj)
    VALUE obj;
{
    VALUE str = get_gzfile(obj)->comment;
    if (!NIL_P(str)) {
        str = rb_str_dup(str);
    }
    OBJ_TAINT(str);  /* for safe */
    return str;
}


close (Zlib::GzipFile)

/*
 * Closes the GzipFile object. This method calls close method of the
 * associated IO object. Returns the associated IO object.
 */
static VALUE
rb_gzfile_close(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE io;

    io = gz->io;
    gzfile_close(gz, 1);
    return io;
}


finish (Zlib::GzipFile)

/*
 * Closes the GzipFile object. Unlike Zlib::GzipFile#close, this method never
 * calls the close method of the associated IO object. Returns the associated IO
 * object.
 */
static VALUE
rb_gzfile_finish(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE io;

    io = gz->io;
    gzfile_close(gz, 0);
    return io;
}


closed? (Zlib::GzipFile)

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_closed_p(obj)
    VALUE obj;
{
    struct gzfile *gz;
    Data_Get_Struct(obj, struct gzfile, gz);
    return NIL_P(gz->io) ? Qtrue : Qfalse;
}


sync (Zlib::GzipFile)

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_sync(obj)
    VALUE obj;
{
    return (get_gzfile(obj)->z.flags & GZFILE_FLAG_SYNC) ? Qtrue : Qfalse;
}


sync= (Zlib::GzipFile)

/*
 * call-seq: sync = flag
 *
 * Same as IO.  If flag is +true+, the associated IO object must respond to the
 * +flush+ method.  While +sync+ mode is +true+, the compression ratio
 * decreases sharply.
 */
static VALUE
rb_gzfile_set_sync(obj, mode)
    VALUE obj, mode;
{
    struct gzfile *gz = get_gzfile(obj);

    if (RTEST(mode)) {
        gz->z.flags |= GZFILE_FLAG_SYNC;
    }
    else {
        gz->z.flags &= ~GZFILE_FLAG_SYNC;
    }
    return mode;
}


lineno (Zlib::GzipReader)

/*
 * ???
 */
static VALUE
rb_gzfile_lineno(obj)
    VALUE obj;
{
    return INT2NUM(get_gzfile(obj)->lineno);
}


lineno= (Zlib::GzipReader)

/*
 * ???
 */
static VALUE
rb_gzfile_set_lineno(obj, lineno)
    VALUE obj, lineno;
{
    struct gzfile *gz = get_gzfile(obj);
    gz->lineno = NUM2INT(lineno);
    return lineno;
}


eof (Zlib::GzipReader)

/*
 * ???
 */
static VALUE
rb_gzfile_eof_p(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    return GZFILE_IS_FINISHED(gz) ? Qtrue : Qfalse;
}


eof? (Zlib::GzipReader)

/*
 * ???
 */
static VALUE
rb_gzfile_eof_p(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    return GZFILE_IS_FINISHED(gz) ? Qtrue : Qfalse;
}


pos (Zlib::GzipReader)

/*
 * ???
 */
static VALUE
rb_gzfile_total_out(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    return rb_uint2inum(gz->z.stream.total_out - gz->z.buf_filled);
}


tell (Zlib::GzipReader)

/*
 * ???
 */
static VALUE
rb_gzfile_total_out(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    return rb_uint2inum(gz->z.stream.total_out - gz->z.buf_filled);
}


open (Zlib::GzipReader)

/*
 * call-seq: Zlib::GzipReader.open(filename) {|gz| ... }
 *
 * Opens a file specified by +filename+ as a gzipped file, and returns a
 * GzipReader object associated with that file.  Further details of this method
 * are in Zlib::GzipReader.new and ZLib::GzipReader.wrap.
 */
static VALUE
rb_gzreader_s_open(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return gzfile_s_open(argc, argv, klass, "rb");
}


new (Zlib::GzipReader)

/*
 * call-seq: Zlib::GzipReader.new(io)
 *
 * Creates a GzipReader object associated with +io+. The GzipReader object reads
 * gzipped data from +io+, and parses/decompresses them.  At least, +io+ must have
 * a +read+ method that behaves same as the +read+ method in IO class.
 *
 * If the gzip file header is incorrect, raises an Zlib::GzipFile::Error
 * exception.
 */
static VALUE
rb_gzreader_initialize(obj, io)
    VALUE obj, io;
{
    struct gzfile *gz;
    int err;

    Data_Get_Struct(obj, struct gzfile, gz);

    /* this is undocumented feature of zlib */
    err = inflateInit2(&gz->z.stream, -MAX_WBITS);
    if (err != Z_OK) {
        raise_zlib_error(err, gz->z.stream.msg);
    }
    gz->io = io;
    ZSTREAM_READY(&gz->z);
    gzfile_read_header(gz);

    return obj;
}


rewind (Zlib::GzipReader)

/*
 * Resets the position of the file pointer to the point created the GzipReader
 * object.  The associated IO object needs to respond to the +seek+ method.
 */
static VALUE
rb_gzreader_rewind(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    gzfile_reader_rewind(gz);
    return INT2FIX(0);
}


unused (Zlib::GzipReader)

/*
 * Returns the rest of the data which had read for parsing gzip format, or
 * +nil+ if the whole gzip file is not parsed yet.
 */
static VALUE
rb_gzreader_unused(obj)
    VALUE obj;
{
    struct gzfile *gz;
    Data_Get_Struct(obj, struct gzfile, gz);
    return gzfile_reader_get_unused(gz);
}


read (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_read(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE vlen;
    int len;

    rb_scan_args(argc, argv, "01", &vlen);
    if (NIL_P(vlen)) {
        return gzfile_read_all(gz);
    }

    len = NUM2INT(vlen);
    if (len < 0) {
        rb_raise(rb_eArgError, "negative length %d given", len);
    }
    return gzfile_read(gz, len);
}


getc (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_getc(obj)
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE dst;

    dst = gzfile_read(gz, 1);
    if (!NIL_P(dst)) {
        dst = INT2FIX((unsigned int)(RSTRING(dst)->ptr[0]) & 0xff);
    }
    return dst;
}


readchar (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readchar(obj)
    VALUE obj;
{
    VALUE dst;
    dst = rb_gzreader_getc(obj);
    if (NIL_P(dst)) {
        rb_raise(rb_eEOFError, "end of file reached");
    }
    return dst;
}


each_byte (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_each_byte(obj)
    VALUE obj;
{
    VALUE c;
    while (!NIL_P(c = rb_gzreader_getc(obj))) {
        rb_yield(c);
    }
    return Qnil;
}


ungetc (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_ungetc(obj, ch)
    VALUE obj, ch;
{
    struct gzfile *gz = get_gzfile(obj);
    gzfile_ungetc(gz, NUM2CHR(ch));
    return Qnil;
}


gets (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_gets(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE dst;
    dst = gzreader_gets(argc, argv, obj);
    if (!NIL_P(dst)) {
        rb_lastline_set(dst);
    }
    return dst;
}


readline (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readline(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE dst;
    dst = rb_gzreader_gets(argc, argv, obj);
    if (NIL_P(dst)) {
        rb_raise(rb_eEOFError, "end of file reached");
    }
    return dst;
}


each (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_each(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE str;
    while (!NIL_P(str = gzreader_gets(argc, argv, obj))) {
        rb_yield(str);
    }
    return obj;
}


each_line (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_each(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE str;
    while (!NIL_P(str = gzreader_gets(argc, argv, obj))) {
        rb_yield(str);
    }
    return obj;
}


readlines (Zlib::GzipReader)

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readlines(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE str, dst;
    dst = rb_ary_new();
    while (!NIL_P(str = gzreader_gets(argc, argv, obj))) {
        rb_ary_push(dst, str);
    }
    return dst;
}


mtime= (Zlib::GzipWriter)

/*
 * ???
 */
static VALUE
rb_gzfile_set_mtime(obj, mtime)
    VALUE obj, mtime;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE val;

    if (gz->z.flags & GZFILE_FLAG_HEADER_FINISHED) {
        rb_raise(cGzError, "header is already written");
    }

    if (FIXNUM_P(time)) {
        gz->mtime = FIX2INT(mtime);
    }
    else {
        val = rb_Integer(mtime);
        gz->mtime = FIXNUM_P(val) ? FIX2INT(val) : rb_big2ulong(val);
    }
    return mtime;
}


orig_name= (Zlib::GzipWriter)

/*
 * ???
 */
static VALUE
rb_gzfile_set_orig_name(obj, str)
    VALUE obj, str;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE s;
    char *p;

    if (gz->z.flags & GZFILE_FLAG_HEADER_FINISHED) {
        rb_raise(cGzError, "header is already written");
    }
    s = rb_str_dup(rb_str_to_str(str));
    p = memchr(RSTRING(s)->ptr, '\0', RSTRING(s)->len);
    if (p) {
        rb_str_resize(s, p - RSTRING(s)->ptr);
    }
    gz->orig_name = s;
    return str;
}


comment= (Zlib::GzipWriter)

/*
 * ???
 */
static VALUE
rb_gzfile_set_comment(obj, str)
    VALUE obj, str;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE s;
    char *p;

    if (gz->z.flags & GZFILE_FLAG_HEADER_FINISHED) {
        rb_raise(cGzError, "header is already written");
    }
    s = rb_str_dup(rb_str_to_str(str));
    p = memchr(RSTRING(s)->ptr, '\0', RSTRING(s)->len);
    if (p) {
        rb_str_resize(s, p - RSTRING(s)->ptr);
    }
    gz->comment = s;
    return str;
}


pos (Zlib::GzipWriter)

/*
 * ???
 */
static VALUE
rb_gzfile_total_in(obj)
    VALUE obj;
{
    return rb_uint2inum(get_gzfile(obj)->z.stream.total_in);
}


tell (Zlib::GzipWriter)

/*
 * ???
 */
static VALUE
rb_gzfile_total_in(obj)
    VALUE obj;
{
    return rb_uint2inum(get_gzfile(obj)->z.stream.total_in);
}


open (Zlib::GzipWriter)

/*
 * call-seq: Zlib::GzipWriter.open(filename, level=nil, strategy=nil) { |gz| ... }
 *
 * Opens a file specified by +filename+ for writing gzip compressed data, and
 * returns a GzipWriter object associated with that file.  Further details of
 * this method are found in Zlib::GzipWriter.new and Zlib::GzipWriter#wrap.
 */
static VALUE
rb_gzwriter_s_open(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return gzfile_s_open(argc, argv, klass, "wb");
}


new (Zlib::GzipWriter)

/*
 * call-seq: Zlib::GzipWriter.new(io, level, strategy)
 *
 * Creates a GzipWriter object associated with +io+. +level+ and +strategy+
 * should be the same as the arguments of Zlib::Deflate.new.  The GzipWriter
 * object writes gzipped data to +io+.  At least, +io+ must respond to the
 * +write+ method that behaves same as write method in IO class.
 */
static VALUE
rb_gzwriter_initialize(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct gzfile *gz;
    VALUE io, level, strategy;
    int err;

    rb_scan_args(argc, argv, "12", &io, &level, &strategy);
    Data_Get_Struct(obj, struct gzfile, gz);

    /* this is undocumented feature of zlib */
    gz->level = ARG_LEVEL(level);
    err = deflateInit2(&gz->z.stream, gz->level, Z_DEFLATED,
                       -MAX_WBITS, DEF_MEM_LEVEL, ARG_STRATEGY(strategy));
    if (err != Z_OK) {
        raise_zlib_error(err, gz->z.stream.msg);
    }
    gz->io = io;
    ZSTREAM_READY(&gz->z);

    return obj;
}


flush (Zlib::GzipWriter)

/*
 * call-seq: flush(flush=nil)
 *
 * Flushes all the internal buffers of the GzipWriter object.  The meaning of
 * +flush+ is same as in Zlib::Deflate#deflate.  <tt>Zlib::SYNC_FLUSH</tt> is used if
 * +flush+ is omitted.  It is no use giving flush <tt>Zlib::NO_FLUSH</tt>.
 */
static VALUE
rb_gzwriter_flush(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE v_flush;
    int flush;

    rb_scan_args(argc, argv, "01", &v_flush);

    flush = FIXNUMARG(v_flush, Z_SYNC_FLUSH);
    if (flush != Z_NO_FLUSH) {  /* prevent Z_BUF_ERROR */
        zstream_run(&gz->z, "", 0, flush);
    }

    gzfile_write_raw(gz);
    if (rb_respond_to(gz->io, id_flush)) {
        rb_funcall(gz->io, id_flush, 0);
    }
    return obj;
}


write (Zlib::GzipWriter)

/*
 * Same as IO.
 */
static VALUE
rb_gzwriter_write(obj, str)
    VALUE obj, str;
{
    struct gzfile *gz = get_gzfile(obj);

    if (TYPE(str) != T_STRING) {
        str = rb_obj_as_string(str);
    }
    gzfile_write(gz, RSTRING(str)->ptr, RSTRING(str)->len);
    return INT2FIX(RSTRING(str)->len);
}


putc (Zlib::GzipWriter)

/*
 * Same as IO.
 */
static VALUE
rb_gzwriter_putc(obj, ch)
    VALUE obj, ch;
{
    struct gzfile *gz = get_gzfile(obj);
    char c = NUM2CHR(ch);

    gzfile_write(gz, &c, 1);
    return ch;
}


inflate (Zlib::Inflate)

/*
 * call-seq: Zlib::Inflate.inflate(string)
 *
 * Decompresses +string+. Raises a Zlib::NeedDict exception if a preset
 * dictionary is needed for decompression.
 *
 * This method is almost equivalent to the following code:
 *
 *   def inflate(string)
 *     zstream = Zlib::Inflate.new
 *     buf = zstream.inflate(string)
 *     zstream.finish
 *     zstream.close
 *     buf
 *   end
 *
 */
static VALUE
rb_inflate_s_inflate(obj, src)
    VALUE obj, src;
{
    struct zstream z;
    VALUE dst, args[2];
    int err;

    StringValue(src);
    zstream_init_inflate(&z);
    err = inflateInit(&z.stream);
    if (err != Z_OK) {
        raise_zlib_error(err, z.stream.msg);
    }
    ZSTREAM_READY(&z);

    args[0] = (VALUE)&z;
    args[1] = src;
    dst = rb_ensure(inflate_run, (VALUE)args, zstream_end, (VALUE)&z);

    OBJ_INFECT(dst, src);
    return dst;
}


new (Zlib::Inflate)

/*
 * call-seq: Zlib::Inflate.new(window_bits)
 *
 * Creates a new inflate stream for decompression. See zlib.h for details
 * of the argument.  If +window_bits+ is +nil+, the default value is used.
 *
 * TODO: document better!
 */
static VALUE
rb_inflate_initialize(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    struct zstream *z;
    VALUE wbits;
    int err;

    rb_scan_args(argc, argv, "01", &wbits);
    Data_Get_Struct(obj, struct zstream, z);

    err = inflateInit2(&z->stream, ARG_WBITS(wbits));
    if (err != Z_OK) {
        raise_zlib_error(err, z->stream.msg);
    }
    ZSTREAM_READY(z);

    return obj;
}


inflate (Zlib::Inflate)

/*
 * call-seq: inflate(string)
 *
 * Inputs +string+ into the inflate stream and returns the output from the
 * stream.  Calling this method, both the input and the output buffer of the
 * stream are flushed.  If string is +nil+, this method finishes the stream,
 * just like Zlib::ZStream#finish.
 *
 * Raises a Zlib::NeedDict exception if a preset dictionary is needed to
 * decompress.  Set the dictionary by Zlib::Inflate#set_dictionary and then
 * call this method again with an empty string.  (<i>???</i>)
 *
 * TODO: document better!
 */
static VALUE
rb_inflate_inflate(obj, src)
    VALUE obj, src;
{
    struct zstream *z = get_zstream(obj);
    VALUE dst;

    OBJ_INFECT(obj, src);

    if (ZSTREAM_IS_FINISHED(z)) {
        if (NIL_P(src)) {
            dst = zstream_detach_buffer(z);
        }
        else {
            StringValue(src);
            zstream_append_buffer2(z, src);
            dst = rb_str_new(0, 0);
        }
    }
    else {
        do_inflate(z, src);
        dst = zstream_detach_buffer(z);
        if (ZSTREAM_IS_FINISHED(z)) {
            zstream_passthrough_input(z);
        }
    }

    OBJ_INFECT(dst, obj);
    return dst;
}


<< (Zlib::Inflate)

/*
 * call-seq: << string
 *
 * Inputs +string+ into the inflate stream just like Zlib::Inflate#inflate, but
 * returns the Zlib::Inflate object itself.  The output from the stream is
 * preserved in output buffer.
 */
static VALUE
rb_inflate_addstr(obj, src)
    VALUE obj, src;
{
    struct zstream *z = get_zstream(obj);

    OBJ_INFECT(obj, src);

    if (ZSTREAM_IS_FINISHED(z)) {
        if (!NIL_P(src)) {
            StringValue(src);
            zstream_append_buffer2(z, src);
        }
    }
    else {
        do_inflate(z, src);
        if (ZSTREAM_IS_FINISHED(z)) {
            zstream_passthrough_input(z);
        }
    }

    return obj;
}


sync (Zlib::Inflate)

/*
 * call-seq: sync(string)
 *
 * Inputs +string+ into the end of input buffer and skips data until a full
 * flush point can be found.  If the point is found in the buffer, this method
 * flushes the buffer and returns false.  Otherwise it returns +true+ and the
 * following data of full flush point is preserved in the buffer.
 */
static VALUE
rb_inflate_sync(obj, src)
    VALUE obj, src;
{
    struct zstream *z = get_zstream(obj);

    OBJ_INFECT(obj, src);
    StringValue(src);
    return zstream_sync(z, RSTRING(src)->ptr, RSTRING(src)->len);
}


sync_point? (Zlib::Inflate)

/*
 * Quoted verbatim from original documentation:
 *
 *   What is this?
 *
 * <tt>:)</tt>
 */
static VALUE
rb_inflate_sync_point_p(obj)
    VALUE obj;
{
    struct zstream *z = get_zstream(obj);
    int err;

    err = inflateSyncPoint(&z->stream);
    if (err == 1) {
        return Qtrue;
    }
    if (err != Z_OK) {
        raise_zlib_error(err, z->stream.msg);
    }
    return Qfalse;
}


set_dictionary (Zlib::Inflate)

/*
 * Sets the preset dictionary and returns +string+.  This method is available just
 * only after a Zlib::NeedDict exception was raised.  See zlib.h for details.
 *
 * TODO: document better!
 */
static VALUE
rb_inflate_set_dictionary(obj, dic)
    VALUE obj, dic;
{
    struct zstream *z = get_zstream(obj);
    VALUE src = dic;
    int err;

    OBJ_INFECT(obj, dic);
    StringValue(src);
    err = inflateSetDictionary(&z->stream,
                               RSTRING(src)->ptr, RSTRING(src)->len);
    if (err != Z_OK) {
        raise_zlib_error(err, z->stream.msg);
    }

    return dic;
}


avail_out (Zlib::ZStream)

/*
 * Returns number of bytes of free spaces in output buffer.  Because the free
 * space is allocated automatically, this method returns 0 normally.
 */
static VALUE
rb_zstream_avail_out(obj)
    VALUE obj;
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return rb_uint2inum(z->stream.avail_out);
}


avail_out= (Zlib::ZStream)

/*
 * Allocates +size+ bytes of free space in the output buffer. If there are more
 * than +size+ bytes already in the buffer, the buffer is truncated. Because
 * free space is allocated automatically, you usually don't need to use this
 * method.
 */
static VALUE
rb_zstream_set_avail_out(obj, size)
    VALUE obj, size;
{
    struct zstream *z = get_zstream(obj);

    Check_Type(size, T_FIXNUM);
    zstream_expand_buffer_into(z, FIX2INT(size));
    return size;
}


avail_in (Zlib::ZStream)

/*
 * Returns bytes of data in the input buffer. Normally, returns 0.
 */
static VALUE
rb_zstream_avail_in(obj)
    VALUE obj;
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return INT2FIX(NIL_P(z->input) ? 0 : (int)(RSTRING(z->input)->len));
}


total_in (Zlib::ZStream)

/*
 * Returns the total bytes of the input data to the stream.  FIXME
 */
static VALUE
rb_zstream_total_in(obj)
    VALUE obj;
{
    return rb_uint2inum(get_zstream(obj)->stream.total_in);
}


total_out (Zlib::ZStream)

/*
 * Returns the total bytes of the output data from the stream.  FIXME
 */
static VALUE
rb_zstream_total_out(obj)
    VALUE obj;
{
    return rb_uint2inum(get_zstream(obj)->stream.total_out);
}


data_type (Zlib::ZStream)

/*
 * Guesses the type of the data which have been inputed into the stream. The
 * returned value is either <tt>Zlib::BINARY</tt>, <tt>Zlib::ASCII</tt>, or
 * <tt>Zlib::UNKNOWN</tt>.
 */
static VALUE
rb_zstream_data_type(obj)
    VALUE obj;
{
    return INT2FIX(get_zstream(obj)->stream.data_type);
}


adler (Zlib::ZStream)

/*
 * Returns the adler-32 checksum.
 */
static VALUE
rb_zstream_adler(obj)
    VALUE obj;
{
        return rb_uint2inum(get_zstream(obj)->stream.adler);
}


finished? (Zlib::ZStream)

/*
 * Returns true if the stream is finished.
 */
static VALUE
rb_zstream_finished_p(obj)
    VALUE obj;
{
    return ZSTREAM_IS_FINISHED(get_zstream(obj)) ? Qtrue : Qfalse;
}


stream_end? (Zlib::ZStream)

/*
 * Returns true if the stream is finished.
 */
static VALUE
rb_zstream_finished_p(obj)
    VALUE obj;
{
    return ZSTREAM_IS_FINISHED(get_zstream(obj)) ? Qtrue : Qfalse;
}


closed? (Zlib::ZStream)

/*
 * Returns true if the stream is closed.
 */
static VALUE
rb_zstream_closed_p(obj)
    VALUE obj;
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return ZSTREAM_IS_READY(z) ? Qfalse : Qtrue;
}


ended? (Zlib::ZStream)

/*
 * Returns true if the stream is closed.
 */
static VALUE
rb_zstream_closed_p(obj)
    VALUE obj;
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return ZSTREAM_IS_READY(z) ? Qfalse : Qtrue;
}


close (Zlib::ZStream)

/*
 * Closes the stream. All operations on the closed stream will raise an
 * exception.
 */
static VALUE
rb_zstream_end(obj)
    VALUE obj;
{
    zstream_end(get_zstream(obj));
    return Qnil;
}


end (Zlib::ZStream)

/*
 * Closes the stream. All operations on the closed stream will raise an
 * exception.
 */
static VALUE
rb_zstream_end(obj)
    VALUE obj;
{
    zstream_end(get_zstream(obj));
    return Qnil;
}


reset (Zlib::ZStream)

/*
 * Resets and initializes the stream. All data in both input and output buffer
 * are discarded.
 */
static VALUE
rb_zstream_reset(obj)
    VALUE obj;
{
    zstream_reset(get_zstream(obj));
    return Qnil;
}


finish (Zlib::ZStream)

/*
 * Finishes the stream and flushes output buffer. See Zlib::Deflate#finish and
 * Zlib::Inflate#finish for details of this behavior.
 */
static VALUE
rb_zstream_finish(obj)
    VALUE obj;
{
    struct zstream *z = get_zstream(obj);
    VALUE dst;

    zstream_run(z, "", 0, Z_FINISH);
    dst = zstream_detach_buffer(z);

    OBJ_INFECT(dst, obj);
    return dst;
}


flush_next_in (Zlib::ZStream)

/*
 * Flushes input buffer and returns all data in that buffer.
 */
static VALUE
rb_zstream_flush_next_in(obj)
    VALUE obj;
{
    struct zstream *z;
    VALUE dst;

    Data_Get_Struct(obj, struct zstream, z);
    dst = zstream_detach_input(z);
    OBJ_INFECT(dst, obj);
    return dst;
}


flush_next_out (Zlib::ZStream)

/*
 * Flushes output buffer and returns all data in that buffer.
 */
static VALUE
rb_zstream_flush_next_out(obj)
    VALUE obj;
{
    struct zstream *z;
    VALUE dst;

    Data_Get_Struct(obj, struct zstream, z);
    dst = zstream_detach_buffer(z);
    OBJ_INFECT(dst, obj);
    return dst;
}


zlib_version (Zlib)

/*
 * Returns the string which represents the version of zlib library.
 */
static VALUE
rb_zlib_version(klass)
    VALUE klass;
{
    VALUE str;

    str = rb_str_new2(zlibVersion());
    OBJ_TAINT(str);  /* for safe */
    return str;
}


adler32 (Zlib)

/*
 * call-seq: Zlib.adler32(string, adler)
 *
 * Calculates Alder-32 checksum for +string+, and returns updated value of
 * +adler+. If +string+ is omitted, it returns the Adler-32 initial value. If
 * +adler+ is omitted, it assumes that the initial value is given to +adler+.
 *
 * FIXME: expression.
 */
static VALUE
rb_zlib_adler32(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return do_checksum(argc, argv, adler32);
}


crc32 (Zlib)

/*
 * call-seq: Zlib.crc32(string, adler)
 *
 * Calculates CRC checksum for +string+, and returns updated value of +crc+. If
 * +string+ is omitted, it returns the CRC initial value. If +crc+ is omitted, it
 * assumes that the initial value is given to +crc+.
 *
 * FIXME: expression.
 */
static VALUE
rb_zlib_crc32(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    return do_checksum(argc, argv, crc32);
}


crc_table (Zlib)

/*
 * Returns the table for calculating CRC checksum as an array.
 */
static VALUE
rb_zlib_crc_table(obj)
    VALUE obj;
{
    const unsigned long *crctbl;
    VALUE dst;
    int i;

    crctbl = get_crc_table();
    dst = rb_ary_new2(256);

    for (i = 0; i < 256; i++) {
        rb_ary_push(dst, rb_uint2inum(crctbl[i]));
    }
    return dst;
}


File: array.c

array.c

Path: | array.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: bignum.c

bignum.c

Path: | bignum.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: compar.c

compar.c

Path: | compar.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: dir.c

dir.c

Path: | dir.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: enum.c

enum.c

Path: | enum.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: error.c

error.c

Path: | error.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: eval.c

eval.c

Path: | eval.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: file.c

file.c

Path: | file.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: gc.c

gc.c

Path: | gc.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: hash.c

hash.c

Path: | hash.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: io.c

io.c

Path: | io.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: marshal.c

marshal.c

Path: | marshal.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: math.c

math.c

Path: | math.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: numeric.c

numeric.c

Path: | numeric.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: object.c

object.c

Path: | object.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: prec.c

prec.c

Path: | prec.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: process.c

process.c

Path: | process.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: range.c

range.c

Path: | range.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: re.c

re.c

Path: | re.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: signal.c

signal.c

Path: | signal.c
Last Update: | Tue Mar 13 02:08:25 -0500 2007


File: string.c

string.c

Path: | string.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: struct.c

struct.c

Path: | struct.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: time.c

time.c

Path: | time.c
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: enumerator.c

enumerator.c

Path: | ext/enumerator/enumerator.c
Last Update: | Tue Mar 13 02:04:53 -0500 2007


File: iconv.c

iconv.c

Path: | ext/iconv/iconv.c
Last Update: | Mon Oct 01 13:18:31 -0500 2007


File: nkf.c

nkf.c

Path: | ext/nkf/nkf.c
Last Update: | Tue Mar 13 02:04:13 -0500 2007


File: kconv.rb

kconv.rb

Path: | ext/nkf/lib/kconv.rb
Last Update: | Tue Mar 13 02:04:13 -0500 2007

kconv.rb - Kanji Converter.

$Id: kconv.rb 11708 2007-02-12 23:01:19Z shyouhei $

kconv.rb implements the Kconv class for Kanji Converter. Additionally, some methods in String classes are added to allow easy conversion.

Required files

nkf


File: socket.c

socket.c

Path: | ext/socket/socket.c
Last Update: | Mon Oct 01 13:18:30 -0500 2007


File: stringio.c

stringio.c

Path: | ext/stringio/stringio.c
Last Update: | Mon Oct 01 13:18:31 -0500 2007


File: strscan.c

strscan.c

Path: | ext/strscan/strscan.c
Last Update: | Tue Mar 13 02:05:04 -0500 2007


File: extconf.rb

extconf.rb

Path: | ext/win32ole/extconf.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

Required files

mkmf

Methods

create_docfile create_win32ole_makefile

Constants

SRCFILES = <<SRC win32ole.c SRC

Public Instance methods

create_docfile(src)
create_win32ole_makefile()


File: win32ole.c

win32ole.c

Path: | ext/win32ole/win32ole.c
Last Update: | Mon Oct 01 13:18:30 -0500 2007


create_docfile (ext/win32ole/extconf.rb)

# File ext/win32ole/extconf.rb, line 15
def create_docfile(src)
  open(File.expand_path($srcdir) + "/.document", "w") {|ofs|
    ofs.print src
  }
end


create_win32ole_makefile (ext/win32ole/extconf.rb)

# File ext/win32ole/extconf.rb, line 21
def create_win32ole_makefile
  if have_library("ole32") and
     have_library("oleaut32") and
     have_library("uuid") and
     have_library("user32") and
     have_library("kernel32") and
     have_library("advapi32") and
     have_header("windows.h")
    create_makefile("win32ole")
    create_docfile(SRCFILES)
  else
    create_docfile("")
  end
end


File: property.rb

property.rb

Path: | ext/win32ole/lib/win32ole/property.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

OLEProperty helper class of Property with arguments.


File: ieconst.rb

ieconst.rb

Path: | ext/win32ole/sample/ieconst.rb
Last Update: | Tue Mar 13 02:04:09 -0500 2007

Required files

win32ole


File: ienavi.rb

ienavi.rb

Path: | ext/win32ole/sample/ienavi.rb
Last Update: | Tue Mar 13 02:04:09 -0500 2007

Required files

win32ole

Methods

default_handler navigate stop_msg_loop

Public Instance methods

default_handler(event, *args)
navigate(url)
stop_msg_loop()


File: oledirs.rb

oledirs.rb

Path: | ext/win32ole/sample/oledirs.rb
Last Update: | Tue Mar 13 02:04:09 -0500 2007

You need WSH(Windows Scripting Host) to run this script.

Required files

win32ole

Methods

listup

Public Instance methods

listup(items)


File: olegen.rb

olegen.rb

Path: | ext/win32ole/sample/olegen.rb
Last Update: | Tue Mar 13 02:04:09 -0500 2007

Required files

win32ole win32ole


File: xml.rb

xml.rb

Path: | ext/win32ole/sample/xml.rb
Last Update: | Tue Mar 13 02:04:09 -0500 2007

This file created by olegen.rb as following.

   ruby olegen.rb 'Microsoft XML, version 2.0' > xml.rb

Required files

win32ole win32ole/property


navigate (ext/win32ole/sample/ienavi.rb)

# File ext/win32ole/sample/ienavi.rb, line 5
def navigate(url)
  $urls << url
end


stop_msg_loop (ext/win32ole/sample/ienavi.rb)

# File ext/win32ole/sample/ienavi.rb, line 9
def stop_msg_loop
  puts "Now Stop IE..."
  $LOOP = FALSE;
end


default_handler (ext/win32ole/sample/ienavi.rb)

# File ext/win32ole/sample/ienavi.rb, line 14
def default_handler(event, *args)
  case event
  when "BeforeNavigate"
    puts "Now Navigate #{args[0]}..."
  end
end


listup (ext/win32ole/sample/oledirs.rb)

# File ext/win32ole/sample/oledirs.rb, line 7
def listup(items)
#  items.each do |i|
  for i in items
    puts i.name
  end
end


File: oleserver.rb

oleserver.rb

Path: | ext/win32ole/tests/oleserver.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

Required files

win32ole

Methods

oletypelib_name

Public Instance methods

oletypelib_name(pat)


File: test_ole_methods.rb

test_ole_methods.rb

Path: | ext/win32ole/tests/test_ole_methods.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

This is test for [ruby-talk:196897]

Required files

win32ole test/unit


File: test_propertyputref.rb

test_propertyputref.rb

Path: | ext/win32ole/tests/test_propertyputref.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

Required files

test/unit win32ole


File: test_word.rb

test_word.rb

Path: | ext/win32ole/tests/test_word.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

This is test for [ruby-Bugs#3237]

Required files

win32ole test/unit


File: testNIL2VTEMPTY.rb

testNIL2VTEMPTY.rb

Path: | ext/win32ole/tests/testNIL2VTEMPTY.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

This is test script to check that WIN32OLE should convert nil to VT_EMPTY in second try. [ruby-talk:137054]

Required files

win32ole test/unit


File: testOLEEVENT.rb

testOLEEVENT.rb

Path: | ext/win32ole/tests/testOLEEVENT.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

Required files

rubyunit win32ole


File: testOLEMETHOD.rb

testOLEMETHOD.rb

Path: | ext/win32ole/tests/testOLEMETHOD.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

You need RubyUnit and MS Excel and MSI to run this test script

Required files

rubyunit win32ole oleserver


File: testOLEPARAM.rb

testOLEPARAM.rb

Path: | ext/win32ole/tests/testOLEPARAM.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

You need RubyUnit and MS Excel and MSI to run this test script

Required files

rubyunit win32ole oleserver


File: testOLETYPE.rb

testOLETYPE.rb

Path: | ext/win32ole/tests/testOLETYPE.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

You need RubyUnit and MS Excel and MSI to run this test script

Required files

rubyunit win32ole oleserver


File: testOLEVARIABLE.rb

testOLEVARIABLE.rb

Path: | ext/win32ole/tests/testOLEVARIABLE.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

You need RubyUnit and MS Excel and MSI to run this test script

Required files

rubyunit win32ole oleserver


File: testVARIANT.rb

testVARIANT.rb

Path: | ext/win32ole/tests/testVARIANT.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

You need RubyUnit and MS Excel and MSI to run this test script

Required files

rubyunit win32ole


File: testWIN32OLE.rb

testWIN32OLE.rb

Path: | ext/win32ole/tests/testWIN32OLE.rb
Last Update: | Tue Mar 13 02:04:10 -0500 2007

You need RubyUnit and MS Excel and MSI to run this test script

Required files

runit/testcase runit/cui/testrunner win32ole oleserver


oletypelib_name (ext/win32ole/tests/oleserver.rb)

# File ext/win32ole/tests/oleserver.rb, line 2
def oletypelib_name(pat)
  WIN32OLE_TYPE.typelibs.each do |lib|
    return lib if pat =~ lib
  end
end


File: zlib.c

zlib.c

Path: | ext/zlib/zlib.c
Last Update: | Tue Mar 13 02:04:09 -0500 2007


File: abbrev.rb

abbrev.rb

Path: | lib/abbrev.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007


File: base64.rb

base64.rb

Path: | lib/base64.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007

base64.rb: methods for base64-encoding and -decoding stings

Author: | Yukihiro Matsumoto
Documentation: | Dave Thomas and Gavin Sinclair

Until Ruby 1.8.1, these methods were defined at the top-level. Now they are in the Base64 module but included in the top-level, where their usage is deprecated.

See Base64 for documentation.

Required files

kconv

Included Modules

Base64::Deprecated


File: benchmark.rb

benchmark.rb

Path: | lib/benchmark.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Included Modules

Benchmark


File: cgi-lib.rb

cgi-lib.rb

Path: | lib/cgi-lib.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

delegate shellwords.rb


File: cgi.rb

cgi.rb

Path: | lib/cgi.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007

cgi.rb - cgi support library

Copyright (C) 2000 Network Applied Communication Laboratory, Inc.

Copyright (C) 2000 Information-technology Promotion Agency, Japan

Author: Wakou Aoyama <wakou@ruby-lang.org>

Documentation: Wakou Aoyama (RDoc‘d and embellished by William Webber)

Overview

The Common Gateway Interface (CGI) is a simple protocol for passing an HTTP request from a web server to a standalone program, and returning the output to the web browser. Basically, a CGI program is called with the parameters of the request passed in either in the environment (GET) or via $stdin (POST), and everything it prints to $stdout is returned to the client.

This file holds the CGI class. This class provides functionality for retrieving HTTP request parameters, managing cookies, and generating HTML output. See the class documentation for more details and examples of use.

The file cgi/session.rb provides session management functionality; see that file for more details.

See www.w3.org/CGI/ for more information on the CGI protocol.

Required files

English nkf delegate tempfile stringio tempfile shellwords


File: complex.rb

complex.rb

Path: | lib/complex.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  complex.rb -
      $Release Version: 0.5 $
      $Revision: 1.3 $
      $Date: 1998/07/08 10:05:28 $
      by Keiju ISHITSUKA(SHL Japan Inc.)

complex.rb implements the Complex class for complex numbers. Additionally, some methods in other Numeric classes are redefined or added to allow greater interoperability with Complex numbers.

Complex numbers can be created in the following manner:

  • Complex(a, b)
  • Complex.polar(radius, theta)

Additionally, note the following:

  • Complex::I (the mathematical constant i)
  • Numeric#im (e.g. 5.im -> 0+5i)

The following Math module methods are redefined to handle Complex arguments. They will work as normal with non-Complex arguments.

   sqrt exp cos sin tan log log10
   cosh sinh tanh acos asin atan atan2 acosh asinh atanh

Methods

Complex

Public Instance methods

Complex(a, b = 0)

Creates a Complex number. a and b should be Numeric. The result will be a+bi.


File: csv.rb

csv.rb

Path: | lib/csv.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

CSV — module for generating/parsing CSV data. Copyright (C) 2000-2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>.


File: date.rb

date.rb

Path: | lib/date.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

date.rb - date and time library

Author: Tadayoshi Funaba 1998-2006

Documentation: William Webber <william@williamwebber.com>

Overview

This file provides two classes for working with dates and times.

The first class, Date, represents dates. It works with years, months, weeks, and days. See the Date class documentation for more details.

The second, DateTime, extends Date to include hours, minutes, seconds, and fractions of a second. It provides basic support for time zones. See the DateTime class documentation for more details.

Ways of calculating the date.

In common usage, the date is reckoned in years since or before the Common Era (CE/BCE, also known as AD/BC), then as a month and day-of-the-month within the current year. This is known as the Civil Date, and abbreviated as civil in the Date class.

Instead of year, month-of-the-year, and day-of-the-month, the date can also be reckoned in terms of year and day-of-the-year. This is known as the Ordinal Date, and is abbreviated as ordinal in the Date class. (Note that referring to this as the Julian date is incorrect.)

The date can also be reckoned in terms of year, week-of-the-year, and day-of-the-week. This is known as the Commercial Date, and is abbreviated as commercial in the Date class. The commercial week runs Monday (day-of-the-week 1) to Sunday (day-of-the-week 7), in contrast to the civil week which runs Sunday (day-of-the-week 0) to Saturday (day-of-the-week 6). The first week of the commercial year starts on the Monday on or before January 1, and the commercial year itself starts on this Monday, not January 1.

For scientific purposes, it is convenient to refer to a date simply as a day count, counting from an arbitrary initial day. The date first chosen for this was January 1, 4713 BCE. A count of days from this date is the Julian Day Number or Julian Date, which is abbreviated as jd in the Date class. This is in local time, and counts from midnight on the initial day. The stricter usage is in UTC, and counts from midday on the initial day. This is referred to in the Date class as the Astronomical Julian Day Number, and abbreviated as ajd. In the Date class, the Astronomical Julian Day Number includes fractional days.

Another absolute day count is the Modified Julian Day Number, which takes November 17, 1858 as its initial day. This is abbreviated as mjd in the Date class. There is also an Astronomical Modified Julian Day Number, which is in UTC and includes fractional days. This is abbreviated as amjd in the Date class. Like the Modified Julian Day Number (and unlike the Astronomical Julian Day Number), it counts from midnight.

Alternative calendars such as the Chinese Lunar Calendar, the Islamic Calendar, or the French Revolutionary Calendar are not supported by the Date class; nor are calendars that are based on an Era different from the Common Era, such as the Japanese Imperial Calendar or the Republic of China Calendar.

Calendar Reform

The standard civil year is 365 days long. However, the solar year is fractionally longer than this. To account for this, a leap year is occasionally inserted. This is a year with 366 days, the extra day falling on February 29. In the early days of the civil calendar, every fourth year without exception was a leap year. This way of reckoning leap years is the Julian Calendar.

However, the solar year is marginally shorter than 365 1/4 days, and so the Julian Calendar gradually ran slow over the centuries. To correct this, every 100th year (but not every 400th year) was excluded as a leap year. This way of reckoning leap years, which we use today, is the Gregorian Calendar.

The Gregorian Calendar was introduced at different times in different regions. The day on which it was introduced for a particular region is the Day of Calendar Reform for that region. This is abbreviated as sg (for Start of Gregorian calendar) in the Date class.

Two such days are of particular significance. The first is October 15, 1582, which was the Day of Calendar Reform for Italy and most Catholic countries. The second is September 14, 1752, which was the Day of Calendar Reform for England and its colonies (including what is now the United States). These two dates are available as the constants Date::ITALY and Date::ENGLAND, respectively. (By comparison, Germany and Holland, less Catholic than Italy but less stubborn than England, changed over in 1698; Sweden in 1753; Russia not till 1918, after the Revolution; and Greece in 1923. Many Orthodox churches still use the Julian Calendar. A complete list of Days of Calendar Reform can be found at www.polysyllabic.com/GregConv.html.)

Switching from the Julian to the Gregorian calendar involved skipping a number of days to make up for the accumulated lag, and the later the switch was (or is) done, the more days need to be skipped. So in 1582 in Italy, 4th October was followed by 15th October, skipping 10 days; in 1752 in England, 2nd September was followed by 14th September, skipping 11 days; and if I decided to switch from Julian to Gregorian Calendar this midnight, I would go from 27th July 2003 (Julian) today to 10th August 2003 (Gregorian) tomorrow, skipping 13 days. The Date class is aware of this gap, and a supposed date that would fall in the middle of it is regarded as invalid.

The Day of Calendar Reform is relevant to all date representations involving years. It is not relevant to the Julian Day Numbers, except for converting between them and year-based representations.

In the Date and DateTime classes, the Day of Calendar Reform or sg can be specified a number of ways. First, it can be as the Julian Day Number of the Day of Calendar Reform. Second, it can be using the constants Date::ITALY or Date::ENGLAND; these are in fact the Julian Day Numbers of the Day of Calendar Reform of the respective regions. Third, it can be as the constant Date::JULIAN, which means to always use the Julian Calendar. Finally, it can be as the constant Date::GREGORIAN, which means to always use the Gregorian Calendar.

Note: in the Julian Calendar, New Years Day was March 25. The Date class does not follow this convention.

Time Zones

DateTime objects support a simple representation of time zones. Time zones are represented as an offset from UTC, as a fraction of a day. This offset is the how much local time is later (or earlier) than UTC. UTC offset 0 is centred on England (also known as GMT). As you travel east, the offset increases until you reach the dateline in the middle of the Pacific Ocean; as you travel west, the offset decreases. This offset is abbreviated as of in the Date class.

This simple representation of time zones does not take into account the common practice of Daylight Savings Time or Summer Time.

Most DateTime methods return the date and the time in local time. The two exceptions are ajd() and amjd(), which return the date and time in UTC time, including fractional days.

The Date class does not support time zone offsets, in that there is no way to create a Date object with a time zone. However, methods of the Date class when used by a DateTime instance will use the time zone offset of this instance.

Examples of use

Print out the date of every Sunday between two dates.

    def print_sundays(d1, d2)
        d1 +=1 while (d1.wday != 0)
        d1.step(d2, 7) do |date|
            puts "#{Date::MONTHNAMES[date.mon]} #{date.day}"
        end
    end

    print_sundays(Date::civil(2003, 4, 8), Date::civil(2003, 5, 23))

Calculate how many seconds to go till midnight on New Year‘s Day.

    def secs_to_new_year(now = DateTime::now())
        new_year = DateTime.new(now.year + 1, 1, 1)
        dif = new_year - now
        hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(dif)
        return hours * 60 * 60 + mins * 60 + secs
    end

    puts secs_to_new_year()

Required files

rational date/format


File: debug.rb

debug.rb

Path: | lib/debug.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan Copyright (C) 2000-2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>

Required files

tracer pp readline

Constants

SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__


File: delegate.rb

delegate.rb

Path: | lib/delegate.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

delegate — Support for the Delegation Pattern

Documentation by James Edward Gray II and Gavin Sinclair

Introduction

This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.

Going a step further, the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.

Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator and customize as needed. (If you find yourself needing this control, have a look at forwardable, also in the standard library. It may suit your needs better.)

Notes

Be advised, RDoc will not detect delegated methods.

delegate.rb provides full-class delegation via the DelegateClass() method. For single-method delegation via def_delegator(), see forwardable.rb.

Examples

SimpleDelegator

Here‘s a simple example that takes advantage of the fact that SimpleDelegator‘s delegation object can be changed at any time.

  class Stats
    def initialize
      @source = SimpleDelegator.new([])
    end

    def stats( records )
      @source.__setobj__(records)

      "Elements:  #{@source.size}\n" +
      " Non-Nil:  #{@source.compact.size}\n" +
      "  Unique:  #{@source.uniq.size}\n"
    end
  end

  s = Stats.new
  puts s.stats(%w{James Edward Gray II})
  puts
  puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])

Prints:

  Elements:  4
   Non-Nil:  4
    Unique:  4

  Elements:  8
   Non-Nil:  7
    Unique:  6

DelegateClass()

Here‘s a sample of use from tempfile.rb.

A Tempfile object is really just a File object with a few special rules about storage location and/or when the File should be deleted. That makes for an almost textbook perfect example of how to use delegation.

  class Tempfile < DelegateClass(File)
    # constant and class member data initialization...

    def initialize(basename, tmpdir=Dir::tmpdir)
      # build up file path/name in var tmpname...

      @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)

      # ...

      super(@tmpfile)

      # below this point, all methods of File are supported...
    end

    # ...
  end

Delegator

SimpleDelegator‘s implementation serves as a nice example here.

   class SimpleDelegator < Delegator
     def initialize(obj)
       super             # pass obj to Delegator constructor, required
       @_sd_obj = obj    # store obj for future use
     end

     def __getobj__
       @_sd_obj          # return object we are delegating to, required
     end

     def __setobj__(obj)
       @_sd_obj = obj    # change delegation object, a feature we're providing
     end

     # ...
   end

Methods

DelegateClass

Public Instance methods

DelegateClass(superclass)

The primary interface to this library. Use to setup delegation when defining your class.

  class MyClass < DelegateClass( ClassToDelegateTo )    # Step 1
    def initiaize
      super(obj_of_ClassToDelegateTo)                   # Step 2
    end
  end


File: e2mmap.rb

e2mmap.rb

Path: | lib/e2mmap.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  e2mmap.rb - for ruby 1.1
      $Release Version: 2.0$
      $Revision: 1.10 $
      $Date: 1999/02/17 12:33:17 $
      by Keiju ISHITSUKA

—

  Usage:

U1)

  class Foo
    extend Exception2MessageMapper
    def_e2message ExistingExceptionClass, "message..."
    def_exception :NewExceptionClass, "message..."[, superclass]
    ...
  end

U2)

  module Error
    extend Exception2MessageMapper
    def_e2meggage ExistingExceptionClass, "message..."
    def_exception :NewExceptionClass, "message..."[, superclass]
    ...
  end
  class Foo
    include Error
    ...
  end

  foo = Foo.new
  foo.Fail ....

U3)

  module Error
    extend Exception2MessageMapper
    def_e2message ExistingExceptionClass, "message..."
    def_exception :NewExceptionClass, "message..."[, superclass]
    ...
  end
  class Foo
    extend Exception2MessageMapper
    include Error
    ...
  end

  Foo.Fail NewExceptionClass, arg...
  Foo.Fail ExistingExceptionClass, arg...


File: erb.rb

erb.rb

Path: | lib/erb.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

ERB — Ruby Templating

Author: | Masatoshi SEKI
Documentation: | James Edward Gray II and Gavin Sinclair

See ERB for primary documentation and ERB::Util for a couple of utility routines.

Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI

You can redistribute it and/or modify it under the same terms as Ruby.

Required files

strscan


File: eregex.rb

eregex.rb

Path: | lib/eregex.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

this is just a proof of concept toy.


File: fileutils.rb

fileutils.rb

Path: | lib/fileutils.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

fileutils.rb

Copyright (c) 2000-2006 Minero Aoki

This program is free software. You can distribute/modify this program under the same terms of ruby.

module FileUtils

Namespace for several file utility methods for copying, moving, removing, etc.

Module Functions

  cd(dir, options)
  cd(dir, options) {|dir| .... }
  pwd()
  mkdir(dir, options)
  mkdir(list, options)
  mkdir_p(dir, options)
  mkdir_p(list, options)
  rmdir(dir, options)
  rmdir(list, options)
  ln(old, new, options)
  ln(list, destdir, options)
  ln_s(old, new, options)
  ln_s(list, destdir, options)
  ln_sf(src, dest, options)
  cp(src, dest, options)
  cp(list, dir, options)
  cp_r(src, dest, options)
  cp_r(list, dir, options)
  mv(src, dest, options)
  mv(list, dir, options)
  rm(list, options)
  rm_r(list, options)
  rm_rf(list, options)
  install(src, dest, mode = <src's>, options)
  chmod(mode, list, options)
  chmod_R(mode, list, options)
  chown(user, group, list, options)
  chown_R(user, group, list, options)
  touch(list, options)

The options parameter is a hash of options, taken from the list :force, :noop, :preserve, and :verbose. :noop means that no changes are made. The other two are obvious. Each method documents the options that it honours.

All methods that have the concept of a "source" file or directory can take either one file or a list of files in that argument. See the method documentation for examples.

There are some `low level’ methods, which do not accept any option:

  copy_entry(src, dest, preserve = false, dereference = false)
  copy_file(src, dest, preserve = false, dereference = true)
  copy_stream(srcstream, deststream)
  remove_entry(path, force = false)
  remove_entry_secure(path, force = false)
  remove_file(path, force = false)
  compare_file(path_a, path_b)
  compare_stream(stream_a, stream_b)
  uptodate?(file, cmp_list)

module FileUtils::Verbose

This module has all methods of FileUtils module, but it outputs messages before acting. This equates to passing the :verbose flag to methods in FileUtils.

module FileUtils::NoWrite

This module has all methods of FileUtils module, but never changes files/directories. This equates to passing the :noop flag to methods in FileUtils.

module FileUtils::DryRun

This module has all methods of FileUtils module, but never changes files/directories. This equates to passing the :noop and :verbose flags to methods in FileUtils.

Required files

etc


File: finalize.rb

finalize.rb

Path: | lib/finalize.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Usage:

add dependency R_method(obj, dependant)

  add(obj, dependant, method = :finalize, *opt)
  add_dependency(obj, dependant, method = :finalize, *opt)

delete dependency R_method(obj, dependant)

  delete(obj_or_id, dependant, method = :finalize)
  delete_dependency(obj_or_id, dependant, method = :finalize)

delete dependency R_*(obj, dependant)

  delete_all_dependency(obj_or_id, dependant)

delete dependency R_method(*, dependant)

  delete_by_dependant(dependant, method = :finalize)

delete dependency R_*(*, dependant)

  delete_all_by_dependant(dependant)

delete all dependency R_*(*, *)

  delete_all

finalize the dependant connected by dependency R_method(obj, dependtant).

  finalize(obj_or_id, dependant, method = :finalize)
  finalize_dependency(obj_or_id, dependant, method = :finalize)

finalize all dependants connected by dependency R_*(obj, dependtant).

  finalize_all_dependency(obj_or_id, dependant)

finalize the dependant connected by dependency R_method(*, dependtant).

  finalize_by_dependant(dependant, method = :finalize)

finalize all dependants connected by dependency R_*(*, dependant).

  finalize_all_by_dependant(dependant)

finalize all dependency registered to the Finalizer.

  finalize_all

stop invoking Finalizer on GC.

  safe{..}


File: find.rb

find.rb

Path: | lib/find.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

find.rb: the Find module for processing all files under a given directory.


File: forwardable.rb

forwardable.rb

Path: | lib/forwardable.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

forwardable - Support for the Delegation Pattern

   $Release Version: 1.1$
   $Revision: 11708 $
   $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
   by Keiju ISHITSUKA(keiju@ishitsuka.com)

   Documentation by James Edward Gray II and Gavin Sinclair

Introduction

This library allows you delegate method calls to an object, on a method by method basis. You can use Forwardable to setup this delegation at the class level, or SingleForwardable to handle it at the object level.

Notes

Be advised, RDoc will not detect delegated methods.

forwardable.rb provides single-method delegation via the def_delegator() and def_delegators() methods. For full-class delegation via DelegateClass(), see delegate.rb.

Examples

Forwardable

Forwardable makes building a new class based on existing work, with a proper interface, almost trivial. We want to rely on what has come before obviously, but with delegation we can take just the methods we need and even rename them as appropriate. In many cases this is preferable to inheritance, which gives us the entire old interface, even if much of it isn‘t needed.

  class Queue
    extend Forwardable

    def initialize
      @q = [ ]    # prepare delegate object
    end

    # setup prefered interface, enq() and deq()...
    def_delegator :@q, :push, :enq
    def_delegator :@q, :shift, :deq

    # support some general Array methods that fit Queues well
    def_delegators :@q, :clear, :first, :push, :shift, :size
  end

  q = Queue.new
  q.enq 1, 2, 3, 4, 5
  q.push 6

  q.shift    # => 1
  while q.size > 0
    puts q.deq
  end

  q.enq "Ruby", "Perl", "Python"
  puts q.first
  q.clear
  puts q.first

Prints:

  2
  3
  4
  5
  6
  Ruby
  nil

SingleForwardable

   printer = String.new
   printer.extend SingleForwardable        # prepare object for delegation
   printer.def_delegator "STDOUT", "puts"  # add delegation for STDOUT.puts()
   printer.puts "Howdy!"

Prints:

   Howdy!


File: ftools.rb

ftools.rb

Path: | lib/ftools.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

ftools.rb: Extra tools for the File class

Author: | WATANABE, Hirofumi
Documentation: | Zachary Landau

This library can be distributed under the terms of the Ruby license. You can freely distribute/modify this library.

It is included in the Ruby standard library.

Description

ftools adds several (class, not instance) methods to the File class, for copying, moving, deleting, installing, and comparing files, as well as creating a directory path. See the File class for details.

FileUtils contains all or nearly all the same functionality and more, and is a recommended option over ftools

When you

  require 'ftools'

then the File class aquires some utility methods for copying, moving, and deleting files, and more.

See the method descriptions below, and consider using FileUtils as it is more comprehensive.


File: generator.rb

generator.rb

Path: | lib/generator.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

generator.rb: convert an internal iterator to an external one

Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>

All rights reserved. You can redistribute and/or modify it under the same terms as Ruby.

Overview

This library provides the Generator class, which converts an internal iterator (i.e. an Enumerable object) to an external iterator. In that form, you can roll many iterators independently.

The SyncEnumerator class, which is implemented using Generator, makes it easy to roll many Enumerable objects synchronously.

See the respective classes for examples of usage.


File: getoptlong.rb

getoptlong.rb

Path: | lib/getoptlong.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

GetoptLong for Ruby

Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara.

You may redistribute and/or modify this library under the same license terms as Ruby.

See GetoptLong for documentation.

Additional documents and the latest version of `getoptlong.rb’ can be found at www.sra.co.jp/people/m-kasahr/ruby/getoptlong/


File: getopts.rb

getopts.rb

Path: | lib/getopts.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
              getopts.rb -
                      $Release Version: $
                      $Revision: 11708 $
                      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
                      by Yasuo OHBA(SHL Japan Inc. Technology Dept.)

— this is obsolete; use getoptlong

2000-03-21 modified by Minero Aoki <aamine@dp.u-netsurf.ne.jp>

2002-03-05 rewritten by Akinori MUSHA <knu@ruby-lang.org>

Methods

getopts

Public Instance methods

getopts(single_options, *options)

getopts is obsolete. Use GetoptLong.


File: gserver.rb

gserver.rb

Path: | lib/gserver.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Copyright (C) 2001 John W. Small All Rights Reserved

Author: | John W. Small
Documentation: | Gavin Sinclair
Licence: | Freeware.

See the class GServer for documentation.

Required files

socket thread


File: ipaddr.rb

ipaddr.rb

Path: | lib/ipaddr.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

ipaddr.rb - A class to manipulate an IP address

Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>. All rights reserved.

You can redistribute and/or modify it under the same terms as Ruby.

$Id: ipaddr.rb 11708 2007-02-12 23:01:19Z shyouhei $

TODO:

  - scope_id support

Required files

socket


File: irb.rb

irb.rb

Path: | lib/irb.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  irb.rb - irb main module
      $Release Version: 0.9.5 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap irb/init irb/context irb/extend-command irb/ruby-lex irb/input-method irb/locale irb/version


File: jcode.rb

jcode.rb

Path: | lib/jcode.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

jcode.rb - ruby code to handle japanese (EUC/SJIS) string


File: logger.rb

logger.rb

Path: | lib/logger.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

logger.rb - saimple logging utility Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>.

Required files

monitor


File: mailread.rb

mailread.rb

Path: | lib/mailread.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

The Mail class represents an internet mail message (as per RFC822, RFC2822) with headers and a body.


File: mathn.rb

mathn.rb

Path: | lib/mathn.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  mathn.rb -
      $Release Version: 0.5 $
      $Revision: 1.1.1.1.4.1 $
      $Date: 1998/01/16 12:36:05 $
      by Keiju ISHITSUKA(SHL Japan Inc.)

—

Required files

complex.rb rational.rb matrix.rb


File: matrix.rb

matrix.rb

Path: | lib/matrix.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

matrix.rb

An implementation of Matrix and Vector classes.

Author: | Keiju ISHITSUKA
Documentation: | Gavin Sinclair (sourced from Ruby in a Nutshell (Matsumoto, O‘Reilly))

See classes Matrix and Vector for documentation.

Required files

e2mmap.rb


File: mkmf.rb

mkmf.rb

Path: | lib/mkmf.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007

module to create Makefile for extension modules invoke like: ruby -r mkmf extconf.rb

Required files

rbconfig fileutils shellwords

Methods

append_library arg_config cc_command check_sizeof checking_for checking_message config_string configuration cpp_command cpp_include create_header create_makefile create_tmpsrc dir_config dir_re dummy_makefile egrep_cpp enable_config find_executable find_executable0 find_header find_library have_func have_header have_library have_macro have_struct_member have_type have_var init_mkmf install_dirs install_files install_rb libpathflag link_command log_src macro_defined? map_dir merge_libs message mkmf_failed modified? pkg_config rm_f scalar_ptr_type? scalar_type? try_compile try_constant try_cpp try_do try_func try_link try_link0 try_run try_static_assert try_var what_type? winsep with_cflags with_config with_cppflags with_destdir with_ldflags xpopen xsystem

Constants

CONFIG | = | Config::MAKEFILE_CONFIG
ORIG_LIBPATH | = | ENV['LIB']
CXX_EXT | = | %w[cc cxx cpp]
SRC_EXT | = | %w[c m] << CXX_EXT
INSTALL_DIRS | = | [ [dir_re('commondir'), "$(RUBYCOMMONDIR)"], [dir_re("sitedir"), "$(RUBYCOMMONDIR)"], [dir_re('rubylibdir'), "$(RUBYLIBDIR)"], [dir_re('archdir'), "$(RUBYARCHDIR)"], [dir_re('sitelibdir'), "$(RUBYLIBDIR)"], [dir_re('sitearchdir'), "$(RUBYARCHDIR)"]
OUTFLAG | = | CONFIG['OUTFLAG']
CPPOUTFILE | = | CONFIG['CPPOUTFILE']
CONFTEST_C | = | "conftest.c"
FailedMessage | = | <<MESSAGE Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: MESSAGE
EXPORT_PREFIX | = | config_string('EXPORT_PREFIX') {|s| s.strip}
COMMON_HEADERS | = | hdr.join("\n")
COMMON_LIBS | = | config_string('COMMON_LIBS', &split) || []
COMPILE_RULES | = | config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
RULE_SUBST | = | config_string('RULE_SUBST')
COMPILE_C | = | config_string('COMPILE_C') || '$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) -c $<'
COMPILE_CXX | = | config_string('COMPILE_CXX') || '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<'
TRY_LINK | = | config_string('TRY_LINK') || "$(CC) #{OUTFLAG}conftest $(INCFLAGS) $(CPPFLAGS) " \ "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"
LINK_SO | = | config_string('LINK_SO') || if CONFIG["DLEXT"] == $OBJEXT

Public Instance methods

append_library(libs, lib)
arg_config(config, *defaults, &block)
cc_command(opt="")
check_sizeof(type, headers = nil, &b)

Returns the size of the given type. You may optionally specify additional headers to search in for the type.

If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with ‘SIZEOF_’, followed by the type name, followed by ’=X’ where ‘X’ is the actual size.

For example, if check_sizeof(‘mystruct’) returned 12, then the SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.

checking_for(m, fmt = nil) {|| ...}
checking_message(target, place = nil, opt = nil)
config_string(key, config = CONFIG) {|s| ...}
configuration(srcdir)
cpp_command(outfile, opt="")
cpp_include(header)
create_header(header = "extconf.h")
create_makefile(target, srcprefix = nil)

Generates the Makefile for your extension, passing along any options and preprocessor constants that you may have generated through other methods.

The target name should correspond the name of the global function name defined within your C extension, minus the ‘Init_’. For example, if your C extension is defined as ‘Init_foo’, then your target would simply be ‘foo’.

If any ’/’ characters are present in the target name, only the last name is interpreted as the target name, and the rest are considered toplevel directory names, and the generated Makefile will be altered accordingly to follow that directory structure.

For example, if you pass ‘test/foo’ as a target name, your extension will be installed under the ‘test’ directory. This means that in order to load the file within a Ruby program later, that directory structure will have to be followed, e.g. "require ‘test/foo’".

create_tmpsrc(src) {|src| ...}
dir_config(target, idefault=nil, ldefault=nil)

Sets a target name that the user can then use to configure various ‘with’ options with on the command line by using that name. For example, if the target is set to "foo", then the user could use the —with-foo-dir command line option.

You may pass along additional ‘include’ or ‘lib’ defaults via the idefault and ldefault parameters, respectively.

Note that dir_config only adds to the list of places to search for libraries and include files. It does not link the libraries into your application.

dir_re(dir)
dummy_makefile(srcdir)
egrep_cpp(pat, src, opt = "", &b)
enable_config(config, *defaults) {|config, *defaults| ...}
find_executable(bin, path = nil)
find_executable0(bin, path = nil)
find_header(header, *paths)

Instructs mkmf to search for the given header in any of the paths provided, and returns whether or not it was found in those paths.

If the header is found then the path it was found on is added to the list of included directories that are sent to the compiler (via the -I switch).

find_library(lib, func, *paths, &b)

Returns whether or not the entry point func can be found within the library lib in one of the paths specified, where paths is an array of strings. If func is nil , then the main() function is used as the entry point.

If lib is found, then the path it was found on is added to the list of library paths searched and linked against.

have_func(func, headers = nil, &b)

Returns whether or not the function func can be found in the common header files, or within any headers that you provide. If found, a macro is passed as a preprocessor constant to the compiler using the function name, in uppercase, prepended with ‘HAVE_’.

For example, if have_func(‘foo’) returned true, then the HAVE_FOO preprocessor macro would be passed to the compiler.

have_header(header, &b)

Returns whether or not the given header file can be found on your system. If found, a macro is passed as a preprocessor constant to the compiler using the header file name, in uppercase, prepended with ‘HAVE_’.

For example, if have_header(‘foo.h’) returned true, then the HAVE_FOO_H preprocessor macro would be passed to the compiler.

have_library(lib, func = nil, headers = nil, &b)

Returns whether or not the given entry point func can be found within lib. If func is nil, the ‘main()’ entry point is used by default. If found, it adds the library to list of libraries to be used when linking your extension.

If headers are provided, it will include those header files as the header files it looks in when searching for func.

Real name of the library to be linked can be altered by ’—with-FOOlib’ configuration option.

have_macro(macro, headers = nil, opt = "", &b)

Returns whether or not macro is defined either in the common header files or within any headers you provide.

Any options you pass to opt are passed along to the compiler.

have_struct_member(type, member, headers = nil, &b)

Returns whether or not the struct of type type contains member. If it does not, or the struct type can‘t be found, then false is returned. You may optionally specify additional headers in which to look for the struct (in addition to the common header files).

If found, a macro is passed as a preprocessor constant to the compiler using the member name, in uppercase, prepended with ‘HAVE_ST_’.

For example, if have_struct_member(‘foo’, ‘bar’) returned true, then the HAVE_ST_BAR preprocessor macro would be passed to the compiler.

have_type(type, headers = nil, opt = "", &b)

Returns whether or not the static type type is defined. You may optionally pass additional headers to check against in addition to the common header files.

You may also pass additional flags to opt which are then passed along to the compiler.

If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with ‘HAVE_TYPE_’.

For example, if have_type(‘foo’) returned true, then the HAVE_TYPE_FOO preprocessor macro would be passed to the compiler.

have_var(var, headers = nil, &b)

Returns whether or not the variable var can be found in the common header files, or within any headers that you provide. If found, a macro is passed as a preprocessor constant to the compiler using the variable name, in uppercase, prepended with ‘HAVE_’.

For example, if have_var(‘foo’) returned true, then the HAVE_FOO preprocessor macro would be passed to the compiler.

init_mkmf(config = CONFIG)
install_dirs(target_prefix = nil)
install_files(mfile, ifiles, map = nil, srcprefix = nil)
install_rb(mfile, dest, srcdir = nil)
libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
log_src(src)
macro_defined?(macro, src, opt = "", &b)
map_dir(dir, map = nil)
merge_libs(*libs)
message(*s)
mkmf_failed(path)
modified?(target, times)
pkg_config(pkg)
rm_f(*files)
scalar_ptr_type?(type, member = nil, headers = nil, &b)
scalar_type?(type, member = nil, headers = nil, &b)
try_compile(src, opt="", &b)
try_constant(const, headers = nil, opt = "", &b)
try_cpp(src, opt="", &b)
try_do(src, command, &b)
try_func(func, libs, headers = nil, &b)
try_link(src, opt="", &b)
try_link0(src, opt="", &b)
try_run(src, opt = "", &b)
try_static_assert(expr, headers = nil, opt = "", &b)
try_var(var, headers = nil, &b)
what_type?(type, member = nil, headers = nil, &b)
winsep(s)
with_cflags(flags) {|| ...}
with_config(config, *defaults) {|config, *defaults| ...}
with_cppflags(flags) {|| ...}
with_destdir(dir)
with_ldflags(flags) {|| ...}
xpopen(command, *mode, &block)
xsystem(command)


File: monitor.rb

monitor.rb

Path: | lib/monitor.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007


File: mutex_m.rb

mutex_m.rb

Path: | lib/mutex_m.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Usage

Extend an object and use it like a Mutex object:

  require "mutex_m.rb"
  obj = Object.new
  obj.extend Mutex_m
  # ...

Or, include Mutex_m in a class to have its instances behave like a Mutex object:

  class Foo
    include Mutex_m
    # ...
  end

  obj = Foo.new


File: observer.rb

observer.rb

Path: | lib/observer.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

observer.rb implements the Observer object-oriented design pattern. The following documentation is copied, with modifications, from "Programming Ruby", by Hunt and Thomas; www.rubycentral.com/book/lib_patterns.html.

About

The Observer pattern, also known as Publish/Subscribe, provides a simple mechanism for one object to inform a set of interested third-party objects when its state changes.

Mechanism

In the Ruby implementation, the notifying class mixes in the Observable module, which provides the methods for managing the associated observer objects.

The observers must implement the update method to receive notifications.

The observable object must:

  • assert that it has changed
  • call notify_observers

Example

The following example demonstrates this nicely. A Ticker, when run, continually receives the stock Price for its +@symbol+. A Warner is a general observer of the price, and two warners are demonstrated, a WarnLow and a WarnHigh, which print a warning if the price is below or above their set limits, respectively.

The update callback allows the warners to run without being explicitly called. The system is set up with the Ticker and several observers, and the observers do their duty without the top-level code having to interfere.

Note that the contract between publisher and subscriber (observable and observer) is not declared or enforced. The Ticker publishes a time and a price, and the warners receive that. But if you don‘t ensure that your contracts are correct, nothing else can warn you.

  require "observer"

  class Ticker          ### Periodically fetch a stock price.
    include Observable

    def initialize(symbol)
      @symbol = symbol
    end

    def run
      lastPrice = nil
      loop do
        price = Price.fetch(@symbol)
        print "Current price: #{price}\n"
        if price != lastPrice
          changed                 # notify observers
          lastPrice = price
          notify_observers(Time.now, price)
        end
        sleep 1
      end
    end
  end

  class Price           ### A mock class to fetch a stock price (60 - 140).
    def Price.fetch(symbol)
      60 + rand(80)
    end
  end

  class Warner          ### An abstract observer of Ticker objects.
    def initialize(ticker, limit)
      @limit = limit
      ticker.add_observer(self)
    end
  end

  class WarnLow < Warner
    def update(time, price)       # callback for observer
      if price < @limit
        print "--- #{time.to_s}: Price below #@limit: #{price}\n"
      end
    end
  end

  class WarnHigh < Warner
    def update(time, price)       # callback for observer
      if price > @limit
        print "+++ #{time.to_s}: Price above #@limit: #{price}\n"
      end
    end
  end

  ticker = Ticker.new("MSFT")
  WarnLow.new(ticker, 80)
  WarnHigh.new(ticker, 120)
  ticker.run

Produces:

  Current price: 83
  Current price: 75
  --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75
  Current price: 90
  Current price: 134
  +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134
  Current price: 134
  Current price: 112
  Current price: 79
  --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79


File: open3.rb

open3.rb

Path: | lib/open3.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

open3.rb: Popen, but with stderr, too

Author: | Yukihiro Matsumoto
Documentation: | Konrad Meyer

Open3 gives you access to stdin, stdout, and stderr when running other programs.


File: open-uri.rb

open-uri.rb

Path: | lib/open-uri.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007

Required files

uri stringio time net/http net/https tempfile socket net/ftp


File: optparse.rb

optparse.rb

Path: | lib/optparse.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

optparse.rb - command-line option analysis with the OptionParser class.

Author: | Nobu Nakada
Documentation: | Nobu Nakada and Gavin Sinclair.

See OptionParser for documentation.

Methods

abort accept accept banner base def_head_option def_option def_tail_option define define_head define_tail environment getopts getopts help inc inc load make_switch new new on on_head on_tail order order! parse parse! permute permute! program_name reject reject release remove separator summarize terminate terminate to_a to_s top top ver version warn with

Constants

DecimalInteger | = | /\A[-+]?#{decimal}/io | Decimal integer format, to be converted to Integer.
OctalInteger | = | /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io | Ruby/C like octal/hexadecimal/binary integer format, to be converted to Integer.
DecimalNumeric | = | floatpat # decimal integer is allowed as float also. | Decimal integer/float number format, to be converted to Integer for integer format, Float for float format.

External Aliases

banner= | -> | set_banner
 | for experimental cascading :-)
program_name= | -> | set_program_name
summary_width= | -> | set_summary_width
summary_indent= | -> | set_summary_indent

Public Class methods

accept(*args, &blk)

See accept.

getopts(*args)

See getopts.

inc(arg, default = nil)

Returns an incremented value of default according to arg.

new(banner = nil, width = 32, indent = ' ' * 4) {|self if block_given?| ...}

Initializes the instance and yields itself if called with a block.

banner: | Banner message.
width: | Summary width.
indent: | Summary indent.
reject(*args, &blk)

See reject.

terminate(arg = nil)
top()
with(*args, &block)

Initializes a new instance and evaluates the optional block in context of the instance. Arguments args are passed to new, see there for description of parameters.

This method is deprecated, its behavior corresponds to the older new method.

Public Instance methods

abort(mesg = $!)
accept(*args, &blk)

Directs to accept specified class t. The argument string is passed to the block in which it should be converted to the desired class.

t: | Argument class specifier, any object including Class.
pat: | Pattern for argument, defaults to t if it responds to match.
  accept(t, pat, &block)
banner()

Heading banner preceding summary.

base()

Subject of on_tail.

def_head_option(*opts, &block)

Alias for define_head

def_option(*opts, &block)

Alias for define

def_tail_option(*opts, &block)

Alias for define_tail

define(*opts, &block)
define_head(*opts, &block)
define_tail(*opts, &block)
environment(env = File.basename($0, '.*'))

Parses environment variable env or its uppercase with splitting like a shell.

env defaults to the basename of the program.

getopts(*args)

Wrapper method for getopts.rb.

  params = ARGV.getopts("ab:", "foo", "bar:")
  # params[:a] = true   # -a
  # params[:b] = "1"    # -b1
  # params[:foo] = "1"  # --foo
  # params[:bar] = "x"  # --bar x
help()

Returns option summary string.

inc(*args)
load(filename = nil)

Loads options from file names as filename. Does nothing when the file is not present. Returns whether successfully loaded.

filename defaults to basename of the program without suffix in a directory ~/.options.

make_switch(opts, block = nil)

Creates an OptionParser::Switch from the parameters. The parsed argument value is passed to the given block, where it can be processed.

See at the beginning of OptionParser for some full examples.

opts can include the following elements:

Argument style:
One of the following:
  :NONE, :REQUIRED, :OPTIONAL
Argument pattern:
Acceptable option argument format, must be pre-defined with OptionParser.accept or OptionParser#accept, or Regexp. This can appear once or assigned as String if not present, otherwise causes an ArgumentError. Examples:
  Float, Time, Array
Possible argument values:
Hash or Array.
  [:text, :binary, :auto]
  %w[iso-2022-jp shift_jis euc-jp utf8 binary]
  { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
Long style switch:
Specifies a long style switch which takes a mandatory, optional or no argument. It‘s a string of the following form:
  "--switch=MANDATORY" or "--switch MANDATORY"
  "--switch[=OPTIONAL]"
  "--switch"
Short style switch:
Specifies short style switch which takes a mandatory, optional or no argument. It‘s a string of the following form:
  "-xMANDATORY"
  "-x[OPTIONAL]"
  "-x"

There is also a special form which matches character range (not full set of regural expression):

  "-[a-z]MANDATORY"
  "-[a-z][OPTIONAL]"
  "-[a-z]"
Argument style and description:
Instead of specifying mandatory or optional orguments directly in the switch parameter, this separate parameter can be used.
  "=MANDATORY"
  "=[OPTIONAL]"
Description:
Description string for the option.
  "Run verbosely"
Handler:
Handler for the parsed argument value. Either give a block or pass a Proc or Method as an argument.
new() {|self| ...}

Pushes a new List.

on(*opts, &block)

Add option switch and handler. See make_switch for an explanation of parameters.

on_head(*opts, &block)

Add option switch like with on, but at head of summary.

on_tail(*opts, &block)

Add option switch like with on, but at tail of summary.

order(*argv, &block)

Parses command line arguments argv in order. When a block is given, each non-option argument is yielded.

Returns the rest of argv left unparsed.

order!(argv = default_argv, &nonopt)

Same as order, but removes switches destructively.

parse(*argv)

Parses command line arguments argv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise.

parse!(argv = default_argv)

Same as parse, but removes switches destructively.

permute(*argv)

Parses command line arguments argv in permutation mode and returns list of non-option arguments.

permute!(argv = default_argv)

Same as permute, but removes switches destructively.

program_name()

Program name to be emitted in error message and default banner, defaults to $0.

reject(*args, &blk)

Directs to reject specified class argument.

t: Argument class speficier, any object including Class.
  reject(t)
release()

Release code

remove()

Removes the last List.

separator(string)

Add separator in summary.

summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)

Puts option summary into to and returns to. Yields each line if a block is given.

to: | Output destination, which must have method <<. Defaults to [].
width: | Width of left side, defaults to @summary_width.
max: | Maximum length allowed for left side, defaults to width - 1.
indent: | Indentation, defaults to @summary_indent.
terminate(arg = nil)

Terminates option parsing. Optional parameter arg is a string pushed back to be the first non-option argument.

to_a()

Returns option summary list.

to_s()

Alias for help

top()

Subject of on / on_head, accept / reject

ver()

Returns version string from program_name, version and release.

version()

Version

warn(mesg = $!)


File: ostruct.rb

ostruct.rb

Path: | lib/ostruct.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

ostruct.rb: OpenStruct implementation

Author: | Yukihiro Matsumoto
Documentation: | Gavin Sinclair

OpenStruct allows the creation of data objects with arbitrary attributes. See OpenStruct for an example.


File: parsearg.rb

parsearg.rb

Path: | lib/parsearg.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
              parsearg.rb - parse arguments
                      $Release Version: $
                      $Revision: 11708 $
                      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
                      by Yasuo OHBA(SHL Japan Inc. Technology Dept.)

—

Required files

getopts

Methods

parseArgs printUsageAndExit setExpression setOrAnd setParenthesis

Public Instance methods

parseArgs(argc, nopt, single_opts, *opts)

parseArgs is obsolete. Use OptionParser instead.

printUsageAndExit()
setExpression(ex, opt, op)
setOrAnd(ex, opt, c)
setParenthesis(ex, opt, c)


File: parsedate.rb

parsedate.rb

Path: | lib/parsedate.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

parsedate.rb: Parses dates

Author: | Tadayoshi Funaba
Documentation: | Konrad Meyer

ParseDate munches on a date and turns it into an array of values.

Required files

date/format


File: pathname.rb

pathname.rb

Path: | lib/pathname.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

pathname.rb

Object-Oriented Pathname Class

Author: | Tanaka Akira <akr@m17n.org>
Documentation: | Author and Gavin Sinclair

For documentation, see class Pathname.

pathname.rb is distributed with Ruby since 1.8.0.

Required files

find fileutils fileutils


File: ping.rb

ping.rb

Path: | lib/ping.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

ping.rb: Check a host for upness

Author: | Yukihiro Matsumoto
Documentation: | Konrad Meyer

Performs the function of the basic network testing tool, ping. See: Ping.

Required files

timeout socket


File: pp.rb

pp.rb

Path: | lib/pp.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Pretty-printer for Ruby objects.

Which seems better?

non-pretty-printed output by p is:

  #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>

pretty-printed output by pp is:

  #<PP:0x81fedf0
   @buffer=[],
   @buffer_width=0,
   @genspace=#<Proc:0x81feda0>,
   @group_queue=
    #<PrettyPrint::GroupQueue:0x81fed3c
     @queue=
      [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
       []]>,
   @group_stack=
    [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
   @indent=0,
   @maxwidth=79,
   @newline="\n",
   @output=#<IO:0x8114ee4>,
   @output_width=2>

I like the latter. If you do too, this library is for you.

Usage

  pp(obj)

output obj to +$>+ in pretty printed format.

It returns nil.

Output Customization

To define your customized pretty printing function for your classes, redefine a method pretty_print(pp) in the class. It takes an argument pp which is an instance of the class PP. The method should use PP#text, PP#breakable, PP#nest, PP#group and PP#pp to print the object.

Author

Tanaka Akira <akr@m17n.org>

Required files

prettyprint etc.so

Methods

pretty_print pretty_print_cycle

Public Instance methods

pretty_print(q)
pretty_print_cycle(q)


File: prettyprint.rb

prettyprint.rb

Path: | lib/prettyprint.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

$Id$

Required files

test/unit


File: profiler.rb

profiler.rb

Path: | lib/profiler.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Methods

print_profile start_profile stop_profile

Public Instance methods

print_profile(f)
start_profile()
stop_profile()


File: pstore.rb

pstore.rb

Path: | lib/pstore.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

PStore — Transactional File Storage for Ruby Objects

pstore.rb -

  originally by matz
  documentation by Kev Jackson and James Edward Gray II

See PStore for documentation.

Required files

fileutils digest/md5


File: rational.rb

rational.rb

Path: | lib/rational.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  rational.rb -
      $Release Version: 0.5 $
      $Revision: 1.7 $
      $Date: 1999/08/24 12:49:28 $
      by Keiju ISHITSUKA(SHL Japan Inc.)

Documentation by Kevin Jackson and Gavin Sinclair.

When you require ‘rational‘, all interactions between numbers potentially return a rational result. For example:

  1.quo(2)              # -> 0.5
  require 'rational'
  1.quo(2)              # -> Rational(1,2)

See Rational for full documentation.

Methods

Rational

Public Instance methods

Rational(a, b = 1)

Creates a Rational number (i.e. a fraction). a and b should be Integers:

  Rational(1,3)           # -> 1/3

Note: trying to construct a Rational with floating point or real values produces errors:

  Rational(1.1, 2.3)      # -> NoMethodError


File: readbytes.rb

readbytes.rb

Path: | lib/readbytes.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

TruncatedDataError is raised when IO#readbytes fails to read enough data.


File: resolv-replace.rb

resolv-replace.rb

Path: | lib/resolv-replace.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

socket resolv


File: resolv.rb

resolv.rb

Path: | lib/resolv.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

socket fcntl timeout thread win32/resolv


File: scanf.rb

scanf.rb

Path: | lib/scanf.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

scanf for Ruby

$Revision: 11708 $ $Id: scanf.rb 11708 2007-02-12 23:01:19Z shyouhei $ $Author: shyouhei $ $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $

A product of the Austin Ruby Codefest (Austin, Texas, August 2002)


File: set.rb

set.rb

Path: | lib/set.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Copyright (c) 2002 Akinori MUSHA <knu@iDaemons.org>

Documentation by Akinori MUSHA and Gavin Sinclair.

All rights reserved. You can redistribute and/or modify it under the same terms as Ruby.

  $Id: set.rb 11980 2007-03-03 16:06:45Z knu $

Overview

This library provides the Set class, which deals with a collection of unordered values with no duplicates. It is a hybrid of Array‘s intuitive inter-operation facilities and Hash‘s fast lookup. If you need to keep values ordered, use the SortedSet class.

The method to_set is added to Enumerable for convenience.

See the Set class for an example of usage.

Required files

tsort rbtree


File: shell.rb

shell.rb

Path: | lib/shell.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  shell.rb -
      $Release Version: 0.6.0 $
      $Revision: 1.8 $
      $Date: 2001/03/19 09:01:11 $
      by Keiju ISHITSUKA(Nippon Rational Inc.)

—

Required files

e2mmap thread shell/error shell/command-processor shell/process-controller


File: shellwords.rb

shellwords.rb

Path: | lib/shellwords.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

shellwords.rb: Split text into an array of tokens a la UNIX shell


File: singleton.rb

singleton.rb

Path: | lib/singleton.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

The Singleton module implements the Singleton pattern.

Usage:

   class Klass
      include Singleton
      # ...
   end
  • this ensures that only one instance of Klass lets call it ``the instance’’ can be created.

    a,b = Klass.instance, Klass.instance a == b # => true a.new # NoMethodError - new is private …

  • ``The instance’’ is created at instantiation time, in other words the first call of Klass.instance(), thus
      class OtherKlass
    include Singleton
    # ...
  end
  ObjectSpace.each_object(OtherKlass){} # => 0.
  • This behavior is preserved under inheritance and cloning.

This is achieved by marking

  • Klass.new and Klass.allocate - as private

Providing (or modifying) the class methods

  • Klass.inherited(sub_klass) and Klass.clone() - to ensure that the Singleton pattern is properly inherited and cloned.
  • Klass.instance() - returning ``the instance’’. After a successful self modifying (normally the first) call the method body is a simple:
       def Klass.instance()
     return @__instance__
   end
  • Klass._load(str) - calling Klass.instance()
  • Klass._instantiate?() - returning ``the instance’’ or nil. This hook method puts a second (or nth) thread calling Klass.instance() on a waiting loop. The return value signifies the successful completion or premature termination of the first, or more generally, current "instantiation thread".

The instance method of Singleton are

  • clone and dup - raising TypeErrors to prevent cloning or duping
  • _dump(depth) - returning the empty string. Marshalling strips by default all state information, e.g. instance variables and taint state, from ``the instance’’. Providing custom _load(str) and _dump(depth) hooks allows the (partially) resurrections of a previous state of ``the instance’’.

Methods

__init__

Public Instance methods

__init__(klass)


File: sync.rb

sync.rb

Path: | lib/sync.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  sync.rb - 2 phase lock with counter
      $Release Version: 1.0$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ishitsuka.com)

—

 Sync_m, Synchronizer_m
 Usage:
  obj.extend(Sync_m)
  or
  class Foo
      include Sync_m
      :
  end

  Sync_m#sync_mode
  Sync_m#sync_locked?, locked?
  Sync_m#sync_shared?, shared?
  Sync_m#sync_exclusive?, sync_exclusive?
  Sync_m#sync_try_lock, try_lock
  Sync_m#sync_lock, lock
  Sync_m#sync_unlock, unlock

  Sync, Synchronicer:
      include Sync_m
  Usage:
  sync = Sync.new

  Sync#mode
  Sync#locked?
  Sync#shared?
  Sync#exclusive?
  Sync#try_lock(mode) -- mode = :EX, :SH, :UN
  Sync#lock(mode)     -- mode = :EX, :SH, :UN
  Sync#unlock
  Sync#synchronize(mode) {...}

Constants

Synchronizer_m | = | Sync_m
Synchronizer | = | Sync


File: tempfile.rb

tempfile.rb

Path: | lib/tempfile.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

tempfile - manipulates temporary files

$Id: tempfile.rb 11708 2007-02-12 23:01:19Z shyouhei $

Required files

delegate tmpdir


File: thread.rb

thread.rb

Path: | lib/thread.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

NOTE:

  This file is overwritten by ext/thread/lib/thread.rb unless ruby
  is configured with --disable-fastthread.

              thread.rb - thread support classes
                      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
                      by Yukihiro Matsumoto <matz@netlab.co.jp>

Copyright (C) 2001 Yukihiro Matsumoto Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan


File: thwait.rb

thwait.rb

Path: | lib/thwait.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  thwait.rb - thread synchronization class
      $Release Version: 0.9 $
      $Revision: 1.3 $
      $Date: 1998/06/26 03:19:34 $
      by Keiju ISHITSUKA(Nihpon Rational Software Co.,Ltd.)

—

 feature:
 provides synchronization for multiple threads.

 class methods:
 * ThreadsWait.all_waits(thread1,...)
   waits until all of specified threads are terminated.
   if a block is supplied for the method, evaluates it for
   each thread termination.
 * th = ThreadsWait.new(thread1,...)
   creates synchronization object, specifying thread(s) to wait.

 methods:
 * th.threads
   list threads to be synchronized
 * th.empty?
   is there any thread to be synchronized.
 * th.finished?
   is there already terminated thread.
 * th.join(thread1,...)
   wait for specified thread(s).
 * th.join_nowait(threa1,...)
   specifies thread(s) to wait.  non-blocking.
 * th.next_wait
   waits until any of specified threads is terminated.
 * th.all_waits
   waits until all of specified threads are terminated.
   if a block is supplied for the method, evaluates it for
   each thread termination.

Required files

thread.rb e2mmap.rb

Constants

ThWait = ThreadsWait


File: time.rb

time.rb

Path: | lib/time.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Introduction

This library extends the Time class:

  • conversion between date string and time object.
    • date-time defined by RFC 2822
    • HTTP-date defined by RFC 2616
    • dateTime defined by XML Schema Part 2: Datatypes (ISO 8601)
    • various formats handled by Date._parse (string to time only)

Design Issues

Specialized interface

This library provides methods dedicated to special purposes:

  • RFC 2822, RFC 2616 and XML Schema.
  • They makes usual life easier.

Doesn‘t depend on strftime

This library doesn‘t use strftime. Especially rfc2822 doesn‘t depend on strftime because:

  • %a and %b are locale sensitive

    Since they are locale sensitive, they may be replaced to invalid weekday/month name in some locales. Since ruby-1.6 doesn‘t invoke setlocale by default, the problem doesn‘t arise until some external library invokes setlocale. Ruby/GTK is the example of such library.

  • %z is not portable

    %z is required to generate zone in date-time of RFC 2822 but it is not portable.

Revision Information

$Id$

Required files

parsedate test/unit


File: timeout.rb

timeout.rb

Path: | lib/timeout.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Description

A way of performing a potentially long-running operation in a thread, and terminating it‘s execution if it hasn‘t finished within fixed amount of time.

Previous versions of timeout didn‘t use a module for namespace. This version provides both Timeout.timeout, and a backwards-compatible timeout.

Synopsis

  require 'timeout'
  status = Timeout::timeout(5) {
    # Something that should be interrupted if it takes too much time...
  }

Constants

TimeoutError = Timeout::Error # :nodoc: Another name for Timeout::Error, defined for backwards compatibility with earlier versions of timeout.rb.


File: tmpdir.rb

tmpdir.rb

Path: | lib/tmpdir.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

tmpdir - retrieve temporary directory path

$Id: tmpdir.rb 11708 2007-02-12 23:01:19Z shyouhei $

Required files

Win32API


File: tracer.rb

tracer.rb

Path: | lib/tracer.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007
  tracer.rb -
      $Release Version: 0.2$
      $Revision: 1.8 $
      $Date: 1998/05/19 03:42:49 $
      by Keiju ISHITSUKA(Nippon Rational Inc.)

—

Constants

SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__


File: tsort.rb

tsort.rb

Path: | lib/tsort.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

test/unit


File: un.rb

un.rb

Path: | lib/un.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

un.rb

Copyright (c) 2003 WATANABE Hirofumi <eban@ruby-lang.org>

This program is free software. You can distribute/modify this program under the same terms of Ruby.

Utilities to replace common UNIX commands in Makefiles etc

SYNOPSIS

  ruby -run -e cp -- [OPTION] SOURCE DEST
  ruby -run -e ln -- [OPTION] TARGET LINK_NAME
  ruby -run -e mv -- [OPTION] SOURCE DEST
  ruby -run -e rm -- [OPTION] FILE
  ruby -run -e mkdir -- [OPTION] DIRS
  ruby -run -e rmdir -- [OPTION] DIRS
  ruby -run -e install -- [OPTION] SOURCE DEST
  ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
  ruby -run -e touch -- [OPTION] FILE
  ruby -run -e help [COMMAND]

Required files

fileutils optparse

Methods

chmod cp help install ln mkdir mv rm rmdir setup touch

Public Instance methods

chmod()

Change the mode of each FILE to OCTAL-MODE.

  ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE

  -v          verbose
cp()

Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY

  ruby -run -e cp -- [OPTION] SOURCE DEST

  -p          preserve file attributes if possible
  -r          copy recursively
  -v          verbose
help()

Display help message.

  ruby -run -e help [COMMAND]
install()

Copy SOURCE to DEST.

  ruby -run -e install -- [OPTION] SOURCE DEST

  -p          apply access/modification times of SOURCE files to
              corresponding destination files
  -m          set permission mode (as in chmod), instead of 0755
  -v          verbose
ln()

Create a link to the specified TARGET with LINK_NAME.

  ruby -run -e ln -- [OPTION] TARGET LINK_NAME

  -s          make symbolic links instead of hard links
  -f          remove existing destination files
  -v          verbose
mkdir()

Create the DIR, if they do not already exist.

  ruby -run -e mkdir -- [OPTION] DIR

  -p          no error if existing, make parent directories as needed
  -v          verbose
mv()

Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

  ruby -run -e mv -- [OPTION] SOURCE DEST

  -v          verbose
rm()

Remove the FILE

  ruby -run -e rm -- [OPTION] FILE

  -f          ignore nonexistent files
  -r          remove the contents of directories recursively
  -v          verbose
rmdir()

Remove the DIR.

  ruby -run -e rmdir -- [OPTION] DIR

  -v          verbose
setup(options = "") {|ARGV, opt_hash| ...}
touch()

Update the access and modification times of each FILE to the current time.

  ruby -run -e touch -- [OPTION] FILE

  -v          verbose


File: uri.rb

uri.rb

Path: | lib/uri.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

URI support for Ruby

Author: | Akira Yamada <akira@ruby-lang.org>
Documentation: | Akira Yamada <akira@ruby-lang.org>, Dmitry V. Sabanin <sdmitry@lrn.ru>
License: | Copyright (c) 2001 akira yamada <akira@ruby-lang.org> You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: uri.rb 11708 2007-02-12 23:01:19Z shyouhei $

See URI for documentation

Required files

uri/common uri/generic uri/ftp uri/http uri/https uri/ldap uri/mailto


File: weakref.rb

weakref.rb

Path: | lib/weakref.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

delegate thread


File: yaml.rb

yaml.rb

Path: | lib/yaml.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

-*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 $Id: yaml.rb 11708 2007-02-12 23:01:19Z shyouhei $

yaml.rb: top-level module with methods for loading and parsing YAML documents

Author: why the lucky stiff

Required files

stringio yaml/error yaml/syck yaml/tag yaml/stream yaml/constants yaml/rubytypes yaml/types


File: session.rb

session.rb

Path: | lib/cgi/session.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

cgi/session.rb - session support for cgi scripts

Copyright (C) 2001 Yukihiro "Matz" Matsumoto Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan

Author: Yukihiro "Matz" Matsumoto

Documentation: William Webber (william@williamwebber.com)

Overview

This file provides the +CGI::Session+ class, which provides session support for CGI scripts. A session is a sequence of HTTP requests and responses linked together and associated with a single client. Information associated with the session is stored on the server between requests. A session id is passed between client and server with every request and response, transparently to the user. This adds state information to the otherwise stateless HTTP request/response protocol.

See the documentation to the +CGI::Session+ class for more details and examples of usage. See cgi.rb for the CGI class itself.

Required files

cgi tmpdir digest/md5 digest/md5


Complex (lib/complex.rb)

# File lib/complex.rb, line 90
def Complex(a, b = 0)
  if b == 0 and (a.kind_of?(Complex) or defined? Complex::Unify)
    a
  else
    Complex.new( a.real-b.imag, a.imag+b.real )
  end
end


File: format.rb

format.rb

Path: | lib/date/format.rb
Last Update: | Tue Mar 13 02:06:46 -0500 2007

format.rb: Written by Tadayoshi Funaba 1999-2007 $Id: format.rb,v 2.30 2007-01-07 09:16:24+09 tadf Exp $

Required files

rational


DelegateClass (lib/delegate.rb)

# File lib/delegate.rb, line 258
def DelegateClass(superclass)
  klass = Class.new
  methods = superclass.public_instance_methods(true)
  methods -= ::Kernel.public_instance_methods(false)
  methods |= ["to_s","to_a","inspect","==","=~","==="]
  klass.module_eval {
    def initialize(obj)  # :nodoc:
      @_dc_obj = obj
    end
    def method_missing(m, *args)  # :nodoc:
      unless @_dc_obj.respond_to?(m)
        super(m, *args)
      end
      @_dc_obj.__send__(m, *args)
    end
    def respond_to?(m)  # :nodoc:
      return true if super
      return @_dc_obj.respond_to?(m)
    end
    def __getobj__  # :nodoc:
      @_dc_obj
    end
    def __setobj__(obj)  # :nodoc:
      raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
      @_dc_obj = obj
    end
    def clone  # :nodoc:
      super
      __setobj__(__getobj__.clone)
    end
    def dup  # :nodoc:
      super
      __setobj__(__getobj__.dup)
    end
  }
  for method in methods
    begin
      klass.module_eval "def \#{method}(*args, &block)\nbegin\n@_dc_obj.__send__(:\#{method}, *args, &block)\nrescue\n$@[0,2] = nil\nraise\nend\nend\n"
    rescue SyntaxError
      raise NameError, "invalid identifier %s" % method, caller(3)
    end
  end
  return klass
end


File: acl.rb

acl.rb

Path: | lib/drb/acl.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

acl-2.0 - simple Access Control List

Copyright (c) 2000,2002,2003 Masatoshi SEKI

acl.rb is copyrighted free software by Masatoshi SEKI. You can redistribute it and/or modify it under the same terms as Ruby.

Required files

ipaddr


File: drb.rb

drb.rb

Path: | lib/drb/drb.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

drb/drb.rb

Distributed Ruby: dRuby version 2.0.4

Copyright (c) 1999-2003 Masatoshi SEKI. You can redistribute it and/or modify it under the same terms as Ruby.

Author: | Masatoshi SEKI
Documentation: | William Webber (william@williamwebber.com)

Overview

dRuby is a distributed object system for Ruby. It allows an object in one Ruby process to invoke methods on an object in another Ruby process on the same or a different machine.

The Ruby standard library contains the core classes of the dRuby package. However, the full package also includes access control lists and the Rinda tuple-space distributed task management system, as well as a large number of samples. The full dRuby package can be downloaded from the dRuby home page (see References).

For an introduction and examples of usage see the documentation to the DRb module.

References

www2a.biglobe.ne.jp/~seki/ruby/druby.html
The dRuby home page, in Japanese. Contains the full dRuby package and links to other Japanese-language sources.
www2a.biglobe.ne.jp/~seki/ruby/druby.en.html
The English version of the dRuby home page.
www.chadfowler.com/ruby/drb.html
A quick tutorial introduction to using dRuby by Chad Fowler.
www.linux-mag.com/2002-09/ruby_05.html
A tutorial introduction to dRuby in Linux Magazine by Dave Thomas. Includes a discussion of Rinda.
www.eng.cse.dmu.ac.uk/~hgs/ruby/dRuby/
Links to English-language Ruby material collected by Hugh Sasse.
www.rubycentral.com/book/ospace.html
The chapter from Programming Ruby by Dave Thomas and Andy Hunt which discusses dRuby.
www.clio.ne.jp/home/web-i31s/Flotuard/Ruby/PRC2K_seki/dRuby.en.html
Translation of presentation on Ruby by Masatoshi Seki.

Required files

socket thread fcntl drb/eq drb/invokemethod drb/invokemethod16

Constants

DRbObject | = | DRb::DRbObject
DRbUndumped | = | DRb::DRbUndumped
DRbIdConv | = | DRb::DRbIdConv


File: eq.rb

eq.rb

Path: | lib/drb/eq.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

drb/drb


File: extserv.rb

extserv.rb

Path: | lib/drb/extserv.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

drb/drb


File: extservm.rb

extservm.rb

Path: | lib/drb/extservm.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

drb/drb thread


File: gw.rb

gw.rb

Path: | lib/drb/gw.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

drb/drb monitor


File: invokemethod.rb

invokemethod.rb

Path: | lib/drb/invokemethod.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

for ruby-1.8.0


File: observer.rb

observer.rb

Path: | lib/drb/observer.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

observer


File: ssl.rb

ssl.rb

Path: | lib/drb/ssl.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

socket openssl drb/drb singleton


File: timeridconv.rb

timeridconv.rb

Path: | lib/drb/timeridconv.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

drb/drb monitor


File: unix.rb

unix.rb

Path: | lib/drb/unix.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

Required files

socket drb/drb tmpdir etc


getopts (lib/getopts.rb)

# File lib/getopts.rb, line 24
def getopts(single_options, *options)
  boolopts = {}
  valopts = {}

  #
  # set defaults
  #
  single_options.scan(/.:?/) do |opt|
    if opt.size == 1
      boolopts[opt] = false
    else
      valopts[opt[0, 1]] = nil
    end
  end if single_options

  options.each do |arg|
    opt, val = arg.split(':', 2)

    if val
      valopts[opt] = val.empty? ? nil : val
    else
      boolopts[opt] = false
    end
  end

  #
  # scan
  #
  c = 0
  argv = ARGV

  while arg = argv.shift
    case arg
    when /\A--(.*)/
      if $1.empty?                      # xinit -- -bpp 24
        break
      end

      opt, val = $1.split('=', 2)

      if opt.size == 1
        argv.unshift arg
        return nil
      elsif valopts.key? opt            # imclean --src +trash
        valopts[opt] = val || argv.shift or return nil
      elsif boolopts.key? opt           # ruby --verbose
        boolopts[opt] = true
      else
        argv.unshift arg
        return nil
      end

      c += 1
    when /\A-(.+)/
      opts = $1

      until opts.empty?
        opt = opts.slice!(0, 1)

        if valopts.key? opt
          val = opts

          if val.empty?                        # ruby -e 'p $:'
            valopts[opt] = argv.shift or return nil
          else                         # cc -ohello ...
            valopts[opt] = val
          end

          c += 1
          break
        elsif boolopts.key? opt
          boolopts[opt] = true         # ruby -h
          c += 1
        else
          argv.unshift arg
          return nil
        end
      end
    else
      argv.unshift arg
      break
    end
  end

  #
  # set
  #
  $OPT = {}

  boolopts.each do |opt, val|
    $OPT[opt] = val

    sopt = opt.gsub(/[^A-Za-z0-9_]/, '_')
    eval "$OPT_#{sopt} = val"
  end
  valopts.each do |opt, val|
    $OPT[opt] = val

    sopt = opt.gsub(/[^A-Za-z0-9_]/, '_')
    eval "$OPT_#{sopt} = val"
  end

  c
end


File: completion.rb

completion.rb

Path: | lib/irb/completion.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007

irb/completor.rb -

    $Release Version: 0.9$
    $Revision: 11708 $
    $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
    by Keiju ISHITSUKA(keiju@ishitsuka.com)
    From Original Idea of shugo@ruby-lang.org

Required files

readline


File: context.rb

context.rb

Path: | lib/irb/context.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/context.rb - irb context
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/workspace


File: extend-command.rb

extend-command.rb

Path: | lib/irb/extend-command.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/extend-command.rb - irb extend command
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: frame.rb

frame.rb

Path: | lib/irb/frame.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  frame.rb -
      $Release Version: 0.9$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—

Required files

e2mmap


File: help.rb

help.rb

Path: | lib/irb/help.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/help.rb - print usase module
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ishitsuka.com)

—


File: init.rb

init.rb

Path: | lib/irb/init.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/init.rb - irb initialize module
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/help


File: input-method.rb

input-method.rb

Path: | lib/irb/input-method.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/input-method.rb - input methods used irb
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

readline


File: locale.rb

locale.rb

Path: | lib/irb/locale.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/locale.rb - internationalization module
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: notifier.rb

notifier.rb

Path: | lib/irb/notifier.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  notifier.rb - optput methods used by irb
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap irb/output-method


File: output-method.rb

output-method.rb

Path: | lib/irb/output-method.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  output-method.rb - optput methods used by irb
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap


File: ruby-lex.rb

ruby-lex.rb

Path: | lib/irb/ruby-lex.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/ruby-lex.rb - ruby lexcal analizer
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap irb/slex irb/ruby-token


File: ruby-token.rb

ruby-token.rb

Path: | lib/irb/ruby-token.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/ruby-token.rb - ruby tokens
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: slex.rb

slex.rb

Path: | lib/irb/slex.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/slex.rb - symple lex analizer
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap irb/notifier

Constants

SLex = IRB::SLex


File: version.rb

version.rb

Path: | lib/irb/version.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/version.rb - irb version definition file
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ishitsuka.com)

—


File: workspace.rb

workspace.rb

Path: | lib/irb/workspace.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  irb/workspace-binding.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

tempfile thread


File: xmp.rb

xmp.rb

Path: | lib/irb/xmp.rb
Last Update: | Tue Mar 13 02:06:30 -0500 2007
  xmp.rb - irb version of gotoken xmp
      $Release Version: 0.9$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nippon Rational Inc.)

—

Required files

irb irb/frame

Methods

xmp

Public Instance methods

xmp(exps, bind = nil)


File: chws.rb

chws.rb

Path: | lib/irb/cmd/chws.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  change-ws.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/cmd/nop.rb irb/ext/change-ws.rb


File: fork.rb

fork.rb

Path: | lib/irb/cmd/fork.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  fork.rb -
      $Release Version: 0.9.5 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: help.rb

help.rb

Path: | lib/irb/cmd/help.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  help.rb - helper using ri
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $

—

Required files

rdoc/ri/ri_driver


File: load.rb

load.rb

Path: | lib/irb/cmd/load.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  load.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/cmd/nop.rb irb/ext/loader


File: nop.rb

nop.rb

Path: | lib/irb/cmd/nop.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  nop.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: pushws.rb

pushws.rb

Path: | lib/irb/cmd/pushws.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  change-ws.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/cmd/nop.rb irb/ext/workspaces.rb


File: subirb.rb

subirb.rb

Path: | lib/irb/cmd/subirb.rb
Last Update: | Tue Mar 13 02:06:28 -0500 2007
  multi.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/cmd/nop.rb irb/ext/multi-irb


File: change-ws.rb

change-ws.rb

Path: | lib/irb/ext/change-ws.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  irb/ext/cb.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: history.rb

history.rb

Path: | lib/irb/ext/history.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  history.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: loader.rb

loader.rb

Path: | lib/irb/ext/loader.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  loader.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: math-mode.rb

math-mode.rb

Path: | lib/irb/ext/math-mode.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  math-mode.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

mathn


File: multi-irb.rb

multi-irb.rb

Path: | lib/irb/ext/multi-irb.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  irb/multi-irb.rb - multiple irb module
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

thread


File: save-history.rb

save-history.rb

Path: | lib/irb/ext/save-history.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  save-history.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKAkeiju@ruby-lang.org)

—

Required files

readline


File: tracer.rb

tracer.rb

Path: | lib/irb/ext/tracer.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  irb/lib/tracer.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

tracer


File: use-loader.rb

use-loader.rb

Path: | lib/irb/ext/use-loader.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  use-loader.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

irb/cmd/load irb/ext/loader


File: workspaces.rb

workspaces.rb

Path: | lib/irb/ext/workspaces.rb
Last Update: | Tue Mar 13 02:06:27 -0500 2007
  push-ws.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—


File: error.rb

error.rb

Path: | lib/irb/lc/error.rb
Last Update: | Tue Mar 13 02:06:26 -0500 2007
  irb/lc/error.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap


File: error.rb

error.rb

Path: | lib/irb/lc/ja/error.rb
Last Update: | Tue Mar 13 02:06:26 -0500 2007
  irb/lc/ja/error.rb -
      $Release Version: 0.9.5$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(keiju@ruby-lang.org)

—

Required files

e2mmap


xmp (lib/irb/xmp.rb)

# File lib/irb/xmp.rb, line 81
def xmp(exps, bind = nil)
  bind = IRB::Frame.top(1) unless bind
  xmp = XMP.new(bind)
  xmp.puts exps
  xmp
end


config_string (lib/mkmf.rb)

# File lib/mkmf.rb, line 66
def config_string(key, config = CONFIG)
  s = config[key] and !s.empty? and block_given? ? yield(s) : s
end


dir_re (lib/mkmf.rb)

# File lib/mkmf.rb, line 70
def dir_re(dir)
  Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
end


install_dirs (lib/mkmf.rb)

# File lib/mkmf.rb, line 83
def install_dirs(target_prefix = nil)
  if $extout
    dirs = [
      ['RUBYCOMMONDIR', '$(extout)/common'],
      ['RUBYLIBDIR',    '$(RUBYCOMMONDIR)$(target_prefix)'],
      ['RUBYARCHDIR',   '$(extout)/$(arch)$(target_prefix)'],
      ['extout',        "#$extout"],
      ['extout_prefix', "#$extout_prefix"],
    ]
  elsif $extmk
    dirs = [
      ['RUBYCOMMONDIR', '$(rubylibdir)'],
      ['RUBYLIBDIR',    '$(rubylibdir)$(target_prefix)'],
      ['RUBYARCHDIR',   '$(archdir)$(target_prefix)'],
    ]
  else
    dirs = [
      ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
      ['RUBYLIBDIR',    '$(sitelibdir)$(target_prefix)'],
      ['RUBYARCHDIR',   '$(sitearchdir)$(target_prefix)'],
    ]
  end
  dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
  dirs
end


map_dir (lib/mkmf.rb)

# File lib/mkmf.rb, line 109
def map_dir(dir, map = nil)
  map ||= INSTALL_DIRS
  map.inject(dir) {|dir, (orig, new)| dir.gsub(orig, new)}
end


rm_f (lib/mkmf.rb)

# File lib/mkmf.rb, line 142
def rm_f(*files)
  FileUtils.rm_f(Dir[files.join("\0")])
end


modified? (lib/mkmf.rb)

# File lib/mkmf.rb, line 146
def modified?(target, times)
  (t = File.mtime(target)) rescue return nil
  Array === times or times = [times]
  t if times.all? {|n| n <= t}
end


merge_libs (lib/mkmf.rb)

# File lib/mkmf.rb, line 152
def merge_libs(*libs)
  libs.inject([]) do |x, y|
    xy = x & y
    xn = yn = 0
    y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
    y.each_with_index do |v, yi|
      if xy.include?(v)
        xi = [x.index(v), xn].max()
        x[xi, 1] = y[yn..yi]
        xn, yn = xi + (yi - yn + 1), yi + 1
      end
    end
    x.concat(y[yn..-1] || [])
  end
end


xsystem (lib/mkmf.rb)

# File lib/mkmf.rb, line 219
def xsystem command
  Logging::open do
    puts command.quote
    system(command)
  end
end


xpopen (lib/mkmf.rb)

# File lib/mkmf.rb, line 226
def xpopen command, *mode, &block
  Logging::open do
    case mode[0]
    when nil, /^r/
      puts "#{command} |"
    else
      puts "| #{command}"
    end
    IO.popen(command, *mode, &block)
  end
end


log_src (lib/mkmf.rb)

# File lib/mkmf.rb, line 238
def log_src(src)
  src = src.split(/^/)
  fmt = "%#{src.size.to_s.size}d: %s"
  Logging::message "checked program was:\n/* begin */\n"
  src.each_with_index {|line, no| Logging::message fmt, no+1, line}
  Logging::message "/* end */\n\n"
end


create_tmpsrc (lib/mkmf.rb)

# File lib/mkmf.rb, line 254
def create_tmpsrc(src)
  src = yield(src) if block_given?
  src = src.gsub(/[ \t]+$/, '').gsub(/\A\n+|^\n+$/, '').sub(/[^\n]\z/, "\\&\n")
  open(CONFTEST_C, "wb") do |cfile|
    cfile.print src
  end
  src
end


try_do (lib/mkmf.rb)

# File lib/mkmf.rb, line 263
def try_do(src, command, &b)
  src = create_tmpsrc(src, &b)
  xsystem(command)
ensure
  log_src(src)
end


link_command (lib/mkmf.rb)

# File lib/mkmf.rb, line 270
def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
  conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote,
                              'src' => CONFTEST_C,
                              'INCFLAGS' => $INCFLAGS,
                              'CPPFLAGS' => $CPPFLAGS,
                              'CFLAGS' => "#$CFLAGS",
                              'ARCH_FLAG' => "#$ARCH_FLAG",
                              'LDFLAGS' => "#$LDFLAGS #{ldflags}",
                              'LIBPATH' => libpathflag(libpath),
                              'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
                              'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS")
  Config::expand(TRY_LINK.dup, conf)
end


cc_command (lib/mkmf.rb)

# File lib/mkmf.rb, line 284
def cc_command(opt="")
  conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote)
  Config::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
                 conf)
end


cpp_command (lib/mkmf.rb)

# File lib/mkmf.rb, line 290
def cpp_command(outfile, opt="")
  conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote)
  Config::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
                 conf)
end


libpathflag (lib/mkmf.rb)

# File lib/mkmf.rb, line 296
def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
  libpath.map{|x|
    case x
    when "$(topdir)", /\A\./
      LIBPATHFLAG
    else
      LIBPATHFLAG+RPATHFLAG
    end % x.quote
  }.join
end


try_link0 (lib/mkmf.rb)

# File lib/mkmf.rb, line 307
def try_link0(src, opt="", &b)
  try_do(src, link_command("", opt), &b)
end


try_link (lib/mkmf.rb)

# File lib/mkmf.rb, line 311
def try_link(src, opt="", &b)
  try_link0(src, opt, &b)
ensure
  rm_f "conftest*", "c0x32*"
end


try_compile (lib/mkmf.rb)

# File lib/mkmf.rb, line 317
def try_compile(src, opt="", &b)
  try_do(src, cc_command(opt), &b)
ensure
  rm_f "conftest*"
end


try_cpp (lib/mkmf.rb)

# File lib/mkmf.rb, line 323
def try_cpp(src, opt="", &b)
  try_do(src, cpp_command(CPPOUTFILE, opt), &b)
ensure
  rm_f "conftest*"
end


cpp_include (lib/mkmf.rb)

# File lib/mkmf.rb, line 329
def cpp_include(header)
  if header
    header = [header] unless header.kind_of? Array
    header.map {|h| "#include <#{h}>\n"}.join
  else
    ""
  end
end


with_cppflags (lib/mkmf.rb)

# File lib/mkmf.rb, line 338
def with_cppflags(flags)
  cppflags = $CPPFLAGS
  $CPPFLAGS = flags
  ret = yield
ensure
  $CPPFLAGS = cppflags unless ret
end


with_cflags (lib/mkmf.rb)

# File lib/mkmf.rb, line 346
def with_cflags(flags)
  cflags = $CFLAGS
  $CFLAGS = flags
  ret = yield
ensure
  $CFLAGS = cflags unless ret
end


with_ldflags (lib/mkmf.rb)

# File lib/mkmf.rb, line 354
def with_ldflags(flags)
  ldflags = $LDFLAGS
  $LDFLAGS = flags
  ret = yield
ensure
  $LDFLAGS = ldflags unless ret
end


try_static_assert (lib/mkmf.rb)

# File lib/mkmf.rb, line 362
def try_static_assert(expr, headers = nil, opt = "", &b)
  headers = cpp_include(headers)
  try_compile("\#{COMMON_HEADERS}\n\#{headers}\n/*top*/\nint conftest_const[(\#{expr}) ? 1 : -1];\n", opt, &b)
end


try_constant (lib/mkmf.rb)

# File lib/mkmf.rb, line 373
def try_constant(const, headers = nil, opt = "", &b)
  includes = cpp_include(headers)
  if CROSS_COMPILING
    if try_static_assert("#{const} > 0", headers, opt)
      # positive constant
    elsif try_static_assert("#{const} < 0", headers, opt)
      neg = true
      const = "-(#{const})"
    elsif try_static_assert("#{const} == 0", headers, opt)
      return 0
    else
      # not a constant
      return nil
    end
    upper = 1
    lower = 0
    until try_static_assert("#{const} <= #{upper}", headers, opt)
      lower = upper
      upper <<= 1
    end
    return nil unless lower
    while upper > lower + 1
      mid = (upper + lower) / 2
      if try_static_assert("#{const} > #{mid}", headers, opt)
        lower = mid
      else
        upper = mid
      end
    end
    upper = -upper if neg
    return upper
  else
    src = %{#{COMMON_HEADERS}
#{includes}
#include <stdio.h>
/*top*/
int conftest_const = (int)(#{const});
int main() {printf("%d\\n", conftest_const); return 0;}
}
    if try_link0(src, opt, &b)
      xpopen("./conftest") do |f|
        return Integer(f.gets)
      end
    end
  end
  nil
end


try_func (lib/mkmf.rb)

# File lib/mkmf.rb, line 421
def try_func(func, libs, headers = nil, &b)
  headers = cpp_include(headers)
  try_link("\#{COMMON_HEADERS}\n\#{headers}\n/*top*/\nint main() { return 0; }\nint t() { void ((*volatile p)()); p = (void ((*)()))\#{func}; return 0; }\n", libs, &b) or try_link("\#{headers}\n/*top*/\nint main() { return 0; }\nint t() { \#{func}(); return 0; }\n", libs, &b)
end


try_var (lib/mkmf.rb)

# File lib/mkmf.rb, line 439
def try_var(var, headers = nil, &b)
  headers = cpp_include(headers)
  try_compile("\#{COMMON_HEADERS}\n\#{headers}\n/*top*/\nint main() { return 0; }\nint t() { const volatile void *volatile p; p = (void *)&\#{var}; return 0; }\n", &b)
end


egrep_cpp (lib/mkmf.rb)

# File lib/mkmf.rb, line 451
def egrep_cpp(pat, src, opt = "", &b)
  src = create_tmpsrc(src, &b)
  xpopen(cpp_command('', opt)) do |f|
    if Regexp === pat
      puts("    ruby -ne 'print if #{pat.inspect}'")
      f.grep(pat) {|l|
        puts "#{f.lineno}: #{l}"
        return true
      }
      false
    else
      puts("    egrep '#{pat}'")
      begin
        stdin = $stdin.dup
        $stdin.reopen(f)
        system("egrep", pat)
      ensure
        $stdin.reopen(stdin)
      end
    end
  end
ensure
  rm_f "conftest*"
  log_src(src)
end


macro_defined? (lib/mkmf.rb)

# File lib/mkmf.rb, line 477
def macro_defined?(macro, src, opt = "", &b)
  src = src.sub(/[^\n]\z/, "\\&\n")
  try_compile(src + "/*top*/\n#ifndef \#{macro}\n# error\n>>>>>> \#{macro} undefined <<<<<<\n#endif\n", opt, &b)
end


try_run (lib/mkmf.rb)

# File lib/mkmf.rb, line 489
def try_run(src, opt = "", &b)
  if try_link0(src, opt, &b)
    xsystem("./conftest")
  else
    nil
  end
ensure
  rm_f "conftest*"
end


install_files (lib/mkmf.rb)

# File lib/mkmf.rb, line 499
def install_files(mfile, ifiles, map = nil, srcprefix = nil)
  ifiles or return
  srcprefix ||= '$(srcdir)'
  Config::expand(srcdir = srcprefix.dup)
  dirs = []
  path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
  ifiles.each do |files, dir, prefix|
    dir = map_dir(dir, map)
    prefix = %r|\A#{Regexp.quote(prefix)}/?| if prefix
    if /\A\.\// =~ files
      # install files which are in current working directory.
      files = files[2..-1]
      len = nil
    else
      # install files which are under the $(srcdir).
      files = File.join(srcdir, files)
      len = srcdir.size
    end
    f = nil
    Dir.glob(files) do |f|
      f[0..len] = "" if len
      d = File.dirname(f)
      d.sub!(prefix, "") if prefix
      d = (d.empty? || d == ".") ? dir : File.join(dir, d)
      f = File.join(srcprefix, f) if len
      path[d] << f
    end
    unless len or f
      d = File.dirname(files)
      d.sub!(prefix, "") if prefix
      d = (d.empty? || d == ".") ? dir : File.join(dir, d)
      path[d] << files
    end
  end
  dirs
end


install_rb (lib/mkmf.rb)

# File lib/mkmf.rb, line 536
def install_rb(mfile, dest, srcdir = nil)
  install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
end


append_library (lib/mkmf.rb)

# File lib/mkmf.rb, line 540
def append_library(libs, lib)
  format(LIBARG, lib) + " " + libs
end


message (lib/mkmf.rb)

# File lib/mkmf.rb, line 544
def message(*s)
  unless $extmk and not $VERBOSE
    printf(*s)
    $stdout.flush
  end
end


checking_for (lib/mkmf.rb)

# File lib/mkmf.rb, line 551
def checking_for(m, fmt = nil)
  f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim
  m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
  message "%s", m
  a = r = nil
  Logging::postpone do
    r = yield
    a = (fmt ? fmt % r : r ? "yes" : "no") << "\n"
    "#{f}#{m}-------------------- #{a}\n"
  end
  message(a)
  Logging::message "--------------------\n\n"
  r
end


checking_message (lib/mkmf.rb)

# File lib/mkmf.rb, line 566
def checking_message(target, place = nil, opt = nil)
  [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
    if noun
      [[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
        if noun.respond_to?(meth)
          break noun = noun.send(meth, *args)
        end
      end
      msg << " #{pre} #{noun}" unless noun.empty?
    end
    msg
  end
end


have_macro (lib/mkmf.rb)

# File lib/mkmf.rb, line 585
def have_macro(macro, headers = nil, opt = "", &b)
  checking_for checking_message(macro, headers, opt) do
    macro_defined?(macro, cpp_include(headers), opt, &b)
  end
end


have_library (lib/mkmf.rb)

# File lib/mkmf.rb, line 602
def have_library(lib, func = nil, headers = nil, &b)
  func = "main" if !func or func.empty?
  lib = with_config(lib+'lib', lib)
  checking_for checking_message("#{func}()", LIBARG%lib) do
    if COMMON_LIBS.include?(lib)
      true
    else
      libs = append_library($libs, lib)
      if try_func(func, libs, headers, &b)
        $libs = libs
        true
      else
        false
      end
    end
  end
end


find_library (lib/mkmf.rb)

# File lib/mkmf.rb, line 627
def find_library(lib, func, *paths, &b)
  func = "main" if !func or func.empty?
  lib = with_config(lib+'lib', lib)
  paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
  checking_for "#{func}() in #{LIBARG%lib}" do
    libpath = $LIBPATH
    libs = append_library($libs, lib)
    begin
      until r = try_func(func, libs, &b) or paths.empty?
        $LIBPATH = libpath | [paths.shift]
      end
      if r
        $libs = libs
        libpath = nil
      end
    ensure
      $LIBPATH = libpath if libpath
    end
    r
  end
end


have_func (lib/mkmf.rb)

# File lib/mkmf.rb, line 657
def have_func(func, headers = nil, &b)
  checking_for checking_message("#{func}()", headers) do
    if try_func(func, $libs, headers, &b)
      $defs.push(format("-DHAVE_%s", func.upcase))
      true
    else
      false
    end
  end
end


have_var (lib/mkmf.rb)

# File lib/mkmf.rb, line 676
def have_var(var, headers = nil, &b)
  checking_for checking_message(var, headers) do
    if try_var(var, headers, &b)
      $defs.push(format("-DHAVE_%s", var.upcase))
      true
    else
      false
    end
  end
end


have_header (lib/mkmf.rb)

# File lib/mkmf.rb, line 694
def have_header(header, &b)
  checking_for header do
    if try_cpp(cpp_include(header), &b)
      $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___")))
      true
    else
      false
    end
  end
end


find_header (lib/mkmf.rb)

# File lib/mkmf.rb, line 711
def find_header(header, *paths)
  header = cpp_include(header)
  checking_for header do
    if try_cpp(header)
      true
    else
      found = false
      paths.each do |dir|
        opt = "-I#{dir}".quote
        if try_cpp(header, opt)
          $INCFLAGS << " " << opt
          found = true
          break
        end
      end
      found
    end
  end
end


have_struct_member (lib/mkmf.rb)

# File lib/mkmf.rb, line 742
def have_struct_member(type, member, headers = nil, &b)
  checking_for checking_message("#{type}.#{member}", headers) do
    if try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(headers)}\n/*top*/\nint main() { return 0; }\nint s = (char *)&((\#{type}*)0)->\#{member} - (char *)0;\n", &b)
      $defs.push(format("-DHAVE_ST_%s", member.upcase))
      true
    else
      false
    end
  end
end


have_type (lib/mkmf.rb)

# File lib/mkmf.rb, line 773
def have_type(type, headers = nil, opt = "", &b)
  checking_for checking_message(type, headers, opt) do
    headers = cpp_include(headers)
    if try_compile("\#{COMMON_HEADERS}\n\#{headers}\n/*top*/\ntypedef \#{type} conftest_type;\nstatic conftest_type conftestval[sizeof(conftest_type)?1:-1];\n", opt, &b)
      $defs.push(format("-DHAVE_TYPE_%s", type.strip.upcase.tr_s("^A-Z0-9_", "_")))
      true
    else
      false
    end
  end
end


check_sizeof (lib/mkmf.rb)

# File lib/mkmf.rb, line 802
def check_sizeof(type, headers = nil, &b)
  expr = "sizeof(#{type})"
  fmt = "%d"
  def fmt.%(x)
    x ? super : "failed"
  end
  checking_for checking_message("size of #{type}", headers), fmt do
    if size = try_constant(expr, headers, &b)
      $defs.push(format("-DSIZEOF_%s=%d", type.upcase.tr_s("^A-Z0-9_", "_"), size))
      size
    end
  end
end


scalar_ptr_type? (lib/mkmf.rb)

# File lib/mkmf.rb, line 816
def  scalar_ptr_type?scalar_ptr_type?(type, member = nil, headers = nil, &b)
  try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(headers)}\n/*top*/\nvolatile \#{type} conftestval;\nint main() { return 0; }\nint t() {return (int)(1-*(conftestval\#{member ? \".\#{member}\" : \"\"}));}\n", &b)   # pointer
end


scalar_type? (lib/mkmf.rb)

# File lib/mkmf.rb, line 828
def scalar_type?(type, member = nil, headers = nil, &b)
  try_compile("\#{COMMON_HEADERS}\n\#{cpp_include(headers)}\n/*top*/\nvolatile \#{type} conftestval;\nint main() { return 0; }\nint t() {return (int)(1-(conftestval\#{member ? \".\#{member}\" : \"\"}));}\n", &b)   # pointer
end


what_type? (lib/mkmf.rb)

# File lib/mkmf.rb, line 840
def what_type?(type, member = nil, headers = nil, &b)
  m = "#{type}"
  name = type
  if member
    m << "." << member
    name = "(((#{type} *)0)->#{member})"
  end
  fmt = "seems %s"
  def fmt.%(x)
    x ? super : "unknown"
  end
  checking_for checking_message(m, headers), fmt do
    if scalar_ptr_type?(type, member, headers, &b)
      if try_static_assert("sizeof(*#{name}) == 1", headers)
        "string"
      end
    elsif scalar_type?(type, member, headers, &b)
      if try_static_assert("sizeof(#{name}) > sizeof(long)", headers)
        "long long"
      elsif try_static_assert("sizeof(#{name}) > sizeof(int)", headers)
        "long"
      elsif try_static_assert("sizeof(#{name}) > sizeof(short)", headers)
        "int"
      elsif try_static_assert("sizeof(#{name}) > 1", headers)
        "short"
      else
        "char"
      end
    end
  end
end


find_executable0 (lib/mkmf.rb)

# File lib/mkmf.rb, line 872
def  find_executable0find_executable0(bin, path = nil)
  ext = config_string('EXEEXT')
  if File.expand_path(bin) == bin
    return bin if File.executable?(bin)
    ext and File.executable?(file = bin + ext) and return file
    return nil
  end
  if path ||= ENV['PATH']
    path = path.split(File::PATH_SEPARATOR)
  else
    path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
  end
  file = nil
  path.each do |dir|
    return file if File.executable?(file = File.join(dir, bin))
    return file if ext and File.executable?(file << ext)
  end
  nil
end


find_executable (lib/mkmf.rb)

# File lib/mkmf.rb, line 892
def find_executable(bin, path = nil)
  checking_for checking_message(bin, path) do
    find_executable0(bin, path)
  end
end


arg_config (lib/mkmf.rb)

# File lib/mkmf.rb, line 898
def arg_config(config, *defaults, &block)
  $arg_config << [config, *defaults]
  defaults << nil if !block and defaults.empty?
  $configure_args.fetch(config.tr('_', '-'), *defaults, &block)
end


with_config (lib/mkmf.rb)

# File lib/mkmf.rb, line 904
def with_config(config, *defaults)
  config = config.sub(/^--with[-_]/, '')
  val = arg_config("--with-"+config) do
    if arg_config("--without-"+config)
      false
    elsif block_given?
      yield(config, *defaults)
    else
      break *defaults
    end
  end
  case val
  when "yes"
    true
  when "no"
    false
  else
    val
  end
end


enable_config (lib/mkmf.rb)

# File lib/mkmf.rb, line 925
def enable_config(config, *defaults)
  if arg_config("--enable-"+config)
    true
  elsif arg_config("--disable-"+config)
    false
  elsif block_given?
    yield(config, *defaults)
  else
    return *defaults
  end
end


create_header (lib/mkmf.rb)

# File lib/mkmf.rb, line 937
def create_header(header = "extconf.h")
  message "creating %s\n", header
  sym = header.tr("a-z./\055", "A-Z___")
  hdr = ["#ifndef #{sym}\n#define #{sym}\n"]
  for line in $defs
    case line
    when /^-D([^=]+)(?:=(.*))?/
      hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0] : 1}\n"
    when /^-U(.*)/
      hdr << "#undef #$1\n"
    end
  end
  hdr << "#endif\n"
  hdr = hdr.join
  unless (IO.read(header) == hdr rescue false)
    open(header, "w") do |hfile|
      hfile.write(hdr)
    end
  end
  $extconf_h = header
end


dir_config (lib/mkmf.rb)

# File lib/mkmf.rb, line 970
def dir_config(target, idefault=nil, ldefault=nil)
  if dir = with_config(target + "-dir", (idefault unless ldefault))
    defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
    idefault = ldefault = nil
  end

  idir = with_config(target + "-include", idefault)
  $arg_config.last[1] ||= "${#{target}-dir}/include"
  ldir = with_config(target + "-lib", ldefault)
  $arg_config.last[1] ||= "${#{target}-dir}/lib"

  idirs = idir ? Array === idir ? idir : idir.split(File::PATH_SEPARATOR) : []
  if defaults
    idirs.concat(defaults.collect {|dir| dir + "/include"})
    idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
  end
  unless idirs.empty?
    idirs.collect! {|dir| "-I" + dir}
    idirs -= Shellwords.shellwords($CPPFLAGS)
    unless idirs.empty?
      $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
    end
  end

  ldirs = ldir ? Array === ldir ? ldir : ldir.split(File::PATH_SEPARATOR) : []
  if defaults
    ldirs.concat(defaults.collect {|dir| dir + "/lib"})
    ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
  end
  $LIBPATH = ldirs | $LIBPATH

  [idir, ldir]
end


pkg_config (lib/mkmf.rb)

# File lib/mkmf.rb, line 1004
def pkg_config(pkg)
  if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
    # iff package specific config command is given
    get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
  elsif ($PKGCONFIG ||=
         (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
         find_executable0(pkgconfig) && pkgconfig) and
      system("#{$PKGCONFIG} --exists #{pkg}")
    # default to pkg-config command
    get = proc {|opt| `#{$PKGCONFIG} --#{opt} #{pkg}`.chomp}
  elsif find_executable0(pkgconfig = "#{pkg}-config")
    # default to package specific config command, as a last resort.
    get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
  end
  if get
    cflags = get['cflags']
    ldflags = get['libs']
    libs = get['libs-only-l']
    ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
    $CFLAGS += " " << cflags
    $LDFLAGS += " " << ldflags
    $libs += " " << libs
    Logging::message "package configuration for %s\n", pkg
    Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n",
                     cflags, ldflags, libs
    [cflags, ldflags, libs]
  else
    Logging::message "package configuration for %s is not found\n", pkg
    nil
  end
end


with_destdir (lib/mkmf.rb)

# File lib/mkmf.rb, line 1036
def with_destdir(dir)
  dir = dir.sub($dest_prefix_pattern, '')
  /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
end


winsep (lib/mkmf.rb)

# File lib/mkmf.rb, line 1041
def winsep(s)
  s.tr('/', '\\')
end


configuration (lib/mkmf.rb)

# File lib/mkmf.rb, line 1045
def configuration(srcdir)
  mk = []
  vpath = %w[$(srcdir) $(topdir) $(hdrdir)]
  if !CROSS_COMPILING
    case CONFIG['build_os']
    when 'cygwin'
      if CONFIG['target_os'] != 'cygwin'
        vpath.each {|p| p.sub!(/.*/, '$(shell cygpath -u \&)')}
      end
    when 'msdosdjgpp', 'mingw32'
      CONFIG['PATH_SEPARATOR'] = ';'
    end
  end
  mk << %{
SHELL = /bin/sh

#### Start of system configuration section. ####

srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {CONFIG[$1||$2]}.quote}
topdir = #{($extmk ? CONFIG["topdir"] : $topdir).quote}
hdrdir = #{$extmk ? CONFIG["hdrdir"].quote : '$(topdir)'}
VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
}
  if $extmk
    mk << "RUBYLIB = -\nRUBYOPT = -rpurelib.rb\n"
  end
  if destdir = CONFIG["prefix"][$dest_prefix_pattern, 1]
    mk << "\nDESTDIR = #{destdir}\n"
  end
  CONFIG.each do |key, var|
    next unless /prefix$/ =~ key
    mk << "#{key} = #{with_destdir(var)}\n"
  end
  CONFIG.each do |key, var|
    next if /^abs_/ =~ key
    next unless /^(?:src|top|hdr|(.*))dir$/ =~ key and $1
    mk << "#{key} = #{with_destdir(var)}\n"
  end
  if !$extmk and !$configure_args.has_key?('--ruby') and
      sep = config_string('BUILD_FILE_SEPARATOR')
    sep = ":/=#{sep}"
  else
    sep = ""
  end
  extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ")<<" "
  mk << %{
CC = #{CONFIG['CC']}
LIBRUBY = #{CONFIG['LIBRUBY']}
LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC

RUBY_EXTCONF_H = #{$extconf_h}
CFLAGS   = #{$static ? '' : CONFIG['CCDLFLAGS']} #$CFLAGS #$ARCH_FLAG
INCFLAGS = -I. #$INCFLAGS
CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
CXXFLAGS = $(CFLAGS) #{CONFIG['CXXFLAGS']}
DLDFLAGS = #$LDFLAGS #$DLDFLAGS #$ARCH_FLAG
LDSHARED = #{CONFIG['LDSHARED']}
AR = #{CONFIG['AR']}
EXEEXT = #{CONFIG['EXEEXT']}

RUBY_INSTALL_NAME = #{CONFIG['RUBY_INSTALL_NAME']}
RUBY_SO_NAME = #{CONFIG['RUBY_SO_NAME']}
arch = #{CONFIG['arch']}
sitearch = #{CONFIG['sitearch']}
ruby_version = #{Config::CONFIG['ruby_version']}
ruby = #{$ruby}
RUBY = $(ruby#{sep})
RM = #{config_string('RM') || '$(RUBY) -run -e rm -- -f'}
MAKEDIRS = #{config_string('MAKEDIRS') || '@$(RUBY) -run -e mkdir -- -p'}
INSTALL = #{config_string('INSTALL') || '@$(RUBY) -run -e install -- -vp'}
INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
COPY = #{config_string('CP') || '@$(RUBY) -run -e cp -- -v'}

#### End of system configuration section. ####

preload = #{$preload ? $preload.join(' ') : ''}
}
  if $nmake == ?b
    mk.each do |x|
      x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do
        "!ifndef " + $1 + "\n" +
        $& +
        "!endif\n"
      end
    end
  end
  mk
end


dummy_makefile (lib/mkmf.rb)

# File lib/mkmf.rb, line 1137
def dummy_makefile(srcdir)
  configuration(srcdir) << "CLEANFILES = \#{$cleanfiles.join(' ')}\nDISTCLEANFILES = \#{$distcleanfiles.join(' ')}\n\nall install static install-so install-rb: Makefile\n\n" << CLEANINGS
end


create_makefile (lib/mkmf.rb)

# File lib/mkmf.rb, line 1165
def create_makefile(target, srcprefix = nil)
  $target = target
  libpath = $DEFLIBPATH|$LIBPATH
  message "creating Makefile\n"
  rm_f "conftest*"
  if CONFIG["DLEXT"] == $OBJEXT
    for lib in libs = $libs.split
      lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
    end
    $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
  end

  if target.include?('/')
    target_prefix, target = File.split(target)
    target_prefix[0,0] = '/'
  else
    target_prefix = ""
  end

  srcprefix ||= '$(srcdir)'
  Config::expand(srcdir = srcprefix.dup)

  if not $objs
    $objs = []
    srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
    for f in srcs
      obj = File.basename(f, ".*") << ".o"
      $objs.push(obj) unless $objs.index(obj)
    end
  elsif !(srcs = $srcs)
    srcs = $objs.collect {|obj| obj.sub(/\.o\z/, '.c')}
  end
  $srcs = srcs
  for i in $objs
    i.sub!(/\.o\z/, ".#{$OBJEXT}")
  end
  $objs = $objs.join(" ")

  target = nil if $objs == ""

  if target and EXPORT_PREFIX
    if File.exist?(File.join(srcdir, target + '.def'))
      deffile = "$(srcdir)/$(TARGET).def"
      unless EXPORT_PREFIX.empty?
        makedef = %{-pe "sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"}
      end
    else
      makedef = %{-e "puts 'EXPORTS', '#{EXPORT_PREFIX}Init_$(TARGET)'"}
    end
    if makedef
      $distcleanfiles << '$(DEFFILE)'
      origdef = deffile
      deffile = "$(TARGET)-$(arch).def"
    end
  end
  origdef ||= ''

  libpath = libpathflag(libpath)

  dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
  staticlib = target ? "$(TARGET).#$LIBEXT" : ""
  mfile = open("Makefile", "wb")
  mfile.print configuration(srcprefix)
  mfile.print "
libpath = #{($DEFLIBPATH|$LIBPATH).join(" ")}
LIBPATH = #{libpath}
DEFFILE = #{deffile}

CLEANFILES = #{$cleanfiles.join(' ')}
DISTCLEANFILES = #{$distcleanfiles.join(' ')}

extout = #{$extout}
extout_prefix = #{$extout_prefix}
target_prefix = #{target_prefix}
LOCAL_LIBS = #{$LOCAL_LIBS}
LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
SRCS = #{srcs.collect(&File.method(:basename)).join(' ')}
OBJS = #{$objs}
TARGET = #{target}
DLLIB = #{dllib}
EXTSTATIC = #{$static || ""}
STATIC_LIB = #{staticlib unless $static.nil?}
#{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""}
"
  install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
  n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET).'
  mfile.print "
TARGET_SO     = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB)
CLEANLIBS     = #{n}#{CONFIG['DLEXT']} #{n}il? #{n}tds #{n}map
CLEANOBJS     = *.#{$OBJEXT} *.#{$LIBEXT} *.s[ol] *.pdb *.exp *.bak

all:            #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
static:         $(STATIC_LIB)#{$extout ? " install-rb" : ""}
"
  mfile.print CLEANINGS
  dirs = []
  mfile.print "install: install-so install-rb\n\n"
  sodir = (dir = "$(RUBYARCHDIR)").dup
  mfile.print("install-so: #{dir}\n")
  if target
    f = "$(DLLIB)"
    dest = "#{dir}/#{f}"
    mfile.print "install-so: #{dest}\n"
    unless $extout
      mfile.print "#{dest}: #{f}\n"
      if (sep = config_string('BUILD_FILE_SEPARATOR'))
        f.gsub!("/", sep)
        dir.gsub!("/", sep)
        sep = ":/="+sep
        f.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2}
        f.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2}
        dir.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2}
        dir.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2}
      end
      mfile.print "\t$(INSTALL_PROG) #{f} #{dir}\n"
      if defined?($installed_list)
        mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
      end
    end
  end
  mfile.print("install-rb: pre-install-rb install-rb-default\n")
  mfile.print("install-rb-default: pre-install-rb-default\n")
  mfile.print("pre-install-rb: Makefile\n")
  mfile.print("pre-install-rb-default: Makefile\n")
  for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
    files = install_files(mfile, i, nil, srcprefix) or next
    for dir, *files in files
      unless dirs.include?(dir)
        dirs << dir
        mfile.print "pre-install-rb#{sfx}: #{dir}\n"
      end
      files.each do |f|
        dest = "#{dir}/#{File.basename(f)}"
        mfile.print("install-rb#{sfx}: #{dest}\n")
        mfile.print("#{dest}: #{f}\n\t$(#{$extout ? 'COPY' : 'INSTALL_DATA'}) ")
        sep = config_string('BUILD_FILE_SEPARATOR')
        if sep
          f = f.gsub("/", sep)
          sep = ":/="+sep
          f = f.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
          f = f.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
        else
          sep = ""
        end
        mfile.print("#{f} $(@D#{sep})\n")
        if defined?($installed_list) and !$extout
          mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
        end
      end
    end
  end
  dirs.unshift(sodir) if target and !dirs.include?(sodir)
  dirs.each {|dir| mfile.print "#{dir}:\n\t$(MAKEDIRS) $@\n"}

  mfile.print "\nsite-install: site-install-so site-install-rb\nsite-install-so: install-so\nsite-install-rb: install-rb\n\n"

  return unless target

  mfile.puts SRC_EXT.collect {|ext| ".path.#{ext} = $(VPATH)"} if $nmake == ?b
  mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n"
  mfile.print "\n"

  CXX_EXT.each do |ext|
    COMPILE_RULES.each do |rule|
      mfile.printf(rule, ext, $OBJEXT)
      mfile.printf("\n\t%s\n\n", COMPILE_CXX)
    end
  end
  %w[c].each do |ext|
    COMPILE_RULES.each do |rule|
      mfile.printf(rule, ext, $OBJEXT)
      mfile.printf("\n\t%s\n\n", COMPILE_C)
    end
  end

  mfile.print "$(RUBYARCHDIR)/" if $extout
  mfile.print "$(DLLIB): ", (makedef ? "$(DEFFILE) " : ""), "$(OBJS)\n"
  mfile.print "\t@-$(RM) $@\n"
  mfile.print "\t@-$(MAKEDIRS) $(@D)\n" if $extout
  link_so = LINK_SO.gsub(/^/, "\t")
  mfile.print link_so, "\n\n"
  unless $static.nil?
    mfile.print "$(STATIC_LIB): $(OBJS)\n\t"
    mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
    config_string('RANLIB') do |ranlib|
      mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true"
    end
  end
  mfile.print "\n\n"
  if makedef
    mfile.print "$(DEFFILE): #{origdef}\n"
    mfile.print "\t$(RUBY) #{makedef} #{origdef} > $@\n\n"
  end

  depend = File.join(srcdir, "depend")
  if File.exist?(depend)
    suffixes = []
    depout = []
    open(depend, "r") do |dfile|
      mfile.printf "###\n"
      cont = implicit = nil
      impconv = proc do
        COMPILE_RULES.each {|rule| depout << (rule % implicit[0]) << implicit[1]}
        implicit = nil
      end
      ruleconv = proc do |line|
        if implicit
          if /\A\t/ =~ line
            implicit[1] << line
            next
          else
            impconv[]
          end
        end
        if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line)
          suffixes << m[1] << m[2]
          implicit = [[m[1], m[2]], [m.post_match]]
          next
        elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line
          line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2}
        end
        depout << line
      end
      while line = dfile.gets()
        line.gsub!(/\.o\b/, ".#{$OBJEXT}")
        line.gsub!(/\$\(hdrdir\)\/config.h/, $config_h) if $config_h
        if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line
          (cont ||= []) << line
          next
        elsif cont
          line = (cont << line).join
          cont = nil
        end
        ruleconv.call(line)
      end
      if cont
        ruleconv.call(cont.join)
      elsif implicit
        impconv.call
      end
    end
    unless suffixes.empty?
      mfile.print ".SUFFIXES: .", suffixes.uniq.join(" ."), "\n\n"
    end
    mfile.print "$(OBJS): $(RUBY_EXTCONF_H)\n\n" if $extconf_h
    mfile.print depout
  else
    headers = %w[ruby.h defines.h]
    if RULE_SUBST
      headers.each {|h| h.sub!(/.*/) {|*m| RULE_SUBST % m}}
    end
    headers << $config_h if $config_h
    headers << "$(RUBY_EXTCONF_H)" if $extconf_h
    mfile.print "$(OBJS): ", headers.join(' '), "\n"
  end

  $makefile_created = true
ensure
  mfile.close if mfile
end


init_mkmf (lib/mkmf.rb)

# File lib/mkmf.rb, line 1433
def init_mkmf(config = CONFIG)
  $makefile_created = false
  $arg_config = []
  $enable_shared = config['ENABLE_SHARED'] == 'yes'
  $defs = []
  $extconf_h = nil
  $CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
  $ARCH_FLAG = with_config("arch_flag", arg_config("ARCH_FLAG", config["ARCH_FLAG"])).dup
  $CPPFLAGS = with_config("cppflags", arg_config("CPPFLAGS", config["CPPFLAGS"])).dup
  $LDFLAGS = with_config("ldflags", arg_config("LDFLAGS", config["LDFLAGS"])).dup
  $INCFLAGS = "-I$(topdir) -I$(hdrdir) -I$(srcdir)"
  $DLDFLAGS = with_config("dldflags", arg_config("DLDFLAGS", config["DLDFLAGS"])).dup
  $LIBEXT = config['LIBEXT'].dup
  $OBJEXT = config["OBJEXT"].dup
  $LIBS = "#{config['LIBS']} #{config['DLDLIBS']}"
  $LIBRUBYARG = ""
  $LIBRUBYARG_STATIC = config['LIBRUBYARG_STATIC']
  $LIBRUBYARG_SHARED = config['LIBRUBYARG_SHARED']
  $DEFLIBPATH = $extmk ? ["$(topdir)"] : CROSS_COMPILING ? [] : ["$(libdir)"]
  $DEFLIBPATH.unshift(".")
  $LIBPATH = []
  $INSTALLFILES = nil

  $objs = nil
  $srcs = nil
  $libs = ""
  if $enable_shared or Config.expand(config["LIBRUBY"].dup) != Config.expand(config["LIBRUBY_A"].dup)
    $LIBRUBYARG = config['LIBRUBYARG']
  end

  $LOCAL_LIBS = ""

  $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
  $cleanfiles << "mkmf.log"
  $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []

  $extout ||= nil
  $extout_prefix ||= nil

  $arg_config.clear
  dir_config("opt")
end


mkmf_failed (lib/mkmf.rb)

# File lib/mkmf.rb, line 1485
def mkmf_failed(path)
  unless $makefile_created or File.exist?("Makefile")
    opts = $arg_config.collect {|t, n| "\t#{t}#{n ? "=#{n}" : ""}\n"}
    abort "*** #{path} failed ***\n" + FailedMessage + opts.join
  end
end


File: ftp.rb

ftp.rb

Path: | lib/net/ftp.rb
Last Update: | Tue Mar 13 02:06:58 -0500 2007

net/ftp.rb - FTP Client Library

Written by Shugo Maeda <shugo@ruby-lang.org>.

Documentation by Gavin Sinclair, sourced from "Programming Ruby" (Hunt/Thomas) and "Ruby In a Nutshell" (Matsumoto), used with permission.

This library is distributed under the terms of the Ruby license. You can freely distribute/modify this library.

It is included in the Ruby standard library.

See the Net::FTP class for an overview.

Required files

socket monitor


File: http.rb

http.rb

Path: | lib/net/http.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

net/http.rb

Copyright (c) 1999-2006 Yukihiro Matsumoto Copyright (c) 1999-2006 Minero Aoki Copyright (c) 2001 GOTOU Yuuzou

Written and maintained by Minero Aoki <aamine@loveruby.net>. HTTPS support added by GOTOU Yuuzou <gotoyuzo@notwork.org>.

This file is derived from "http-access.rb".

Documented by Minero Aoki; converted to RDoc by William Webber.

This program is free software. You can re-distribute and/or modify this program under the same terms of ruby itself — Ruby Distribution License or GNU General Public License.

See Net::HTTP for an overview and examples.

NOTE: You can find Japanese version of this document here: www.ruby-lang.org/ja/man/?cmd=view;name=net%2Fhttp.rb

Required files

net/protocol uri


File: https.rb

https.rb

Path: | lib/net/https.rb
Last Update: | Tue Mar 13 02:06:58 -0500 2007

Required files

net/http openssl


File: imap.rb

imap.rb

Path: | lib/net/imap.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007

net/imap.rb

Copyright (C) 2000 Shugo Maeda <shugo@ruby-lang.org>

This library is distributed under the terms of the Ruby license. You can freely distribute/modify this library.

Documentation: Shugo Maeda, with RDoc conversion and overview by William Webber.

See Net::IMAP for documentation.

Required files

socket monitor digest/md5 openssl


File: pop.rb

pop.rb

Path: | lib/net/pop.rb
Last Update: | Tue Mar 13 02:06:58 -0500 2007

net/pop.rb

Copyright (c) 1999-2003 Yukihiro Matsumoto.

Copyright (c) 1999-2003 Minero Aoki.

Written & maintained by Minero Aoki <aamine@loveruby.net>.

Documented by William Webber and Minero Aoki.

This program is free software. You can re-distribute and/or modify this program under the same terms as Ruby itself, Ruby Distribute License or GNU General Public License.

NOTE: You can find Japanese version of this document in the doc/net directory of the standard ruby interpreter package.

  $Id: pop.rb 11708 2007-02-12 23:01:19Z shyouhei $

See Net::POP3 for documentation.

Required files

net/protocol digest/md5


File: protocol.rb

protocol.rb

Path: | lib/net/protocol.rb
Last Update: | Tue Mar 13 02:06:58 -0500 2007

net/protocol.rb

WARNING: This file is going to remove. Do not rely on the implementation written in this file.

Required files

socket timeout


File: smtp.rb

smtp.rb

Path: | lib/net/smtp.rb
Last Update: | Tue Mar 13 02:06:58 -0500 2007

net/smtp.rb

Copyright (c) 1999-2003 Yukihiro Matsumoto.

Copyright (c) 1999-2003 Minero Aoki.

Written & maintained by Minero Aoki <aamine@loveruby.net>.

Documented by William Webber and Minero Aoki.

This program is free software. You can re-distribute and/or modify this program under the same terms as Ruby itself, Ruby Distribute License or GNU General Public License.

NOTE: You can find Japanese version of this document in the doc/net directory of the standard ruby interpreter package.

$Id: smtp.rb 11708 2007-02-12 23:01:19Z shyouhei $

See Net::SMTP for documentation.

Required files

net/protocol digest/md5


File: telnet.rb

telnet.rb

Path: | lib/net/telnet.rb
Last Update: | Tue Mar 13 02:06:58 -0500 2007

net/telnet.rb - Simple Telnet Client Library

Author: | Wakou Aoyama <wakou@ruby-lang.org>
Documentation: | William Webber and Wakou Aoyama

This file holds the class Net::Telnet, which provides client-side telnet functionality.

For documentation, see Net::Telnet.

Required files

socket delegate timeout English


with (lib/optparse.rb)

# File lib/optparse.rb, line 749
  def self.with(*args, &block)
    opts = new(*args)
    opts.instance_eval(&block)
    opts
  end


inc (lib/optparse.rb)

# File lib/optparse.rb, line 758
  def self.inc(arg, default = nil)
    case arg
    when Integer
      arg.nonzero?
    when nil
      default.to_i + 1
    end
  end


inc (lib/optparse.rb)

# File lib/optparse.rb, line 766
  def inc(*args)
    self.class.inc(*args)
  end


new (lib/optparse.rb)

# File lib/optparse.rb, line 777
  def initialize(banner = nil, width = 32, indent = ' ' * 4)
    @stack = [DefaultList, List.new, List.new]
    @program_name = nil
    @banner = banner
    @summary_width = width
    @summary_indent = indent
    @default_argv = ARGV
    add_officious
    yield self if block_given?
  end


terminate (lib/optparse.rb)

# File lib/optparse.rb, line 799
  def terminate(arg = nil)
    self.class.terminate(arg)
  end


terminate (lib/optparse.rb)

# File lib/optparse.rb, line 802
  def self.terminate(arg = nil)
    throw :terminate, arg
  end


top (lib/optparse.rb)

# File lib/optparse.rb, line 807
  def self.top() DefaultList end


accept (lib/optparse.rb)

# File lib/optparse.rb, line 818
  def accept(*args, &blk) top.accept(*args, &blk) end


accept (lib/optparse.rb)

# File lib/optparse.rb, line 822
  def self.accept(*args, &blk) top.accept(*args, &blk) end


reject (lib/optparse.rb)

# File lib/optparse.rb, line 831
  def reject(*args, &blk) top.reject(*args, &blk) end


reject (lib/optparse.rb)

# File lib/optparse.rb, line 835
  def self.reject(*args, &blk) top.reject(*args, &blk) end


banner (lib/optparse.rb)

# File lib/optparse.rb, line 860
  def banner
    unless @banner
      @banner = "Usage: #{program_name} [options]"
      visit(:add_banner, @banner)
    end
    @banner
  end


program_name (lib/optparse.rb)

# File lib/optparse.rb, line 872
  def program_name
    @program_name || File.basename($0, '.*')
  end


version (lib/optparse.rb)

# File lib/optparse.rb, line 890
  def version
    @version || (defined?(::Version) && ::Version)
  end


release (lib/optparse.rb)

# File lib/optparse.rb, line 897
  def release
    @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
  end


ver (lib/optparse.rb)

# File lib/optparse.rb, line 904
  def ver
    if v = version
      str = "#{program_name} #{[v].join('.')}"
      str << " (#{v})" if v = release
      str
    end
  end


warn (lib/optparse.rb)

# File lib/optparse.rb, line 912
  def warn(mesg = $!)
    super("#{program_name}: #{mesg}")
  end


abort (lib/optparse.rb)

# File lib/optparse.rb, line 916
  def abort(mesg = $!)
    super("#{program_name}: #{mesg}")
  end


top (lib/optparse.rb)

# File lib/optparse.rb, line 923
  def top
    @stack[-1]
  end


base (lib/optparse.rb)

# File lib/optparse.rb, line 930
  def base
    @stack[1]
  end


new (lib/optparse.rb)

# File lib/optparse.rb, line 937
  def new
    @stack.push(List.new)
    if block_given?
      yield self
    else
      self
    end
  end


remove (lib/optparse.rb)

# File lib/optparse.rb, line 949
  def remove
    @stack.pop
  end


summarize (lib/optparse.rb)

# File lib/optparse.rb, line 962
  def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
    visit(:summarize, {}, {}, width, max, indent, &(blk || proc {|l| to << l + $/}))
    to
  end


help (lib/optparse.rb)

# File lib/optparse.rb, line 970
  def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end


to_a (lib/optparse.rb)

# File lib/optparse.rb, line 976
  def to_a; summarize(banner.to_a.dup) end


make_switch (lib/optparse.rb)

# File lib/optparse.rb, line 1057
  def make_switch(opts, block = nil)
    short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
    ldesc, sdesc, desc, arg = [], [], []
    default_style = Switch::NoArgument
    default_pattern = nil
    klass = nil
    o = nil
    n, q, a = nil

    opts.each do |o|
      # argument class
      next if search(:atype, o) do |pat, c|
        klass = notwice(o, klass, 'type')
        if not_style and not_style != Switch::NoArgument
          not_pattern, not_conv = pat, c
        else
          default_pattern, conv = pat, c
        end
      end

      # directly specified pattern(any object possible to match)
      if !(String === o) and o.respond_to?(:match)
        pattern = notwice(o, pattern, 'pattern')
        conv = (pattern.method(:convert).to_proc if pattern.respond_to?(:convert))
        next
      end

      # anything others
      case o
      when Proc, Method
        block = notwice(o, block, 'block')
      when Array, Hash
        case pattern
        when CompletingHash
        when nil
          pattern = CompletingHash.new
          conv = (pattern.method(:convert).to_proc if pattern.respond_to?(:convert))
        else
          raise ArgumentError, "argument pattern given twice"
        end
        o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}}
      when Module
        raise ArgumentError, "unsupported argument type: #{o}"
      when *ArgumentStyle.keys
        style = notwice(ArgumentStyle[o], style, 'style')
      when /^--no-([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        o = notwice(a ? Object : TrueClass, klass, 'type')
        not_pattern, not_conv = search(:atype, o) unless not_style
        not_style = (not_style || default_style).guess(arg = a) if a
        default_style = Switch::NoArgument
        default_pattern, conv = search(:atype, FalseClass) unless default_pattern
        ldesc << "--no-#{q}"
        long << 'no-' + (q = q.downcase)
        nolong << q
      when /^--\[no-\]([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        o = notwice(a ? Object : TrueClass, klass, 'type')
        if a
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        ldesc << "--[no-]#{q}"
        long << (o = q.downcase)
        not_pattern, not_conv = search(:atype, FalseClass) unless not_style
        not_style = Switch::NoArgument
        nolong << 'no-' + o
      when /^--([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        if a
          o = notwice(NilClass, klass, 'type')
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        ldesc << "--#{q}"
        long << (o = q.downcase)
      when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
        q, a = $1, $2
        o = notwice(Object, klass, 'type')
        if a
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        sdesc << "-#{q}"
        short << Regexp.new(q)
      when /^-(.)(.+)?/
        q, a = $1, $2
        if a
          o = notwice(NilClass, klass, 'type')
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        sdesc << "-#{q}"
        short << q
      when /^=/
        style = notwice(default_style.guess(arg = o), style, 'style')
        default_pattern, conv = search(:atype, Object) unless default_pattern
      else
        desc.push(o)
      end
    end

    default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
    if !(short.empty? and long.empty?)
      s = (style || default_style).new(pattern || default_pattern,
                                       conv, sdesc, ldesc, arg, desc, block)
    elsif !block
      raise ArgumentError, "no switch given" if style or pattern
      s = desc
    else
      short << pattern
      s = (style || default_style).new(pattern,
                                       conv, nil, nil, arg, desc, block)
    end
    return s, short, long,
      (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
      nolong
  end


define (lib/optparse.rb)

# File lib/optparse.rb, line 1176
  def define(*opts, &block)
    top.append(*(sw = make_switch(opts, block)))
    sw[0]
  end


on (lib/optparse.rb)

# File lib/optparse.rb, line 1185
  def on(*opts, &block)
    define(*opts, &block)
    self
  end


define_head (lib/optparse.rb)

# File lib/optparse.rb, line 1191
  def define_head(*opts, &block)
    top.prepend(*(sw = make_switch(opts, block)))
    sw[0]
  end


on_head (lib/optparse.rb)

# File lib/optparse.rb, line 1199
  def on_head(*opts, &block)
    define_head(*opts, &block)
    self
  end


define_tail (lib/optparse.rb)

# File lib/optparse.rb, line 1205
  def define_tail(*opts, &block)
    base.append(*(sw = make_switch(opts, block)))
    sw[0]
  end


on_tail (lib/optparse.rb)

# File lib/optparse.rb, line 1213
  def on_tail(*opts, &block)
    define_tail(*opts, &block)
    self
  end


separator (lib/optparse.rb)

# File lib/optparse.rb, line 1222
  def separator(string)
    top.append(string, nil, nil)
  end


order (lib/optparse.rb)

# File lib/optparse.rb, line 1232
  def order(*argv, &block)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    order!(argv, &block)
  end


order! (lib/optparse.rb)

# File lib/optparse.rb, line 1240
  def order!(argv = default_argv, &nonopt)
    parse_in_order(argv, &nonopt)
  end


permute (lib/optparse.rb)

# File lib/optparse.rb, line 1321
  def permute(*argv)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    permute!(argv)
  end


permute! (lib/optparse.rb)

# File lib/optparse.rb, line 1329
  def permute!(argv = default_argv)
    nonopts = []
    arg = nil
    order!(argv) {|arg| nonopts << arg}
    argv[0, 0] = nonopts
    argv
  end


parse (lib/optparse.rb)

# File lib/optparse.rb, line 1341
  def parse(*argv)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    parse!(argv)
  end


parse! (lib/optparse.rb)

# File lib/optparse.rb, line 1349
  def parse!(argv = default_argv)
    if ENV.include?('POSIXLY_CORRECT')
      order!(argv)
    else
      permute!(argv)
    end
  end


getopts (lib/optparse.rb)

# File lib/optparse.rb, line 1366
  def getopts(*args)
    argv = Array === args.first ? args.shift : default_argv
    single_options, *long_options = *args

    result = {}

    single_options.scan(/(.)(:)?/) do |opt, val|
      if val
        result[opt] = nil
        define("-#{opt} VAL")
      else
        result[opt] = false
        define("-#{opt}")
      end
    end if single_options

    long_options.each do |arg|
      opt, val = arg.split(':', 2)
      if val
        result[opt] = val.empty? ? nil : val
        define("--#{opt} VAL")
      else
        result[opt] = false
        define("--#{opt}")
      end
    end

    parse_in_order(argv, result.method(:[]=))
    result
  end


getopts (lib/optparse.rb)

# File lib/optparse.rb, line 1400
  def self.getopts(*args)
    new.getopts(*args)
  end


load (lib/optparse.rb)

# File lib/optparse.rb, line 1455
  def load(filename = nil)
    begin
      filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
    rescue
      return false
    end
    begin
      parse(*IO.readlines(filename).each {|s| s.chomp!})
      true
    rescue Errno::ENOENT, Errno::ENOTDIR
      false
    end
  end


environment (lib/optparse.rb)

# File lib/optparse.rb, line 1475
  def environment(env = File.basename($0, '.*'))
    env = ENV[env] || ENV[env.upcase] or return
    parse(*Shellwords.shellwords(env))
  end


printUsageAndExit (lib/parsearg.rb)

# File lib/parsearg.rb, line 19
def printUsageAndExit()
  if $USAGE
    eval($USAGE)
  end
  exit()
end


setParenthesis (lib/parsearg.rb)

# File lib/parsearg.rb, line 26
def setParenthesis(ex, opt, c)
  if opt != ""
    ex = sprintf("%s$OPT_%s%s", ex, opt, c)
  else
    ex = sprintf("%s%s", ex, c)
  end
  return ex
end


setOrAnd (lib/parsearg.rb)

# File lib/parsearg.rb, line 35
def setOrAnd(ex, opt, c)
  if opt != ""
    ex = sprintf("%s$OPT_%s %s%s ", ex, opt, c, c)
  else
    ex = sprintf("%s %s%s ", ex, c, c)
  end
  return ex
end


setExpression (lib/parsearg.rb)

# File lib/parsearg.rb, line 44
def setExpression(ex, opt, op)
  if !op
    ex = sprintf("%s$OPT_%s", ex, opt)
    return ex
  end
  case op.chr
  when "(", ")"
    ex = setParenthesis(ex, opt, op.chr)
  when "|", "&"
    ex = setOrAnd(ex, opt, op.chr)
  else
    return nil
  end
  return ex
end


parseArgs (lib/parsearg.rb)

# File lib/parsearg.rb, line 62
def parseArgs(argc, nopt, single_opts, *opts)
  if (noOptions = getopts(single_opts, *opts)) == nil
    printUsageAndExit()
  end
  if nopt
    ex = nil
    pos = 0
    for o in nopt.split(/[()|&]/)
      pos += o.length
      ex = setExpression(ex, o, nopt[pos])
      pos += 1
    end
    begin
      if !eval(ex)
        printUsageAndExit()
      end
    rescue
      print "Format Error!! : \"" + nopt + "\"\t[parseArgs]\n"
      exit!(-1)
    end
  end
  if ARGV.length < argc
    printUsageAndExit()
  end
  return noOptions
end


pretty_print_cycle (lib/pp.rb)

# File lib/pp.rb, line 459
    def pretty_print_cycle(q)
      q.text inspect
    end


pretty_print (lib/pp.rb)

# File lib/pp.rb, line 467
    def pretty_print(q)
      q.text inspect
    end


start_profile (lib/profiler.rb)

# File lib/profiler.rb, line 23
  def start_profile
    @@start = Process.times[0]
    @@stack = []
    @@map = {}
    set_trace_func PROFILE_PROC
  end


stop_profile (lib/profiler.rb)

# File lib/profiler.rb, line 29
  def stop_profile
    set_trace_func nil
  end


print_profile (lib/profiler.rb)

# File lib/profiler.rb, line 32
  def print_profile(f)
    stop_profile
    total = Process.times[0] - @@start
    if total == 0 then total = 0.01 end
    data = @@map.values
    data.sort!{|a,b| b[2] <=> a[2]}
    sum = 0
    f.printf "  %%   cumulative   self              self     total\n"
    f.printf " time   seconds   seconds    calls  ms/call  ms/call  name\n"
    for d in data
      sum += d[2]
      f.printf "%6.2f %8.2f  %8.2f %8d ", d[2]/total*100, sum, d[2], d[0]
      f.printf "%8.2f %8.2f  %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3])
    end
    f.printf "%6.2f %8.2f  %8.2f %8d ", 0.0, total, 0.0, 1     # ???
    f.printf "%8.2f %8.2f  %s\n", 0.0, total*1000, "#toplevel" # ???
  end


File: parser.rb

parser.rb

Path: | lib/racc/parser.rb
Last Update: | Tue Mar 13 02:07:05 -0500 2007

$originalId: parser.rb,v 1.8 2006/07/06 11:42:07 aamine Exp $

Copyright (c) 1999-2006 Minero Aoki

This program is free software. You can distribute/modify this program under the same terms of ruby.

As a special exception, when this code is copied by Racc into a Racc output file, you may use that output file without restriction.

Required files

racc/cparse

Constants

NotImplementedError | = | NotImplementError
ParseError | = | Racc::ParseError


Rational (lib/rational.rb)

# File lib/rational.rb, line 31
def Rational(a, b = 1)
  if a.kind_of?(Rational) && b == 1
    a
  else
    Rational.reduce(a, b)
  end
end


File: code_objects.rb

code_objects.rb

Path: | lib/rdoc/code_objects.rb
Last Update: | Tue Mar 13 02:06:40 -0500 2007

We represent the various high-level code constructs that appear in Ruby programs: classes, modules, methods, and so on.

Required files

rdoc/tokenstream


File: diagram.rb

diagram.rb

Path: | lib/rdoc/diagram.rb
Last Update: | Tue Mar 13 02:06:40 -0500 2007

A wonderful hack by to draw package diagrams using the dot package. Originally written by Jah, team Enticla.

You must have the V1.7 or later in your path www.research.att.com/sw/tools/graphviz/

Required files

rdoc/dot/dot rdoc/options


File: options.rb

options.rb

Path: | lib/rdoc/options.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

We handle the parsing of options, and subsequently as a singleton object to be queried for option values

Required files

rdoc/ri/ri_paths singleton getoptlong


File: rdoc.rb

rdoc.rb

Path: | lib/rdoc/rdoc.rb
Last Update: | Tue Mar 13 02:06:40 -0500 2007

See README.

Required files

rdoc/parsers/parse_rb.rb rdoc/parsers/parse_c.rb rdoc/parsers/parse_f95.rb rdoc/parsers/parse_simple.rb rdoc/options rdoc/diagram find ftools time

Constants

VERSION_STRING = %{RDoc V1.0.1 - 20041108} See README.


File: template.rb

template.rb

Path: | lib/rdoc/template.rb
Last Update: | Tue Mar 13 02:06:40 -0500 2007

Cheap-n-cheerful HTML page template system. You create a template containing:

  • variable names between percent signs (%fred%)
  • blocks of repeating stuff:
      START:key
    ... stuff
  END:key

You feed the code a hash. For simple variables, the values are resolved directly from the hash. For blocks, the hash entry corresponding to key will be an array of hashes. The block will be generated once for each entry. Blocks can be nested arbitrarily deeply.

The template may also contain

  IF:key
    ... stuff
  ENDIF:key

stuff will only be included in the output if the corresponding key is set in the value hash.

Usage: Given a set of templates T1, T2, etc

           values = { "name" => "Dave", state => "TX" }

           t = TemplatePage.new(T1, T2, T3)
           File.open(name, "w") {|f| t.write_html_on(f, values)}
        or
           res = ''
           t.write_html_on(res, values)


File: tokenstream.rb

tokenstream.rb

Path: | lib/rdoc/tokenstream.rb
Last Update: | Tue Mar 13 02:06:40 -0500 2007

A TokenStream is a list of tokens, gathered during the parse of some entity (say a method). Entities populate these streams by being registered with the lexer. Any class can collect tokens by including TokenStream. From the outside, you use such an object by calling the start_collecting_tokens method, followed by calls to add_token and pop_token


File: usage.rb

usage.rb

Path: | lib/rdoc/usage.rb
Last Update: | Tue Mar 13 02:06:40 -0500 2007

Synopsis

This library allows command-line tools to encapsulate their usage as a comment at the top of the main file. Calling RDoc::usage then displays some or all of that comment, and optionally exits the program with an exit status. We always look for the comment in the main program file, so it is safe to call this method from anywhere in the executing program.

Usage

  RDoc::usage( [ exit_status ], [ section, ...])
  RDoc::usage_no_exit( [ section, ...])

where:

exit_status: | the integer exit code (default zero). RDoc::usage will exit the calling program with this status.
section: | an optional list of section names. If specified, only the sections with the given names as headings will be output. For example, this section is named ‘Usage’, and the next section is named ‘Examples’. The section names are case insensitive.

Examples

   # Comment block describing usage
   # with (optional) section headings
   # . . .

   require 'rdoc/usage'

   # Display all usage and exit with a status of 0

   RDoc::usage

   # Display all usage and exit with a status of 99

   RDoc::usage(99)

   # Display usage in the 'Summary' section only, then
   # exit with a status of 99

   RDoc::usage(99, 'Summary')

   # Display information in the Author and Copyright
   # sections, then exit 0.

   RDoc::usage('Author', 'Copyright')

   # Display information in the Author and Copyright
   # sections, but don't exit

   RDoc::usage_no_exit('Author', 'Copyright')

Author

Dave Thomas, The Pragmatic Programmers, LLC

Copyright

Copyright (c) 2004 Dave Thomas. Licensed under the same terms as Ruby

Required files

rdoc/markup/simple_markup rdoc/markup/simple_markup/to_flow rdoc/ri/ri_formatter rdoc/ri/ri_options


File: dot.rb

dot.rb

Path: | lib/rdoc/dot/dot.rb
Last Update: | Tue Mar 13 02:06:36 -0500 2007


File: chm_generator.rb

chm_generator.rb

Path: | lib/rdoc/generators/chm_generator.rb
Last Update: | Tue Mar 13 02:06:38 -0500 2007

Required files

rdoc/generators/html_generator


File: html_generator.rb

html_generator.rb

Path: | lib/rdoc/generators/html_generator.rb
Last Update: | Tue Mar 13 02:06:38 -0500 2007

We‘re responsible for generating all the HTML files from the object tree defined in code_objects.rb. We generate:

files
an html file for each input file given. These input files appear as objects of class TopLevel
classes
an html file for each class or module encountered. These classes are not grouped by file: if a file contains four classes, we‘ll generate an html file for the file itself, and four html files for the individual classes.
indices
we generate three indices for files, classes, and methods. These are displayed in a browser like window with three index panes across the top and the selected description below

Method descriptions appear in whatever entity (file, class, or module) that contains them.

We generate files in a structure below a specified subdirectory, normally doc.

 opdir
    |
    |___ files
    |       |__  per file summaries
    |
    |___ classes
            |__ per class/module descriptions

HTML is generated using the Template class.

Required files

ftools rdoc/options rdoc/template rdoc/markup/simple_markup rdoc/markup/simple_markup/to_html cgi


File: ri_generator.rb

ri_generator.rb

Path: | lib/rdoc/generators/ri_generator.rb
Last Update: | Tue Mar 13 02:06:38 -0500 2007

We‘re responsible for generating all the HTML files from the object tree defined in code_objects.rb. We generate:

files
an html file for each input file given. These input files appear as objects of class TopLevel
classes
an html file for each class or module encountered. These classes are not grouped by file: if a file contains four classes, we‘ll generate an html file for the file itself, and four html files for the individual classes.
indices
we generate three indices for files, classes, and methods. These are displayed in a browser like window with three index panes across the top and the selected description below

Method descriptions appear in whatever entity (file, class, or module) that contains them.

We generate files in a structure below a specified subdirectory, normally doc.

 opdir
    |
    |___ files
    |       |__  per file summaries
    |
    |___ classes
            |__ per class/module descriptions

HTML is generated using the Template class.

Required files

ftools rdoc/options rdoc/template rdoc/markup/simple_markup rdoc/markup/simple_markup/to_flow cgi rdoc/ri/ri_cache rdoc/ri/ri_reader rdoc/ri/ri_writer rdoc/ri/ri_descriptions


File: xml_generator.rb

xml_generator.rb

Path: | lib/rdoc/generators/xml_generator.rb
Last Update: | Tue Mar 13 02:06:38 -0500 2007

Required files

ftools rdoc/options rdoc/markup/simple_markup rdoc/markup/simple_markup/to_html rdoc/generators/html_generator


File: chm.rb

chm.rb

Path: | lib/rdoc/generators/template/chm/chm.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007

Required files

rdoc/generators/template/html/html


File: hefss.rb

hefss.rb

Path: | lib/rdoc/generators/template/html/hefss.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007


File: html.rb

html.rb

Path: | lib/rdoc/generators/template/html/html.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007

CSS2 RDoc HTML template

This is a template for RDoc that uses XHTML 1.0 Transitional and dictates a bit more of the appearance of the output to cascading stylesheets than the default. It was designed for clean inline code display, and uses DHTMl to toggle the visbility of each method‘s source with each click on the ’[source]’ link.

Authors

  • Michael Granger <ged@FaerieMUD.org>

Copyright (c) 2002, 2003 The FaerieMUD Consortium. Some rights reserved.

This work is licensed under the Creative Commons Attribution License. To view a copy of this license, visit creativecommons.org/licenses/by/1.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

Required files

rdoc/generators/template/html/one_page_html


File: kilmer.rb

kilmer.rb

Path: | lib/rdoc/generators/template/html/kilmer.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007


File: old_html.rb

old_html.rb

Path: | lib/rdoc/generators/template/html/old_html.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007

Required files

rdoc/generators/template/html/one_page_html


File: one_page_html.rb

one_page_html.rb

Path: | lib/rdoc/generators/template/html/one_page_html.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007


File: rdf.rb

rdf.rb

Path: | lib/rdoc/generators/template/xml/rdf.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007


File: xml.rb

xml.rb

Path: | lib/rdoc/generators/template/xml/xml.rb
Last Update: | Tue Mar 13 02:06:37 -0500 2007


File: simple_markup.rb

simple_markup.rb

Path: | lib/rdoc/markup/simple_markup.rb
Last Update: | Tue Mar 13 02:06:33 -0500 2007

Introduction

SimpleMarkup parses plain text documents and attempts to decompose them into their constituent parts. Some of these parts are high-level: paragraphs, chunks of verbatim text, list entries and the like. Other parts happen at the character level: a piece of bold text, a word in code font. This markup is similar in spirit to that used on WikiWiki webs, where folks create web pages using a simple set of formatting rules.

SimpleMarkup itself does no output formatting: this is left to a different set of classes.

SimpleMarkup is extendable at runtime: you can add new markup elements to be recognised in the documents that SimpleMarkup parses.

SimpleMarkup is intended to be the basis for a family of tools which share the common requirement that simple, plain-text should be rendered in a variety of different output formats and media. It is envisaged that SimpleMarkup could be the basis for formating RDoc style comment blocks, Wiki entries, and online FAQs.

Basic Formatting

  • SimpleMarkup looks for a document‘s natural left margin. This is used as the initial margin for the document.
  • Consecutive lines starting at this margin are considered to be a paragraph.
  • If a paragraph starts with a "*", "-", or with "<digit>.", then it is taken to be the start of a list. The margin in increased to be the first non-space following the list start flag. Subsequent lines should be indented to this new margin until the list ends. For example:
       * this is a list with three paragraphs in
     the first item. This is the first paragraph.

     And this is the second paragraph.

     1. This is an indented, numbered list.
     2. This is the second item in that list

     This is the third conventional paragraph in the
     first list item.

   * This is the second item in the original list
  • You can also construct labeled lists, sometimes called description or definition lists. Do this by putting the label in square brackets and indenting the list body:
        [cat]  a small furry mammal
           that seems to sleep a lot

    [ant]  a little insect that is known
           to enjoy picnics

    A minor variation on labeled lists uses two colons to separate the label from the list body:

        cat::  a small furry mammal
           that seems to sleep a lot

    ant::  a little insect that is known
           to enjoy picnics

    This latter style guarantees that the list bodies’ left margins are aligned: think of them as a two column table.

  • Any line that starts to the right of the current margin is treated as verbatim text. This is useful for code listings. The example of a list above is also verbatim text.
  • A line starting with an equals sign (=) is treated as a heading. Level one headings have one equals sign, level two headings have two,and so on.
  • A line starting with three or more hyphens (at the current indent) generates a horizontal rule. THe more hyphens, the thicker the rule (within reason, and if supported by the output device)
  • You can use markup within text (except verbatim) to change the appearance of parts of that text. Out of the box, SimpleMarkup supports word-based and general markup.

    Word-based markup uses flag characters around individual words:

    *word*
    displays word in a bold font
    _word_
    displays word in an emphasized font
    +word+
    displays word in a code font

    General markup affects text between a start delimiter and and end delimiter. Not surprisingly, these delimiters look like HTML markup.

    <b>text…</b>
    displays word in a bold font
    <em>text…</em>
    displays word in an emphasized font
    <i>text…</i>
    displays word in an emphasized font
    <tt>text…</tt>
    displays word in a code font

    Unlike conventional Wiki markup, general markup can cross line boundaries. You can turn off the interpretation of markup by preceding the first character with a backslash, so \<b>bold text</b> and \*bold* produce <b>bold text</b> and *bold respectively.

Using SimpleMarkup

For information on using SimpleMarkup programatically, see SM::SimpleMarkup.

Author: | Dave Thomas, dave@pragmaticprogrammer.com
Version: | 0.0
License: | Ruby license

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/lines.rb


File: fragments.rb

fragments.rb

Path: | lib/rdoc/markup/simple_markup/fragments.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007

Required files

rdoc/markup/simple_markup/lines.rb


File: inline.rb

inline.rb

Path: | lib/rdoc/markup/simple_markup/inline.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007


File: lines.rb

lines.rb

Path: | lib/rdoc/markup/simple_markup/lines.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007

We store the lines we‘re working on as objects of class Line. These contain the text of the line, along with a flag indicating the line type, and an indentation level


File: preprocess.rb

preprocess.rb

Path: | lib/rdoc/markup/simple_markup/preprocess.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007


File: to_flow.rb

to_flow.rb

Path: | lib/rdoc/markup/simple_markup/to_flow.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/inline cgi


File: to_html.rb

to_html.rb

Path: | lib/rdoc/markup/simple_markup/to_html.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/inline cgi


File: to_latex.rb

to_latex.rb

Path: | lib/rdoc/markup/simple_markup/to_latex.rb
Last Update: | Tue Mar 13 02:06:32 -0500 2007

Required files

rdoc/markup/simple_markup/fragments rdoc/markup/simple_markup/inline cgi


File: parse_c.rb

parse_c.rb

Path: | lib/rdoc/parsers/parse_c.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Classes and modules built in to the interpreter. We need these to define superclasses of user objects

Required files

rdoc/code_objects rdoc/parsers/parserfactory rdoc/options rdoc/rdoc


File: parse_f95.rb

parse_f95.rb

Path: | lib/rdoc/parsers/parse_f95.rb
Last Update: | Tue Mar 13 02:06:35 -0500 2007

parse_f95.rb - Fortran95 Parser

Overview

"parse_f95.rb" parses Fortran95 files with suffixes "f90", "F90", "f95" and "F95". Fortran95 files are expected to be conformed to Fortran95 standards.

Rules

Fundamental rules are same as that of the Ruby parser. But comment markers are ’!’ not ’#’.

Correspondence between RDoc documentation and Fortran95 programs

"parse_f95.rb" parses main programs, modules, subroutines, functions, derived-types, public variables, public constants, defined operators and defined assignments. These components are described in items of RDoc documentation, as follows.

Files : | Files (same as Ruby)
Classes : | Modules
Methods : | Subroutines, functions, variables, constants, derived-types, defined operators, defined assignments
Required files : | Files in which imported modules, external subroutines and external functions are defined.
Included Modules : | List of imported modules
Attributes : | List of derived-types, List of imported modules all of whose components are published again

Components listed in ‘Methods’ (subroutines, functions, …) defined in modules are described in the item of ‘Classes’. On the other hand, components defined in main programs or as external procedures are described in the item of ‘Files’.

Components parsed by default

By default, documentation on public components (subroutines, functions, variables, constants, derived-types, defined operators, defined assignments) are generated. With "—all" option, documentation on all components are generated (almost same as the Ruby parser).

Information parsed automatically

The following information is automatically parsed.

  • Types of arguments
  • Types of variables and constants
  • Types of variables in the derived types, and initial values
  • NAMELISTs and types of variables in them, and initial values

Aliases by interface statement are described in the item of ‘Methods’.

Components which are imported from other modules and published again are described in the item of ‘Methods’.

Format of comment blocks

Comment blocks should be written as follows. Comment blocks are considered to be ended when the line without ’!’ appears. The indentation is not necessary.

     ! (Top of file)
     !
     ! Comment blocks for the files.
     !
     !--
     ! The comment described in the part enclosed by
     ! "!--" and "!++" is ignored.
     !++
     !
     module hogehoge
       !
       ! Comment blocks for the modules (or the programs).
       !

       private

       logical            :: a     ! a private variable
       real, public       :: b     ! a public variable
       integer, parameter :: c = 0 ! a public constant

       public :: c
       public :: MULTI_ARRAY
       public :: hoge, foo

       type MULTI_ARRAY
         !
         ! Comment blocks for the derived-types.
         !
         real, pointer :: var(:) =>null() ! Comments block for the variables.
         integer       :: num = 0
       end type MULTI_ARRAY

     contains

       subroutine hoge( in,   &   ! Comment blocks between continuation lines are ignored.
           &            out )
         !
         ! Comment blocks for the subroutines or functions
         !
         character(*),intent(in):: in ! Comment blocks for the arguments.
         character(*),intent(out),allocatable,target  :: in
                                      ! Comment blocks can be
                                      ! written under Fortran statements.

         character(32) :: file ! This comment parsed as a variable in below NAMELIST.
         integer       :: id

         namelist /varinfo_nml/ file, id
                 !
                 ! Comment blocks for the NAMELISTs.
                 ! Information about variables are described above.
                 !

       ....

       end subroutine hoge

       integer function foo( in )
         !
         ! This part is considered as comment block.

         ! Comment blocks under blank lines are ignored.
         !
         integer, intent(in):: inA ! This part is considered as comment block.

                                   ! This part is ignored.

       end function foo

       subroutine hide( in,   &
         &              out )      !:nodoc:
         !
         ! If "!:nodoc:" is described at end-of-line in subroutine
         ! statement as above, the subroutine is ignored.
         ! This assignment can be used to modules, subroutines,
         ! functions, variables, constants, derived-types,
         ! defined operators, defined assignments,
         ! list of imported modules ("use" statement).
         !

       ....

       end subroutine hide

     end module hogehoge

Required files

rdoc/code_objects


File: parse_rb.rb

parse_rb.rb

Path: | lib/rdoc/parsers/parse_rb.rb
Last Update: | Tue Mar 13 02:06:35 -0500 2007

Parse a Ruby source file, building a set of objects representing the modules, classes, methods, requires, and includes we find (these classes are defined in code_objects.rb).

Required files

e2mmap irb/slex rdoc/code_objects rdoc/tokenstream rdoc/markup/simple_markup/preprocess rdoc/parsers/parserfactory


File: parse_simple.rb

parse_simple.rb

Path: | lib/rdoc/parsers/parse_simple.rb
Last Update: | Tue Mar 13 02:06:35 -0500 2007

Parse a non-source file. We basically take the whole thing as one big comment. If the first character in the file is ’#’, we strip leading pound signs.

Required files

rdoc/code_objects rdoc/markup/simple_markup/preprocess


File: parserfactory.rb

parserfactory.rb

Path: | lib/rdoc/parsers/parserfactory.rb
Last Update: | Tue Mar 13 02:06:35 -0500 2007

Required files

rdoc/parsers/parse_simple


File: ri_cache.rb

ri_cache.rb

Path: | lib/rdoc/ri/ri_cache.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007


File: ri_descriptions.rb

ri_descriptions.rb

Path: | lib/rdoc/ri/ri_descriptions.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

Required files

yaml rdoc/markup/simple_markup/fragments


File: ri_display.rb

ri_display.rb

Path: | lib/rdoc/ri/ri_display.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

Required files

rdoc/ri/ri_util rdoc/ri/ri_formatter rdoc/ri/ri_options


File: ri_driver.rb

ri_driver.rb

Path: | lib/rdoc/ri/ri_driver.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

Required files

rdoc/ri/ri_paths rdoc/usage rdoc/ri/ri_cache rdoc/ri/ri_util rdoc/ri/ri_reader rdoc/ri/ri_formatter rdoc/ri/ri_options


File: ri_formatter.rb

ri_formatter.rb

Path: | lib/rdoc/ri/ri_formatter.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007


File: ri_options.rb

ri_options.rb

Path: | lib/rdoc/ri/ri_options.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

We handle the parsing of options, and subsequently as a singleton object to be queried for option values

Required files

rdoc/ri/ri_paths rdoc/ri/ri_display singleton getoptlong


File: ri_paths.rb

ri_paths.rb

Path: | lib/rdoc/ri/ri_paths.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

Required files

rbconfig rubygems


File: ri_reader.rb

ri_reader.rb

Path: | lib/rdoc/ri/ri_reader.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

Required files

rdoc/ri/ri_descriptions rdoc/ri/ri_writer rdoc/markup/simple_markup/to_flow


File: ri_util.rb

ri_util.rb

Path: | lib/rdoc/ri/ri_util.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007


File: ri_writer.rb

ri_writer.rb

Path: | lib/rdoc/ri/ri_writer.rb
Last Update: | Tue Mar 13 02:06:39 -0500 2007

Required files

fileutils


File: attlistdecl.rb

attlistdecl.rb

Path: | lib/rexml/attlistdecl.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

vim:ts=2 sw=2 noexpandtab:

Required files

rexml/child rexml/source


File: attribute.rb

attribute.rb

Path: | lib/rexml/attribute.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

Required files

rexml/namespace rexml/text


File: cdata.rb

cdata.rb

Path: | lib/rexml/cdata.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/text


File: child.rb

child.rb

Path: | lib/rexml/child.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

Required files

rexml/node


File: comment.rb

comment.rb

Path: | lib/rexml/comment.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/child


File: doctype.rb

doctype.rb

Path: | lib/rexml/doctype.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/parent rexml/parseexception rexml/namespace rexml/entity rexml/attlistdecl rexml/xmltokens


File: document.rb

document.rb

Path: | lib/rexml/document.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

Required files

rexml/element rexml/xmldecl rexml/source rexml/comment rexml/doctype rexml/instruction rexml/rexml rexml/parseexception rexml/output rexml/parsers/baseparser rexml/parsers/streamparser rexml/parsers/treeparser


File: element.rb

element.rb

Path: | lib/rexml/element.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

Required files

rexml/parent rexml/namespace rexml/attribute rexml/cdata rexml/xpath rexml/parseexception


File: encoding.rb

encoding.rb

Path: | lib/rexml/encoding.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

-*- mode: ruby; ruby-indent-level: 2; indent-tabs-mode: t; tab-width: 2 -*- vim: sw=2 ts=2

Required files

rexml/encodings/ICONV.rb rexml/encodings/UTF-8.rb


File: entity.rb

entity.rb

Path: | lib/rexml/entity.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/child rexml/source rexml/xmltokens


File: functions.rb

functions.rb

Path: | lib/rexml/functions.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007


File: instruction.rb

instruction.rb

Path: | lib/rexml/instruction.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/child rexml/source


File: namespace.rb

namespace.rb

Path: | lib/rexml/namespace.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

Required files

rexml/xmltokens


File: node.rb

node.rb

Path: | lib/rexml/node.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/parseexception rexml/formatters/pretty rexml/formatters/default


File: output.rb

output.rb

Path: | lib/rexml/output.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

Required files

rexml/encoding


File: parent.rb

parent.rb

Path: | lib/rexml/parent.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

Required files

rexml/child


File: parseexception.rb

parseexception.rb

Path: | lib/rexml/parseexception.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007


File: quickpath.rb

quickpath.rb

Path: | lib/rexml/quickpath.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

Required files

rexml/functions rexml/xmltokens


File: rexml.rb

rexml.rb

Path: | lib/rexml/rexml.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

-*- encoding: utf-8 -*- REXML is an XML toolkit for Ruby, in Ruby.

REXML is a pure Ruby, XML 1.0 conforming, non-validating toolkit with an intuitive API. REXML passes 100% of the non-validating Oasis tests, and provides tree, stream, SAX2, pull, and lightweight APIs. REXML also includes a full XPath 1.0 implementation. Since Ruby 1.8, REXML is included in the standard Ruby distribution.

Main page: | www.germane-software.com/software/rexml
Author: | Sean Russell <serATgermaneHYPHENsoftwareDOTcom>
Version: | 3.1.7.2
Date: | 2007/275
Revision: | $Revision: 13815 $

This API documentation can be downloaded from the REXML home page, or can be accessed online

A tutorial is available in the REXML distribution in docs/tutorial.html, or can be accessed online


File: sax2listener.rb

sax2listener.rb

Path: | lib/rexml/sax2listener.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007


File: source.rb

source.rb

Path: | lib/rexml/source.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

Required files

rexml/encoding


File: streamlistener.rb

streamlistener.rb

Path: | lib/rexml/streamlistener.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007


File: syncenumerator.rb

syncenumerator.rb

Path: | lib/rexml/syncenumerator.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007


File: text.rb

text.rb

Path: | lib/rexml/text.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/entity rexml/doctype rexml/child rexml/doctype rexml/parseexception


File: undefinednamespaceexception.rb

undefinednamespaceexception.rb

Path: | lib/rexml/undefinednamespaceexception.rb
Last Update: | Tue Jan 22 17:04:00 -0600 2008

Required files

rexml/parseexception


File: xmldecl.rb

xmldecl.rb

Path: | lib/rexml/xmldecl.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/encoding rexml/source


File: xmltokens.rb

xmltokens.rb

Path: | lib/rexml/xmltokens.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007


File: xpath_parser.rb

xpath_parser.rb

Path: | lib/rexml/xpath_parser.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/namespace rexml/xmltokens rexml/attribute rexml/syncenumerator rexml/parsers/xpathparser


File: xpath.rb

xpath.rb

Path: | lib/rexml/xpath.rb
Last Update: | Tue Mar 13 02:06:00 -0500 2007

Required files

rexml/functions rexml/xpath_parser


File: attlistdecl.rb

attlistdecl.rb

Path: | lib/rexml/dtd/attlistdecl.rb
Last Update: | Tue Mar 13 02:05:59 -0500 2007

Required files

rexml/child


File: dtd.rb

dtd.rb

Path: | lib/rexml/dtd/dtd.rb
Last Update: | Tue Jan 22 17:03:59 -0600 2008

Required files

rexml/dtd/elementdecl rexml/dtd/entitydecl rexml/comment rexml/dtd/notationdecl rexml/dtd/attlistdecl rexml/parent


File: elementdecl.rb

elementdecl.rb

Path: | lib/rexml/dtd/elementdecl.rb
Last Update: | Tue Mar 13 02:05:59 -0500 2007

Required files

rexml/child


File: entitydecl.rb

entitydecl.rb

Path: | lib/rexml/dtd/entitydecl.rb
Last Update: | Tue Mar 13 02:05:59 -0500 2007

Required files

rexml/child


File: notationdecl.rb

notationdecl.rb

Path: | lib/rexml/dtd/notationdecl.rb
Last Update: | Tue Mar 13 02:05:59 -0500 2007

Required files

rexml/child


File: CP-1252.rb

CP-1252.rb

Path: | lib/rexml/encodings/CP-1252.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

This class was contributed by Mikko Tiihonen mikko DOT tiihonen AT hut DOT fi


File: EUC-JP.rb

EUC-JP.rb

Path: | lib/rexml/encodings/EUC-JP.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007

Required files

uconv nkf


File: ICONV.rb

ICONV.rb

Path: | lib/rexml/encodings/ICONV.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007

Required files

iconv


File: ISO-8859-1.rb

ISO-8859-1.rb

Path: | lib/rexml/encodings/ISO-8859-1.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007

Required files

rexml/encodings/US-ASCII


File: ISO-8859-15.rb

ISO-8859-15.rb

Path: | lib/rexml/encodings/ISO-8859-15.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

This class was contributed by Mikko Tiihonen mikko DOT tiihonen AT hut DOT fi


File: SHIFT-JIS.rb

SHIFT-JIS.rb

Path: | lib/rexml/encodings/SHIFT-JIS.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007

Required files

uconv nkf


File: UNILE.rb

UNILE.rb

Path: | lib/rexml/encodings/UNILE.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007


File: US-ASCII.rb

US-ASCII.rb

Path: | lib/rexml/encodings/US-ASCII.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007


File: UTF-8.rb

UTF-8.rb

Path: | lib/rexml/encodings/UTF-8.rb
Last Update: | Tue Mar 13 02:05:57 -0500 2007


File: UTF-16.rb

UTF-16.rb

Path: | lib/rexml/encodings/UTF-16.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007


File: default.rb

default.rb

Path: | lib/rexml/formatters/default.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007


File: pretty.rb

pretty.rb

Path: | lib/rexml/formatters/pretty.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/formatters/default


File: transitive.rb

transitive.rb

Path: | lib/rexml/formatters/transitive.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/formatters/pretty


File: node.rb

node.rb

Path: | lib/rexml/light/node.rb
Last Update: | Tue Mar 13 02:05:59 -0500 2007

Required files

rexml/xmltokens rexml/light/node


File: baseparser.rb

baseparser.rb

Path: | lib/rexml/parsers/baseparser.rb
Last Update: | Tue Jan 22 17:03:59 -0600 2008

Required files

rexml/parseexception rexml/undefinednamespaceexception rexml/source set


File: lightparser.rb

lightparser.rb

Path: | lib/rexml/parsers/lightparser.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007

Required files

rexml/parsers/streamparser rexml/parsers/baseparser rexml/light/node


File: pullparser.rb

pullparser.rb

Path: | lib/rexml/parsers/pullparser.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007

Required files

forwardable rexml/parseexception rexml/parsers/baseparser rexml/xmltokens


File: sax2parser.rb

sax2parser.rb

Path: | lib/rexml/parsers/sax2parser.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/parsers/baseparser rexml/parseexception rexml/namespace rexml/text


File: streamparser.rb

streamparser.rb

Path: | lib/rexml/parsers/streamparser.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007


File: treeparser.rb

treeparser.rb

Path: | lib/rexml/parsers/treeparser.rb
Last Update: | Tue Jan 22 17:03:59 -0600 2008

Required files

rexml/validation/validationexception rexml/undefinednamespaceexception


File: ultralightparser.rb

ultralightparser.rb

Path: | lib/rexml/parsers/ultralightparser.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007

Required files

rexml/parsers/streamparser rexml/parsers/baseparser


File: xpathparser.rb

xpathparser.rb

Path: | lib/rexml/parsers/xpathparser.rb
Last Update: | Mon Oct 01 13:18:31 -0500 2007

Required files

rexml/namespace rexml/xmltokens


File: relaxng.rb

relaxng.rb

Path: | lib/rexml/validation/relaxng.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007

Required files

rexml/validation/validation rexml/parsers/baseparser


File: validation.rb

validation.rb

Path: | lib/rexml/validation/validation.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007

Required files

rexml/validation/validationexception


File: validationexception.rb

validationexception.rb

Path: | lib/rexml/validation/validationexception.rb
Last Update: | Tue Mar 13 02:05:54 -0500 2007


File: rinda.rb

rinda.rb

Path: | lib/rinda/rinda.rb
Last Update: | Tue Mar 13 02:07:00 -0500 2007

Required files

drb/drb thread


File: ring.rb

ring.rb

Path: | lib/rinda/ring.rb
Last Update: | Tue Mar 13 02:07:00 -0500 2007

Note: Rinda::Ring API is unstable.

Required files

drb/drb rinda/rinda thread rinda/tuplespace


File: tuplespace.rb

tuplespace.rb

Path: | lib/rinda/tuplespace.rb
Last Update: | Mon Oct 01 13:18:32 -0500 2007

Required files

monitor thread drb/drb rinda/rinda


File: 0.9.rb

0.9.rb

Path: | lib/rss/0.9.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/parser


File: 1.0.rb

1.0.rb

Path: | lib/rss/1.0.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/parser


File: 2.0.rb

2.0.rb

Path: | lib/rss/2.0.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/0.9


File: content.rb

content.rb

Path: | lib/rss/content.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/1.0


File: converter.rb

converter.rb

Path: | lib/rss/converter.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/utils iconv uconv nkf nkf nkf nkf nkf


File: dublincore.rb

dublincore.rb

Path: | lib/rss/dublincore.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/1.0


File: image.rb

image.rb

Path: | lib/rss/image.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/1.0 rss/dublincore


File: maker.rb

maker.rb

Path: | lib/rss/maker.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/rss rss/maker/1.0 rss/maker/2.0 rss/maker/content rss/maker/dublincore rss/maker/syndication rss/maker/taxonomy rss/maker/trackback rss/maker/image


File: parser.rb

parser.rb

Path: | lib/rss/parser.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

forwardable open-uri rss/rss


File: rexmlparser.rb

rexmlparser.rb

Path: | lib/rss/rexmlparser.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rexml/document rexml/streamlistener


File: rss.rb

rss.rb

Path: | lib/rss/rss.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

time English rss/utils rss/converter rss/xml-stylesheet


File: syndication.rb

syndication.rb

Path: | lib/rss/syndication.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/1.0


File: taxonomy.rb

taxonomy.rb

Path: | lib/rss/taxonomy.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/1.0 rss/dublincore


File: trackback.rb

trackback.rb

Path: | lib/rss/trackback.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/1.0 rss/2.0


File: utils.rb

utils.rb

Path: | lib/rss/utils.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007


File: xml-stylesheet.rb

xml-stylesheet.rb

Path: | lib/rss/xml-stylesheet.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

rss/utils


File: xmlparser.rb

xmlparser.rb

Path: | lib/rss/xmlparser.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

xml/parser xmlparser xml/encoding-ja xmlencoding-ja


File: xmlscanner.rb

xmlscanner.rb

Path: | lib/rss/xmlscanner.rb
Last Update: | Tue Mar 13 02:06:25 -0500 2007

Required files

xmlscan/scanner stringio


File: 0.9.rb

0.9.rb

Path: | lib/rss/maker/0.9.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/0.9 rss/maker/base


File: 1.0.rb

1.0.rb

Path: | lib/rss/maker/1.0.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/1.0 rss/maker/base


File: 2.0.rb

2.0.rb

Path: | lib/rss/maker/2.0.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/2.0 rss/maker/0.9


File: base.rb

base.rb

Path: | lib/rss/maker/base.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

forwardable rss/rss


File: content.rb

content.rb

Path: | lib/rss/maker/content.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/content rss/maker/1.0


File: dublincore.rb

dublincore.rb

Path: | lib/rss/maker/dublincore.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/dublincore rss/maker/1.0


File: image.rb

image.rb

Path: | lib/rss/maker/image.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/image rss/maker/1.0 rss/maker/dublincore


File: syndication.rb

syndication.rb

Path: | lib/rss/maker/syndication.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/syndication rss/maker/1.0


File: taxonomy.rb

taxonomy.rb

Path: | lib/rss/maker/taxonomy.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/taxonomy rss/maker/1.0 rss/maker/dublincore


File: trackback.rb

trackback.rb

Path: | lib/rss/maker/trackback.rb
Last Update: | Tue Mar 13 02:06:23 -0500 2007

Required files

rss/trackback rss/maker/1.0 rss/maker/2.0


File: assert.rb

assert.rb

Path: | lib/runit/assert.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/assertions runit/error


File: error.rb

error.rb

Path: | lib/runit/error.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/assertionfailederror.rb


File: testcase.rb

testcase.rb

Path: | lib/runit/testcase.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

runit/testresult runit/testsuite runit/assert runit/error test/unit/testcase


File: testresult.rb

testresult.rb

Path: | lib/runit/testresult.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/testresult


File: testsuite.rb

testsuite.rb

Path: | lib/runit/testsuite.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/testsuite


File: topublic.rb

topublic.rb

Path: | lib/runit/topublic.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.


File: testrunner.rb

testrunner.rb

Path: | lib/runit/cui/testrunner.rb
Last Update: | Tue Mar 13 02:06:04 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/ui/console/testrunner runit/testresult


File: builtin-command.rb

builtin-command.rb

Path: | lib/shell/builtin-command.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  shell/builtin-command.rb -
      $Release Version: 0.6.0 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—

Required files

shell/filter


File: command-processor.rb

command-processor.rb

Path: | lib/shell/command-processor.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  shell/command-controller.rb -
      $Release Version: 0.6.0 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nippon Rational Inc.)

—

Required files

e2mmap ftools thread shell/error shell/filter shell/system-command shell/builtin-command


File: error.rb

error.rb

Path: | lib/shell/error.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  shell/error.rb -
      $Release Version: 0.6.0 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—

Required files

e2mmap


File: filter.rb

filter.rb

Path: | lib/shell/filter.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  shell/filter.rb -
      $Release Version: 0.6.0 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—


File: process-controller.rb

process-controller.rb

Path: | lib/shell/process-controller.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  shell/process-controller.rb -
      $Release Version: 0.6.0 $
      $Revision: 12008 $
      $Date: 2007-03-06 04:12:12 -0600 (Tue, 06 Mar 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—

Required files

mutex_m monitor sync


File: system-command.rb

system-command.rb

Path: | lib/shell/system-command.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  shell/system-command.rb -
      $Release Version: 0.6.0 $
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—

Required files

shell/filter


File: version.rb

version.rb

Path: | lib/shell/version.rb
Last Update: | Tue Mar 13 02:06:45 -0500 2007
  version.rb - shell version definition file
      $Release Version: 0.6.0$
      $Revision: 11708 $
      $Date: 2007-02-12 17:01:19 -0600 (Mon, 12 Feb 2007) $
      by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)

—


__init__ (lib/singleton.rb)

# File lib/singleton.rb, line 157
  def __init__(klass)
    klass.instance_eval { @__instance__ = nil }
    class << klass
      define_method(:instance,FirstInstanceCall)
    end
    klass
  end


File: attachment.rb

attachment.rb

Path: | lib/soap/attachment.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

soap/attachment.rb: SOAP4R - SwA implementation. Copyright (C) 2002, 2003 Jamie Herre and NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/baseData soap/mapping


File: baseData.rb

baseData.rb

Path: | lib/soap/baseData.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

soap/baseData.rb: SOAP4R - Base type library Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/datatypes soap/soap soap/mapping/typeMap


File: element.rb

element.rb

Path: | lib/soap/element.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - SOAP elements library Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname soap/baseData


File: generator.rb

generator.rb

Path: | lib/soap/generator.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - SOAP XML Instance Generator library. Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/ns soap/soap soap/baseData soap/encodingstyle/handler


File: httpconfigloader.rb

httpconfigloader.rb

Path: | lib/soap/httpconfigloader.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - HTTP config loader. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/property


File: marshal.rb

marshal.rb

Path: | lib/soap/marshal.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - Marshalling/Unmarshalling Ruby‘s object using SOAP Encoding. Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/mapping soap/processor

Constants

SOAPMarshal = SOAP::Marshal


File: mimemessage.rb

mimemessage.rb

Path: | lib/soap/mimemessage.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - MIME Message implementation. Copyright (C) 2002 Jamie Herre.

Required files

soap/attachment


File: netHttpClient.rb

netHttpClient.rb

Path: | lib/soap/netHttpClient.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - net/http wrapper Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

net/http


File: parser.rb

parser.rb

Path: | lib/soap/parser.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - SOAP XML Instance Parser library. Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/ns xsd/xmlparser soap/soap soap/baseData soap/encodingstyle/handler


File: processor.rb

processor.rb

Path: | lib/soap/processor.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - marshal/unmarshal interface. Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/datatypes soap/soap soap/element soap/parser soap/generator soap/encodingstyle/soapHandler soap/encodingstyle/literalHandler soap/encodingstyle/aspDotNetHandler


File: property.rb

property.rb

Path: | lib/soap/property.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

soap/property.rb: SOAP4R - Property implementation. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: soap.rb

soap.rb

Path: | lib/soap/soap.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

soap/soap.rb: SOAP4R - Base definitions. Copyright (C) 2000-2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname xsd/charset


File: streamHandler.rb

streamHandler.rb

Path: | lib/soap/streamHandler.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - Stream handler. Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/soap soap/httpconfigloader stringio zlib http-access2 soap/netHttpClient


File: wsdlDriver.rb

wsdlDriver.rb

Path: | lib/soap/wsdlDriver.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - SOAP WSDL driver Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/parser wsdl/importer xsd/qname xsd/codegen/gensupport soap/mapping/wsdlencodedregistry soap/mapping/wsdlliteralregistry soap/rpc/driver wsdl/soap/methodDefCreator


File: aspDotNetHandler.rb

aspDotNetHandler.rb

Path: | lib/soap/encodingstyle/aspDotNetHandler.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - ASP.NET EncodingStyle handler library Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/encodingstyle/handler


File: handler.rb

handler.rb

Path: | lib/soap/encodingstyle/handler.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - EncodingStyle handler library Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/soap soap/baseData soap/element


File: literalHandler.rb

literalHandler.rb

Path: | lib/soap/encodingstyle/literalHandler.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - XML Literal EncodingStyle handler library Copyright (C) 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/encodingstyle/handler


File: soapHandler.rb

soapHandler.rb

Path: | lib/soap/encodingstyle/soapHandler.rb
Last Update: | Tue Mar 13 02:06:17 -0500 2007

SOAP4R - SOAP EncodingStyle handler library Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/encodingstyle/handler


File: handler.rb

handler.rb

Path: | lib/soap/header/handler.rb
Last Update: | Tue Mar 13 02:06:07 -0500 2007

SOAP4R - SOAP Header handler item Copyright (C) 2003, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/element


File: handlerset.rb

handlerset.rb

Path: | lib/soap/header/handlerset.rb
Last Update: | Tue Mar 13 02:06:07 -0500 2007

SOAP4R - SOAP Header handler set Copyright (C) 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/namedelements


File: simplehandler.rb

simplehandler.rb

Path: | lib/soap/header/simplehandler.rb
Last Update: | Tue Mar 13 02:06:07 -0500 2007

SOAP4R - SOAP Simple header item handler Copyright (C) 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/header/handler soap/baseData


File: factory.rb

factory.rb

Path: | lib/soap/mapping/factory.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - Mapping factory. Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: mapping.rb

mapping.rb

Path: | lib/soap/mapping/mapping.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - Ruby type mapping utility. Copyright (C) 2000, 2001, 2003-2005 NAKAMURA Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport


File: registry.rb

registry.rb

Path: | lib/soap/mapping/registry.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - Mapping registry. Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/baseData soap/mapping/mapping soap/mapping/typeMap soap/mapping/factory soap/mapping/rubytypeFactory


File: rubytypeFactory.rb

rubytypeFactory.rb

Path: | lib/soap/mapping/rubytypeFactory.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - Ruby type mapping factory. Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: typeMap.rb

typeMap.rb

Path: | lib/soap/mapping/typeMap.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - Base type mapping definition Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: wsdlencodedregistry.rb

wsdlencodedregistry.rb

Path: | lib/soap/mapping/wsdlencodedregistry.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - WSDL encoded mapping registry. Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname xsd/namedelements soap/baseData soap/mapping/mapping soap/mapping/typeMap


File: wsdlliteralregistry.rb

wsdlliteralregistry.rb

Path: | lib/soap/mapping/wsdlliteralregistry.rb
Last Update: | Tue Mar 13 02:06:11 -0500 2007

SOAP4R - WSDL literal mapping registry. Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/baseData soap/mapping/mapping soap/mapping/typeMap xsd/codegen/gensupport xsd/namedelements


File: cgistub.rb

cgistub.rb

Path: | lib/soap/rpc/cgistub.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - CGI/mod_ruby stub library Copyright (C) 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/streamHandler webrick/httpresponse webrick/httpstatus logger soap/rpc/soaplet


File: driver.rb

driver.rb

Path: | lib/soap/rpc/driver.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - SOAP RPC driver Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/soap soap/mapping soap/mapping/wsdlliteralregistry soap/rpc/rpc soap/rpc/proxy soap/rpc/element soap/streamHandler soap/property soap/header/handlerset


File: element.rb

element.rb

Path: | lib/soap/rpc/element.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - RPC element definition. Copyright (C) 2000, 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/baseData


File: httpserver.rb

httpserver.rb

Path: | lib/soap/rpc/httpserver.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - WEBrick HTTP Server Copyright (C) 2003, 2004 by NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

logger soap/rpc/soaplet soap/streamHandler webrick


File: proxy.rb

proxy.rb

Path: | lib/soap/rpc/proxy.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - RPC Proxy library. Copyright (C) 2000, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/soap soap/processor soap/mapping soap/rpc/rpc soap/rpc/element soap/streamHandler soap/mimemessage


File: router.rb

router.rb

Path: | lib/soap/rpc/router.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - RPC Routing library Copyright (C) 2001, 2002, 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/soap soap/processor soap/mapping soap/mapping/wsdlliteralregistry soap/rpc/rpc soap/rpc/element soap/streamHandler soap/mimemessage soap/header/handlerset


File: rpc.rb

rpc.rb

Path: | lib/soap/rpc/rpc.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - RPC utility. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: soaplet.rb

soaplet.rb

Path: | lib/soap/rpc/soaplet.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - SOAP handler servlet for WEBrick Copyright (C) 2001-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

webrick/httpservlet/abstract webrick/httpstatus soap/rpc/router soap/streamHandler stringio zlib webrick/log


File: standaloneServer.rb

standaloneServer.rb

Path: | lib/soap/rpc/standaloneServer.rb
Last Update: | Tue Mar 13 02:06:06 -0500 2007

SOAP4R - WEBrick Server Copyright (C) 2003 by NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/rpc/httpserver


File: unit.rb

unit.rb

Path: | lib/test/unit.rb
Last Update: | Tue Mar 13 02:06:51 -0500 2007

Required files

test/unit/testcase test/unit/autorunner


File: assertionfailederror.rb

assertionfailederror.rb

Path: | lib/test/unit/assertionfailederror.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


File: assertions.rb

assertions.rb

Path: | lib/test/unit/assertions.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/assertionfailederror test/unit/util/backtracefilter pp


File: autorunner.rb

autorunner.rb

Path: | lib/test/unit/autorunner.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

test/unit test/unit/ui/testrunnerutilities optparse test/unit/ui/gtk/testrunner test/unit/ui/gtk2/testrunner test/unit/ui/fox/testrunner test/unit/ui/tk/testrunner test/unit/collector/dir


File: collector.rb

collector.rb

Path: | lib/test/unit/collector.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


File: error.rb

error.rb

Path: | lib/test/unit/error.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

test/unit/util/backtracefilter


File: failure.rb

failure.rb

Path: | lib/test/unit/failure.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


File: testcase.rb

testcase.rb

Path: | lib/test/unit/testcase.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

test/unit/assertions test/unit/failure test/unit/error test/unit/testsuite test/unit/assertionfailederror test/unit/util/backtracefilter


File: testresult.rb

testresult.rb

Path: | lib/test/unit/testresult.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

test/unit/util/observable


File: testsuite.rb

testsuite.rb

Path: | lib/test/unit/testsuite.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


File: dir.rb

dir.rb

Path: | lib/test/unit/collector/dir.rb
Last Update: | Tue Mar 13 02:06:48 -0500 2007

Required files

test/unit/testsuite test/unit/collector


File: objectspace.rb

objectspace.rb

Path: | lib/test/unit/collector/objectspace.rb
Last Update: | Tue Mar 13 02:06:48 -0500 2007
Author: | Nathaniel Talbott.
Copyright: | Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
License: | Ruby license.

Required files

test/unit/collector


File: testrunnermediator.rb

testrunnermediator.rb

Path: | lib/test/unit/ui/testrunnermediator.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

test/unit test/unit/util/observable test/unit/testresult


File: testrunnerutilities.rb

testrunnerutilities.rb

Path: | lib/test/unit/ui/testrunnerutilities.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


File: testrunner.rb

testrunner.rb

Path: | lib/test/unit/ui/console/testrunner.rb
Last Update: | Tue Mar 13 02:06:49 -0500 2007

Required files

test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: testrunner.rb

testrunner.rb

Path: | lib/test/unit/ui/fox/testrunner.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

fox test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities

Included Modules

Fox


File: testrunner.rb

testrunner.rb

Path: | lib/test/unit/ui/gtk/testrunner.rb
Last Update: | Tue Mar 13 02:06:49 -0500 2007

Required files

gtk test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: testrunner.rb

testrunner.rb

Path: | lib/test/unit/ui/gtk2/testrunner.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

gtk2 test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: testrunner.rb

testrunner.rb

Path: | lib/test/unit/ui/tk/testrunner.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

tk test/unit/ui/testrunnermediator test/unit/ui/testrunnerutilities


File: backtracefilter.rb

backtracefilter.rb

Path: | lib/test/unit/util/backtracefilter.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


File: observable.rb

observable.rb

Path: | lib/test/unit/util/observable.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007

Required files

test/unit/util/procwrapper


File: procwrapper.rb

procwrapper.rb

Path: | lib/test/unit/util/procwrapper.rb
Last Update: | Tue Mar 13 02:06:50 -0500 2007


setup (lib/un.rb)

# File lib/un.rb, line 32
def setup(options = "")
  ARGV.map! do |x|
    case x
    when /^-/
      x.delete "^-#{options}v"
    when /[*?\[{]/
      Dir[x]
    else
      x
    end
  end
  ARGV.flatten!
  ARGV.delete_if{|x| x == "-"}
  opt_hash = {}
  OptionParser.new do |o|
    options.scan(/.:?/) do |s|
      o.on("-" + s.tr(":", " ")) do |val|
        opt_hash[s.delete(":").intern] = val
      end
    end
    o.on("-v") do opt_hash[:verbose] = true end
    o.parse!
  end
  yield ARGV, opt_hash
end


cp (lib/un.rb)

# File lib/un.rb, line 68
def cp
  setup("pr") do |argv, options|
    cmd = "cp"
    cmd += "_r" if options.delete :r
    options[:preserve] = true if options.delete :p
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.send cmd, argv, dest, options
  end
end


ln (lib/un.rb)

# File lib/un.rb, line 89
def ln
  setup("sf") do |argv, options|
    cmd = "ln"
    cmd += "_s" if options.delete :s
    options[:force] = true if options.delete :f
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.send cmd, argv, dest, options
  end
end


mv (lib/un.rb)

# File lib/un.rb, line 108
def mv
  setup do |argv, options|
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.mv argv, dest, options
  end
end


rm (lib/un.rb)

# File lib/un.rb, line 126
def rm
  setup("fr") do |argv, options|
    cmd = "rm"
    cmd += "_r" if options.delete :r
    options[:force] = true if options.delete :f
    FileUtils.send cmd, argv, options
  end
end


mkdir (lib/un.rb)

# File lib/un.rb, line 144
def mkdir
  setup("p") do |argv, options|
    cmd = "mkdir"
    cmd += "_p" if options.delete :p
    FileUtils.send cmd, argv, options
  end
end


rmdir (lib/un.rb)

# File lib/un.rb, line 160
def rmdir
  setup do |argv, options|
    FileUtils.rmdir argv, options
  end
end


install (lib/un.rb)

# File lib/un.rb, line 177
def install
  setup("pm:") do |argv, options|
    options[:mode] = (mode = options.delete :m) ? mode.oct : 0755
    options[:preserve] = true if options.delete :p
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.install argv, dest, options
  end
end


chmod (lib/un.rb)

# File lib/un.rb, line 195
def chmod
  setup do |argv, options|
    mode = argv.shift.oct
    FileUtils.chmod mode, argv, options
  end
end


touch (lib/un.rb)

# File lib/un.rb, line 210
def touch
  setup do |argv, options|
    FileUtils.touch argv, options
  end
end


help (lib/un.rb)

# File lib/un.rb, line 222
def help
  setup do |argv,|
    all = argv.empty?
    open(__FILE__) do |me|
      while me.gets("##\n")
        if help = me.gets("\n\n")
          if all or argv.delete help[/-e \w+/].sub(/-e /, "")
            print help.gsub(/^# ?/, "")
          end
        end
      end
    end
  end
end


File: common.rb

common.rb

Path: | lib/uri/common.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/common.rb

Author: | Akira Yamada <akira@ruby-lang.org>
Revision: | $Id: common.rb 11747 2007-02-15 02:41:45Z knu $
License: | You can redistribute it and/or modify it under the same term as Ruby.


File: ftp.rb

ftp.rb

Path: | lib/uri/ftp.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/ftp.rb

Author: | Akira Yamada <akira@ruby-lang.org>
License: | You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: ftp.rb 11757 2007-02-15 11:36:28Z knu $

Required files

uri/generic


File: generic.rb

generic.rb

Path: | lib/uri/generic.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/generic.rb

Author: | Akira Yamada <akira@ruby-lang.org>
License: | You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: generic.rb 11751 2007-02-15 07:45:04Z knu $

Required files

uri/common


File: http.rb

http.rb

Path: | lib/uri/http.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/http.rb

Author: | Akira Yamada <akira@ruby-lang.org>
License: | You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: http.rb 11747 2007-02-15 02:41:45Z knu $

Required files

uri/generic


File: https.rb

https.rb

Path: | lib/uri/https.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/https.rb

Author: | Akira Yamada <akira@ruby-lang.org>
License: | You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: https.rb 11747 2007-02-15 02:41:45Z knu $

Required files

uri/http


File: ldap.rb

ldap.rb

Path: | lib/uri/ldap.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/ldap.rb

Author: | Takaaki Tateishi <ttate@jaist.ac.jp> Akira Yamada <akira@ruby-lang.org>
License: | URI::LDAP is copyrighted free software by Takaaki Tateishi and Akira Yamada. You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: ldap.rb 11708 2007-02-12 23:01:19Z shyouhei $

Required files

uri/generic


File: mailto.rb

mailto.rb

Path: | lib/uri/mailto.rb
Last Update: | Tue Mar 13 02:06:44 -0500 2007

uri/mailto.rb

Author: | Akira Yamada <akira@ruby-lang.org>
License: | You can redistribute it and/or modify it under the same term as Ruby.
Revision: | $Id: mailto.rb 11747 2007-02-15 02:41:45Z knu $

Required files

uri/generic


File: accesslog.rb

accesslog.rb

Path: | lib/webrick/accesslog.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

accesslog.rb — Access log handling utilities

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2002 keita yamaguchi Copyright (c) 2002 Internet Programming with Ruby writers

$IPR: accesslog.rb,v 1.1 2002/10/01 17:16:32 gotoyuzo Exp $


File: cgi.rb

cgi.rb

Path: | lib/webrick/cgi.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

cgi.rb — Yet another CGI library

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$Id: cgi.rb 11708 2007-02-12 23:01:19Z shyouhei $

Required files

webrick/httprequest webrick/httpresponse webrick/config stringio


File: compat.rb

compat.rb

Path: | lib/webrick/compat.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

compat.rb — cross platform compatibility

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2002 GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: compat.rb,v 1.6 2002/10/01 17:16:32 gotoyuzo Exp $


File: config.rb

config.rb

Path: | lib/webrick/config.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

config.rb — Default configurations.

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: config.rb,v 1.52 2003/07/22 19:20:42 gotoyuzo Exp $

Required files

webrick/version webrick/httpversion webrick/httputils webrick/utils webrick/log


File: cookie.rb

cookie.rb

Path: | lib/webrick/cookie.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

cookie.rb — Cookie class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: cookie.rb,v 1.16 2002/09/21 12:23:35 gotoyuzo Exp $

Required files

time webrick/httputils


File: htmlutils.rb

htmlutils.rb

Path: | lib/webrick/htmlutils.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

htmlutils.rb — HTMLUtils Module

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: htmlutils.rb,v 1.7 2002/09/21 12:23:35 gotoyuzo Exp $


File: httpauth.rb

httpauth.rb

Path: | lib/webrick/httpauth.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httpauth.rb — HTTP access authentication

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpauth.rb,v 1.14 2003/07/22 19:20:42 gotoyuzo Exp $

Required files

webrick/httpauth/basicauth webrick/httpauth/digestauth webrick/httpauth/htpasswd webrick/httpauth/htdigest webrick/httpauth/htgroup


File: httpproxy.rb

httpproxy.rb

Path: | lib/webrick/httpproxy.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httpproxy.rb — HTTPProxy Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2002 GOTO Kentaro Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpproxy.rb,v 1.18 2003/03/08 18:58:10 gotoyuzo Exp $ $kNotwork: straw.rb,v 1.3 2002/02/12 15:13:07 gotoken Exp $

Required files

webrick/httpserver net/http


File: httprequest.rb

httprequest.rb

Path: | lib/webrick/httprequest.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httprequest.rb — HTTPRequest Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httprequest.rb,v 1.64 2003/07/13 17:18:22 gotoyuzo Exp $

Required files

timeout uri webrick/httpversion webrick/httpstatus webrick/httputils webrick/cookie


File: httpresponse.rb

httpresponse.rb

Path: | lib/webrick/httpresponse.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httpresponse.rb — HTTPResponse Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpresponse.rb,v 1.45 2003/07/11 11:02:25 gotoyuzo Exp $

Required files

time webrick/httpversion webrick/htmlutils webrick/httputils webrick/httpstatus


File: https.rb

https.rb

Path: | lib/webrick/https.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

https.rb — SSL/TLS enhancement for HTTPServer

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2001 GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: https.rb,v 1.15 2003/07/22 19:20:42 gotoyuzo Exp $

Required files

webrick/ssl


File: httpserver.rb

httpserver.rb

Path: | lib/webrick/httpserver.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httpserver.rb — HTTPServer Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpserver.rb,v 1.63 2002/10/01 17:16:32 gotoyuzo Exp $

Required files

webrick/server webrick/httputils webrick/httpstatus webrick/httprequest webrick/httpresponse webrick/httpservlet webrick/accesslog


File: httpservlet.rb

httpservlet.rb

Path: | lib/webrick/httpservlet.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httpservlet.rb — HTTPServlet Utility File

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpservlet.rb,v 1.21 2003/02/23 12:24:46 gotoyuzo Exp $

Required files

webrick/httpservlet/abstract webrick/httpservlet/filehandler webrick/httpservlet/cgihandler webrick/httpservlet/erbhandler webrick/httpservlet/prochandler


File: httpstatus.rb

httpstatus.rb

Path: | lib/webrick/httpstatus.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httpstatus.rb — HTTPStatus Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpstatus.rb,v 1.11 2003/03/24 20:18:55 gotoyuzo Exp $


File: httputils.rb

httputils.rb

Path: | lib/webrick/httputils.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

httputils.rb — HTTPUtils Module

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httputils.rb,v 1.34 2003/06/05 21:34:08 gotoyuzo Exp $

Required files

socket tempfile


File: httpversion.rb

httpversion.rb

Path: | lib/webrick/httpversion.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

HTTPVersion.rb — presentation of HTTP version

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: httpversion.rb,v 1.5 2002/09/21 12:23:37 gotoyuzo Exp $


File: log.rb

log.rb

Path: | lib/webrick/log.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

log.rb — Log Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: log.rb,v 1.26 2002/10/06 17:06:10 gotoyuzo Exp $


File: server.rb

server.rb

Path: | lib/webrick/server.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

server.rb — GenericServer Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: server.rb,v 1.62 2003/07/22 19:20:43 gotoyuzo Exp $

Required files

thread socket timeout webrick/config webrick/log


File: ssl.rb

ssl.rb

Path: | lib/webrick/ssl.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

ssl.rb — SSL/TLS enhancement for GenericServer

Copyright (c) 2003 GOTOU Yuuzou All rights reserved.

$Id: ssl.rb 11708 2007-02-12 23:01:19Z shyouhei $

Required files

webrick openssl


File: utils.rb

utils.rb

Path: | lib/webrick/utils.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

utils.rb — Miscellaneous utilities

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: utils.rb,v 1.10 2003/02/16 22:22:54 gotoyuzo Exp $

Required files

socket fcntl etc


File: version.rb

version.rb

Path: | lib/webrick/version.rb
Last Update: | Tue Mar 13 02:05:53 -0500 2007

version.rb — version and release date

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: version.rb,v 1.74 2003/07/22 19:20:43 gotoyuzo Exp $


File: authenticator.rb

authenticator.rb

Path: | lib/webrick/httpauth/authenticator.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/authenticator.rb — Authenticator mix-in module.

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: authenticator.rb,v 1.3 2003/02/20 07:15:47 gotoyuzo Exp $


File: basicauth.rb

basicauth.rb

Path: | lib/webrick/httpauth/basicauth.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/basicauth.rb — HTTP basic access authentication

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: basicauth.rb,v 1.5 2003/02/20 07:15:47 gotoyuzo Exp $

Required files

webrick/config webrick/httpstatus webrick/httpauth/authenticator


File: digestauth.rb

digestauth.rb

Path: | lib/webrick/httpauth/digestauth.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/digestauth.rb — HTTP digest access authentication

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. Copyright (c) 2003 H.M.

The original implementation is provided by H.M.

  URL: http://rwiki.jin.gr.jp/cgi-bin/rw-cgi.rb?cmd=view;name=
       %C7%A7%BE%DA%B5%A1%C7%BD%A4%F2%B2%FE%C2%A4%A4%B7%A4%C6%A4%DF%A4%EB

$IPR: digestauth.rb,v 1.5 2003/02/20 07:15:47 gotoyuzo Exp $

Required files

webrick/config webrick/httpstatus webrick/httpauth/authenticator digest/md5 digest/sha1


File: htdigest.rb

htdigest.rb

Path: | lib/webrick/httpauth/htdigest.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/htdigest.rb — Apache compatible htdigest file

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: htdigest.rb,v 1.4 2003/07/22 19:20:45 gotoyuzo Exp $

Required files

webrick/httpauth/userdb webrick/httpauth/digestauth tempfile


File: htgroup.rb

htgroup.rb

Path: | lib/webrick/httpauth/htgroup.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/htgroup.rb — Apache compatible htgroup file

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: htgroup.rb,v 1.1 2003/02/16 22:22:56 gotoyuzo Exp $

Required files

tempfile


File: htpasswd.rb

htpasswd.rb

Path: | lib/webrick/httpauth/htpasswd.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/htpasswd — Apache compatible htpasswd file

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: htpasswd.rb,v 1.4 2003/07/22 19:20:45 gotoyuzo Exp $

Required files

webrick/httpauth/userdb webrick/httpauth/basicauth tempfile


File: userdb.rb

userdb.rb

Path: | lib/webrick/httpauth/userdb.rb
Last Update: | Tue Mar 13 02:05:52 -0500 2007

httpauth/userdb.rb — UserDB mix-in module.

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: userdb.rb,v 1.2 2003/02/20 07:15:48 gotoyuzo Exp $


File: abstract.rb

abstract.rb

Path: | lib/webrick/httpservlet/abstract.rb
Last Update: | Tue Mar 13 02:05:51 -0500 2007

httpservlet.rb — HTTPServlet Module

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: abstract.rb,v 1.24 2003/07/11 11:16:46 gotoyuzo Exp $

Required files

thread webrick/htmlutils webrick/httputils webrick/httpstatus


File: cgi_runner.rb

cgi_runner.rb

Path: | lib/webrick/httpservlet/cgi_runner.rb
Last Update: | Tue Mar 13 02:05:51 -0500 2007

cgi_runner.rb — CGI launcher.

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: cgi_runner.rb,v 1.9 2002/09/25 11:33:15 gotoyuzo Exp $

Methods

sysread

Public Instance methods

sysread(io, size)

cgi_runner.rb — CGI launcher.

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: cgi_runner.rb,v 1.9 2002/09/25 11:33:15 gotoyuzo Exp $


File: cgihandler.rb

cgihandler.rb

Path: | lib/webrick/httpservlet/cgihandler.rb
Last Update: | Tue Mar 13 02:05:51 -0500 2007

cgihandler.rb — CGIHandler Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: cgihandler.rb,v 1.27 2003/03/21 19:56:01 gotoyuzo Exp $

Required files

rbconfig tempfile webrick/config webrick/httpservlet/abstract


File: erbhandler.rb

erbhandler.rb

Path: | lib/webrick/httpservlet/erbhandler.rb
Last Update: | Tue Mar 13 02:05:51 -0500 2007

erbhandler.rb — ERBHandler Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: erbhandler.rb,v 1.25 2003/02/24 19:25:31 gotoyuzo Exp $

Required files

webrick/httpservlet/abstract.rb erb


File: filehandler.rb

filehandler.rb

Path: | lib/webrick/httpservlet/filehandler.rb
Last Update: | Tue Mar 13 02:05:51 -0500 2007

filehandler.rb — FileHandler Module

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2003 Internet Programming with Ruby writers. All rights reserved.

$IPR: filehandler.rb,v 1.44 2003/06/07 01:34:51 gotoyuzo Exp $

Required files

thread time webrick/htmlutils webrick/httputils webrick/httpstatus


File: prochandler.rb

prochandler.rb

Path: | lib/webrick/httpservlet/prochandler.rb
Last Update: | Tue Mar 13 02:05:51 -0500 2007

prochandler.rb — ProcHandler Class

Author: IPR — Internet Programming with Ruby — writers Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou Copyright (c) 2002 Internet Programming with Ruby writers. All rights reserved.

$IPR: prochandler.rb,v 1.7 2002/09/21 12:23:42 gotoyuzo Exp $

Required files

webrick/httpservlet/abstract.rb


sysread (lib/webrick/httpservlet/cgi_runner.rb)

# File lib/webrick/httpservlet/cgi_runner.rb, line 11
def sysread(io, size)
  buf = ""
  while size > 0
    tmp = io.sysread(size)
    buf << tmp
    size -= tmp.size
  end
  return buf
end


File: binding.rb

binding.rb

Path: | lib/wsdl/binding.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL binding definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: data.rb

data.rb

Path: | lib/wsdl/data.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL data definitions. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname wsdl/documentation wsdl/definitions wsdl/types wsdl/message wsdl/part wsdl/portType wsdl/operation wsdl/param wsdl/binding wsdl/operationBinding wsdl/service wsdl/port wsdl/import


File: definitions.rb

definitions.rb

Path: | lib/wsdl/definitions.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL definitions. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: documentation.rb

documentation.rb

Path: | lib/wsdl/documentation.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP documentation element. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: import.rb

import.rb

Path: | lib/wsdl/import.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL import definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/importer


File: importer.rb

importer.rb

Path: | lib/wsdl/importer.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL importer library. Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/xmlSchema/importer wsdl/parser


File: info.rb

info.rb

Path: | lib/wsdl/info.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL information base. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: message.rb

message.rb

Path: | lib/wsdl/message.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL message definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: operation.rb

operation.rb

Path: | lib/wsdl/operation.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL operation definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: operationBinding.rb

operationBinding.rb

Path: | lib/wsdl/operationBinding.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL bound operation definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: param.rb

param.rb

Path: | lib/wsdl/param.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL param definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: parser.rb

parser.rb

Path: | lib/wsdl/parser.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL XML Instance parser library. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname xsd/ns xsd/charset xsd/datatypes xsd/xmlparser wsdl/wsdl wsdl/data wsdl/xmlSchema/data wsdl/soap/data


File: part.rb

part.rb

Path: | lib/wsdl/part.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL part definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: port.rb

port.rb

Path: | lib/wsdl/port.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL port definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: portType.rb

portType.rb

Path: | lib/wsdl/portType.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL portType definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: service.rb

service.rb

Path: | lib/wsdl/service.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL service definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: types.rb

types.rb

Path: | lib/wsdl/types.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL types definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: wsdl.rb

wsdl.rb

Path: | lib/wsdl/wsdl.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Base definitions. Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname


File: address.rb

address.rb

Path: | lib/wsdl/soap/address.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP address definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: binding.rb

binding.rb

Path: | lib/wsdl/soap/binding.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP binding definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: body.rb

body.rb

Path: | lib/wsdl/soap/body.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP body definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: cgiStubCreator.rb

cgiStubCreator.rb

Path: | lib/wsdl/soap/cgiStubCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating CGI stub code from WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/mappingRegistryCreator wsdl/soap/methodDefCreator wsdl/soap/classDefCreatorSupport


File: classDefCreator.rb

classDefCreator.rb

Path: | lib/wsdl/soap/classDefCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating class definition from WSDL Copyright (C) 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/data wsdl/soap/classDefCreatorSupport xsd/codegen


File: classDefCreatorSupport.rb

classDefCreatorSupport.rb

Path: | lib/wsdl/soap/classDefCreatorSupport.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating class code support from WSDL. Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info soap/mapping soap/mapping/typeMap xsd/codegen/gensupport


File: clientSkeltonCreator.rb

clientSkeltonCreator.rb

Path: | lib/wsdl/soap/clientSkeltonCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating client skelton code from WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/classDefCreatorSupport


File: complexType.rb

complexType.rb

Path: | lib/wsdl/soap/complexType.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - SOAP complexType definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/xmlSchema/complexType soap/mapping


File: data.rb

data.rb

Path: | lib/wsdl/soap/data.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP binding data definitions. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname wsdl/soap/definitions wsdl/soap/binding wsdl/soap/operation wsdl/soap/body wsdl/soap/element wsdl/soap/header wsdl/soap/headerfault wsdl/soap/fault wsdl/soap/address wsdl/soap/complexType


File: definitions.rb

definitions.rb

Path: | lib/wsdl/soap/definitions.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL additional definitions for SOAP. Copyright (C) 2002-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements soap/mapping


File: driverCreator.rb

driverCreator.rb

Path: | lib/wsdl/soap/driverCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating driver code from WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/mappingRegistryCreator wsdl/soap/methodDefCreator wsdl/soap/classDefCreatorSupport xsd/codegen


File: element.rb

element.rb

Path: | lib/wsdl/soap/element.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - XMLSchema element definition for WSDL. Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/xmlSchema/element


File: fault.rb

fault.rb

Path: | lib/wsdl/soap/fault.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP body definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: header.rb

header.rb

Path: | lib/wsdl/soap/header.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP body definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: headerfault.rb

headerfault.rb

Path: | lib/wsdl/soap/headerfault.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP body definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: mappingRegistryCreator.rb

mappingRegistryCreator.rb

Path: | lib/wsdl/soap/mappingRegistryCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating MappingRegistry code from WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/classDefCreatorSupport


File: methodDefCreator.rb

methodDefCreator.rb

Path: | lib/wsdl/soap/methodDefCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating driver code from WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/classDefCreatorSupport soap/rpc/element


File: operation.rb

operation.rb

Path: | lib/wsdl/soap/operation.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL SOAP operation definition. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: servantSkeltonCreator.rb

servantSkeltonCreator.rb

Path: | lib/wsdl/soap/servantSkeltonCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating servant skelton code from WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/classDefCreatorSupport xsd/codegen


File: standaloneServerStubCreator.rb

standaloneServerStubCreator.rb

Path: | lib/wsdl/soap/standaloneServerStubCreator.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - Creating standalone server stub code from WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/soap/mappingRegistryCreator wsdl/soap/methodDefCreator wsdl/soap/classDefCreatorSupport


File: wsdl2ruby.rb

wsdl2ruby.rb

Path: | lib/wsdl/soap/wsdl2ruby.rb
Last Update: | Tue Mar 13 02:05:49 -0500 2007

WSDL4R - WSDL to ruby mapping library. Copyright (C) 2002-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

logger xsd/qname wsdl/importer wsdl/soap/classDefCreator wsdl/soap/servantSkeltonCreator wsdl/soap/driverCreator wsdl/soap/clientSkeltonCreator wsdl/soap/standaloneServerStubCreator wsdl/soap/cgiStubCreator


File: all.rb

all.rb

Path: | lib/wsdl/xmlSchema/all.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema complexType definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: annotation.rb

annotation.rb

Path: | lib/wsdl/xmlSchema/annotation.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - WSDL SOAP documentation element. Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: any.rb

any.rb

Path: | lib/wsdl/xmlSchema/any.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema any definition for WSDL. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: attribute.rb

attribute.rb

Path: | lib/wsdl/xmlSchema/attribute.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema attribute definition for WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: choice.rb

choice.rb

Path: | lib/wsdl/xmlSchema/choice.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema complexType definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: complexContent.rb

complexContent.rb

Path: | lib/wsdl/xmlSchema/complexContent.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema complexContent definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: complexType.rb

complexType.rb

Path: | lib/wsdl/xmlSchema/complexType.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema complexType definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/xmlSchema/content wsdl/xmlSchema/element xsd/namedelements


File: content.rb

content.rb

Path: | lib/wsdl/xmlSchema/content.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema complexType definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: data.rb

data.rb

Path: | lib/wsdl/xmlSchema/data.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema data definitions. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/datatypes wsdl/xmlSchema/annotation wsdl/xmlSchema/schema wsdl/xmlSchema/import wsdl/xmlSchema/include wsdl/xmlSchema/simpleType wsdl/xmlSchema/simpleRestriction wsdl/xmlSchema/simpleExtension wsdl/xmlSchema/complexType wsdl/xmlSchema/complexContent wsdl/xmlSchema/simpleContent wsdl/xmlSchema/any wsdl/xmlSchema/element wsdl/xmlSchema/all wsdl/xmlSchema/choice wsdl/xmlSchema/sequence wsdl/xmlSchema/attribute wsdl/xmlSchema/unique wsdl/xmlSchema/enumeration wsdl/xmlSchema/length wsdl/xmlSchema/pattern


File: element.rb

element.rb

Path: | lib/wsdl/xmlSchema/element.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema element definition for WSDL. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: enumeration.rb

enumeration.rb

Path: | lib/wsdl/xmlSchema/enumeration.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema enumeration definition for WSDL. Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: import.rb

import.rb

Path: | lib/wsdl/xmlSchema/import.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema import definition. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/xmlSchema/importer


File: importer.rb

importer.rb

Path: | lib/wsdl/xmlSchema/importer.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XSD importer library. Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/httpconfigloader wsdl/xmlSchema/parser http-access2 soap/netHttpClient


File: include.rb

include.rb

Path: | lib/wsdl/xmlSchema/include.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema include definition. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info wsdl/xmlSchema/importer


File: length.rb

length.rb

Path: | lib/wsdl/xmlSchema/length.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema length definition for WSDL. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: parser.rb

parser.rb

Path: | lib/wsdl/xmlSchema/parser.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - WSDL XML Instance parser library. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname xsd/ns xsd/charset xsd/datatypes xsd/xmlparser wsdl/xmlSchema/data


File: pattern.rb

pattern.rb

Path: | lib/wsdl/xmlSchema/pattern.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema pattern definition for WSDL. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: schema.rb

schema.rb

Path: | lib/wsdl/xmlSchema/schema.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema schema definition for WSDL. Copyright (C) 2002, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: sequence.rb

sequence.rb

Path: | lib/wsdl/xmlSchema/sequence.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema complexType definition for WSDL. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: simpleContent.rb

simpleContent.rb

Path: | lib/wsdl/xmlSchema/simpleContent.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema simpleContent definition for WSDL. Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: simpleExtension.rb

simpleExtension.rb

Path: | lib/wsdl/xmlSchema/simpleExtension.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema simpleType extension definition for WSDL. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: simpleRestriction.rb

simpleRestriction.rb

Path: | lib/wsdl/xmlSchema/simpleRestriction.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema simpleContent restriction definition for WSDL. Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: simpleType.rb

simpleType.rb

Path: | lib/wsdl/xmlSchema/simpleType.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema simpleType definition for WSDL. Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info xsd/namedelements


File: unique.rb

unique.rb

Path: | lib/wsdl/xmlSchema/unique.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

WSDL4R - XMLSchema unique element. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

wsdl/info


File: xsd2ruby.rb

xsd2ruby.rb

Path: | lib/wsdl/xmlSchema/xsd2ruby.rb
Last Update: | Tue Mar 13 02:05:47 -0500 2007

XSD4R - XSD to ruby mapping library. Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport wsdl/xmlSchema/importer wsdl/soap/classDefCreator


File: charset.rb

charset.rb

Path: | lib/xsd/charset.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - Charset handling library. Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/iconvcharset nkf uconv


File: datatypes1999.rb

datatypes1999.rb

Path: | lib/xsd/datatypes1999.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML Schema Datatype 1999 support Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/datatypes


File: datatypes.rb

datatypes.rb

Path: | lib/xsd/datatypes.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML Schema Datatype implementation. Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname xsd/charset uri rational date


File: iconvcharset.rb

iconvcharset.rb

Path: | lib/xsd/iconvcharset.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - Charset handling with iconv. Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

iconv


File: mapping.rb

mapping.rb

Path: | lib/xsd/mapping.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML Mapping for Ruby Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

soap/parser soap/encodingstyle/literalHandler soap/generator soap/mapping soap/mapping/wsdlliteralregistry


File: namedelements.rb

namedelements.rb

Path: | lib/xsd/namedelements.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - WSDL named element collection. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: ns.rb

ns.rb

Path: | lib/xsd/ns.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML Schema Namespace library Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/datatypes


File: qname.rb

qname.rb

Path: | lib/xsd/qname.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML QName definition. Copyright (C) 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: xmlparser.rb

xmlparser.rb

Path: | lib/xsd/xmlparser.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML Instance parser library. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/xmlparser/parser


File: classdef.rb

classdef.rb

Path: | lib/xsd/codegen/classdef.rb
Last Update: | Tue Mar 13 02:06:01 -0500 2007

XSD4R - Generating class definition code Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport xsd/codegen/moduledef xsd/codegen/methoddef xsd/codegen/classdef

Included Modules

XSD::CodeGen


File: commentdef.rb

commentdef.rb

Path: | lib/xsd/codegen/commentdef.rb
Last Update: | Tue Mar 13 02:06:01 -0500 2007

XSD4R - Generating comment definition code Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport


File: gensupport.rb

gensupport.rb

Path: | lib/xsd/codegen/gensupport.rb
Last Update: | Tue Mar 13 02:06:01 -0500 2007

XSD4R - Code generation support Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.


File: methoddef.rb

methoddef.rb

Path: | lib/xsd/codegen/methoddef.rb
Last Update: | Tue Mar 13 02:06:01 -0500 2007

XSD4R - Generating method definition code Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport xsd/codegen/commentdef


File: moduledef.rb

moduledef.rb

Path: | lib/xsd/codegen/moduledef.rb
Last Update: | Tue Mar 13 02:06:01 -0500 2007

XSD4R - Generating module definition code Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/codegen/gensupport xsd/codegen/methoddef xsd/codegen/commentdef xsd/codegen/moduledef

Included Modules

XSD::CodeGen


File: parser.rb

parser.rb

Path: | lib/xsd/xmlparser/parser.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XML Instance parser library. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/qname xsd/ns xsd/charset


File: rexmlparser.rb

rexmlparser.rb

Path: | lib/xsd/xmlparser/rexmlparser.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - REXMLParser XML parser library. Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/xmlparser rexml/streamlistener rexml/document


File: xmlparser.rb

xmlparser.rb

Path: | lib/xsd/xmlparser/xmlparser.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XMLParser XML parser library. Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/xmlparser xml/parser xml/encoding-ja


File: xmlscanner.rb

xmlscanner.rb

Path: | lib/xsd/xmlparser/xmlscanner.rb
Last Update: | Tue Mar 13 02:06:02 -0500 2007

XSD4R - XMLScan XML parser library. Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.

Required files

xsd/xmlparser xmlscan/scanner


File: baseemitter.rb

baseemitter.rb

Path: | lib/yaml/baseemitter.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

BaseEmitter

Required files

yaml/constants yaml/encoding yaml/error


File: basenode.rb

basenode.rb

Path: | lib/yaml/basenode.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

YAML::BaseNode class

Required files

yaml/ypath


File: constants.rb

constants.rb

Path: | lib/yaml/constants.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

Constants used throughout the library


File: dbm.rb

dbm.rb

Path: | lib/yaml/dbm.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

Required files

yaml dbm


File: encoding.rb

encoding.rb

Path: | lib/yaml/encoding.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

Handle Unicode-to-Internal conversion


File: error.rb

error.rb

Path: | lib/yaml/error.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

Error messages and exception class


File: loader.rb

loader.rb

Path: | lib/yaml/loader.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

YAML::Loader class .. type handling ..


File: rubytypes.rb

rubytypes.rb

Path: | lib/yaml/rubytypes.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

-*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4

Required files

date


File: store.rb

store.rb

Path: | lib/yaml/store.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

YAML::Store

Required files

yaml pstore


File: stream.rb

stream.rb

Path: | lib/yaml/stream.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007


File: stringio.rb

stringio.rb

Path: | lib/yaml/stringio.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

Limited StringIO if no core lib is available

Required files

stringio


File: syck.rb

syck.rb

Path: | lib/yaml/syck.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

YAML::Syck module .. glues syck and yaml.rb together ..

Required files

syck yaml/basenode


File: tag.rb

tag.rb

Path: | lib/yaml/tag.rb
Last Update: | Tue Mar 13 20:34:51 -0500 2007

-*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4 $Id: tag.rb 11708 2007-02-12 23:01:19Z shyouhei $

yaml/tag.rb: methods for associating a taguri to a class.

Author: why the lucky stiff


File: types.rb

types.rb

Path: | lib/yaml/types.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

-*- mode: ruby; ruby-indent-level: 4 -*- vim: sw=4

Classes required by the full core typeset


File: yamlnode.rb

yamlnode.rb

Path: | lib/yaml/yamlnode.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

YAML::YamlNode class

Required files

yaml/basenode


File: ypath.rb

ypath.rb

Path: | lib/yaml/ypath.rb
Last Update: | Tue Mar 13 02:07:02 -0500 2007

YAML::YPath